Coverage for src/python/ensembl/vep/annotators/consequence/facts/base.py: 98%

120 statements  

« 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"""Lazy, memoised, cost-tagged facts for consequence annotation. 

15 

16Facts form a dependency graph and are computed at most once per ``FactContext``. Declared costs 

17allow strategies to order work and measure avoided computation. 

18 

19Registered functions have two forms: 

20 

21* Boolean facts have public names and may appear in catalogue formulas. 

22* Internal value facts have private names and share non-Boolean intermediate values between facts. 

23 

24Internal value facts must not declare ``requires`` because a failed guard returns ``False``. 

25Keep single-use calculations as plain helpers; registration only benefits values shared by 

26multiple facts. 

27""" 

28 

29from __future__ import annotations 

30 

31import json 

32from collections.abc import Callable, Iterable, Mapping 

33from functools import wraps 

34from importlib.resources import files 

35from typing import TYPE_CHECKING, Any 

36 

37from attrs import Factory, evolve, field, frozen 

38 

39if TYPE_CHECKING: 

40 from ensembl.vep.annotators.consequence.context.fact import FactContext 

41 

42__all__ = [ 

43 "FACT_COST_OVERRIDE_RESOURCE", 

44 "Fact", 

45 "REGISTRY", 

46 "apply_fact_cost_overrides", 

47 "apply_packaged_fact_cost_overrides", 

48 "atom_names", 

49 "build_requires_guard", 

50 "closure_cost", 

51 "get_fact", 

52 "implied_false", 

53 "load_fact_cost_overrides_from_package", 

54 "register_fact", 

55 "total_cost", 

56 "verify_requires", 

57] 

58 

59 

60@frozen(kw_only=True, auto_attribs=True) 

61class Fact: 

62 """Represent a named, cost-tagged property derived from a context. 

63 

64 ``deps`` names values the implementation reads. ``requires`` names Boolean preconditions; 

65 these are also dependencies and allow evaluation to return ``False`` before running the fact. 

66 

67 Attributes: 

68 name (str): Registry key and rule atom name. 

69 cost (int): Marginal evaluation cost, excluding dependencies. 

70 compute (Callable[[FactContext[Any]], object]): Guarded computation called by 

71 ``get_fact``. 

72 unguarded_compute (Callable[[FactContext[Any]], object]): Original computation used to 

73 validate ``requires`` declarations. 

74 deps (tuple[str, ...]): Facts read by the computation. 

75 requires (tuple[str, ...]): Boolean preconditions that gate the computation. 

76 documentation (str): Description copied from the registered function. 

77 """ 

78 

79 name: str 

80 cost: int 

81 compute: Callable[[FactContext[Any]], object] 

82 unguarded_compute: Callable[[FactContext[Any]], object] = field( 

83 default=Factory(lambda self: self.compute, takes_self=True) 

84 ) 

85 deps: tuple[str, ...] = field(default=()) 

86 requires: tuple[str, ...] = field(default=()) 

87 documentation: str = field(default="") 

88 

89 

90REGISTRY: dict[str, Fact] = {} 

91"""Every registered fact, keyed by name. Populated by importing the ``facts`` subpackage via the decorator.""" 

92 

93 

94def register_fact( 

95 cost: int, deps: tuple[str, ...] = (), requires: tuple[str, ...] = () 

96) -> Callable[[Callable[[FactContext[Any]], object]], Callable[[FactContext[Any]], object]]: 

97 """Register a function as a named Fact in REGISTRY. 

98 

99 ``requires`` names are folded into ``deps`` automatically because an atom that has to 

100 be *true* first necessarily has to be *computed* first, so declaring it twice was only ever 

101 an opportunity to declare it inconsistently. 

102 

103 Args: 

104 cost (int): The fact's marginal cost. 

105 deps (tuple[str, ...]): Names of facts that must be computed before this one. 

106 requires (tuple[str, ...]): Atoms this fact is gated on. 

107 

108 Returns: 

109 Callable[[Callable[[FactContext[Any]], object]], Callable[[FactContext[Any]], object]]: A 

110 decorator that registers the wrapped function and returns the original function 

111 unchanged, so a module-level reference to it still calls the unguarded body. 

112 """ 

113 

114 def register(compute: Callable[[FactContext[Any]], object]) -> Callable[[FactContext[Any]], object]: 

115 REGISTRY[compute.__name__] = Fact( 

116 name=compute.__name__, 

117 cost=cost, 

118 compute=build_requires_guard(compute, requires), 

119 unguarded_compute=compute, 

120 deps=deps + tuple(name for name in requires if name not in deps), 

121 documentation=compute.__doc__ or "", 

122 requires=requires, 

123 ) 

124 return compute 

125 

126 return register 

127 

128 

129def build_requires_guard( 

130 compute: Callable[[FactContext[Any]], object], requires: tuple[str, ...] 

131) -> Callable[[FactContext[Any]], object]: 

