Skip to content

Fasta.fetch: size the output buffer from the intervals and free it - #100

Open
DylanCosto wants to merge 2 commits into
lmdu:masterfrom
DylanCosto:perf-size-fetch-buffer
Open

DylanCosto wants to merge 2 commits into
lmdu:masterfrom
DylanCosto:perf-size-fetch-buffer

Conversation

@DylanCosto

Copy link
Copy Markdown

For a list of intervals, pyfastx_fasta_fetch allocates strlen(seq) + 1 bytes, one chromosome's worth, and never frees it. That causes three problems:

  • every call scans the whole cached chromosome with strlen, so repeated exon extraction is slow
  • the buffer leaks on every call
  • repeated or overlapping intervals can add up to more than the chromosome length, which overflows the buffer (fetch('chr', [(1, n), (1, n)]) aborts with heap corruption)

The leaked buffer also applies to the single-interval form.

This converts and validates all intervals first, allocates exactly the total requested length, frees it after building the result, and routes every error through a single cleanup path. List arguments are snapshotted as tuples before integer conversion, since __index__ can run Python code. Integer subclasses and list/tuple subclasses behave as before.

The new validation raises ValueError for an empty interval list, start < 1 or end past the end of the sequence. Before, those read outside the buffer.

On a cached 25 Mb chromosome, 1,000 two-exon fetches drop from about 0.73 s to 0.3 ms. On a 1 kb contig, peak RSS for 50,000 fetches drops from about 72 MB to 19 MB. Output is identical: I checked 4,000 results against independently sliced plain and gzipped FASTA.

The existing fetch test now covers repeated and overlapping intervals, invalid intervals, keyword arguments, callbacks that modify their input, and list/tuple subclasses. The FASTA tests pass, both normally and under ASan/UBSan.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant