392 lines
14 KiB
Python
392 lines
14 KiB
Python
from __future__ import annotations
|
|
|
|
from datetime import datetime, timezone
|
|
import json
|
|
from typing import Any
|
|
|
|
import httpx
|
|
|
|
from ..db.storage import Storage
|
|
from ..settings import settings
|
|
|
|
|
|
TRIAGE_DIAGNOSIS_EVENT_TYPE = "testing_triage_diagnosis"
|
|
_MAX_MODEL_EVIDENCE_CHARS = 24000
|
|
_MAX_MODEL_OUTPUT_CHARS = 12000
|
|
_ASCII_CODEPOINT_LIMIT = 128
|
|
_DIAGNOSIS_SYSTEM_PROMPT = (
|
|
"You are Ariadne's local testing triage model. Use only the supplied JSON evidence. "
|
|
"Return exactly one diagnosis object that matches the requested schema. Do not copy "
|
|
"or summarize the evidence as nested input data. Confidence must be low, medium, or "
|
|
"high. Next actions must be read-only verification or Flux/IaC changes; never suggest "
|
|
"mutating kubectl commands or reading Kubernetes Secret values. If evidence is "
|
|
"insufficient, say that plainly in root_cause. All response values must be written "
|
|
"in English using ASCII text only. Never answer in Chinese or any other non-English "
|
|
"language. Use normal English words with spaces; do not concatenate words."
|
|
)
|
|
_DIAGNOSIS_RESPONSE_SCHEMA: dict[str, Any] = {
|
|
"type": "object",
|
|
"additionalProperties": False,
|
|
"properties": {
|
|
"headline": {"type": "string"},
|
|
"root_cause": {"type": "string"},
|
|
"blast_radius": {"type": "string"},
|
|
"confidence": {"type": "string", "enum": ["low", "medium", "high"]},
|
|
"needs_human": {"type": "boolean"},
|
|
"next_actions": {
|
|
"type": "array",
|
|
"items": {"type": "string"},
|
|
"minItems": 1,
|
|
"maxItems": 6,
|
|
},
|
|
"evidence_refs": {
|
|
"type": "array",
|
|
"items": {"type": "string"},
|
|
"minItems": 1,
|
|
"maxItems": 8,
|
|
},
|
|
},
|
|
"required": [
|
|
"headline",
|
|
"root_cause",
|
|
"blast_radius",
|
|
"confidence",
|
|
"needs_human",
|
|
"next_actions",
|
|
"evidence_refs",
|
|
],
|
|
}
|
|
|
|
|
|
def latest_testing_triage_diagnosis(storage: Storage) -> dict[str, Any] | None:
|
|
"""Return the most recent stored local-model testing diagnosis, if present."""
|
|
|
|
rows = storage.list_events(limit=1, event_type=TRIAGE_DIAGNOSIS_EVENT_TYPE)
|
|
if not rows:
|
|
return None
|
|
detail = rows[0].get("detail")
|
|
if isinstance(detail, dict):
|
|
return detail
|
|
if isinstance(detail, str):
|
|
try:
|
|
payload = json.loads(detail)
|
|
except json.JSONDecodeError:
|
|
return None
|
|
return payload if isinstance(payload, dict) else None
|
|
return None
|
|
|
|
|
|
def model_diagnosis_enabled() -> bool:
|
|
"""Return whether Ariadne has a local testing diagnosis model configured."""
|
|
|
|
return bool(_model_url())
|
|
|
|
|
|
def diagnose_testing_triage(bundle: dict[str, Any]) -> dict[str, Any]:
|
|
"""Ask the configured local model to summarize a deterministic triage bundle."""
|
|
|
|
base_url = _model_url()
|
|
if not base_url:
|
|
return _diagnosis_unavailable(bundle, "model_url_not_configured")
|
|
|
|
try:
|
|
with httpx.Client(timeout=_model_timeout()) as client:
|
|
response = client.post(
|
|
f"{base_url}/api/generate",
|
|
json={
|
|
"model": _model_name(),
|
|
"system": _DIAGNOSIS_SYSTEM_PROMPT,
|
|
"prompt": _diagnosis_prompt(bundle),
|
|
"stream": False,
|
|
"format": _DIAGNOSIS_RESPONSE_SCHEMA,
|
|
"options": {"temperature": 0.1, "top_p": 0.9},
|
|
},
|
|
)
|
|
response.raise_for_status()
|
|
payload = response.json()
|
|
except Exception as exc:
|
|
return _diagnosis_unavailable(bundle, f"model_request_failed: {exc}")
|
|
|
|
raw = str(payload.get("response") or "")
|
|
parsed, parse_error = _parse_model_response(raw)
|
|
return _diagnosis_from_model(bundle, parsed, raw, parse_error)
|
|
|
|
|
|
def _model_url() -> str:
|
|
return str(getattr(settings, "testing_triage_model_url", "") or "").strip().rstrip("/")
|
|
|
|
|
|
def _model_name() -> str:
|
|
return str(getattr(settings, "testing_triage_model", "qwen2.5:7b-instruct-q4_0") or "").strip()
|
|
|
|
|
|
def _model_timeout() -> float:
|
|
return float(getattr(settings, "testing_triage_model_timeout_sec", 180.0) or 180.0)
|
|
|
|
|
|
def _diagnosis_prompt(bundle: dict[str, Any]) -> str:
|
|
payload = {
|
|
"task": (
|
|
"Diagnose the highest-priority testing or cluster issue for tonight. "
|
|
"Write a compact triage finding, not an evidence dump."
|
|
),
|
|
"output_rules": [
|
|
"Return only headline, root_cause, blast_radius, confidence, needs_human, next_actions, evidence_refs.",
|
|
"Do not include keys named pipelines, quality, bundle, evidence, summary, or unknowns.",
|
|
"Prefer concrete Jenkins job names, Flux Kustomizations, pod names, nodes, and metrics when present.",
|
|
"Only discuss Jenkins suite jobs listed in bundle.summary.failed_suites; ignore stale unrelated jobs.",
|
|
"Write every string in English ASCII only.",
|
|
],
|
|
"bundle": _model_evidence_payload(bundle),
|
|
}
|
|
evidence = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)
|
|
if len(evidence) > _MAX_MODEL_EVIDENCE_CHARS:
|
|
evidence = evidence[:_MAX_MODEL_EVIDENCE_CHARS] + "\n[truncated]"
|
|
return evidence
|
|
|
|
|
|
def _model_evidence_payload(bundle: dict[str, Any]) -> dict[str, Any]:
|
|
summary = bundle.get("summary") if isinstance(bundle.get("summary"), dict) else {}
|
|
evidence = bundle.get("evidence") if isinstance(bundle.get("evidence"), dict) else {}
|
|
return {
|
|
"kind": bundle.get("kind"),
|
|
"generated_at": bundle.get("generated_at"),
|
|
"summary": summary,
|
|
"evidence": evidence,
|
|
"unknowns": bundle.get("unknowns") if isinstance(bundle.get("unknowns"), list) else [],
|
|
}
|
|
|
|
|
|
def _parse_model_response(raw: str) -> tuple[dict[str, Any], str | None]:
|
|
if not raw.strip():
|
|
return {}, "empty_model_response"
|
|
try:
|
|
parsed = json.loads(raw)
|
|
except json.JSONDecodeError as exc:
|
|
return {}, f"model_json_parse_failed: {exc}"
|
|
return (parsed if isinstance(parsed, dict) else {}, None)
|
|
|
|
|
|
def _diagnosis_from_model(bundle: dict[str, Any], parsed: dict[str, Any], raw: str, parse_error: str | None) -> dict[str, Any]:
|
|
summary = bundle.get("summary") if isinstance(bundle.get("summary"), dict) else {}
|
|
unknowns = list(bundle.get("unknowns") or []) if isinstance(bundle.get("unknowns"), list) else []
|
|
if parse_error:
|
|
unknowns.append(parse_error)
|
|
blocked_jobs = _out_of_scope_jobs(parsed, summary)
|
|
diagnosis = {
|
|
"headline": _safe_text_value(
|
|
parsed.get("headline"),
|
|
"Testing triage needs review.",
|
|
unknowns,
|
|
"headline",
|
|
blocked_jobs,
|
|
),
|
|
"root_cause": _safe_text_value(
|
|
parsed.get("root_cause"),
|
|
"Evidence is insufficient for a confident root cause.",
|
|
unknowns,
|
|
"root_cause",
|
|
blocked_jobs,
|
|
),
|
|
"blast_radius": _safe_text_value(
|
|
parsed.get("blast_radius"),
|
|
_blast_radius_fallback(summary),
|
|
unknowns,
|
|
"blast_radius",
|
|
blocked_jobs,
|
|
),
|
|
"confidence": _confidence(parsed.get("confidence")),
|
|
"needs_human": _bool_value(parsed.get("needs_human"), bool(summary.get("problem_count"))),
|
|
"next_actions": _safe_text_list(parsed.get("next_actions"), unknowns, "next_actions", blocked_jobs)
|
|
or _default_next_actions(summary),
|
|
"evidence_refs": _safe_evidence_refs(parsed.get("evidence_refs"), summary, unknowns)
|
|
or _default_evidence_refs(summary),
|
|
}
|
|
return {
|
|
"kind": "testing_triage_diagnosis",
|
|
"generated_at": datetime.now(timezone.utc).isoformat(),
|
|
"evidence_generated_at": bundle.get("generated_at") or "",
|
|
"evidence_summary": summary,
|
|
"status": "needs_attention" if diagnosis["needs_human"] or summary.get("problem_count") else "ok",
|
|
"model": _model_name(),
|
|
"source": "local_ollama",
|
|
"diagnosis": diagnosis,
|
|
"openclaw": {
|
|
"ariadne_latest_url": "/api/internal/testing/triage/diagnosis/latest",
|
|
"ariadne_run_url": "/api/internal/testing/triage/diagnosis/run",
|
|
"evidence_url": "/api/internal/testing/triage/latest",
|
|
},
|
|
"unknowns": unknowns,
|
|
"raw_model": raw[:_MAX_MODEL_OUTPUT_CHARS],
|
|
}
|
|
|
|
|
|
def _diagnosis_unavailable(bundle: dict[str, Any], reason: str) -> dict[str, Any]:
|
|
summary = bundle.get("summary") if isinstance(bundle.get("summary"), dict) else {}
|
|
return {
|
|
"kind": "testing_triage_diagnosis",
|
|
"generated_at": datetime.now(timezone.utc).isoformat(),
|
|
"evidence_generated_at": bundle.get("generated_at") or "",
|
|
"evidence_summary": summary,
|
|
"status": "unavailable",
|
|
"model": _model_name(),
|
|
"source": "local_ollama",
|
|
"diagnosis": {
|
|
"headline": "Local model diagnosis is unavailable.",
|
|
"root_cause": reason,
|
|
"blast_radius": _blast_radius_fallback(summary),
|
|
"confidence": "low",
|
|
"needs_human": True,
|
|
"next_actions": [
|
|
"Use the stored evidence bundle for manual triage.",
|
|
"Verify the Ariadne testing triage model URL and OpenClaw Ollama service health.",
|
|
],
|
|
"evidence_refs": _default_evidence_refs(summary),
|
|
},
|
|
"openclaw": {
|
|
"ariadne_latest_url": "/api/internal/testing/triage/diagnosis/latest",
|
|
"ariadne_run_url": "/api/internal/testing/triage/diagnosis/run",
|
|
"evidence_url": "/api/internal/testing/triage/latest",
|
|
},
|
|
"unknowns": [reason],
|
|
"raw_model": "",
|
|
}
|
|
|
|
|
|
def _text_value(value: Any, default: str) -> str:
|
|
if isinstance(value, str) and value.strip():
|
|
return value.strip()
|
|
return default
|
|
|
|
|
|
def _safe_text_value(value: Any, default: str, unknowns: list[Any], field: str, blocked_jobs: set[str]) -> str:
|
|
text = _text_value(value, default)
|
|
if not _english_ascii(text):
|
|
unknowns.append(f"model_{field}_non_english")
|
|
return default
|
|
if _mentions_blocked_job(text, blocked_jobs):
|
|
unknowns.append(f"model_{field}_out_of_scope")
|
|
return default
|
|
return text
|
|
|
|
|
|
def _text_list(value: Any) -> list[str]:
|
|
if isinstance(value, str) and value.strip():
|
|
return [value.strip()]
|
|
if not isinstance(value, list):
|
|
return []
|
|
return [str(item).strip() for item in value if str(item).strip()][:8]
|
|
|
|
|
|
def _safe_text_list(value: Any, unknowns: list[Any], field: str, blocked_jobs: set[str]) -> list[str]:
|
|
values = []
|
|
for item in _text_list(value):
|
|
if not _english_ascii(item):
|
|
unknowns.append(f"model_{field}_non_english")
|
|
continue
|
|
if _mentions_blocked_job(item, blocked_jobs):
|
|
unknowns.append(f"model_{field}_out_of_scope")
|
|
continue
|
|
values.append(item)
|
|
return values
|
|
|
|
|
|
def _safe_evidence_refs(value: Any, summary: dict[str, Any], unknowns: list[Any]) -> list[str]:
|
|
refs = []
|
|
for ref in _text_list(value):
|
|
if not _english_ascii(ref):
|
|
unknowns.append("model_evidence_refs_non_english")
|
|
continue
|
|
if not _evidence_ref_in_scope(ref, summary):
|
|
unknowns.append("model_evidence_refs_out_of_scope")
|
|
continue
|
|
refs.append(ref)
|
|
return refs
|
|
|
|
|
|
def _english_ascii(text: str) -> bool:
|
|
return all(ord(char) < _ASCII_CODEPOINT_LIMIT for char in text)
|
|
|
|
|
|
def _mentions_blocked_job(text: str, blocked_jobs: set[str]) -> bool:
|
|
lowered = text.lower()
|
|
return any(job.lower() in lowered for job in blocked_jobs)
|
|
|
|
|
|
def _out_of_scope_jobs(parsed: dict[str, Any], summary: dict[str, Any]) -> set[str]:
|
|
allowed = _allowed_suite_jobs(summary)
|
|
jobs = {_job_name_from_ref(ref) for ref in _text_list(parsed.get("evidence_refs"))}
|
|
return {job for job in jobs if job and job not in allowed}
|
|
|
|
|
|
def _evidence_ref_in_scope(ref: str, summary: dict[str, Any]) -> bool:
|
|
job = _job_name_from_ref(ref)
|
|
return not job or job in _allowed_suite_jobs(summary)
|
|
|
|
|
|
def _job_name_from_ref(ref: str) -> str:
|
|
marker = "/job/"
|
|
if marker not in ref:
|
|
return ""
|
|
return ref.split(marker, 1)[1].split("/", 1)[0].strip().lower()
|
|
|
|
|
|
def _allowed_suite_jobs(summary: dict[str, Any]) -> set[str]:
|
|
failed_suites = summary.get("failed_suites") if isinstance(summary.get("failed_suites"), list) else []
|
|
aliases = {
|
|
"bstein_home": "bstein-dev-home",
|
|
"data_prepper": "data-prepper",
|
|
"titan_iac": "titan-iac",
|
|
}
|
|
allowed = set()
|
|
for suite in failed_suites:
|
|
name = str(suite).strip().lower()
|
|
if not name:
|
|
continue
|
|
allowed.add(name)
|
|
allowed.add(name.replace("_", "-"))
|
|
if name in aliases:
|
|
allowed.add(aliases[name])
|
|
return allowed
|
|
|
|
|
|
def _confidence(value: Any) -> str:
|
|
confidence = str(value or "").strip().lower()
|
|
return confidence if confidence in {"low", "medium", "high"} else "low"
|
|
|
|
|
|
def _bool_value(value: Any, default: bool) -> bool:
|
|
if isinstance(value, bool):
|
|
return value
|
|
if isinstance(value, str):
|
|
lowered = value.strip().lower()
|
|
if lowered in {"true", "yes", "1"}:
|
|
return True
|
|
if lowered in {"false", "no", "0"}:
|
|
return False
|
|
return default
|
|
|
|
|
|
def _blast_radius_fallback(summary: dict[str, Any]) -> str:
|
|
failed_suites = summary.get("failed_suites") if isinstance(summary.get("failed_suites"), list) else []
|
|
if failed_suites:
|
|
return ", ".join(str(item) for item in failed_suites[:6])
|
|
return "No failed suite scope identified in the evidence bundle."
|
|
|
|
|
|
def _default_next_actions(summary: dict[str, Any]) -> list[str]:
|
|
if int(summary.get("problem_count") or 0) > 0:
|
|
return [
|
|
"Review the evidence bundle sections with non-empty problem lists.",
|
|
"Check the named Jenkins build logs and Flux Kustomizations before changing manifests.",
|
|
]
|
|
return ["No action required unless a fresh bundle changes the status."]
|
|
|
|
|
|
def _default_evidence_refs(summary: dict[str, Any]) -> list[str]:
|
|
refs = [f"summary.status={summary.get('status')}", f"summary.problem_count={summary.get('problem_count')}"]
|
|
failed_suites = summary.get("failed_suites") if isinstance(summary.get("failed_suites"), list) else []
|
|
if failed_suites:
|
|
refs.append("summary.failed_suites=" + ",".join(str(item) for item in failed_suites[:6]))
|
|
return refs
|