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

86 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"""The cross-payload feature pool contract, and the transcript pool that implements it. 

15 

16``BinnedFeatureCache`` (the worker's per-payload transcript cache) is cleared before every new 

17payload, so a worker that revisits the same gene across many payloads -- a dense or targeted input, 

18or simply a long run of variants on one chromosome -- rebuilds the same ``Transcript`` from GXF 

19records every time. Building one is not free: grouping records, constructing ``Exon``/``Translation`` 

20objects, and resolving the shared ``Gene``. 

21 

22``Transcript`` objects are never mutated after ``GXFTranscriptSource`` builds them, so reusing the 

23same object across payloads is safe -- the only growth over a transcript's pooled lifetime is 

24whatever ``cached_property`` values get resolved on it (introns, spliced sequence, CDS, translated 

25sequence, and so on), which is why the pool is bounded by bytes rather than kept forever. 

26 

27``TranscriptPool`` is keyed by ``(region, stable_id, start, end)`` -- the same fields 

28``BinnedFeatureCache`` already uses as its own dedup key -- and mirrors ``ZoneMapCache``'s 

29byte-budgeted LRU shape: build outside the pool, insert and evict under a lock. 

30""" 

31 

32from __future__ import annotations 

33 

34from collections import OrderedDict 

35from threading import RLock 

36from typing import Protocol, TypeVar, runtime_checkable 

37 

38from attrs import define, field 

39 

40from ensembl.vep.models import Feature 

41from ensembl.vep.models.genic import Transcript 

42 

43__all__ = [ 

44 "DEFAULT_TRANSCRIPT_POOL_BYTES", 

45 "FeatureKey", 

46 "FeaturePool", 

47 "TranscriptKey", 

48 "TranscriptPool", 

49] 

50 

51FeatureT = TypeVar("FeatureT", bound=Feature) 

52 

53FeatureKey = tuple[str, str, int, int] 

54"""``(seq_region_name, stable_id, start, end)`` -- a built feature's pool identity. 

55 

56Matches ``BinnedFeatureCache.add``'s own dedup key, so a feature is addressed the same way whether 

57the caller means "the cache for this payload" or "the pool across payloads". 

58""" 

59 

60 

61@runtime_checkable 

62class FeaturePool(Protocol[FeatureT]): 

63 """Define an interchangeable cache of built features, reused across payloads. 

64 

65 A source builds features from its own records; a pool lets the next payload reuse those 

66 objects instead of rebuilding them. Implementations decide what to retain and when to evict, 

67 so a pool is a hint, never a source of truth: ``get`` may miss at any time and ``put`` may 

68 discard what it was given. 

69 

70 Attributes: 

71 max_bytes (int): Byte budget for pooled features. ``<= 0`` disables the pool. 

72 hit_count (int): Number of ``get`` calls served from the pool so far. 

73 miss_count (int): Number of ``get`` calls that found nothing so far. 

74 """ 

75 

76 max_bytes: int 

77 hit_count: int 

78 miss_count: int 

79 

80 def get(self, key: FeatureKey) -> FeatureT | None: 

81 """Return the pooled feature for a key, or None on a miss.""" 

82 

83 raise NotImplementedError 

84 

85 def put(self, key: FeatureKey, feature: FeatureT) -> None: 

86 """Offer a freshly built feature to the pool.""" 

87 

88 raise NotImplementedError 

89 

90 def clear(self) -> None: 

91 """Clear pooled features.""" 

92 

93 raise NotImplementedError 

94 

95 

96DEFAULT_TRANSCRIPT_POOL_BYTES = 128 * 1024 * 1024 

97"""Default byte budget for ``TranscriptPool``, shared by the config default and every call site.""" 

98 

99TranscriptKey = FeatureKey 

100"""``(seq_region_name, stable_id, start, end)`` -- the ``FeatureKey`` spelling a transcript pool uses.""" 

101 

102_BYTES_PER_EXON = 600 

