ariadne/ariadne/services/hermes_autotriage_metrics.py
codex 9f24f8d999
All checks were successful
Tests / Declarative: Post Actions passed: 1275
feat(hermes): let a diagnosis propose a remediation that does not exist yet
Every action in the allowlist got there because someone hit the failure by
hand, recognised the pattern, and wired a job for it. That loop only closes if
a person happens to read enough issues to notice the same failure recurring,
so a failure nobody reviews twice never earns an action. Until now a diagnosis
that fit nothing could only say a human was needed; it could not say what the
human should build.

An optional suggested_remediation field closes the other half of the loop.
When nothing in the allowlist fits, Hermes may name the remediation it
believes would work and the evidence that should be required before running it
is safe. It lands in the incident issue under a heading that states plainly
the remediation does not exist and was not performed, and in the audit event,
where the same proposal recurring across unrelated incidents is the evidence
that building it is worth the effort.

The field is inert by construction. No gate reads it, and an id that is not
already allowlisted still fails action_not_allowlisted exactly as before -
naming a remediation and being granted one stay different things, and only the
second needs a human to change a deployment. It is rejected outright alongside
a requested action: the field reports that nothing fit, so something fitting
contradicts it, and allowing both would invite a rationale to be attached to a
request the gates must judge on evidence alone. The key is optional rather
than required so a response written before today still validates unchanged,
and unknown keys are still refused.

Also names reclaim_workspace_storage, clear_stuck_agent_pods and
abort_hung_build in KNOWN_ACTION_LABELS. They were reporting as "unknown" in
metrics on any deployment that had not enabled them, which is the one case
where you most want to see the real name.

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

120 lines
4.2 KiB
Python

"""Prometheus metrics for Hermes auto-triage, with restart-safe rehydration.
The incident gauge is one-hot per (jenkins_job, build): the current status
holds 1 and every other status holds 0. Because gauge state lives in
process memory, each scheduler tick republishes the gauges for known
incidents so pod restarts cannot silently drop an active human-required
signal before the alert's hold window elapses.
"""
from __future__ import annotations
from typing import Any
from prometheus_client import Counter, Gauge
INCIDENT_STATUSES = (
"detected",
"diagnosed",
"repairing",
"awaiting_rebuild",
"resolved",
"human_required",
"failed",
)
PROPOSE_CODE_FIX_ACTION = "propose_code_fix"
# The bounded `action` label set for HERMES_TRIAGE_ACTION_TOTAL. Anything the
# model asks for that is neither deployed in hermes_allowed_actions nor listed
# here collapses to "unknown", so a hallucinated action id can never mint a new
# metric series. `propose_code_fix` and `abort_hung_build` are the orchestrator's
# own additive steps rather than model-requested remediations, so they have to be
# named here. The remaining ids are named so a deployment that has not enabled
# one of them still reports it under its own name rather than as "unknown".
ABORT_HUNG_BUILD_ACTION = "abort_hung_build"
KNOWN_ACTION_LABELS = (
"repair_demo_fixture",
"retry_transient_infra",
"reclaim_workspace_storage",
"clear_stuck_agent_pods",
ABORT_HUNG_BUILD_ACTION,
PROPOSE_CODE_FIX_ACTION,
)
HERMES_TRIAGE_INCIDENT = Gauge(
"ariadne_hermes_triage_incident",
"Hermes auto-triage incident state (1=current status, 0=other statuses)",
["jenkins_job", "build", "status"],
)
HERMES_TRIAGE_ACTION_TOTAL = Counter(
"ariadne_hermes_triage_action_total",
"Hermes auto-triage remediation actions by result",
["action", "result"],
)
HERMES_TRIAGE_SUGGESTION_TOTAL = Counter(
"ariadne_hermes_triage_suggestion_total",
"Remediations Hermes proposed for failures no allowlisted action covers",
)
HERMES_TRIAGE_LAST_SUCCESS_TS = Gauge(
"ariadne_hermes_triage_last_success_timestamp_seconds",
"Last Hermes auto-triage incident resolution timestamp",
)
HERMES_TRIAGE_DURATION_SECONDS = Gauge(
"ariadne_hermes_triage_duration_seconds",
"Duration of the latest Hermes auto-triage phase in seconds",
["phase"],
)
def set_incident_gauge(job: str, build: str, active: set[str]) -> None:
"""Set the incident gauge to 1 for active statuses and 0 for the rest.
Inputs: the Jenkins job name, the build number as a string, and the
set of statuses that should read 1. Outputs: none.
"""
for status in INCIDENT_STATUSES:
HERMES_TRIAGE_INCIDENT.labels(jenkins_job=job, build=build, status=status).set(
1 if status in active else 0
)
def refresh_incident_gauges(job: str, last_build: dict[str, Any], incidents: dict[str, dict[str, Any]]) -> None:
"""Republish incident gauges for one job from stored incident state.
Inputs: the job name, its Jenkins lastBuild summary, and the folded
latest-state-per-incident map. Outputs: none. Unresolved incidents keep
their one-hot status (a repair failure also keeps human_required); an
incident superseded by a newer successful build is zeroed so the
human-required alert clears once the job is green again. Resolved
incidents are left quiet.
"""
number = _int_value(last_build.get("number"))
superseded = str(last_build.get("result") or "").upper() == "SUCCESS"
for incident in incidents.values():
if incident.get("job") != job:
continue
status = str(incident.get("status") or "")
if status not in INCIDENT_STATUSES or status == "resolved":
continue
build = str(incident.get("build_number"))
if superseded and _int_value(incident.get("build_number")) < number:
set_incident_gauge(job, build, set())
elif status == "failed":
set_incident_gauge(job, build, {"failed", "human_required"})
else:
set_incident_gauge(job, build, {status})
def _int_value(value: Any) -> int:
"""Coerce a value to int, defaulting to zero."""
try:
return int(value)
except (TypeError, ValueError):
return 0