ariadne/ariadne/services/hermes_console_evidence.py
codex d2ffc6a1e0 fix(hermes): rank console failure regions by evidence strength
On a long pipeline the earliest-first region budget was consumed entirely by
successful tool output. Ariadne build 404 retained six regions spanning lines
259-476 - Trivy setup, Sonar banners, and three lines whose only failure
signal was the word 'coverage' - and dropped the actual pytest failure at line
1487. Hermes then correctly refused to diagnose, reporting that the retained
excerpts did not contain the enforced failure.

Split the markers into those that assert a failure and those that only name a
tool or gate that ran, and fill the budget with strong regions first. Also
ignore pytest progress lines ending in a passing verdict: Ariadne's own suite
parametrizes marker detection with strings like 'FAILED tests/a.py::b', and
those passing lines were being collected as failure evidence.

Verified against the real build 404 console: the retained regions now carry
the failing test name, its source file, and the assertion text.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 00:57:29 -03:00

295 lines
9.9 KiB
Python

from __future__ import annotations
import re
from typing import Any
# Markers that assert a failure happened. A line carrying one of these is
# evidence on its own.
STRONG_MARKERS: tuple[str, ...] = (
# kubernetes / build-agent signals: long and unambiguous, so they are
# matched first and never mislabelled as a generic test failure
"ImagePullBackOff",
"OOMKilled",
"Failed to establish a new connection",
"Temporary failure in name resolution",
# pytest / unittest signals: they name the real failure
"=== FAILURES ===",
"short test summary",
"ERROR at setup",
"Traceback (most recent call last)",
"AssertionError",
"FAILED ",
"E ",
# generic build signals
"BUILD FAILED",
"FAILURE:",
"non-zero exit",
"command not found",
"No such file",
"Exception",
"ERROR:",
)
# Markers that only say a gate or tool ran. Every green build prints
# "coverage", "SonarQube", "Trivy" and "ruff" dozens of times before any real
# failure appears, so treating these as evidence let successful setup output
# crowd the actual failure out of the byte budget on long pipelines. They are
# retained only after every strong region has had its chance.
WEAK_MARKERS: tuple[str, ...] = (
"exit code",
"Quality gate",
"fail-under",
"coverage",
"docstring",
"Semgrep",
"SonarQube",
"Trivy",
"ruff",
"[loc]",
)
FAILURE_MARKERS: tuple[str, ...] = STRONG_MARKERS + WEAK_MARKERS
_STRONG_TIER = 0
_WEAK_TIER = 1
# A pytest progress line ending in a passing verdict is not a failure even when
# its parametrized id quotes one. Ariadne's own suite parametrizes marker
# detection with strings like "FAILED tests/test_a.py::test_b", and those
# passing lines were being collected as failure evidence.
_PASSING_VERDICT = re.compile(r"\b(PASSED|SKIPPED|XFAIL|XPASS)\b\s*(\[\s*\d+%\])?\s*$")
# Markers that are only meaningful at the start of a (stripped) line; matching
# them anywhere would swallow every line that merely says "... failed ...".
# All matching is case-insensitive, so these are stored lowercased.
PREFIX_ONLY_MARKERS: frozenset[str] = frozenset({"e ", "failed "})
_DEFAULTS: dict[str, int] = {
"context_before": 6,
"context_after": 12,
"tail_lines": 40,
"max_total_bytes": 12000,
"max_tail_bytes": 4000,
"max_regions": 6,
}
_EMPTY: dict[str, Any] = {"regions": [], "tail": "", "total_lines": 0, "truncated": False}
_DIGITS = re.compile(r"\d+")
def extract_console_evidence(console_text: str, cfg: dict | None = None) -> dict:
"""Extract failure regions and the tail from a Jenkins console log.
Inputs: the full `consoleText` of a build and an optional config dict
(`context_before`, `context_after`, `tail_lines`, `max_total_bytes`,
`max_tail_bytes`, `max_regions`; each falls back to its default).
Outputs: {"regions": [{"marker", "line_number", "text"}, ...] in
chronological order, "tail": str, "total_lines": int, "truncated": bool}.
The tail alone is unreliable on long pipelines, so regions carry the
earliest enforced failure. Pure function, no I/O, never raises.
"""
try:
options = _options(cfg)
lines = _lines(console_text)
regions, truncated = _budgeted(_deduped(_regions(lines, options)), options)
return {
"regions": regions,
"tail": _tail(lines, options),
"total_lines": len(lines),
"truncated": truncated,
}
except Exception:
return dict(_EMPTY)
def marker_for_line(line: str) -> str | None:
"""Return the highest-priority failure marker matching one console line.
Inputs: a single console line. Outputs: the marker as declared in
`FAILURE_MARKERS`, or None when the line carries no failure signal.
"""
raw = str(line)
if _PASSING_VERDICT.search(raw.rstrip()):
return None
lowered = raw.lower()
stripped = lowered.lstrip()
for marker in FAILURE_MARKERS:
needle = marker.lower()
if needle in PREFIX_ONLY_MARKERS:
if stripped.startswith(needle):
return marker
elif needle in lowered:
return marker
return None
def marker_tier(marker: str | None) -> int:
"""Return the evidence tier of a marker: 0 asserts failure, 1 only hints.
Inputs: a marker string as returned by `marker_for_line`, or None.
Outputs: `_STRONG_TIER` for markers that assert a failure occurred and
`_WEAK_TIER` for markers that merely name a tool or gate that ran.
"""
return _STRONG_TIER if marker in STRONG_MARKERS else _WEAK_TIER
def _lines(console_text: Any) -> list[str]:
"""Split console text into lines, tolerating None and non-strings."""
return console_text.splitlines() if isinstance(console_text, str) else []
def _options(cfg: dict | None) -> dict[str, int]:
"""Merge caller config over the module defaults, ignoring bad values."""
source = cfg if isinstance(cfg, dict) else {}
return {key: _bounded_int(source.get(key), default) for key, default in _DEFAULTS.items()}
def _bounded_int(value: Any, default: int) -> int:
"""Coerce a config value to a non-negative int, else return the default."""
try:
number = int(value)
except (TypeError, ValueError):
return default
return number if number >= 0 else default
def _regions(lines: list[str], options: dict[str, int]) -> list[dict[str, Any]]:
"""Build merged context windows around every failure marker hit."""
spans: list[dict[str, Any]] = []
for index, line in enumerate(lines):
marker = marker_for_line(line)
if marker is None:
continue
start = max(0, index - options["context_before"])
end = min(len(lines), index + options["context_after"] + 1)
tier = marker_tier(marker)
if spans and start <= spans[-1]["end"]:
spans[-1]["end"] = max(spans[-1]["end"], end)
if tier < spans[-1]["tier"]:
# A merged span inherits the strongest signal inside it, so a
# real failure a few lines below a tool banner is not demoted.
spans[-1].update({"tier": tier, "marker": marker, "line_number": index + 1})
continue
spans.append(
{"marker": marker, "line_number": index + 1, "start": start, "end": end, "tier": tier}
)
return [
{
"marker": span["marker"],
"line_number": span["line_number"],
"tier": span["tier"],
"text": "\n".join(lines[span["start"] : span["end"]]),
}
for span in spans
]
def _deduped(regions: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Collapse near-identical repeated regions into one annotated region."""
first: dict[str, dict[str, Any]] = {}
counts: dict[str, int] = {}
order: list[str] = []
for region in regions:
key = _fingerprint(region["text"])
if key in first:
counts[key] += 1
continue
first[key] = region
counts[key] = 1
order.append(key)
return [_with_repeat_note(first[key], counts[key]) for key in order]
def _fingerprint(text: str) -> str:
"""Normalize region text so retries differing only in numbers collapse."""
return _DIGITS.sub("#", " ".join(text.split()))
def _with_repeat_note(region: dict[str, Any], count: int) -> dict[str, Any]:
"""Append a repeat note to a region seen more than once."""
if count <= 1:
return region
return {**region, "text": f"{region['text']}\n(repeated {count} times)"}
def _budgeted(
regions: list[dict[str, Any]], options: dict[str, int]
) -> tuple[list[dict[str, Any]], bool]:
"""Keep the strongest, then earliest, regions that fit the budgets.
Regions are offered strongest-tier-first and earliest-first within a tier,
so on a long pipeline the enforced failure is retained even when hundreds
of successful tool banners precede it. The kept regions are returned in
chronological order, which is the order the reader needs them in.
"""
limit = options["max_total_bytes"]
kept: list[dict[str, Any]] = []
used = 0
truncated = False
ordered = sorted(regions, key=lambda region: (region.get("tier", _WEAK_TIER), region["line_number"]))
for region in ordered:
if len(kept) >= options["max_regions"]:
truncated = True
break
size = _byte_len(region["text"])
if used + size > limit:
if kept:
truncated = True
break
region = {**region, "text": _clip_head(region["text"], limit)}
size = _byte_len(region["text"])
truncated = True
kept.append(region)
used += size
chronological = sorted(kept, key=lambda region: region["line_number"])
return [_without_tier(region) for region in chronological], truncated
def _without_tier(region: dict[str, Any]) -> dict[str, Any]:
"""Drop the internal tier key so the emitted region shape stays frozen."""
return {key: value for key, value in region.items() if key != "tier"}
def _tail(lines: list[str], options: dict[str, int]) -> str:
"""Return the byte-capped last lines of the console log."""
tail_lines = options["tail_lines"]
if tail_lines <= 0:
return ""
return _clip_tail("\n".join(lines[-tail_lines:]), options["max_tail_bytes"])
def _byte_len(text: str) -> int:
"""Return the UTF-8 byte length of a string."""
return len(text.encode("utf-8", "ignore"))
def _clip_head(text: str, limit: int) -> str:
"""Return at most `limit` bytes from the start of the text."""
if limit <= 0:
return ""
return text.encode("utf-8", "ignore")[:limit].decode("utf-8", "ignore")
def _clip_tail(text: str, limit: int) -> str:
"""Return at most `limit` bytes from the end of the text."""
if limit <= 0:
return ""
return text.encode("utf-8", "ignore")[-limit:].decode("utf-8", "ignore")