Coverage for src/python/ensembl/vep/annotators/consequence/rules/validation.py: 97%
368 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
1# See the NOTICE file distributed with this work for additional information
2# regarding copyright ownership.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Validate consequence rule structure and satisfiability.
16Validation has three tiers:
18* ``StructuralChecks`` validates references, ranks, subsumption, and catalogue metadata.
19* ``RuleReachability`` and ``RulePairFinding`` search bounded ``FactAssignmentSpace`` instances.
20* Optional ``SolverChecks`` asks equivalent whole-rule-set questions through an SAT solver.
21"""
23from __future__ import annotations
25from collections.abc import Iterable, Iterator
26from typing import Any
28from attrs import field, frozen
30from ensembl.vep.annotators.consequence.rules.catalogue import (
31 EXCLUDED_TERMS,
32 ConsequenceDefinition,
33 load_consequence_definitions,
34)
35from ensembl.vep.annotators.consequence.facts.base import REGISTRY
36from ensembl.vep.annotators.consequence.rules.expressions import And, Atom, Expr, Not, Or
37from ensembl.vep.annotators.consequence.rules.rulesets import (
38 FactRule,
39 FactRuleSet,
40 build_fact_ruleset_from_definitions,
41)
42from ensembl.vep.common import ConsequenceImpact
44__all__ = [
45 "FactAssignmentSpace",
46 "RulePairFinding",
47 "RuleReachability",
48 "SolverChecks",
49 "StructuralChecks",
50 "ValidationReport",
51]
53# --------------------------------------------------------------------------
54# Tier 1: structural checks (no formula evaluation).
55# --------------------------------------------------------------------------
58class StructuralChecks:
59 """Run validation checks that require no formula evaluation.
61 Grouped rather than left as loose functions because they share one subject - the declared
62 shape of a rule set.
63 """
65 @classmethod
66 def ruleset_problems(cls, ruleset: FactRuleSet) -> tuple[list[str], list[str]]:
67 """Run structural checks over a rule set.
69 Rank inversions are warnings rather than errors on purpose: VEP has real ones
70 (``splice_donor_region_variant`` is ranked below ``splice_region_variant`` yet suppresses
71 it), so ranking order and suppression order are genuinely two different orders. Making that
72 visible is more useful than pretending one implies the other.
74 Args:
75 ruleset (FactRuleSet): The rule set to validate.
77 Returns:
78 tuple[list[str], list[str]]: ``(errors, warnings)``. A non-empty ``errors`` list means
79 the rule set is broken (unknown/internal fact reference, duplicate rank, mutual/cyclic
80 suppression); a non-empty ``warnings`` list flags rank inversions, which are expected
81 and not a failure.
82 """
83 errors: list[str] = []
84 warnings: list[str] = []
85 seen_ranks: dict[int, str] = {}
87 for rule in ruleset.rules:
88 if rule.rank in seen_ranks:
89 errors.append(f"duplicate rank {rule.rank}: {rule.term} and {seen_ranks[rule.rank]}")
90 seen_ranks[rule.rank] = rule.term
92 for atom_name in rule.atoms():
93 if atom_name not in REGISTRY:
94 errors.append(f"{rule.term} references unknown fact {atom_name!r}")
95 elif atom_name.startswith("_"):
96 errors.append(f"{rule.term} references internal fact {atom_name!r}")
98 for subsumed_term in rule.subsumes:
99 if subsumed_term not in ruleset.by_term:
100 errors.append(f"{rule.term} subsumes unknown term {subsumed_term!r}")
101 elif ruleset.by_term[subsumed_term].rank < rule.rank:
102 warnings.append(
103 f"rank inversion: {rule.term} (rank {rule.rank}) suppresses higher-ranked "
104 f"{subsumed_term} (rank {ruleset.by_term[subsumed_term].rank})"
105 )
107 # A term that suppresses something which suppresses it back could never settle. This is the
108 # 2-cycle special case of subsumption_cycles below; kept as its own check (rather than
109 # folded away) so the "mutual suppression" wording -- and the tests that assert on it -- keep
110 # working, while subsumption_cycles additionally catches longer cycles.
111 for rule in ruleset.rules:
112 for subsumed_term in rule.subsumes:
113 subsumed_rule = ruleset.by_term.get(subsumed_term)
114 if subsumed_rule is not None and rule.term in subsumed_rule.subsumes:
115 errors.append(f"mutual suppression between {rule.term} and {subsumed_term}")
117 errors.extend(cls.subsumption_cycles(ruleset))
118 return errors, warnings
120 @classmethod
121 def subsumption_cycles(cls, ruleset: FactRuleSet) -> list[str]:
122 """Detect every cycle in the ``subsumes`` graph via DFS.
124 Stronger than a pairwise mutual-suppression check (which only catches 2-cycles: A subsumes B
125 and B subsumes A): a longer cycle (A subsumes B subsumes C subsumes A) would let ``prune``
126 drop every term in the cycle whenever any one of them fires, which is never the intended
127 suppression shape and is worth surfacing on its own even though the pairwise check in
128 ruleset_problems also happens to catch the 2-cycle case.
130 Args:
131 ruleset (FactRuleSet): The rule set to inspect.
133 Returns:
134 list[str]: One description per distinct cycle found (deduplicated by member-set, so a
135 cycle reached via two different DFS roots is reported once), or an empty list if the
136 ``subsumes`` graph is acyclic.
137 """
138 reported_cycles: set[frozenset[str]] = set()
139 cycle_descriptions: list[str] = []
140 visit_state: dict[str, int] = {} # 0 = unvisited (default), 1 = in progress, 2 = done
141 path: list[str] = []
143 def visit(term: str) -> None:
144 visit_state[term] = 1
145 path.append(term)
146 rule = ruleset.by_term.get(term)
147 if rule is not None: 147 ↛ 163line 147 didn't jump to line 163 because the condition on line 147 was always true
148 for subsumed_term in rule.subsumes:
149 if subsumed_term not in ruleset.by_term:
150 continue # unknown target: already reported by validate_ruleset
151 subsumed_state = visit_state.get(subsumed_term, 0)
152 if subsumed_state == 1:
153 cycle_start_index = path.index(subsumed_term)
154 cycle_terms = tuple(path[cycle_start_index:])
155 dedup_key = frozenset(cycle_terms)
156 if dedup_key not in reported_cycles: 156 ↛ 148line 156 didn't jump to line 148 because the condition on line 156 was always true
157 reported_cycles.add(dedup_key)
158 cycle_descriptions.append(
159 "subsumption cycle: " + " -> ".join((*cycle_terms, subsumed_term))
160 )
161 elif subsumed_state == 0:
162 visit(subsumed_term)
163 path.pop()
164 visit_state[term] = 2
166 for term in ruleset.by_term:
167 if visit_state.get(term, 0) == 0:
168 visit(term)
169 return cycle_descriptions
171 @classmethod
172 def missing_when_terms(cls) -> list[str]:
173 """Cross-check EXCLUDED_TERMS against the catalogue.
175 ``build_fact_ruleset`` silently skips any catalogue entry without a ``when``, on the
176 documented assumption that every such entry is listed in ``EXCLUDED_TERMS``. This check makes
177 that assumption checked rather than trusted: a catalogue edit that adds a ``when``-less term
178 without updating ``EXCLUDED_TERMS`` (or vice versa) would otherwise silently under- or
179 over-cover the ruleset.
181 Returns:
182 list[str]: One description per catalogue entry whose ``when``-presence disagrees with its
183 ``EXCLUDED_TERMS`` membership, or an empty list if they agree everywhere.
184 """
185 problems: list[str] = []
186 for definition in load_consequence_definitions():
187 has_when = definition.when is not None
188 is_documented_exclusion = definition.term in EXCLUDED_TERMS
189 if has_when and is_documented_exclusion:
190 problems.append(f"{definition.term} has a 'when' expression but is listed in EXCLUDED_TERMS")
191 if not has_when and not is_documented_exclusion:
192 problems.append(
193 f"{definition.term} has no 'when' expression but is not listed in EXCLUDED_TERMS"
194 )
195 return problems
197 @classmethod
198 def subsumes_so_parent_drift(cls, ruleset: FactRuleSet) -> list[str]:
199 """Report where the declared ``subsumes`` graph disagrees with the SO ``so_supported_parents``.
201 These are two genuinely different relations that happen to overlap a lot: ``subsumes`` is
202 VEP's empirical suppression behaviour (term A, if it fires, hides term B), while
203 ``so_supported_parents`` is the Sequence Ontology's ``is_a`` parent graph (term A *is a kind
204 of* term B), restricted to parents also represented in this catalogue. A rule can subsume a
205 term it is not an SO child of (e.g. suppressing a sibling), and a rule can have an SO parent it
206 does not need to suppress (the parent's own ``when`` may already be false whenever the child's
207 is true, with no pruning required). So this report is informational context for a catalogue
208 reviewer, not a pass/fail check -- drift here is common and often fine; it is a prompt to look,
209 not a bug report.
211 Args:
212 ruleset (FactRuleSet): The rule set to report drift for.
214 Returns:
215 list[str]: One description per rule with at least one asymmetry between its ``subsumes``
216 set and its SO-parent-derived term set, or an empty list if every rule's two sets
217 match exactly.
218 """
219 all_definitions = load_consequence_definitions()
220 definitions_by_term = {definition.term: definition for definition in all_definitions}
221 term_by_accession = {definition.accession: definition.term for definition in all_definitions}
223 drift: list[str] = []
224 for rule in ruleset.rules:
225 definition = definitions_by_term.get(rule.term)
226 if definition is None:
227 continue
228 so_parent_terms = {
229 term_by_accession[accession]
230 for accession in definition.so_supported_parents
231 if accession in term_by_accession
232 }
233 subsumed_terms = set(rule.subsumes)
234 subsumes_without_so_parent = sorted(subsumed_terms - so_parent_terms)
235 so_parent_without_subsumes = sorted(so_parent_terms - subsumed_terms)
236 if subsumes_without_so_parent or so_parent_without_subsumes:
237 drift.append(
238 f"{rule.term}: subsumes-only={subsumes_without_so_parent}, "
239 f"so-parent-only={so_parent_without_subsumes}"
240 )
241 return drift
243 @classmethod
244 def term_and_rank_uniqueness(cls, entries: list[dict[str, Any]]) -> list[str]:
245 """Check term/rank uniqueness across *every* entry, including ``when``-less ones.
247 ruleset_problems only sees entries that made it into a FactRuleSet (i.e. have a ``when``), so
248 a duplicate rank between two ``when``-less entries -- or between a ``when``-less entry and a
249 compiled rule -- would otherwise go unnoticed.
251 Args:
252 entries (list[dict[str, Any]]): The candidate catalogue's ``consequences`` list.
254 Returns:
255 list[str]: One description per duplicate term or rank found, or an empty list if every
256 term and rank is unique.
257 """
258 errors: list[str] = []
259 seen_terms: set[str] = set()
260 for entry in entries:
261 term = entry["term"]
262 if term in seen_terms:
263 errors.append(f"duplicate catalogue term: {term}")
264 seen_terms.add(term)
266 seen_ranks: dict[int, str] = {}
267 for entry in entries:
268 rank = int(entry.get("rank", 0))
269 if rank in seen_ranks:
270 errors.append(f"duplicate catalogue rank {rank}: {entry['term']} and {seen_ranks[rank]}")
271 seen_ranks[rank] = entry["term"]
273 return errors
276# --------------------------------------------------------------------------
277# Tier 2: per-rule enumeration and per-pair propositional search.
278#
279# A rule's atom *support* is its formula's own atoms, extended by the requires-closure (every
280# atom that some support atom's declared `requires` would force, transitively) and by a small
281# hand-declared exclusivity/equivalence axiom set covering relationships the fact layer's
282# `requires` mechanism does not itself express (e.g. "is_insertion and is_deletion cannot both
283# hold" is true by construction of the two fact functions, but neither fact declares the other in
284# its `requires`, since `requires` only expresses "if X is False, so am I", not general mutual
285# exclusion). Enumerating every assignment over that support and discarding the ones the axioms
286# rule out gives every *possible* combination of fact values a real Context could produce, which
287# is exactly what "is this rule ever true" needs to be sound. See the module docstring for why
288# this -- not equality saturation -- is the right tool for that question.
289# --------------------------------------------------------------------------
291_EXCLUSIVITY_AXIOM_PAIRS: tuple[tuple[str, str], ...] = (
292 # alternate_allele_length > reference_allele_length and reference_allele_length >
293 # alternate_allele_length cannot both hold.
294 ("is_insertion", "is_deletion"),
295 # is_upstream/is_downstream both explicitly return False whenever the variant overlaps the
296 # transcript at all (facts/position.py).
297 ("overlap_feature", "is_upstream"),
298 ("overlap_feature", "is_downstream"),
299 # overlap_exon requires overlap_feature, and is_upstream/is_downstream require the opposite,
300 # so this pair is implied by the two axioms above.
301 ("overlap_exon", "is_upstream"),
302 ("overlap_exon", "is_downstream"),
303 # A fixed transcript has one 5' side and one 3' side; a variant that misses the transcript
304 # cannot be simultaneously "before the 5' end" and "after the 3' end" of the same feature.
305 ("is_upstream", "is_downstream"),
306)
307"""Atom pairs that can never both be True, true by construction of the fact functions involved
308and not an approximation"""
310_EQUIVALENCE_AXIOM_PAIRS: tuple[tuple[str, str], ...] = ()
311"""Atom pairs that always carry the same value (duplicate fact formulas under different names)."""
314@frozen(kw_only=True, auto_attribs=True)
315class FactAssignmentSpace:
316 """Define consistent Boolean fact assignments over an atom support.
318 Centralises ``requires`` closure, declared axioms, enumeration, and satisfiability searches
319 used by single-rule and pairwise validation.
321 Attributes:
322 support (tuple[str, ...]): The atom names this space is defined over, sorted.
323 """
325 support: tuple[str, ...]
327 @classmethod
328 def for_rule(cls, rule: FactRule) -> FactAssignmentSpace:
329 """Return the space a rule's formula must be evaluated over to be judged soundly.
331 Args:
332 rule (FactRule): The rule to compute a support for.
334 Returns:
335 FactAssignmentSpace: The space over ``rule.atoms()``, extended by the ``requires`` closure
336 and by any declared axiom atoms that touch it, sorted for a deterministic
337 enumeration order.
338 """
339 support = cls._extend_with_relevant_axiom_atoms(cls._requires_closure(rule.atoms()))
340 return cls(support=tuple(sorted(support)))
342 def union(self, other: FactAssignmentSpace) -> FactAssignmentSpace:
343 """Return the space covering both supports, for a question about a pair of rules."""
344 return type(self)(support=tuple(sorted(set(self.support) | set(other.support))))
346 def allows(self, assignment: dict[str, bool]) -> bool:
347 """Return whether an assignment over this support violates no ``requires``/axiom.
349 Args:
350 assignment (dict[str, bool]): A full assignment over some atom support.
352 Returns:
353 bool: False if the assignment sets some atom True while a declared ``requires`` of it is
354 False in the same assignment, or violates an exclusivity/equivalence axiom; True
355 otherwise (i.e. this is an assignment a real Context could actually produce, as far as
356 the declared constraints can tell).
357 """
358 for atom_name, value in assignment.items():
359 if not value:
360 continue
361 registered_fact = REGISTRY.get(atom_name)
362 if registered_fact is None:
363 continue
364 for required_atom in registered_fact.requires:
365 if assignment.get(required_atom) is False:
366 return False
367 for atom_a, atom_b in _EXCLUSIVITY_AXIOM_PAIRS:
368 if assignment.get(atom_a) and assignment.get(atom_b):
369 return False
370 for atom_a, atom_b in _EQUIVALENCE_AXIOM_PAIRS:
371 value_a, value_b = assignment.get(atom_a), assignment.get(atom_b)
372 if value_a is not None and value_b is not None and value_a != value_b:
373 return False
374 return True
376 def consistent_assignments(self) -> Iterator[dict[str, bool]]:
377 """Yield every assignment over this support consistent with ``requires``/the declared axioms.
379 Yields:
380 dict[str, bool]: One consistent full assignment per iteration.
381 """
382 for bitmask in range(1 << len(self.support)):
383 assignment = {
384 atom_name: bool(bitmask & (1 << index)) for index, atom_name in enumerate(self.support)
385 }
386 if self.allows(assignment):
387 yield assignment
389 def satisfies(self, expression: Expr) -> bool:
390 """Return whether an expression has a consistent assignment over ``support``.
392 This searches different combinations of values of atoms making up an expression to check
393 whether given the logical constraints of the expression, it is possible for the expression
394 to be satisfied. It is just checking if it is possible for the expression to be satisfied,
395 so it stops as soon as it finds a valid set of assignments.
397 Args:
398 expression (Expr): The expression whose satisfiability is being checked.
400 Returns:
401 bool: True if at least one consistent assignment satisfies ``expression``.
402 """
403 support_set = frozenset(self.support)
404 forced_values: dict[tuple[str, bool], list[tuple[str, bool]]] = {}
406 def add_forced_value(source: str, source_value: bool, target: str, target_value: bool) -> None:
407 if source in support_set and target in support_set:
408 forced_values.setdefault((source, source_value), []).append((target, target_value))
410 for atom_name in self.support:
411 registered_fact = REGISTRY.get(atom_name)
412 if registered_fact is None: 412 ↛ 413line 412 didn't jump to line 413 because the condition on line 412 was never true
413 continue
414 for required_atom in registered_fact.requires:
415 add_forced_value(atom_name, True, required_atom, True)
416 add_forced_value(required_atom, False, atom_name, False)
418 for atom_a, atom_b in _EXCLUSIVITY_AXIOM_PAIRS:
419 add_forced_value(atom_a, True, atom_b, False)
420 add_forced_value(atom_b, True, atom_a, False)
422 for atom_a, atom_b in _EQUIVALENCE_AXIOM_PAIRS: 422 ↛ 423line 422 didn't jump to line 423 because the loop on line 422 never started
423 for value in (False, True):
424 add_forced_value(atom_a, value, atom_b, value)
425 add_forced_value(atom_b, value, atom_a, value)
427 def extend(assignment: dict[str, bool], atom_name: str, value: bool) -> dict[str, bool] | None:
428 extended = assignment.copy()
429 pending = [(atom_name, value)]
431 while pending:
432 pending_atom, pending_value = pending.pop()
433 if pending_atom in extended:
434 if extended[pending_atom] != pending_value: 434 ↛ 435line 434 didn't jump to line 435 because the condition on line 434 was never true
435 return None
436 continue
438 extended[pending_atom] = pending_value
439 pending.extend(forced_values.get((pending_atom, pending_value), ()))
441 return extended
443 expression_atoms = sorted(
444 expression.atoms(),
445 key=lambda atom_name: len(forced_values.get((atom_name, True), ())),
446 reverse=True,
447 )
449 def search(assignment: dict[str, bool]) -> bool:
450 value = expression.evaluate_partial(assignment)
451 if value is not None:
452 return value
454 for atom_name in expression_atoms: 454 ↛ 465line 454 didn't jump to line 465 because the loop on line 454 didn't complete
455 if atom_name in assignment:
456 continue
457 for atom_value in (True, False):
458 extended = extend(assignment, atom_name, atom_value)
459 if extended is not None and search(extended):
460 return True
461 return False
463 # A custom Expr may remain unknown after all of its declared atoms are assigned. Preserve
464 # the exhaustive enumerator's behaviour for that uncommon extension point.
465 return any(expression.evaluate_partial(candidate) for candidate in self.consistent_assignments())
467 return search({})
469 @staticmethod
470 def _requires_closure(atom_names: Iterable[str]) -> frozenset[str]:
471 """Extend a set of atom names with everything their declared ``requires`` would pull in.
473 Args:
474 atom_names (Iterable[str]): The starting atom names.
476 Returns:
477 frozenset[str]: ``atom_names`` plus every atom reachable by following ``requires`` edges
478 to a fixed point.
479 """
480 support = set(atom_names)
481 changed = True
482 while changed:
483 changed = False
484 for atom_name in tuple(support):
485 registered_fact = REGISTRY.get(atom_name)
486 if registered_fact is None:
487 continue
488 for required_atom in registered_fact.requires:
489 if required_atom not in support:
490 support.add(required_atom)
491 changed = True
492 return frozenset(support)
494 @staticmethod
495 def _extend_with_relevant_axiom_atoms(support: frozenset[str]) -> frozenset[str]:
496 """Pull in the other half of any declared axiom pair that already touches ``support``.
498 Args:
499 support (frozenset[str]): The atom support so far.
501 Returns:
502 frozenset[str]: ``support`` extended with the partner atom of every
503 _EXCLUSIVITY_AXIOM_PAIRS/_EQUIVALENCE_AXIOM_PAIRS entry that already
504 has at least one member in ``support``.
505 """
506 extended = set(support)
507 for atom_a, atom_b in (*_EXCLUSIVITY_AXIOM_PAIRS, *_EQUIVALENCE_AXIOM_PAIRS):
508 if atom_a in extended or atom_b in extended:
509 extended.add(atom_a)
510 extended.add(atom_b)
511 return frozenset(extended)
514_MAX_UNION_SUPPORT_FOR_PAIR_ENUMERATION = 18
515"""Maximum combined atom support for a CONTRADICTORY or REDUNDANT pair search.
517The search propagates constraints and stops as soon as the expression is settled, but remains
518exponential in the worst case. The cap lets a future, larger catalogue skip oversized pairs
519instead of allowing an unbounded search.
520"""
523@frozen(kw_only=True, auto_attribs=True)
524class RuleReachability:
525 """Represent the Tier 2 reachability result for one rule.
527 Attributes:
528 term (str): The rule's SO term.
529 support (tuple[str, ...]): The atom support (see atom_support_for_rule) the rule
530 was enumerated over.
531 valid_assignment_count (int): Number of assignments over ``support`` consistent with the
532 declared ``requires``/axioms.
533 satisfying_assignment_count (int): Of those, the number for which the rule's ``when``
534 evaluates True.
535 """
537 term: str
538 support: tuple[str, ...]
539 valid_assignment_count: int
540 satisfying_assignment_count: int
542 @property
543 def is_reachable(self) -> bool:
544 """Return whether a valid assignment satisfies the rule."""
545 return self.satisfying_assignment_count > 0
547 @classmethod
548 def for_rule(cls, rule: FactRule) -> RuleReachability:
549 """Determine whether a rule is reachable within its fact-assignment space.
551 Args:
552 rule (FactRule): The rule to check.
554 Returns:
555 RuleReachability: The enumeration result. ``evaluate_partial`` never returns None here,
556 because ``support`` is constructed to be a superset of ``rule.atoms()``.
557 """
558 space = FactAssignmentSpace.for_rule(rule)
559 valid_assignment_count = 0
560 satisfying_assignment_count = 0
561 for assignment in space.consistent_assignments():
562 valid_assignment_count += 1
563 if rule.when.evaluate_partial(assignment):
564 satisfying_assignment_count += 1
565 return cls(
566 term=rule.term,
567 support=space.support,
568 valid_assignment_count=valid_assignment_count,
569 satisfying_assignment_count=satisfying_assignment_count,
570 )
572 @classmethod
573 def unreachable_in(cls, ruleset: FactRuleSet) -> list[RuleReachability]:
574 """Return every rule whose ``when`` formula is unsatisfiable under the Tier 2 axioms.
576 An unreachable rule is dead code: it can never contribute a term to any output, which -- unlike
577 the CONTRADICTORY/REDUNDANT findings below -- is a genuine defect rather than informational
578 context, so callers (the validation script, the test suite) should treat a non-empty result as
579 a build-breaking error.
581 Args:
582 ruleset (FactRuleSet): The rule set to check.
584 Returns:
585 list[RuleReachability]: The unreachable rules' results (``is_reachable`` False for all of
586 them), or an empty list if every rule is reachable.
587 """
588 return [result for rule in ruleset.rules if not (result := cls.for_rule(rule)).is_reachable]
591@frozen(kw_only=True, auto_attribs=True)
592class RulePairFinding:
593 """Record one pairwise rule-validation finding.
595 Attributes:
596 kind (str): Either ``"CONTRADICTORY"`` (the two rules' formulas can never both hold) or
597 ``"REDUNDANT"`` (rule ``term_a`` subsumes ``term_b`` *and* ``term_a``'s formula
598 logically entails ``term_b``'s, confirming the subsumption is logically grounded).
599 Both kinds are informational governance signal, not build-breaking errors -- see
600 RulePairFinding.contradictory_in/RulePairFinding.redundant_in.
601 term_a (str): The first rule's term.
602 term_b (str): The second rule's term.
603 message (str): Human-readable description.
604 """
606 kind: str
607 term_a: str
608 term_b: str
609 message: str
611 @classmethod
612 def contradictory_in(
613 cls, ruleset: FactRuleSet, *, max_union_support: int = _MAX_UNION_SUPPORT_FOR_PAIR_ENUMERATION
614 ) -> list[RulePairFinding]:
615 """Find rule pairs whose formulas can never both hold, and that do not subsume each other.
617 This is informational rather than an error: two rules never co-firing is often simply how the
618 ruleset is meant to work (e.g. ``stop_gained`` and ``synonymous_variant`` are naturally
619 mutually exclusive), not a defect. It is useful context for a catalogue reviewer -- a pair
620 that *should* be able to co-fire but this check finds contradictory would be worth a second
621 look -- rather than something a script should fail the build over.
623 Args:
624 ruleset (FactRuleSet): The rule set to check every pair of.
625 max_union_support (int): Skip a pair whose combined atom support exceeds this size, so a
626 future larger catalogue degrades to "fewer pairs checked" rather than a slow/unbounded
627 enumeration.
629 Returns:
630 list[RulePairFinding]: One ``"CONTRADICTORY"`` finding per such pair.
631 """
632 findings: list[RulePairFinding] = []
633 rules = ruleset.rules
634 spaces = {rule.term: FactAssignmentSpace.for_rule(rule) for rule in rules}
636 for index_a, rule_a in enumerate(rules):
637 for index_b in range(index_a + 1, len(rules)):
638 rule_b = rules[index_b]
639 if rule_b.term in rule_a.subsumes or rule_a.term in rule_b.subsumes:
640 continue
641 union = spaces[rule_a.term].union(spaces[rule_b.term])
642 if len(union.support) > max_union_support:
643 continue
644 can_both_hold = union.satisfies(And(rule_a.when, rule_b.when))
645 if not can_both_hold:
646 findings.append(
647 RulePairFinding(
648 kind="CONTRADICTORY",
649 term_a=rule_a.term,
650 term_b=rule_b.term,
651 message=f"{rule_a.term} and {rule_b.term} never co-fire under the Tier 2 axioms",
652 )
653 )
654 return findings
656 @classmethod
657 def redundant_in(
658 cls, ruleset: FactRuleSet, *, max_union_support: int = _MAX_UNION_SUPPORT_FOR_PAIR_ENUMERATION
659 ) -> list[RulePairFinding]:
660 """Find declared ``subsumes`` edges whose entailment is confirmed by the formulas themselves.
662 For each declared ``A subsumes B``, check whether ``A.when`` logically entails ``B.when`` over
663 every valid assignment of their combined support (i.e. whenever A's formula could possibly be
664 true, B's formula is necessarily true too). Where it holds, the subsumption is *logically
665 redundant* in the sense that A firing already guarantees B's condition holds -- the ``subsumes``
666 declaration is provably sound, not merely asserted. Where it does not hold under this bounded
667 axiom set, that is *not* reported as an error: most of this catalogue's subsumption edges rely
668 on domain knowledge broader than the small declared axiom set here (e.g. "a deletion spanning
669 the whole transcript necessarily also overlaps every intron and UTR" is true, but nothing in
670 _EXCLUSIVITY_AXIOM_PAIRS encodes it), so a pair not appearing in this report is
671 inconclusive, not suspect.
673 Args:
674 ruleset (FactRuleSet): The rule set to check every declared ``subsumes`` edge of.
675 max_union_support (int): Skip an edge whose combined atom support exceeds this size.
677 Returns:
678 list[RulePairFinding]: One ``"REDUNDANT"`` finding per confirmed-entailed edge.
679 """
680 findings: list[RulePairFinding] = []
681 spaces = {rule.term: FactAssignmentSpace.for_rule(rule) for rule in ruleset.rules}
683 for rule_a in ruleset.rules:
684 for subsumed_term in rule_a.subsumes:
685 rule_b = ruleset.by_term.get(subsumed_term)
686 if rule_b is None:
687 continue
688 union = spaces[rule_a.term].union(spaces[rule_b.term])
689 if len(union.support) > max_union_support:
690 continue
691 counterexample = And(rule_a.when, Not(rule_b.when))
692 entailed = not union.satisfies(counterexample)
693 if entailed:
694 findings.append(
695 RulePairFinding(
696 kind="REDUNDANT",
697 term_a=rule_a.term,
698 term_b=subsumed_term,
699 message=(
700 f"{rule_a.term}'s when provably entails {subsumed_term}'s when -- the "
701 "declared subsumption is logically sound, confirmed under the Tier 2 axioms"
702 ),
703 )
704 )
705 return findings
708@frozen(kw_only=True, auto_attribs=True)
709class ValidationReport:
710 """Combine structural and bounded-search validation results.
712 Attributes:
713 errors (list[str]): From validate_ruleset; non-empty means the ruleset is broken.
714 warnings (list[str]): From validate_ruleset; expected rank inversions.
715 missing_when_problems (list[str]): From report_missing_when_terms; non-empty means
716 the catalogue and ``EXCLUDED_TERMS`` have drifted apart -- treat as an error.
717 so_parent_drift (list[str]): From report_subsumes_so_parent_drift; informational.
718 unreachable_rules (list[RuleReachability]): From RuleReachability.unreachable_in; non-empty
719 means a rule can never fire -- treat as an error.
720 contradictory_pairs (list[RulePairFinding]): From RulePairFinding.contradictory_in;
721 informational.
722 redundant_pairs (list[RulePairFinding]): From RulePairFinding.redundant_in;
723 informational.
724 """
726 errors: list[str]
727 warnings: list[str]
728 missing_when_problems: list[str]
729 so_parent_drift: list[str]
730 unreachable_rules: list[RuleReachability]
731 contradictory_pairs: list[RulePairFinding]
732 redundant_pairs: list[RulePairFinding] = field(factory=list)
734 @property
735 def has_errors(self) -> bool:
736 """Return whether the report contains a build-breaking finding."""
737 return bool(self.errors or self.missing_when_problems or self.unreachable_rules)
739 @classmethod
740 def for_ruleset(cls, ruleset: FactRuleSet) -> ValidationReport:
741 """Run every Tier 1 + Tier 2 check over a rule set. Pure Python, always on; no z3 required.
743 Args:
744 ruleset (FactRuleSet): The rule set to validate.
746 Returns:
747 ValidationReport: The combined result. See ValidationReport.has_errors for the
748 build-breaking subset.
749 """
750 errors, warnings = StructuralChecks.ruleset_problems(ruleset)
751 return cls(
752 errors=errors,
753 warnings=warnings,
754 missing_when_problems=StructuralChecks.missing_when_terms(),
755 so_parent_drift=StructuralChecks.subsumes_so_parent_drift(ruleset),
756 unreachable_rules=RuleReachability.unreachable_in(ruleset),
757 contradictory_pairs=RulePairFinding.contradictory_in(ruleset),
758 redundant_pairs=RulePairFinding.redundant_in(ruleset),
759 )
761 @classmethod
762 def for_catalogue_entries(
763 cls, entries: list[dict[str, Any]], baseline_entries: list[dict[str, Any]]
764 ) -> ValidationReport:
765 """Validate a candidate ``consequences`` list before it is ever written to disk.
767 Reuses ensembl.vep.annotators.consequence.rules.validation's structural (Tier 1) and enumeration
768 (Tier 2) checks over a FactRuleSet built from the *candidate* entries (see
769 _ruleset_from_entries) -- not the packaged catalogue, which is what makes this safe to
770 call before a real term has been added or removed on disk. The two checks that hardcode a call
771 to the packaged load_consequence_definitions() (report_missing_when_terms,
772 report_subsumes_so_parent_drift) are intentionally not reused here, since they are defined in
773 terms of the checked-in EXCLUDED_TERMS/catalogue rather than a candidate in-memory one; a
774 needs-review, ``when``-less addition is instead surfaced separately, at add-time, by
775 resolve_when's NEEDS REVIEW banner.
777 Unreachable-rule findings are diffed against ``baseline_entries`` (the catalogue before this
778 add/remove was applied) rather than treated as build-breaking outright: the checked-in
779 catalogue already carries one known, pre-existing dead rule (``feature_truncation``). Treating
780 every unreachable rule as build-breaking here would permanently refuse every write against the
781 real catalogue, for a reason unrelated to whatever term is being added or removed. A rule
782 unreachable in *both* the baseline and the candidate is downgraded to an informational warning;
783 one that only became unreachable in the candidate is a genuine regression introduced by this
784 operation and stays build-breaking.
786 Args:
787 entries (list[dict[str, Any]]): The candidate catalogue's ``consequences`` list.
788 baseline_entries (list[dict[str, Any]]): The catalogue's ``consequences`` list *before*
789 this operation, used only to distinguish pre-existing unreachable rules from new ones.
791 Returns:
792 ValidationReport: errors/unreachable_rules non-empty means refuse to write; warnings are
793 informational only (see ValidationReport.has_errors).
794 """
795 ruleset = cls._ruleset_from_entries(entries)
796 structural_errors, warnings = StructuralChecks.ruleset_problems(ruleset)
797 errors = StructuralChecks.term_and_rank_uniqueness(entries) + structural_errors
799 baseline_ruleset = cls._ruleset_from_entries(baseline_entries)
800 baseline_unreachable_terms = frozenset(
801 result.term for result in RuleReachability.unreachable_in(baseline_ruleset)
802 )
803 all_unreachable: list[RuleReachability] = RuleReachability.unreachable_in(ruleset)
804 new_unreachable = [
805 result for result in all_unreachable if result.term not in baseline_unreachable_terms
806 ]
807 warnings = list(warnings) + [
808 f"pre-existing unreachable rule (not introduced by this change, not build-breaking here): "
809 f"{result.term}"
810 for result in all_unreachable
811 if result.term in baseline_unreachable_terms
812 ]
814 return cls(
815 errors=errors,
816 warnings=warnings,
817 missing_when_problems=[],
818 so_parent_drift=[],
819 unreachable_rules=new_unreachable,
820 contradictory_pairs=[],
821 redundant_pairs=[],
822 )
824 @classmethod
825 def _ruleset_from_entries(cls, entries: list[dict[str, Any]]) -> FactRuleSet:
826 """Compile a rule set from raw catalogue entry dicts.
828 Parses each entry into a ConsequenceDefinition and hands them to the one compilation path, so
829 a candidate cannot be validated against a rule set built differently from the one the
830 annotators will evaluate.
831 """
832 definitions = []
833 for entry in entries:
834 impact = entry.get("impact")
835 definitions.append(
836 ConsequenceDefinition(
837 term=entry["term"],
838 accession=entry["accession"],
839 rank=int(entry.get("rank", 0)),
840 tier=int(entry.get("tier", 3)),
841 impact=ConsequenceImpact(impact) if impact else None,
842 when=entry.get("when"),
843 subsumes=tuple(entry.get("subsumes", ())),
844 so_supported_parents=tuple(entry.get("so_supported_parents", ())),
845 notes=entry.get("notes"),
846 )
847 )
848 return build_fact_ruleset_from_definitions(definitions)
851# --------------------------------------------------------------------------
852# Tier 3: whole-ruleset SAT queries via z3 (optional dev dependency).
853#
854# Same two query shapes as Tier 2 (reachability, subsumption-edge soundness), same axiom set, but
855# posed to a solver instead of enumerated -- so a query is not limited to one rule/pair's bounded
856# atom support the way Tier 2's brute force is. z3 is imported lazily, only when this function is
857# actually called (--solver=z3), so it stays an optional dependency
858# ([project.optional-dependencies] validation = ["z3-solver"] in pyproject.toml) rather than a
859# hard one.
860# --------------------------------------------------------------------------
863class SolverChecks:
864 """Run whole-rule-set validation through z3."""
866 @classmethod
867 def findings(cls, ruleset: FactRuleSet) -> list[str]:
868 """Run the whole-ruleset reachability and subsumption-soundness queries via z3.
870 Args:
871 ruleset (FactRuleSet): The rule set to check.
873 Returns:
874 list[str]: Findings, prefixed ``"UNREACHABLE (z3): ..."`` (a rule whose formula is
875 unsatisfiable under the axioms -- a real defect) or ``"NOT ENTAILED (z3): ..."`` (a
876 declared ``subsumes`` edge not backed by formula entailment -- informational, see
877 RulePairFinding.redundant_in's docstring for why that is not automatically a bug).
879 Raises:
880 RuntimeError: If ``z3`` is not installed. Install the optional ``validation`` extra
881 (``pip install '.[validation]'`` / ``uv sync --extra validation``) to use this.
882 """
883 try:
884 import z3 # pylint: disable=import-outside-toplevel
885 except ImportError as import_error:
886 raise RuntimeError(
887 "z3-solver is not installed. Install the optional 'validation' extra "
888 "(e.g. `uv sync --extra validation`) to use --solver=z3."
889 ) from import_error
891 atom_names_in_ruleset = sorted({atom_name for rule in ruleset.rules for atom_name in rule.atoms()})
892 z3_atoms = {atom_name: z3.Bool(atom_name) for atom_name in atom_names_in_ruleset}
894 axioms: list[Any] = []
895 for atom_name in atom_names_in_ruleset:
896 registered_fact = REGISTRY.get(atom_name)
897 if registered_fact is None:
898 continue
899 for required_atom in registered_fact.requires:
900 if required_atom in z3_atoms:
901 axioms.append(z3.Implies(z3_atoms[atom_name], z3_atoms[required_atom]))
902 for atom_a, atom_b in _EXCLUSIVITY_AXIOM_PAIRS:
903 if atom_a in z3_atoms and atom_b in z3_atoms:
904 axioms.append(z3.Not(z3.And(z3_atoms[atom_a], z3_atoms[atom_b])))
905 for atom_a, atom_b in _EQUIVALENCE_AXIOM_PAIRS:
906 if atom_a in z3_atoms and atom_b in z3_atoms: 906 ↛ 905line 906 didn't jump to line 905 because the condition on line 906 was always true
907 axioms.append(z3_atoms[atom_a] == z3_atoms[atom_b])
909 findings: list[str] = []
911 for rule in ruleset.rules:
912 solver = z3.Solver()
913 solver.add(*axioms)
914 solver.add(cls._expression_to_z3(rule.when, z3_atoms, z3))
915 if solver.check() == z3.unsat:
916 findings.append(f"UNREACHABLE (z3): {rule.term} is unsatisfiable under the declared axioms")
918 for rule in ruleset.rules:
919 for subsumed_term in rule.subsumes:
920 subsumed_rule = ruleset.by_term.get(subsumed_term)
921 if subsumed_rule is None:
922 continue
923 solver = z3.Solver()
924 solver.add(*axioms)
925 solver.add(cls._expression_to_z3(rule.when, z3_atoms, z3))
926 solver.add(z3.Not(cls._expression_to_z3(subsumed_rule.when, z3_atoms, z3)))
927 if solver.check() == z3.sat:
928 findings.append(
929 f"NOT ENTAILED (z3): {rule.term} subsumes {subsumed_term} but {rule.term}'s when "
930 f"does not entail {subsumed_term}'s when (informational)"
931 )
932 return findings
934 @classmethod
935 def _expression_to_z3(cls, expression: Expr, atoms: dict[str, Any], z3_module: Any) -> Any:
936 """Translate an Expr tree into a z3 boolean expression.
938 Typed with ``Any`` throughout rather than a z3 stub: z3 is an optional dependency (see the
939 module docstring), so this module must import cleanly whether or not it -- and therefore any
940 type stub for it -- is installed.
942 Args:
943 expression (Expr): The formula to translate.
944 atoms (dict[str, Any]): Fact atom name -> ``z3.BoolRef`` lookup table.
945 z3_module (Any): The imported ``z3`` module (passed through rather than imported here
946 again, since the caller already did the lazy import).
948 Returns:
949 Any: The equivalent ``z3.BoolRef``.
951 Raises:
952 TypeError: If ``expression`` is a node type this translator does not support.
953 """
954 if isinstance(expression, Atom):
955 return atoms[expression.name]
956 if isinstance(expression, Not):
957 return z3_module.Not(cls._expression_to_z3(expression.child, atoms, z3_module))
958 if isinstance(expression, And):
959 return z3_module.And(
960 *(cls._expression_to_z3(child, atoms, z3_module) for child in expression.children)
961 )
962 if isinstance(expression, Or):
963 return z3_module.Or(
964 *(cls._expression_to_z3(child, atoms, z3_module) for child in expression.children)
965 )
966 raise TypeError(f"unsupported expression node type: {type(expression).__name__}")