File size: 11,508 Bytes
ab54eb4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | """
CBMC error classification (Phase 1 of autonomous mode).
Reads ``cbmc_result.json`` raw output and classifies the first ERROR
message into a finite taxonomy. The taxonomy drives the auto-retry
registry in :mod:`bmc_agent.auto_retry_registry`, which proposes a
runtime fix (force-opaque a parameter, strip an extra typedef, etc.)
that can be applied without modifying bmc-agent source code.
Two-stage retry loop (in pipeline.py after Phase 2):
function CBMC-errors β classify β retry plan β regen harness β
re-run CBMC β if still errored, classify again β registry returns
NO_ACTION β give up and report.
The classifier never alters program state. All it does is parse the
CBMC raw output and return a :class:`CbmcErrorDiagnosis`. The retry
registry decides what to do with the diagnosis.
"""
from __future__ import annotations
import json
import re
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Optional
class CbmcErrorClass(str, Enum):
"""Finite taxonomy of CBMC failure modes the auto-retry layer can act on.
Only the classes flagged "actionable" below are reachable by the
registry's recovery actions. UNKNOWN / OOM / TIMEOUT are bucketed
separately so the pipeline can decide whether to skip, retry with a
smaller unwind, or give up.
"""
# Parse-time errors (CBMC's C frontend rejected the harness).
PARSE_UNDEFINED_TYPEDEF = "parse_undefined_typedef" # actionable
PARSE_INCOMPLETE_TYPE = "parse_incomplete_type" # actionable
PARSE_SYNTAX_BEFORE_STAR = "parse_syntax_before_star" # actionable (typically same root cause)
PARSE_SYNTAX_BEFORE_ID = "parse_syntax_before_id" # actionable
# Convert-time errors (parse OK, type-check / symbol-table reject).
CONVERT_TYPE_REDEFINITION = "convert_type_redefinition" # actionable
CONVERT_BODY_REDEFINITION = "convert_body_redefinition" # actionable
CONVERT_UNDEFINED_IDENTIFIER = "convert_undefined_identifier" # actionable
# Resource limits / unclassified.
OUT_OF_MEMORY = "out_of_memory"
TIMEOUT = "timeout"
UNKNOWN = "unknown"
@dataclass
class CbmcErrorDiagnosis:
"""The classifier's verdict for a single failed CBMC run."""
error_class: CbmcErrorClass
"""The taxonomy class the error belongs to."""
identifier: Optional[str] = None
"""The offending typedef / struct tag / identifier, when extractable.
For ``CONVERT_BODY_REDEFINITION`` this is the struct/union tag.
For ``PARSE_UNDEFINED_TYPEDEF`` / ``CONVERT_UNDEFINED_IDENTIFIER`` this
is the missing identifier. For syntax-before patterns it's the token
that triggered the syntax error.
"""
aggregate_kind: Optional[str] = None
"""For BODY_REDEFINITION: 'struct' or 'union'. None otherwise."""
source_line: Optional[int] = None
"""Line in the harness where the error fired, if reported by CBMC."""
raw_message: str = ""
"""The first CBMC ERROR-level messageText, verbatim. Useful for
logs and for debugging when ``error_class == UNKNOWN``.
"""
extras: dict[str, Any] = field(default_factory=dict)
"""Free-form bag for future class-specific data."""
@property
def actionable(self) -> bool:
"""True iff the registry has at least one recovery action wired
up for this class. (UNKNOWN/OOM/TIMEOUT are never actionable.)
"""
return self.error_class not in (
CbmcErrorClass.OUT_OF_MEMORY,
CbmcErrorClass.TIMEOUT,
CbmcErrorClass.UNKNOWN,
)
# ---------------------------------------------------------------------------
# Pattern table
# ---------------------------------------------------------------------------
#
# Patterns are matched in order; first match wins. The "extractor" returns
# the (identifier, aggregate_kind) tuple to populate the diagnosis.
#
# These patterns are validated against CBMC 5.95.1 outputs from the
# libarchive sweep (4829 failures across 124 files). New patterns added
# only when an UNKNOWN bucket on a real sweep proves we missed one.
_PARSE_INCOMPLETE_TYPE = re.compile(r"incomplete type not permitted here")
_PARSE_SYNTAX_BEFORE_QUOTED_ID = re.compile(r"syntax error before '(\w+)'")
_PARSE_SYNTAX_BEFORE_STAR = re.compile(r"syntax error before '\*'")
# CBMC's "defined twice" message format. Captures the colliding symbol name.
_CONVERT_TYPE_REDEFINITION = re.compile(
r"type symbol '(\w+)' defined twice"
)
# CBMC body-redefinition format: literal newlines are stored as ``\n`` in
# the JSON-encoded raw output, so the regex sees a backslash + "n". Allow
# both forms to keep the matcher robust across CBMC versions.
_CONVERT_BODY_REDEFINITION = re.compile(
r"redefinition of body of '(struct|union) (\w+)'"
)
_CONVERT_UNDEFINED_IDENTIFIER = re.compile(
r"undefined identifier '(\w+)'|unknown type name '(\w+)'"
)
_OOM_HINTS = (
"Out of memory", "std::bad_alloc", "Cannot allocate memory",
)
_TIMEOUT_HINTS = ("Timed out", "timeout",)
def classify(cbmc_result: dict) -> CbmcErrorDiagnosis:
"""Inspect a parsed ``cbmc_result.json`` payload and produce a diagnosis.
Accepts the *outer* dict (the one ``ArtifactStore.save_cbmc_result``
writes, with keys ``saved_at`` and ``result``) OR the inner
``result`` dict directly. Robust to both β callers in different
parts of the codebase pass different layers.
"""
inner = cbmc_result.get("result") if "result" in cbmc_result else cbmc_result
if not isinstance(inner, dict):
return CbmcErrorDiagnosis(
error_class=CbmcErrorClass.UNKNOWN,
raw_message="cbmc_result has no usable inner dict",
)
err_field = inner.get("error") or ""
raw_output = inner.get("raw_output") or ""
if not err_field and inner.get("verified") is not None:
# No error β no diagnosis (caller should not have called us).
return CbmcErrorDiagnosis(
error_class=CbmcErrorClass.UNKNOWN,
raw_message="cbmc_result has no error",
)
# Resource-limit fast paths.
for hint in _OOM_HINTS:
if hint in err_field or hint in raw_output:
return CbmcErrorDiagnosis(
error_class=CbmcErrorClass.OUT_OF_MEMORY,
raw_message=err_field or hint,
)
for hint in _TIMEOUT_HINTS:
if hint.lower() in err_field.lower():
return CbmcErrorDiagnosis(
error_class=CbmcErrorClass.TIMEOUT,
raw_message=err_field,
)
# Find the first ERROR-level message in the raw output.
messages = _extract_messages(raw_output)
error_msgs = [m for m in messages if "error" in m.get("type", "").lower()]
if not error_msgs:
return CbmcErrorDiagnosis(
error_class=CbmcErrorClass.UNKNOWN,
raw_message=err_field or "no ERROR-level message in raw_output",
)
# Walk error messages in order; first concrete pattern wins.
for em in error_msgs:
text = em.get("text", "")
source_line = em.get("line")
# Skip the bare "PARSING ERROR" / "CONVERSION ERROR" summaries
# that CBMC emits after the specific diagnostic.
if text in ("PARSING ERROR", "CONVERSION ERROR"):
continue
m = _CONVERT_BODY_REDEFINITION.search(text)
if m:
return CbmcErrorDiagnosis(
error_class=CbmcErrorClass.CONVERT_BODY_REDEFINITION,
identifier=m.group(2),
aggregate_kind=m.group(1),
source_line=source_line,
raw_message=text,
)
m = _CONVERT_TYPE_REDEFINITION.search(text)
if m:
return CbmcErrorDiagnosis(
error_class=CbmcErrorClass.CONVERT_TYPE_REDEFINITION,
identifier=m.group(1),
source_line=source_line,
raw_message=text,
)
m = _CONVERT_UNDEFINED_IDENTIFIER.search(text)
if m:
return CbmcErrorDiagnosis(
error_class=CbmcErrorClass.CONVERT_UNDEFINED_IDENTIFIER,
identifier=m.group(1) or m.group(2),
source_line=source_line,
raw_message=text,
)
if _PARSE_INCOMPLETE_TYPE.search(text):
# Identifier not present in the message itself; the caller
# may extract it from the surrounding harness line via
# the ``source_line`` hint.
return CbmcErrorDiagnosis(
error_class=CbmcErrorClass.PARSE_INCOMPLETE_TYPE,
source_line=source_line,
raw_message=text,
)
m = _PARSE_SYNTAX_BEFORE_QUOTED_ID.search(text)
if m:
return CbmcErrorDiagnosis(
error_class=CbmcErrorClass.PARSE_SYNTAX_BEFORE_ID,
identifier=m.group(1),
source_line=source_line,
raw_message=text,
)
if _PARSE_SYNTAX_BEFORE_STAR.search(text):
return CbmcErrorDiagnosis(
error_class=CbmcErrorClass.PARSE_SYNTAX_BEFORE_STAR,
source_line=source_line,
raw_message=text,
)
# No concrete pattern matched any error message β bucket as unknown
# but preserve the first error text so a human can triage.
first_text = error_msgs[0].get("text", "")
return CbmcErrorDiagnosis(
error_class=CbmcErrorClass.UNKNOWN,
raw_message=first_text or err_field,
)
def classify_path(path: str) -> CbmcErrorDiagnosis:
"""Convenience: load a ``cbmc_result.json`` from disk and classify it."""
with open(path) as f:
return classify(json.load(f))
# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------
# CBMC's raw_output is a JSON-encoded *string* containing a JSON array.
# Parse that out so we can iterate over messages structurally instead of
# regexing the whole blob. Fall back to text-scan if it doesn't parse.
def _extract_messages(raw_output: str) -> list[dict[str, Any]]:
if not raw_output:
return []
# Try the structured path first.
try:
arr = json.loads(raw_output)
except json.JSONDecodeError:
arr = None
if isinstance(arr, list):
out: list[dict[str, Any]] = []
for item in arr:
if not isinstance(item, dict):
continue
text = item.get("messageText", "") or ""
mtype = item.get("messageType", "") or ""
loc = item.get("sourceLocation") or {}
line: Optional[int] = None
if isinstance(loc, dict):
lstr = loc.get("line")
if isinstance(lstr, str) and lstr.isdigit():
line = int(lstr)
elif isinstance(lstr, int):
line = lstr
out.append({"text": text, "type": mtype, "line": line})
return out
# Unstructured fallback: split on "messageText" / "messageType"
# boundaries β best-effort only.
text_msgs: list[dict[str, Any]] = []
for m in re.finditer(
r'"messageText"\s*:\s*"((?:[^"\\]|\\.)*)"[^{]*?"messageType"\s*:\s*"(\w+)"',
raw_output,
re.DOTALL,
):
text_msgs.append({"text": m.group(1), "type": m.group(2), "line": None})
return text_msgs
|