Skip to content

Bug: Python index.add and exact search run 50–1,500× slower while another Python thread is busy (GIL re-acquired per item since v2.25.3) #831

Closed

Description

@clemlesne

Describe the bug

Since v2.25.3, the Python bindings release the GIL around long C++ calls (commit d8be67d, "Improve: Release Python GIL during long index operations"). The worker then re-acquires the GIL at every progress tick to run PyErr_CheckSignals() and the progress functor:

  • python/lib.cpp, progress_t::operator() takes py::gil_scoped_acquire on every call, including when no Python callback was given and the functor is the default dummy_progress. In the loops below it runs nested inside an explicit acquisition, so the explicit acquisitions are the ones that wait.
  • The add and search loops do py::gil_scoped_acquire + PyErr_CheckSignals() + progress_(...) for each item handled by worker 0 (every item when threads=1).
  • exact_search (search_many_brute_force) wraps its progress lambda the same way (py::gil_scoped_acquire acquire; return PyErr_CheckSignals() == 0 && progress(passed, total);).

When any other Python thread is runnable, each of these acquisitions can wait up to the interpreter's switch interval (sys.getswitchinterval(), 5 ms by default). Releasing the GIL once already costs up to one switch interval when the call returns. That is the normal CPython cost, and it accounts for the single-query index.search row below: a 0.08 ms hashlib.sha256 call, which also releases the GIL, takes about 6 ms in the same setup. The per-item and per-tick acquisitions multiply that cost. index.add of 1,000 vectors with threads=1 pays about 6 ms per vector, and exact search over 20,000 rows makes one acquisition per row. Lowering the switch interval shrinks the slowdown roughly in proportion. v2.25.1 does not show this, because it holds the GIL for the whole call. The code is the same on main today.

Steps to reproduce

import statistics, sys, threading, time
import numpy as np
from usearch.index import Index, search

if len(sys.argv) > 1:
    sys.setswitchinterval(float(sys.argv[1]))

rng = np.random.default_rng(0)
DIM = 256
dataset = rng.standard_normal((20_000, DIM), dtype=np.float32)
queries = rng.standard_normal((1, DIM), dtype=np.float32)
to_add = rng.standard_normal((1_000, DIM), dtype=np.float32)

index = Index(ndim=DIM, metric="cos", dtype="f32")
index.add(np.arange(len(dataset)), dataset, threads=1)

def exact_search():
    search(dataset, queries, 10, metric="cos", exact=True, threads=1)

def hnsw_search():
    index.search(queries, 10, threads=1)

def bulk_add():
    fresh = Index(ndim=DIM, metric="cos", dtype="f32")
    fresh.add(np.arange(len(to_add)), to_add, threads=1)

def median_ms(fn, repeats):
    samples = []
    for _ in range(repeats):
        start = time.perf_counter()
        fn()
        samples.append((time.perf_counter() - start) * 1e3)
    return statistics.median(samples)

stop = threading.Event()

def busy_python_loop():
    counter = 0
    while not stop.is_set():
        counter += 1

for name, fn, repeats in (("exact search", exact_search, 20), ("index.search", hnsw_search, 200), ("index.add 1k", bulk_add, 5)):
    alone = median_ms(fn, repeats)
    stop.clear()
    worker = threading.Thread(target=busy_python_loop)
    worker.start()
    try:
        contended = median_ms(fn, repeats)
    finally:
        stop.set()
        worker.join()
    print(f"{name:14s} alone {alone:9.3f} ms   with a busy Python thread {contended:10.3f} ms   x{contended / alone:8.1f}")

Median wall time per call on CPython 3.14.3, NumPy 2.4.4:

Version Call Alone With a busy Python thread Slowdown
2.25.1 exact search 1.797 ms 1.783 ms ×1.0
2.25.1 index.search 0.182 ms 0.183 ms ×1.0
2.25.1 index.add 1k 107.6 ms 115.5 ms ×1.1
2.25.3 exact search 2.994 ms 4,639.7 ms ×1,549.5
2.25.3 index.search 0.190 ms 6.502 ms ×34.1
2.25.3 index.add 1k 108.7 ms 6,301.2 ms ×58.0
2.26.6 exact search 3.018 ms 1,497.4 ms ×496.2
2.26.6 index.search 0.190 ms 6.481 ms ×34.1
2.26.6 index.add 1k 107.9 ms 6,184.4 ms ×57.3
2.26.6, sys.setswitchinterval(0.0001) exact search 2.990 ms 95.2 ms ×31.8
2.26.6, sys.setswitchinterval(0.0001) index.search 0.185 ms 0.333 ms ×1.8
2.26.6, sys.setswitchinterval(0.0001) index.add 1k 111.4 ms 254.8 ms ×2.3

Exact search with a busy thread varies between runs (1.5–4.6 s on 2.25.3 and 2.26.6 across repeated runs). Uncontended exact search is also slower on 2.25.3/2.26.6 (≈ 3.0 ms) than on 2.25.1 (≈ 1.8 ms) in every run.

Expected behavior

A call that releases the GIL should pay the GIL hand-off at most once per call, not once per item or progress tick. With no Python progress callback supplied, the worker should not need the GIL per item; signal checks can run at a bounded rate.

Possible directions, untested:

  • acquire the GIL in the worker only when a Python progress callback was supplied or a signal check is due (skipping the nested acquisition in progress_t::operator() for dummy_progress alone does not remove the wait, because the loops already acquire the GIL explicitly around PyErr_CheckSignals());
  • check signals at a bounded rate (for example every N items or every few milliseconds) instead of once per item or tick.

USearch version

v2.26.6 (also v2.25.3 and main; v2.25.1 not affected)

Operating System

macOS 27.0.1

Hardware architecture

Arm

Which interface are you using?

Python bindings

Contact Details

No response

Are you open to being tagged as a contributor?

  • I am open to being mentioned in the project .git history as a contributor

Is there an existing issue for this?

  • I have searched the existing issues

Code of Conduct

  • I agree to follow this project's Code of Conduct

Activity

  1. ashvardanian commented on Nov 14, 2026

    @ashvardanian
    Member

    @clemlesne, thanks for the thorough measurements! In 3.0 the Python glue is plain C: each call releases the GIL once and never takes it back unless you pass a progress handler, which then reports at most progress_steps times, so a busy Python thread can no longer stall it per item.

    It's in the 3.0 release candidate on main. Until it reaches PyPI, where installing will be the usual pip install usearch, you can build it for your own CPU in about 5 minutes:

    USEARCH_MARCH=native USEARCH_MULTIVERSIONED=OFF pip install git+https://github.com/unum-cloud/USearch.git

    Any rough edges you hit there are very welcome as issues. See the Python docs.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions