Coverage for src/python/ensembl/vep/caches/mapper_cache.py: 100%

60 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"""Cache expanded mapper indexes used by consequence annotation. 

15 

16``MapperIndex`` accelerates repeated coordinate conversion but varies substantially in size, so 

17the LRU cache uses a byte budget rather than an entry count. 

18""" 

19 

20from __future__ import annotations 

21 

22import sys 

23from collections import OrderedDict 

24from collections.abc import Callable 

25from threading import RLock 

26from typing import TYPE_CHECKING, Protocol, TypeAlias, runtime_checkable 

27 

28from attrs import define, field 

29 

30from ensembl.vep.models.sequence import MapperIndex 

31 

32if TYPE_CHECKING: 

33 from ensembl.vep.models.genic import Transcript 

34 

35__all__ = ["MapperIndexCache", "MapperIndexLRUCache", "MapperIndexLoader"] 

36 

37MapperIndexLoader: TypeAlias = Callable[[], MapperIndex] 

38 

39 

40@runtime_checkable 

41class MapperIndexCache(Protocol): 

42 """Define storage used to reuse mapper indexes.""" 

43 

44 def get_index(self, transcript: Transcript, loader: MapperIndexLoader) -> MapperIndex: 

45 """Return the cached mapper index, loading it on a miss. 

46 

47 Args: 

48 transcript (Transcript): Transcript used to key the cache by stable ID. 

49 loader (MapperIndexLoader): Loader used when the transcript is not cached. 

50 

51 Returns: 

52 MapperIndex: Cached or newly loaded mapper index. 

53 """ 

54 raise NotImplementedError 

55 

56 def clear(self) -> None: 

57 """Clear cached state.""" 

58 raise NotImplementedError 

59 

60 

61def _estimate_mapper_index_bytes(mapper_index: MapperIndex) -> int: 

62 """Estimate the heap space used by a mapper index. 

63 

64 Args: 

65 mapper_index (MapperIndex): Mapper index to size. 

66 

67 Returns: 

68 int: Estimated size in bytes. 

69 """ 

70 offset_to_position = mapper_index.offset_to_position 

71 position_to_offset = mapper_index.position_to_offset 

72 list_bytes = sys.getsizeof(offset_to_position) + sum( 

73 sys.getsizeof(position) for position in offset_to_position 

74 ) 

75 dict_bytes = sys.getsizeof(position_to_offset) + sum( 

76 sys.getsizeof(position) + sys.getsizeof(offset) for position, offset in position_to_offset.items() 

77 ) 

78 return list_bytes + dict_bytes 

79 

80 

81@define(kw_only=True, auto_attribs=True, eq=False) 

82class MapperIndexLRUCache: 

83 """Store mapper indexes in an instance-scoped, byte-budget LRU cache. 

84 

85 Entries use transcript stable IDs because ``Transcript`` is not hashable. ``eq=False`` 

86 preserves identity semantics for mutable shared state. 

87 

88 Attributes: 

89 enabled (bool): Whether caching is enabled. 

90 max_bytes (int): Maximum estimated size of cached entries in bytes. 

91 hit_count (int): Number of lookups served from the cache. 

92 miss_count (int): Number of lookups that invoked ``loader``. 

93 """ 

94 

95 enabled: bool = True 

96 max_bytes: int = 64 * 1024 * 1024 

97 hit_count: int = field(default=0, init=False) 

98 miss_count: int = field(default=0, init=False) 

99 _cache: OrderedDict[str, MapperIndex] = field(factory=OrderedDict, init=False, repr=False) 

100 _sizes: dict[str, int] = field(factory=dict, init=False, repr=False) 

101 _total_bytes: int = field(default=0, init=False, repr=False) 

102 _lock: RLock = field(factory=RLock, init=False, repr=False) 

103 

104 def get_index(self, transcript: Transcript, loader: MapperIndexLoader) -> MapperIndex: 

105 """Return the cached mapper index, loading and storing it on a miss. 

106 

107 Args: 

108 transcript (Transcript): Transcript used to key the cache. 

109 loader (MapperIndexLoader): Loader used when the transcript is not cached. 

110 

111 Returns: 

112 MapperIndex: Cached or newly loaded mapper index. 

113 """ 

114 if not self.enabled: 

115 self.miss_count += 1 

116 return loader() 

117 

118 key = transcript.stable_id 

119 with self._lock: 

120 cached = self._cache.get(key) 

121 if cached is not None: 

122 self._cache.move_to_end(key) 

123 self.hit_count += 1 

124 return cached 

125 

126 mapper_index = loader() 

127 size = _estimate_mapper_index_bytes(mapper_index) 

128 

129 with self._lock: 

130 if key in self._sizes: 

131 # Another thread built and inserted the same key first; keep this build 

132 # (deterministic given the same transcript) but do not double-count its bytes. 

133 self._total_bytes -= self._sizes[key] 

134 self._cache[key] = mapper_index 

135 self._cache.move_to_end(key) 

136 self._sizes[key] = size 

137 self._total_bytes += size 

138 self.miss_count += 1 

139 while self._total_bytes > self.max_bytes and self._cache: 

140 evicted_key, _ = self._cache.popitem(last=False) 

141 self._total_bytes -= self._sizes.pop(evicted_key, 0) 

142 

143 return mapper_index 

144 

145 def clear(self) -> None: 

146 """Clear the cache contents.""" 

147 with self._lock: 

148 self._cache.clear() 

149 self._sizes.clear() 

150 self._total_bytes = 0