103"""Estimated per-exon overhead: the ``Exon`` object, its ``Slice`` reference and attrs bookkeeping. 

104 

105Calibrated loosely, not measured with ``tracemalloc`` the way ``ZoneMap.estimated_bytes`` was -- 

106see the module docstring on why an exact figure is not the point. It is one term of two so that a 

107transcript with many small exons and one with few huge exons are both charged something realistic. 

108""" 

109 

110_BYTES_PER_GENOMIC_BASE = 0.5 

111"""Estimated per-base overhead for the transcript's own genomic span. 

112 

113Stands in for the ``cached_property`` values a pooled transcript accumulates once fully read 

114(spliced sequence, CDS, translated sequence, introns, mapper state): each is at most on the order 

115of one byte per base, and several (translated sequence at a third the length; CDS restricted to 

116the coding portion; non-coding transcripts with no CDS/translation at all) are shorter, so half a 

117byte per base approximates the mix without enumerating every property. 

118 

119Calibrated with ``tracemalloc`` over a real dense region (GRCh38 chr1:1-20,000,000, 8,021 

120transcripts, 70,786 exons): building alone grew the heap by 35.0 MB; reading ``spliced_seq``, 

121``translated_seq``, ``introns`` and ``cds`` on every transcript afterwards grew it to 102.2 MB. 

122At this value the estimate for that region is 155.1 MB, 1.52x the fully-read figure. A first 

123attempt at 3 B/base put the estimate at 719 MB for the unread population alone (roughly 20x too 

124high), capping the pool at a few hundred transcripts regardless of ``max_bytes``; plain 1 B/base 

125(the next value tried) still overshot fully-read at 267.8 MB, 2.62x. 

126""" 

127 

128 

129def _estimate_transcript_bytes(transcript: Transcript) -> int: 

130 """Estimate a built transcript's heap footprint, for LRU byte accounting. 

131 

132 ``600 * len(spliced_exons) + 0.5 * (end - start)``: a per-exon term for the ``Exon`` objects 

133 themselves, plus a per-base term standing in for cached derived state (introns, spliced 

134 sequence, CDS, translated sequence, ...) once read. This is deliberately approximate -- an 

135 exact accounting would have to walk every ``cached_property`` a transcript might have resolved 

136 by the time it is evicted, which depends on what the workflow happened to read from it. The 

137 budget is a soft cap for the same reason: bound pool memory to roughly the right order of 

138 magnitude, not to an exact byte count. It also does not count memory a transcript keeps alive 

139 indirectly -- an evicted transcript can still be reachable (and so not actually freed) through 

140 a pooled sibling's ``gene.transcripts``. 

141 

142 Args: 

143 transcript (Transcript): The transcript to size. 

144 

145 Returns: 

146 int: The estimated size in bytes, clamped to be non-negative. 

147 """ 

148 span = max(0, transcript.end - transcript.start) 

149 return _BYTES_PER_EXON * len(transcript.spliced_exons) + int(_BYTES_PER_GENOMIC_BASE * span) 

150 

151 

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

153class TranscriptPool(FeaturePool[Transcript]): 

154 """A byte-budgeted, least-recently-used cache of built ``Transcript`` models. 

155 

156 Reuse across payloads within one worker -- a payload's own ``BinnedFeatureCache`` is still 

157 cleared every time (``BufferedWorker._begin_payload``); this pool is what survives that clear. 

158 Construct one per worker and hand it to ``GXFTranscriptSource.transcript_pool``. 

159 

160 Only one sequence region is held at a time: inserting a transcript from a different region than 

161 the one currently pooled drops every entry from the old region first. A sorted VCF input visits 

162 one region for a long run of payloads before moving to the next, so this keeps the common case 

163 (many payloads over the same region) cheap without holding memory for regions no longer being 

164 annotated. It is a size optimisation, not a correctness requirement -- a transcript is always 

165 addressed by its full key, so nothing breaks if the same region is revisited later; it is just 

166 a pool miss. 

167 

168 ``eq=False`` keeps identity semantics: this is a shared, mutable instance, not a value object, 

169 so two pools with equal counters must not compare equal. 

170 

171 Attributes: 

172 max_bytes (int): Byte budget for pooled transcripts. ``<= 0`` disables the pool: ``get`` 

173 always misses and ``put`` never stores anything. Default is 

174 ``DEFAULT_TRANSCRIPT_POOL_BYTES``. 

175 hit_count (int): Number of ``get`` calls served from the pool so far. 

176 miss_count (int): Number of ``get`` calls that found nothing so far. 

177 eviction_count (int): Number of entries evicted for being over the byte budget so far. 

178 seq_region_eviction_count (int): Number of entries dropped so far because the pooled seq_region 

179 changed. 

180 """ 