132 """Wrap ``Fact.compute`` so it short-circuits to False when any required atom is False. 

133 

134 Args: 

135 compute (Callable[[FactContext[Any]], object]): The fact's raw computation. 

136 requires (tuple[str, ...]): Atoms that must all be true for ``compute`` to run. 

137 

138 Returns: 

139 Callable[[FactContext[Any]], object]: ``compute`` itself when ``requires`` is empty, 

140 else a guarded wrapper around it. 

141 """ 

142 if not requires: 

143 return compute 

144 

145 # TBD: wrapping value-fact causes problem here (e.g. _nearby_introns, _cds_footprint) 

146 @wraps(compute) 

147 def guarded(fact_context: FactContext[Any]) -> object: 

148 for required_name in requires: 

149 if not get_fact(fact_context, required_name): 

150 return False 

151 return compute(fact_context) 

152 

153 return guarded 

154 

155 

156def get_fact(fact_context: FactContext, name: str) -> object: 

157 """Fetch a fact's value for this context, computing it at most once. 

158 

159 The hottest function in the system, so it does the least it can when tracing is off: one 

160 ``is not None`` check, shared by both paths, whose body is a single dict bump. Everything else 

161 a derivation trace shows -- origins, costs, forced-False facts -- is reconstructed afterwards 

162 from the memo table (``ensembl.vep.trace.reconstruct``), because it can be. The read count is 

163 the one thing that cannot: a replay sees only memo hits, so it never observes the original 

164 read pattern. Making the counter unconditional to drop the branch measures 1.30x here. 

165 

166 Args: 

167 fact_context (FactContext): The per-overlap memoisation context to read from and populate. 

168 name (str): The name of a registered fact. 

169 

170 Returns: 

171 object: The fact's value, from the memo table if already computed. 

172 """ 

173 recorder = fact_context.recorder 

174 if recorder is not None: 

175 read_counts = recorder.read_counts 

176 read_counts[name] = read_counts.get(name, 0) + 1 

177 

178 memo = fact_context.memo 

179 if name in memo: 

180 return memo[name] 

181 

182 registered_fact = REGISTRY[name] 

183 value = registered_fact.compute(fact_context) 

184 memo[name] = value 

185 return value 

186 

187 

188def atom_names() -> list[str]: 

189 """Return the Boolean facts a rule may reference. 

190 

191 Returns: 

192 list[str]: Sorted names of every registered fact that does not start with ``_``. 

193 """ 

194 return sorted(name for name in REGISTRY if not name.startswith("_")) 

195 

196 

197def implied_false(known: Mapping[str, bool]) -> dict[str, bool]: 

198 """Extend known facts that are implied False by the current assignment. 

199 

200 The result also explains itself later: a name this added is False here and absent from the 

201 memo, which is how ``trace.reconstruct.forced_false_events`` recovers the forced-False set 

202 and its cause without this function recording anything, and without the explanation 

203 duplicating the propagation. 

204 

205 Args: 

206 known (Mapping[str, bool]): A partial assignment of fact names to boolean values. 

207 

208 Returns: 

209 dict[str, bool]: ``known`` extended with every fact that ``requires`` proves False given 

210 the input, iterated to a fixed point. 

211 """ 

212 extended = dict(known) 

213 changed = True 

214 while changed: 

215 changed = False 

216 for name, registered_fact in REGISTRY.items(): 

217 if name in extended or not registered_fact.requires: 

218 continue 

219 if any(extended.get(required) is False for required in registered_fact.requires): 

220 extended[name] = False 

221 changed = True 

222 return extended 

223 

224 

225def verify_requires(fact_contexts: Iterable[FactContext[Any]]) -> list[str]: 

226 """Check every ``requires`` claim against real contexts. 

227 

228 A wrong declaration would silently produce wrong consequences. This is a sanity check to make sure 

229 that never happens. 

230 

231 Checks a fact by running a fact's compute function without its requires guard, and then checking 

232 when the result is True all of its required atoms are True. if one required atom is False, the claim 

233 is false and the fact's compute function is mis-declared. 

234 

235 Running the **unguarded** body is the whole point: a guarded call can never disprove its own 

236 guard, since the guard returns False whenever a required atom is False. Checking through 

237 ``get_fact`` would therefore pass for every declaration, correct or not. 

238 

239 A body that *raises* when its required atoms are false is reported too. That is the same class 

240 of defect seen from the other side: the body is relying on the guard having already 

241 short-circuited, rather than being independently consistent with what it declares. 

242 

243 Args: 

244 fact_contexts (Iterable[FactContext]): Contexts to check the claims against. Each is 

245 reset before use. 

246 

247 Returns: 

248 list[str]: A description of every ``requires`` claim found to be false, or an empty list 

249 if every claim held. 

250 """ 

251 problems: list[str] = [] 

252 for fact_context in fact_contexts: 

253 fact_context.reset() 

254 for name, registered_fact in REGISTRY.items(): 

255 if not registered_fact.requires: 

256 continue 

257 required_all_true = all(get_fact(fact_context, required) for required in registered_fact.requires) 

258 if required_all_true: 

259 continue 

260 try: 

261 value = registered_fact.unguarded_compute(fact_context) 

262 except Exception as exc: # pylint: disable=broad-except 

