edgartools icon indicating copy to clipboard operation
edgartools copied to clipboard

[PERF] parse_investment_identifier() recompiles up to 933 regexes per call, past re's 512-entry cache

Open mmitc opened this issue 2 months ago • 0 comments

Issue Type

  • [ ] Data Quality Issue (incorrect financial values, missing data)
  • [ ] XBRL Parsing Issue (statement rendering, concept mapping)
  • [ ] Filing Access Issue (download failures, attachment problems)
  • [x] Performance Issue (slow operations, memory problems)
  • [ ] Compatibility Issue (platform/dependency conflicts)
  • [ ] Documentation Issue (unclear instructions, missing examples)

Environment

EdgarTools Version: 5.58.0 (reproduced at main e46440e, 2026-09-22) Python Version: 3.14.3 Operating System: Windows 11

Bug Description

What you expected to happen: parse_investment_identifier builds several regex patterns per call from re.escape(investment_type) for investment_type in INVESTMENT_TYPES (a fixed, 181-entry list the module ships). Parsing a schedule's identifiers should reuse those compiled patterns, through Python's re cache (512 entries) or otherwise, rather than recompiling them for every identifier.

What actually happened: One piped identifier touches on the order of 930 of these per-call patterns (six call sites, several looping the full 181-entry list). That is almost twice the 512-entry cache re keeps, so within a single call the earlier patterns are evicted before the loop that built them finishes, and the next identifier's overlapping investment types (drawn from the same 181-entry list) recompile from scratch too. On BXSL's 703-position 10-Q this is 40.8 s of parsing, against 1.1 s with the patterns cached.

Error message (if any):

none — no exception, just repeated compilation the cache should have absorbed

Reproduction

Minimal code to reproduce (offline, no network — member_candidates=() takes the path that does not need a filing's own XBRL):

import re, time
from edgar.bdc.investments import parse_investment_identifier

identifier = "Snoopy Bidco, Inc. | Non-Affiliated Issuer"

n = 0
orig = re._compiler.compile
def counting(*a, **k):
    global n
    n += 1
    return orig(*a, **k)
re._compiler.compile = counting

t0 = time.perf_counter()
parse_investment_identifier(identifier, member_candidates=())
t1 = time.perf_counter()
re._compiler.compile = orig

print(f"{n} compilations, {(t1 - t0) * 1000:.1f} ms")

Prints 933 compilations, ~55 ms on this machine, one call, cold cache.

Where it happens (file:line, main e46440e, edgar/bdc/investments.py): six sites build a pattern at call time from investment_type/inv_type (never from filing text, always one of the 181 INVESTMENT_TYPES entries or a value already matched against them, so the key space is bounded):

  • :352, _known_investment_type_matches — loops all 181 entries every call
  • :482, _portfolio_company_fields — one call, bounded pattern
  • :1171, the piped-format branch — loops up to 181 entries, sorted by length
  • :1194, the trailing-delimiter branch — loops up to 181 entries
  • :1234, the pipe-right-is-instrument check — loops up to 181 entries
  • :1249, the pipe-left industry-prefix branch — loops up to 181 entries

_known_investment_type_matches alone is reachable from five places inside one parse, so a single piped identifier can enter the 181-entry loop more than once.

Measured, one call per identifier (the shape a caller that parses once

actually uses), on the newest 10-Q or 10-K on file for nine BDCs, from EDGAR:

ticker positions piped compiles (unpatched, total) unpatched, s patched, s outputs identical?
ARCC 1,481 1,425 47,420 5.862 2.956 yes
BXSL 703 699 653,866 40.799 1.078 yes
CGBD 352 350 278,881 17.773 0.697 yes
SLRC 200 200 155,624 10.396 0.452 yes
HTGC 391 0 0 0.725 0.639 yes
KBDC 311 0 0 0.601 0.530 yes
PFX 96 0 0 0.137 0.107 yes
TRIN 529 0 0 0.718 0.763 yes
TSLX 214 0 0 0.863 0.819 yes

"Compiles" and timing are parse_investment_identifier, called once per position, summed over the filing; "unpatched"/"patched" is parse_total_seconds for that same loop. Five of the nine filings hold no piped identifiers at this accession (HTGC, KBDC, PFX, TRIN, TSLX) and are unaffected: the cost appears wherever a filer's schedule uses the piped Company | Type shape. ARCC gains less (2x) than the other piped filers (23-38x): its identifiers cost about 33 compilations each, against about 935 for BXSL's. "Outputs identical" is a SHA-256 over every field of every parsed result and over PortfolioInvestments.from_xbrl's own rows, unpatched vs. patched.

Proposed Fix

Cache the compiled pattern instead of recompiling it: one @lru_cache(maxsize=None) def _compiled(pattern, flags=0): return re.compile(pattern, flags) beside _get_investment_member_candidates, and the six sites above call _compiled(pattern, flags).fullmatch/match/search/ finditer(...) instead of re.fullmatch/match/search/finditer(pattern, subject, flags). The cache key is bounded because every pattern is built from this module's own fixed vocabulary, never from filing text, so it cannot grow without limit. Patch and PR description attached.

Additional Context

Reproduced on 5.58.0 and on main e46440e, counting re._compiler.compile directly (cProfile inflates regex compilation several-fold, so its timings overstate the cost). With the patch, tests/bdc -m "not network" passes 93 of 93 and test_issue_1324_member_candidates_keep_company_name.py 4 of 4, the same as without it. Happy to send the PR.

mmitc avatar Sep 23 '26 20:09 mmitc