181 

182 max_bytes: int = DEFAULT_TRANSCRIPT_POOL_BYTES 

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

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

185 eviction_count: int = field(default=0, init=False) 

186 seq_region_eviction_count: int = field(default=0, init=False) 

187 _seq_region_name: str | None = field(default=None, init=False, repr=False) 

188 _transcripts: OrderedDict[TranscriptKey, Transcript] = field(factory=OrderedDict, init=False, repr=False) 

189 _sizes: dict[TranscriptKey, int] = field(factory=dict, init=False, repr=False) 

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

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

192 

193 def get(self, key: TranscriptKey) -> Transcript | None: 

194 """Return the pooled transcript for ``key``, moving it to most-recently-used. 

195 

196 Args: 

197 key (TranscriptKey): The transcript's pool identity. 

198 

199 Returns: 

200 Transcript | None: The cached transcript, or None on a miss (including when the pool 

201 is disabled). 

202 """ 

203 if self.max_bytes <= 0: 

204 return None 

205 

206 with self._lock: 

207 transcript = self._transcripts.get(key) 

208 if transcript is None: 

209 self.miss_count += 1 

210 return None 

211 self._transcripts.move_to_end(key) 

212 self.hit_count += 1 

213 return transcript 

214 

215 def put(self, key: TranscriptKey, transcript: Transcript) -> None: 

216 """Insert a freshly built transcript, evicting by seq_region_name change and then by byte budget. 

217 

218 A no-op when the pool is disabled (``max_bytes <= 0``). 

219 

220 Args: 

221 key (TranscriptKey): The transcript's pool identity. ``key[0]`` is the seq_region_name. 

222 transcript (Transcript): The built transcript to store. 

223 """ 

224 if self.max_bytes <= 0: 

225 return 

226 

227 seq_region_name = key[0] 

228 size = _estimate_transcript_bytes(transcript) 

229 

230 with self._lock: 

231 if self._seq_region_name is not None and self._seq_region_name != seq_region_name: 

232 self._drop_region_locked(self._seq_region_name) 

233 self._seq_region_name = seq_region_name 

234 

235 if key in self._sizes: 

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

237 self._transcripts[key] = transcript 

238 self._transcripts.move_to_end(key) 

239 self._sizes[key] = size 

240 self._total_bytes += size 

241 

242 while self._total_bytes > self.max_bytes and len(self._transcripts) > 1: 

243 evicted_key, _ = self._transcripts.popitem(last=False) 

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

245 self.eviction_count += 1 

246 

247 def clear(self) -> None: 

248 """Clear the pool contents.""" 

249 with self._lock: 

250 self._transcripts.clear() 

251 self._sizes.clear() 

252 self._total_bytes = 0 

253 self._seq_region_name = None 

254 

255 def __len__(self) -> int: 

256 """Return the number of pooled transcripts.""" 

257 return len(self._transcripts) 

258 

259 def _drop_region_locked(self, seq_region_name: str) -> None: 

260 """Remove every entry for ``seq_region_name``. Caller must hold ``_lock``.""" 

261 stale_keys = [key for key in self._transcripts if key[0] == seq_region_name] 

262 for key in stale_keys: 

263 del self._transcripts[key] 

264 self._total_bytes -= self._sizes.pop(key, 0) 

265 self.seq_region_eviction_count += len(stale_keys)