263 # A body that cannot even run unguarded meaning the fact fails to compute when any require is 

264 # False is itself a finding. It may mean the requirement declaration is not just about truth, 

265 # and the body silently depends on the guard having already short-circuited. 

266 problems.append( 

267 f"{name} raised {type(exc).__name__}: {exc} for overlap " 

268 f"{fact_context.overlap!r} when requires={registered_fact.requires} was not met" 

269 ) 

270 continue 

271 if value: 

272 problems.append( 

273 f"{name} is true for overlap {fact_context.overlap!r} despite " 

274 f"requires={registered_fact.requires}" 

275 ) 

276 return problems 

277 

278 

279_closure_cost_cache: dict[str, int] = {} 

280 

281 

282def closure_cost(name: str) -> int: 

283 """Return the cost of a fact and its dependencies. 

284 

285 Args: 

286 name (str): The name of a registered fact. 

287 

288 Returns: 

289 int: The total cost of computing ``name`` and every fact it (transitively) depends on, 

290 counting each shared dependency once. 

291 """ 

292 if name in _closure_cost_cache: 

293 return _closure_cost_cache[name] 

294 seen: set[str] = set() 

295 

296 def walk(fact_name: str) -> int: 

297 if fact_name in seen: 

298 return 0 

299 seen.add(fact_name) 

300 registered_fact = REGISTRY[fact_name] 

301 return registered_fact.cost + sum(walk(dep) for dep in registered_fact.deps) 

302 

303 _closure_cost_cache[name] = walk(name) 

304 return _closure_cost_cache[name] 

305 

306 

307def total_cost(names: Iterable[str]) -> int: 

308 """Return the cost of facts and their shared dependencies. 

309 

310 Args: 

311 names (Iterable[str]): Names of registered facts. 

312 

313 Returns: 

314 int: The total cost, with every shared dependency (transitively) counted exactly once. 

315 """ 

316 seen: set[str] = set() 

317 total = 0 

318 stack = list(names) 

319 while stack: 

320 name = stack.pop() 

321 if name in seen: 

322 continue 

323 seen.add(name) 

324 registered_fact = REGISTRY[name] 

325 total += registered_fact.cost 

326 stack.extend(registered_fact.deps) 

327 return total 

328 

329 

330# -------------------------------------------------------------------------- 

331# Optional measured-cost override: 

332# 

333# ``vep catalogue costs`` profiles every fact's real self-time over a corpus and can persist the 

334# result to ``annotators/consequence/data/fact_costs.json`` -- see 

335# ensembl.vep.annotators.consequence.facts.costs. 

336# 

337# This section only ever overrides an already-registered fact's ``cost`` field, and only when the 

338# ``fact_cost_override`` configuration option asks for it (see annotators/factory.py). Could be 

339# useful if in certain platform the measured costs are significantly different from the declared 

340# ones. 

341# -------------------------------------------------------------------------- 

342 

343FACT_COST_OVERRIDE_RESOURCE = "data/fact_costs.json" 

344 

345 

346def apply_fact_cost_overrides(overrides: Mapping[str, int]) -> None: 

347 """Override REGISTRY entries' ``cost`` in place from a measured fact-cost table. 

348 

349 Declared cost tiers are untouched for any fact not present in ``overrides``. Also closure_cost's 

350 memoisation cache is cleared so subsequent calls reflect the new costs rather than a stale value 

351 computed before the override was applied. 

352 

353 Args: 

354 overrides (Mapping[str, int]): Fact name -> cost unit, typically loaded from 

355 ``annotators/consequence/data/fact_costs.json``. 

356 """ 

357 for fact_name, cost in overrides.items(): 

358 registered_fact = REGISTRY.get(fact_name) 

359 if registered_fact is not None: 

360 REGISTRY[fact_name] = evolve(registered_fact, cost=int(cost)) 

361 _closure_cost_cache.clear() 

362 

363 

364def load_fact_cost_overrides_from_package() -> dict[str, int]: 

365 """Read the checked-in measured fact-cost table, if any, without applying it. 

366 

367 Returns: 

368 dict[str, int]: The ``{fact_name: cost_units}`` table from 

369 ``annotators/data/fact_costs.json``, or an empty dict if that resource does not exist. 

370 """ 

371 resource = files("ensembl.vep.annotators.consequence").joinpath(FACT_COST_OVERRIDE_RESOURCE) 

372 if not resource.is_file(): 

373 return {} 

374 return dict(json.loads(resource.read_text(encoding="utf-8"))) 

375 

376 

377def apply_packaged_fact_cost_overrides() -> None: 

378 """Apply the packaged measured-cost table, if the package ships one. 

379 

380 Call after every fact submodule has registered, since REGISTRY is empty before that. Costs 

381 change evaluation order only, never the terms emitted. 

382 """ 

383 overrides = load_fact_cost_overrides_from_package() 

384 if overrides: 384 ↛ exitline 384 didn't return from function 'apply_packaged_fact_cost_overrides' because the condition on line 384 was always true

385 apply_fact_cost_overrides(overrides)