edgartools icon indicating copy to clipboard operation
edgartools copied to clipboard

Importing edgar.reference on one thread while another thread imports edgar deadlocks (_DeadlockError, ImportError)

Open mmitc opened this issue 2 months ago • 3 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)
  • [ ] Performance Issue (slow operations, memory problems)
  • [x] Compatibility Issue (platform/dependency conflicts)
  • [ ] Documentation Issue (unclear instructions, missing examples)

Environment

EdgarTools Version: 5.58.0 Python Version: 3.14.3 Operating System: Windows 11

Bug Description

What you expected to happen: Two threads importing edgartools at the same time — one import edgar, the other from edgar.reference import describe_form — both complete, as they would for a package with no import cycle. This happens in a web app that warms import edgar on one thread while a request thread enters edgar.reference (for example to describe a form type).

What actually happened: Both imports fail, deterministically. The import edgar thread raises _DeadlockError and the edgar.reference thread raises ImportError. After that, import edgar on the main thread does succeed, so the process does not hang — but the two exceptions land wherever the imports happened to run, and on a daemon thread that is nowhere visible.

Error message (if any):

main: import edgar: _DeadlockError: deadlock detected by _ModuleLock('edgar.reference') at 3134643893328
thread: from edgar.reference import describe_form: ImportError: cannot import name 'describe_form' from partially initialized module 'edgar.reference' (most likely due to a circular import) (...\site-packages\edgar\reference\__init__.py)

3 of 3 fresh processes, elapsed about 1.0 s each.

The cycle, by line (5.58.0):

  • edgar/__init__.py:12 imports edgar._filings
  • edgar/_filings.py:63 imports edgar.headers
  • edgar/headers.py:20 — from edgar.reference import describe_form (used once, at line 547, inside a __rich__ method)
  • edgar/reference/__init__.py:2 imports edgar.reference.company_dataset, whose line 31 is from edgar.core import log — and importing edgar.core first initialises the edgar package, which is the top of this list.

So a thread that enters edgar.reference first holds that module's import lock and needs edgar; a thread that entered edgar first holds edgar's lock and, via _filings → headers, needs edgar.reference. CPython detects the cycle and raises _DeadlockError in one thread; the other sees a partially initialised edgar.reference.

Reproduction

Minimal code to reproduce (fresh process, no network):

import threading, time

results = {}
barrier = threading.Barrier(2)

def a():
    try:
        barrier.wait(timeout=10)
        import edgar  # noqa
        results["main: import edgar"] = "ok"
    except BaseException as e:
        results["main: import edgar"] = f"{type(e).__name__}: {e}"

def b():
    try:
        barrier.wait(timeout=10)
        from edgar.reference import describe_form  # noqa
        results["thread: from edgar.reference import describe_form"] = "ok"
    except BaseException as e:
        results["thread: from edgar.reference import describe_form"] = f"{type(e).__name__}: {e}"

t = threading.Thread(target=b, daemon=True); t.start()
a(); t.join(timeout=90)
for k, v in results.items():
    print(f"{k}: {v}")

Two threads that both run plain import edgar complete cleanly (3 of 3), so the race needs one thread to enter edgar.reference directly; that is what the script does.

Additional Context

Correction on the fix. Moving the describe_form import in edgar/headers.py into the method does not fix this, and neither does a lazy log in edgar/reference/company_dataset.py: applied together to a copy of 5.58.0, the script above still deadlocks 3 of 3. The cause is CPython's import-lock order, not a cycle in the code. The thread importing edgar.reference takes that module's lock and then needs the parent edgar; the import edgar thread holds the parent's lock and needs edgar.reference because edgar/__init__.py imports it (through _filings.py lines 65-66 and twelve other modules). The same race reproduces with edgar.entity, edgar.xbrl and edgar.bdc, and with a two-file package whose child imports nothing from its parent. Two real options, and which is yours to pick: document "import edgar on the main thread before starting any thread that imports a submodule" (importing edgar first prevents it, 3 of 3), or make edgar/__init__.py lazy through a module __getattr__ so the package init imports no submodule eagerly.

mmitc avatar Sep 12 '26 17:09 mmitc

Thanks — this is an unusually well-researched report, and the correction about the fix that doesn't work saved me the wasted attempt.

