kani_obligations.py
verification/tools/kani_obligations.py
1"""Source-declared Kani obligations, independent of successful verifier output.23This is a deliberately small lexer for the checked proof sources, not Rust macro4expansion or call-graph analysis. The reviewed manifest pins each complete input5file and declares the harness/helper functions whose assertion and cover macros6must survive into that harness's report. Unsupported macro syntax fails closed.7"""8from dataclasses import dataclass9from functools import lru_cache10from pathlib import Path11import hashlib12import json13import re14import tomllib15from rust_source import Token, tokens, closing16import rust_source17import proof_admission181920ROOT = Path(__file__).resolve().parents[2]21PROOFS = ROOT / 'verification/proofs'22MANIFEST = Path(__file__).with_suffix('.toml')23INPUTS = (Path(__file__), MANIFEST, *proof_admission.INPUTS)24_AUDITED_MANIFESTS = set()252627def require(condition, message):28 if not condition:29 raise RuntimeError('Kani obligation inventory: ' + message)303132# The lexer is shared with source selection; this module retains the narrower33# obligation grammar and owns semantic registration/admission.34def normalized(source):35 return tuple(token.text for token in tokens(source))363738@lru_cache(maxsize=256)39def function_tokens(source, name):40 items = tokens(source)41 starts = [i for i in range(len(items) - 1)42 if items[i].text == 'fn' and items[i + 1].text == name]43 require(len(starts) == 1, 'missing or ambiguous source function ' + name)44 index = starts[0] + 245 while index < len(items) and items[index].text != '{':46 require(items[index].text != ';', 'function has no body: ' + name)47 index = closing(items, index) + 1 if items[index].text in ('(', '[') else index + 148 require(index < len(items), 'function has no body: ' + name)49 return tuple(items[index + 1:closing(items, index)])505152def arguments(items):53 result, start, index = [], 0, 054 while index < len(items):55 value = items[index].text56 if value in ('(', '[', '{'):57 index = closing(items, index) + 158 elif value == ',':59 result.append(items[start:index])60 start = index = index + 161 else:62 index += 163 if start < len(items):64 result.append(items[start:])65 return result666768@dataclass(frozen=True)69class Obligation:70 file: str71 line: int72 column: int73 category: str74 description: tuple7576 def check(self, status=None):77 """Build a synthetic check for validator tests, never proof evidence."""78 return {'category': self.category,79 'description': ' '.join(self.description),80 'location': {'file': self.file, 'line': str(self.line), 'column': str(self.column)},81 'status': status or ('Satisfied' if self.category == 'cover' else 'Success')}828384def source_obligations(path, name=None):85 path = Path(path).resolve()86 source = path.read_text()87 items = function_tokens(source, name) if name is not None else tokens(source)88 result = []89 for index, token in enumerate(items):90 require(token.text != 'macro_rules', 'expand proof macros explicitly before registration')91 require(not (token.text in ('debug_assert', 'debug_assert_eq', 'debug_assert_ne') and92 index + 1 < len(items) and items[index + 1].text == '!'),93 'authored debug assertions need explicit unconditional semantic registration')94 if token.text not in ('assert', 'assert_eq', 'assert_ne', 'cover'):95 continue96 if index + 2 >= len(items) or items[index + 1].text != '!':97 continue98 opening = index + 299 require(items[opening].text == '(', 'unsupported assertion delimiter')100 args = arguments(items[opening + 1:closing(items, opening)])101 category = 'cover' if token.text == 'cover' else 'assertion'102 minimum = 1 if token.text == 'assert' else 2103 if category == 'cover':104 require(index >= 3 and [t.text for t in items[index - 3:index]] == ['kani', ':', ':'],105 'cover must be kani::cover!')106 require(len(args) == 2 and len(args[-1]) == 1 and args[-1][0].text.startswith('"'),107 'cover needs one explicit literal identity')108 description = (json.loads(args[-1][0].text),)109 start = items[index - 3].offset110 elif len(args) == minimum:111 expression = tuple(t.text for t in args[0])112 if minimum == 2:113 operator = ('=', '=') if token.text == 'assert_eq' else ('!', '=')114 expression += operator + tuple(t.text for t in args[1])115 description = normalized('assertion failed:') + expression116 start = token.offset117 else:118 require(len(args) == minimum + 1 and len(args[-1]) == 1119 and args[-1][0].text.startswith('"'), 'unsupported assertion message')120 description = (args[-1][0].text,)121 start = token.offset122 result.append(Obligation(str(path), source.count('\n', 0, start) + 1,123 start - source.rfind('\n', 0, start), category, description))124 require(len(result) == len(set(result)), 'duplicate source obligation')125 return result126127128def _descriptor(obligation):129 return hashlib.sha256(json.dumps(obligation.description,130 separators=(',', ':')).encode()).hexdigest()131132133def _separate_entrypoints(source):134 """Other explicitly annotated proof functions are separate claims, not helpers."""135 items = tokens(source)136 result = []137 for i in range(len(items) - 2):138 if [t.text for t in items[i:i + 2]] != ['#', '[']:139 continue140 end = closing(items, i + 1)141 attribute = [t.text for t in items[i + 2:end]]142 if attribute[:4] not in (['kani', ':', ':', 'proof'],143 ['kani', ':', ':', 'proof_for_contract']):144 continue145 cursor = end + 1146 while cursor + 1 < len(items) and [t.text for t in items[cursor:cursor + 2]] == ['#', '[']:147 cursor = closing(items, cursor + 1) + 1148 while cursor < len(items) and items[cursor].text not in ('fn', '{', ';'):149 cursor += 1150 require(cursor + 1 < len(items) and items[cursor].text == 'fn',151 'proof attribute is not attached to a function')152 result.append(items[cursor + 1].text)153 return result154155156def manifest_obligations(manifest, proof_root=PROOFS):157 """Audit the authored macro population, separately from implicit safety VCs.158159 Registration is a union across the manifest, not a demand that unrelated160 harnesses execute each other's assertions. The report gate below separately161 checks that an emitted authored macro belongs to its selected harness.162 """163 policy_text = proof_admission.POLICY.read_text()164 policy = proof_admission.parse_policy(policy_text)165 hashes = []166 for filename, expected in manifest['files'].items():167 path = proof_root / filename168 require(path.is_file() and not path.is_symlink(), 'missing reviewed source ' + filename)169 digest = hashlib.sha256(path.read_bytes()).hexdigest()170 require(digest == expected, 'source obligations changed without manifest review: ' + filename)171 hashes.append((filename, digest))172 key = (str(proof_root), json.dumps(manifest, sort_keys=True), policy_text, tuple(hashes))173 if key in _AUDITED_MANIFESTS:174 return175 declared = {}176 for harnesses in manifest['suites'].values():177 for selectors in harnesses.values():178 for selector in selectors:179 filename, function = selector.rsplit('::', 1)180 require(filename in manifest['files'], 'unbound helper source ' + filename)181 path = proof_root / filename182 declared.setdefault(filename, set()).update(source_obligations(path, function))183 for filename, digest in manifest['files'].items():184 path = proof_root / filename185 require(path.is_file() and not path.is_symlink() and186 hashlib.sha256(path.read_bytes()).hexdigest() == digest,187 'source obligations changed without manifest review: ' + filename)188 if path.suffix != '.rs':189 continue190 proof_admission.audit_file(path, policy=policy, proof_root=proof_root)191 policy_name = proof_admission.source_name(path, proof_root)192 if policy_name in policy.get('non_kani', {}):193 require(isinstance(policy['non_kani'][policy_name], str) and194 len(policy['non_kani'][policy_name].strip()) >= 12,195 'non-Kani population needs an explicit reason: ' + filename)196 require(filename not in declared,197 'non-Kani source cannot also supply harness obligations: ' + filename)198 continue199 found = set(source_obligations(path))200 for harness, function, descriptor, reason in policy.get('branch_unreachable', {}).get(policy_name, []):201 require(isinstance(harness, str) and len(reason.strip()) >= 12 and202 sum(_descriptor(item) == descriptor for item in source_obligations(path, function)) == 1,203 'stale or ambiguous specialized branch exclusion: ' + filename)204 separate = set()205 for name in _separate_entrypoints(path.read_text()):206 separate.update(source_obligations(path, name))207 # Per-action manifests may select a positive or negative entrypoint208 # from the same file. Other annotated harnesses are not helper claims.209 # If their checks appear in this report, validate() still rejects them.210 found -= separate - declared.get(filename, set())211 extra = found - declared.get(filename, set())212 permits = policy.get('assertion_exclusions', {}).get(policy_name, [])213 allowed = set()214 for mode, function, descriptor, reason in permits:215 require(mode in ('compile-time', 'forbidden-call', 'native-helper') and len(reason.strip()) >= 12,216 'invalid authored assertion exclusion')217 candidates = (source_obligations(path, function) if function else source_obligations(path))218 matches = [x for x in candidates if _descriptor(x) == descriptor]219 require(len(matches) == 1, 'stale or ambiguous authored assertion exclusion: ' + filename)220 if mode == 'compile-time':221 source = path.read_text();offset = source.splitlines(keepends=True)222 byte = sum(map(len, offset[:matches[0].line - 1])) + matches[0].column - 1223 lexical = tokens(source)224 constants = [(t.offset, proof_admission._end(lexical, i))225 for i, t in enumerate(lexical[:-2])226 if t.text == 'const' and227 [x.text for x in lexical[i + 1:i + 3]] == ['_', ':']]228 require(any(start <= byte <= lexical[end].offset for start, end in constants),229 'compile-time assertion moved into runtime code: ' + filename)230 allowed.update(matches)231 require(extra == allowed,232 'authored assertions/covers lack explicit helper registration: ' + filename +233 ' at ' + str(sorted((x.line, x.column) for x in extra - allowed)))234 # Content, policy and complete manifest are keys; edits cannot inherit an235 # earlier admission. Keep this per-process memo bounded for fixture runs.236 if len(_AUDITED_MANIFESTS) >= 64:237 _AUDITED_MANIFESTS.clear()238 _AUDITED_MANIFESTS.add(key)239240241def required(suite, harnesses, *, manifest=None, proof_root=PROOFS):242 manifest = tomllib.loads(MANIFEST.read_text()) if manifest is None else manifest243 require(suite in manifest['suites'], 'no qualified source inventory for suite ' + suite)244 entries = manifest['suites'][suite]245 require(set(entries) == set(harnesses), 'harness/source inventory mismatch: ' + suite)246 result = {}247 for harness, selectors in entries.items():248 obligations = []249 require(len(selectors) == len(set(selectors)), 'duplicate helper selector')250 for selector in selectors:251 filename, function = selector.rsplit('::', 1)252 path = proof_root / filename253 require(filename in manifest['files'] and path.is_file(), 'missing reviewed source ' + filename)254 require(hashlib.sha256(path.read_bytes()).hexdigest() == manifest['files'][filename],255 'source obligations changed without manifest review: ' + filename)256 obligations += source_obligations(path, function)257 excluded = manifest.get('excluded', {}).get(harness, [])258 policy = proof_admission.parse_policy(proof_admission.POLICY.read_text())259 for expression in excluded:260 matches = [item for item in obligations261 if item.category == 'assertion' and item.description == normalized(expression)]262 require(len(matches) == 1, 'missing or ambiguous compile-time exclusion')263 item = matches[0]264 name = proof_admission.source_name(Path(item.file), proof_root)265 permits = policy.get('branch_unreachable', {}).get(name, [])266 require(sum(row[0] == harness and row[2] == _descriptor(item) and267 len(row[3].strip()) >= 12 and268 item in source_obligations(Path(item.file), row[1]) for row in permits) == 1,269 'specialized branch exclusion needs a precise authored reason: ' + harness)270 obligations.remove(matches[0])271 require(obligations, 'empty semantic inventory: ' + harness)272 require(len(obligations) == len(set(obligations)), 'overlapping helper inventories')273 result[harness] = obligations274 manifest_obligations(manifest, proof_root)275 return result276277278def check_identity(check):279 location = check.get('location')280 if not isinstance(location, dict) or not all(key in location for key in ('file', 'line', 'column')):281 return None282 try:283 category = check['category']284 description = ((check['description'],) if category == 'cover'285 else normalized(check['description']))286 return Obligation(str(Path(location['file']).resolve()), int(location['line']),287 int(location['column']), category, description)288 except (TypeError, ValueError, KeyError):289 return None290291292def validate(checks, obligations, harness, *, negative=False, unreachable=None):293 # Some dedicated fatal-boundary consumers prove a named no-return marker294 # unreachable, then independently require its exact fatal panic/check.295 # Such authored exceptions must stay in the full inventory with a reason.296 unreachable = {} if unreachable is None else unreachable297 require(isinstance(unreachable, dict) and set(unreachable) <= set(obligations) and298 all(isinstance(reason, str) and len(reason.strip()) >= 12299 for reason in unreachable.values()), 'invalid explicit no-return obligation')300 identities = [check_identity(check) for check in checks]301 for required_check in obligations:302 require(identities.count(required_check) == 1,303 'missing, replaced or duplicate required ' + required_check.category + ' in '304 + harness + ' at ' + required_check.file + ':' + str(required_check.line))305 if required_check.category == 'assertion':306 status = checks[identities.index(required_check)]['status']307 allowed_status = (('Unreachable',) if required_check in unreachable else308 ('Success', 'Failure') if negative else ('Success',))309 require(status in allowed_status,310 'required semantic assertion is not reachable: ' + harness + ' at '311 + required_check.file + ':' + str(required_check.line))312 # Covers establish specifically named witnesses, so an unregistered cover313 # is also a manifest error. Compiler/library safety checks remain permitted314 # and all their statuses are validated by kani.validate_report.315 require(all(identity is not None for check, identity in zip(checks, identities)316 if check['category'] == 'cover'), 'cover has no source identity')317 require({item for item in identities if item is not None and item.category == 'cover'}318 == {item for item in obligations if item.category == 'cover'},319 'unexpected cover identity: ' + harness)320 # Compiler-generated bounds/overflow/forbidden-call checks may legitimately321 # be unreachable. A syntactic authored macro in our proof tree is different:322 # reaching or emitting it requires this harness to declare it explicitly.323 policy = proof_admission.parse_policy(proof_admission.POLICY.read_text())324 authored = {}325 for check, identity in zip(checks, identities):326 if identity is None or identity in obligations:327 continue328 path = Path(identity.file)329 if not path.is_relative_to(PROOFS) or not path.is_file():330 continue331 name = path.relative_to(PROOFS).as_posix()332 if path not in authored:333 authored[path] = set(source_obligations(path))334 macros = authored[path]335 if identity not in macros:336 continue337 allowed = [row for row in policy.get('assertion_exclusions', {}).get(name, [])338 if row[2] == _descriptor(identity)]339 branches = [row for row in policy.get('branch_unreachable', {}).get(name, [])340 if row[0] == harness and row[2] == _descriptor(identity) and341 len(row[3].strip()) >= 12 and342 identity in source_obligations(path, row[1])]343 require((len(branches) == 1 and check['status'] == 'Unreachable') or344 (len(allowed) == 1 and (345 allowed[0][0] == 'compile-time' or346 allowed[0][0] == 'forbidden-call' and check['status'] == 'Unreachable')),347 'emitted authored assertion is not registered for harness ' + harness +348 ' at ' + name + ':' + str(identity.line))