"""Failure memory (learner): SQLite run history + failure patterns; token-Jaccard similarity. PgVectorMemory is a stub (production target: Postgres + pgvector embeddings).""" from __future__ import annotations import json import re from typing import Protocol from .rundb import RunDB, now_iso _NOISE = [(re.compile(r"\x1b\[[0-9;]*[A-Za-z]"), ""), (re.compile(r"\d+(\.\d+)?"), ""), (re.compile(r"'[^']{0,80}'|\"[^\"]{0,80}\""), ""), (re.compile(r"\s+"), " ")] def signature(message: str) -> str: s = (message or "").split("\n")[0][:300] for rx, rep in _NOISE: s = rx.sub(rep, s) return s.strip().lower() def tokens(message: str) -> set[str]: return set(re.findall(r"[a-z_]{3,}", (message or "").lower())) def jaccard(a: set, b: set) -> float: return len(a & b) / len(a | b) if a and b else 0.0 class FailureMemory(Protocol): def record_run(self, run_id: str, module: str, patch_id: str, decision: str, counts: dict) -> None: ... def record_failure(self, rec: dict) -> int: ... def label(self, run_id: str, case_id: str, human_label: str, **kw) -> None: ... def earlier_labels(self, case_id: str, exclude_run: str) -> list[str]: ... def similar(self, message: str, module: str | None = None, k: int = 5) -> list[dict]: ... def case_history(self, case_id: str, last_n: int = 10) -> list[dict]: ... def metrics(self, module: str) -> dict: ... class SqliteFailureMemory: def __init__(self, db: RunDB): self.db = db def record_run(self, run_id: str, module: str, patch_id: str, decision: str, counts: dict) -> None: self.db.x("INSERT INTO run_history (run_id, module, patch_id, decision, counts, ts) VALUES (?,?,?,?,?,?) " "ON CONFLICT(run_id, module) DO UPDATE SET decision=excluded.decision, counts=excluded.counts", (run_id, module, patch_id, decision, json.dumps(counts), now_iso())) def record_failure(self, rec: dict) -> int: """One row per (run, case): a human label recorded earlier (review happens before the learner) is kept.""" msg = rec.get("message") or "" fields = {"module": rec.get("module"), "signature": signature(msg), "message": msg[:2000], "category": rec.get("category"), "confidence": rec.get("confidence"), "healed": int(bool(rec.get("healed")))} cur = self.db.one("SELECT id, human_label FROM failure_patterns WHERE run_id=? AND case_id=?", (rec["run_id"], rec.get("case_id"))) if cur: if rec.get("human_label") and not cur["human_label"]: fields["human_label"] = rec["human_label"] self.db.update("failure_patterns", "id", cur["id"], **fields) return cur["id"] return self.db.insert("failure_patterns", {"run_id": rec["run_id"], "case_id": rec.get("case_id"), **fields, "human_label": rec.get("human_label"), "ts": now_iso()}) def label(self, run_id: str, case_id: str, human_label: str, *, module: str | None = None, message: str = "", category: str | None = None) -> None: """Upsert: labels the run's failure row, creating it if the learner has not recorded it yet.""" cur = self.db.one("SELECT id FROM failure_patterns WHERE run_id=? AND case_id=?", (run_id, case_id)) if cur: self.db.update("failure_patterns", "id", cur["id"], human_label=human_label) else: self.db.insert("failure_patterns", {"run_id": run_id, "module": module or case_id.split("-", 1)[0], "case_id": case_id, "signature": signature(message), "message": message[:2000], "category": category, "confidence": None, "healed": 0, "human_label": human_label, "ts": now_iso()}) def earlier_labels(self, case_id: str, exclude_run: str) -> list[str]: return [r["human_label"] for r in self.db.q("SELECT human_label FROM failure_patterns WHERE case_id=? AND run_id<>? " "AND human_label IS NOT NULL", (case_id, exclude_run))] def similar(self, message: str, module: str | None = None, k: int = 5, exclude_run: str | None = None) -> list[dict]: t = tokens(message) sql, args = "SELECT * FROM failure_patterns", [] conds = [] if module: conds.append("module=?"); args.append(module) if exclude_run: conds.append("run_id<>?"); args.append(exclude_run) if conds: sql += " WHERE " + " AND ".join(conds) rows = self.db.q(sql + " ORDER BY id DESC LIMIT 2000", args) scored = [] for r in rows: s = jaccard(t, tokens(r["message"])) if s >= 0.5: scored.append({"run_id": r["run_id"], "case_id": r["case_id"], "category": r["category"], "human_label": r["human_label"], "similarity": round(s, 3), "signature": r["signature"]}) return sorted(scored, key=lambda x: -x["similarity"])[:k] def case_history(self, case_id: str, last_n: int = 10) -> list[dict]: return self.db.q("SELECT run_id, category, human_label, healed, ts FROM failure_patterns WHERE case_id=? " "ORDER BY id DESC LIMIT ?", (case_id, last_n)) def history(self, module: str | None = None, limit: int = 100, offset: int = 0) -> list[dict]: if module: return self.db.q("SELECT * FROM run_history WHERE module=? ORDER BY id DESC LIMIT ? OFFSET ?", (module, limit, offset)) return self.db.q("SELECT * FROM run_history ORDER BY id DESC LIMIT ? OFFSET ?", (limit, offset)) def patterns(self, module: str | None = None, case_id: str | None = None) -> list[dict]: sql, args, conds = "SELECT * FROM failure_patterns", [], [] if module: conds.append("module=?"); args.append(module) if case_id: conds.append("case_id=?"); args.append(case_id) if conds: sql += " WHERE " + " AND ".join(conds) groups: dict[tuple, dict] = {} for r in self.db.q(sql + " ORDER BY id", args): g = groups.setdefault((r["signature"], r["case_id"]), {"signature": r["signature"], "case_id": r["case_id"], "module": r["module"], "count": 0, "labels": {}, "example": r["message"][:300]}) g["count"] += 1 g["last_seen"] = r["ts"] lbl = r["human_label"] or r["category"] or "unlabelled" g["labels"][lbl] = g["labels"].get(lbl, 0) + 1 return sorted(groups.values(), key=lambda g: -g["count"]) def metrics(self, module: str) -> dict: rows = self.db.q("SELECT * FROM failure_patterns WHERE module=?", (module,)) labeled = [r for r in rows if r["human_label"] in ("real_defect", "not_defect")] agree = sum(1 for r in labeled if (r["category"] == "real_defect") == (r["human_label"] == "real_defect")) real = [r for r in labeled if r["human_label"] == "real_defect"] caught = sum(1 for r in real if r["category"] == "real_defect") overrides = len(labeled) - agree nd = sum(1 for r in labeled if r["human_label"] == "not_defect") appr = self.db.q("SELECT a.decision, a.case_id FROM approvals a JOIN runs r ON r.run_id=a.run_id " "WHERE a.gate='approve_cases' AND a.auto=0 AND r.modules LIKE ?", (f"%{module}%",)) approved = sum(1 for a in appr if a["decision"] == "approved") props = self.db.q("SELECT COUNT(*) n FROM drafts WHERE module=?", (module,))[0]["n"] return {"n_labeled": len(labeled), "agreement": round(agree / len(labeled), 4) if labeled else None, "real_defect_recall": round(caught / len(real), 4) if real else None, "override_rate": round(overrides / len(labeled), 4) if labeled else None, "false_fail_rate": round(nd / len(labeled), 4) if labeled else None, "n_approval_decisions": len(appr), "case_approval_rate": round(approved / len(appr), 4) if appr else None, "n_proposals": props} class PgVectorMemory: """STUB: production target Postgres + pgvector (embedding similarity). Not installed in this pilot.""" def __init__(self, *_, **__): raise RuntimeError("pgvector is not available in this pilot; use SqliteFailureMemory")