Reproduced, 3 of 3, on macOS with Python 3.11.6 against 5.58.0 source. One platform difference worth recording: both threads raise ImportError on a partially initialized edgar.reference here, where you saw _DeadlockError on the import edgar side under Windows and 3.14.3. Same failure, caught at a different point. Note that on my runs the main-thread import edgar fails too, so this isn't only a background-thread problem.

Your correction is right. Moving the describe_form import in edgar/headers.py into its one call site changes nothing — still 3 of 3. Instrumenting __import__ during import edgar shows why: ten modules reached during package init import edgar.reference or one of its submodules.

edgar.headers, edgar._filings, edgar.sgml.sgml_header, edgar.current_filings,
edgar.entity.filings, edgar.entity.tickers, edgar.entity.core,
edgar.thirteenf.parsers.infotable_xml,
edgar.thirteenf.parsers.infotable_txt.format_columnar,
edgar.thirteenf.parsers.infotable_txt.format_multiline

Removing any single edge is pointless, as you found.

One claim I couldn't confirm, and I'd like your help on it. I built the reduction you describe — a two-file package whose __init__ eagerly imports its child, with the child importing nothing from the parent — and it passed 3 of 3 for me, with sleeps in both modules to widen the window. If you still have your version, could you paste it? It matters: if the failure really is pure import-lock ordering, independent of how many edges we have, then reducing our eager imports won't help and documenting is the only option. If it depends on the ten edges above, reducing them genuinely fixes it. My reduction says the latter, but yours may be the more faithful one.

Disposition: both of your options, staged.

Near term, the ordering rule gets documented — import edgar once on the main thread before any thread touches a submodule. I confirmed that prevents it, 3 of 3, and it's what nearly every application already does implicitly.

Structurally, lazy submodule loading via a module __getattr__ is already planned for 6.0. It was queued on import cost alone (import edgar measures about 0.66s via -X importtime), and this issue is a second, independent reason to do it. I've cross-referenced the two so it isn't scheduled as a pure performance nicety.

So no PR needed from you on the lazy change, since it's entangled with the public-API surface work for 6.0. The reduction above is the thing I'd most like from you.

dgunning avatar Sep 17 '26 00:09 dgunning

Following up on my question about your minimal reduction — you can disregard it, and I owe you a correction.

My reduction was the unfaithful one. A toy package whose __init__ imports a child passes 3 of 3 here whether or not the child imports back from a sibling, so the toy proves nothing in either direction and my asking you to defend yours was misplaced. What settles it is measurement on the real package, and there I can now answer the question your report actually poses.

Single-threaded is unaffected. from edgar.reference import describe_form as the first import in a fresh process works, as does importing edgar.reference.tickers directly. So the rule really is threads-only, which is what the documentation now says.

There is no cheap fix, and I tried the specific one your traceback points at. Beyond the headers.py deferral you already ruled out, the failing stack on the submodule side runs through edgar/reference/tickers.py:25, from edgar.urls import ..., which re-enters the parent. All four builders there are used only inside functions, so deferring it is a safe change. It still fails 3 of 3, and it degrades the error from ImportError to KeyError: 'edgar'.

So removing edges one at a time relocates the failure rather than fixing it, on both sides of the cycle. Your conclusion stands: the eager-import surface has to shrink as a whole.

#1333 documents the ordering rule under Common Pitfalls, with a test that pins the documented pattern rather than the racy failure. The structural half stays with the 6.0 lazy submodule work, which this has now given a second reason to do beyond the import cost it was queued on.

Thanks for the report, and for the correction in it — the headers.py note saved me from shipping a fix that does nothing.

dgunning avatar Sep 20 '26 23:09 dgunning

Reopening. #1333 merged, but it only shipped the documentation half, and closing this automatically overstated what has changed.

What is fixed: the ordering rule is now written down under Common Pitfalls, with a test pinning it. Importing edgar once on the main thread before starting any thread that imports a submodule avoids the failure.

What is not: the underlying behaviour. The unsafe ordering still fails exactly as you reported. Anyone who hits it without having read that page gets the same two exceptions.

Leaving this open until the structural fix lands, which is lazy submodule loading via PEP 562, queued for 6.0. That work was previously justified on import cost alone; this issue is now a second, independent reason for it, and the two are cross-referenced internally.

No further action needed from you. The Fixes #1325 in my pull request body was the wrong keyword for a change that resolves half the problem, and that is on me.

dgunning avatar Sep 21 '26 00:09 dgunning