Real-service triage returned "undetermined" because the console tail held only post-build noise; this Jenkins has no junit or stage-view plugin, so console text is the only structured evidence available. - hermes_console_evidence: scan the full console for failure markers (pytest, build, tool gates, k8s/agent), capture context windows, merge overlaps, collapse repeats, and prefer the earliest regions under a byte budget; bundle gains jenkins.console_failures and console_truncated - evidence: fetch the full console (head + tail bounded at 2MB) instead of the last 8KB; signature detection now also scans regions - prompt: one line explaining that the earliest region usually holds the first enforced failure - code flow: check for an already-open hermes-repair/* pull request before spending model tokens; fail open so a Gitea error cannot suppress work Verified on a synthetic 4018-line pipeline: the real failure at line 7 is now captured where the previous tail-only slice missed it entirely. 95 new tests; 281 pass in the hermes suite. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
237 lines
7.3 KiB
Python
237 lines
7.3 KiB
Python
from __future__ import annotations
|
|
|
|
import re
|
|
from typing import Any
|
|
|
|
|
|
FAILURE_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",
|
|
"exit code",
|
|
"command not found",
|
|
"No such file",
|
|
"Exception",
|
|
"ERROR:",
|
|
# tool gates
|
|
"Quality gate",
|
|
"fail-under",
|
|
"coverage",
|
|
"docstring",
|
|
"Semgrep",
|
|
"SonarQube",
|
|
"Trivy",
|
|
"ruff",
|
|
"[loc]",
|
|
)
|
|
|
|
# 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.
|
|
"""
|
|
|
|
lowered = str(line).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 _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)
|
|
if spans and start <= spans[-1]["end"]:
|
|
spans[-1]["end"] = max(spans[-1]["end"], end)
|
|
continue
|
|
spans.append({"marker": marker, "line_number": index + 1, "start": start, "end": end})
|
|
return [
|
|
{
|
|
"marker": span["marker"],
|
|
"line_number": span["line_number"],
|
|
"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 earliest regions that fit the byte and count budgets."""
|
|
|
|
limit = options["max_total_bytes"]
|
|
kept: list[dict[str, Any]] = []
|
|
used = 0
|
|
truncated = False
|
|
for region in regions:
|
|
if len(kept) >= options["max_regions"]:
|
|
return kept, True
|
|
size = _byte_len(region["text"])
|
|
if used + size > limit:
|
|
if kept:
|
|
return kept, True
|
|
region = {**region, "text": _clip_head(region["text"], limit)}
|
|
size = _byte_len(region["text"])
|
|
truncated = True
|
|
kept.append(region)
|
|
used += size
|
|
return kept, truncated
|
|
|
|
|
|
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")
|