Skip to content

nanobind: leaked ... when a DuckDB type is referenced in overload signature and numpy is imported #732

Closed

Description

@bm371613

What happens?

When the interpreter exits, duckdb 2.0.0 prints nanobind leak warnings if both of these are true:

  • a DuckDB type (e.g. DuckDBPyConnection) is referenced from a typing.overload signature, which typing keeps in its module-level overload registry until shutdown
  • numpy is imported (torch 2.6.0 triggers it the same way)
nanobind: leaked 27 instances!
nanobind: leaked 6 types!
 - leaked type "_duckdb._sqltypes.DuckDBPyType"
 - leaked type "_duckdb.DuckDBPyConnection"
 - leaked type "FunctionNullHandling"
 - leaked type "PythonUDFType"
 - leaked type "ExplainType"
 - leaked type "PythonExceptionHandling"
nanobind: leaked 84 functions!
 - leaked function "fetchone"
 - leaked function "fetch_df"
 - leaked function "__exit__"
 - leaked function "_result_as_arrow"
 - leaked function ""
 - leaked function "abort"
 - leaked function "append"
 - leaked function "interrupt"
 - leaked function "dtype"
 - leaked function "_register_values"
 - ... skipped remainder
nanobind: this is likely caused by a reference counting issue in the binding code.
See https://nanobind.readthedocs.io/en/latest/refleaks.html%

To Reproduce

with duckdb_nanobind_leak.py as follows

# /// script
# requires-python = ">=3.13"
# dependencies = ["duckdb==2.0.0", "numpy==2.5.2"]
# ///
"""duckdb 2.0.0 prints "nanobind: leaked ..." at interpreter exit.

Run: uv run --script duckdb_nanobind_leak.py

Triggered when a DuckDB type is referenced from a `typing.overload` signature (typing keeps overloads in a
module-level registry until shutdown) and numpy is imported. Without the overload, or without numpy, exit is clean.
torch (2.6.0) triggers it the same way as numpy.
"""

from typing import overload

import duckdb
import numpy


@overload
def connect(database: str) -> duckdb.DuckDBPyConnection: ...
@overload
def connect(database: None) -> None: ...
def connect(database):
    return None if database is None else duckdb.connect(database)

run uv run --script duckdb_nanobind_leak.py

OS:

x86_64

DuckDB Version:

2.0.0

DuckDB Client:

Python

Hardware:

No response

Full Name:

Bartosz Marcinkowski

Affiliation:

MIM Fertility

Did you include all relevant configuration (e.g., CPU architecture, Linux distribution) to reproduce the issue?

  • Yes, I have

Did you include all code required to reproduce the issue?

  • Yes, I have

Did you include all relevant data sets for reproducing the issue?

Not applicable - the reproduction does not require a data set

Activity

  1. bm371613 commented on Oct 29, 2026

    @bm371613
    Author

    Workaround: from __future__ import annotations keeps annotations as strings, so the overload registry holds no reference to the DuckDB type.

  2. smachen42 commented on Oct 29, 2026

    @smachen42

    Another trigger, without typing.overload or numpy (duckdb 2.0.0, polars 2.1.0, Python 3.14):

    import duckdb, polars as pl
    pl.DataFrame(duckdb.connect().sql("select 1 as a"))
    nanobind: leaked 27 instances!
    nanobind: leaked 2 types!
     - leaked type "ExplainType"
     - leaked type "_duckdb._sqltypes.DuckDBPyType"
    nanobind: leaked 10 functions!
    ...
    
  3. Wolfje63 commented on Oct 30, 2026

    @Wolfje63

    On importing data from Parquet files to DuckDB:

    # Import into DUCKDB.
    if flow['PROCESS_DUCKDB']:
        log.info("DuckDB...")
        tic = time.perf_counter()
        with duckdb.connect(conf['duckdb']) as database:
            for parquetfile in os.listdir(os.path.join(SCRIPT_PATH, "backup")):
                if parquetfile.endswith(".parquet"):
                    tablename = os.path.splitext(parquetfile)[0]
                    log.info(f"'{parquetfile}' -> DuckDB '{tablename}'...")
                    database.sql(f"DROP TABLE IF EXISTS {tablename};")
                    database.sql(f"CREATE TABLE {tablename} AS SELECT * FROM '{os.path.join(SCRIPT_PATH, "backup", parquetfile)}';")
        log.trace(f"DuckDB: {time.perf_counter() - tic:.4f} s")

    All files are imported correctly, however I get output from NanoBind after the module processed:

    nanobind: leaked 28 instances!
    nanobind: leaked 1 keep_alive records!
    nanobind: leaked 6 types!
     - leaked type "ExplainType"
     - leaked type "PythonExceptionHandling"
     - leaked type "_duckdb._sqltypes.DuckDBPyType"
     - leaked type "PythonUDFType"
     - leaked type "_duckdb.DuckDBPyConnection"
     - leaked type "FunctionNullHandling"
    nanobind: leaked 84 functions!
     - leaked function "fetch_df_chunk"
     - leaked function "__enter__"
     - leaked function "fetchmany"
     - leaked function "get_profiling_information"
     - leaked function "_result_as_arrow"
     - leaked function "begin"
     - leaked function "df"
     - leaked function "decimal_type"
     - leaked function "struct_type"
     - leaked function "register"
     - ... skipped remainder
    nanobind: this is likely caused by a reference counting issue in the binding code.
    See https://nanobind.readthedocs.io/en/latest/refleaks.html
    

    Windows 11, Python 3.15.0, duckdb module 2.0.0

  4. WeijieH commented on Oct 30, 2026

    @WeijieH

    Another occurrence on duckdb 2.0.0 (Python 3.13, Linux x86_64, run via uv run --script), without typing.overload in our own code.

    The output at interpreter exit is identical to the report above: 27 instances, 6 types (DuckDBPyType, DuckDBPyConnection, FunctionNullHandling, PythonUDFType, ExplainType, PythonExceptionHandling), 84 functions.

    Our usage is simple. A fresh in-memory connection is created per request with duckdb.connect(":memory:"), and tables are stored from pandas DataFrames. Worker threads use connection.cursor(). We explicitly call close() on the connection before exit, and the warning still appears.

    Observations:

    • Closing the connection explicitly does not prevent it.
    • We have no @overload that references a DuckDB type anywhere in our code. A scan of live functions at exit found none with a DuckDB type in its annotations, so whatever holds the reference is not in our code, or is not an annotation.
    • Standalone scripts that mimic our usage (unclosed or closed connection, cursors used from threads, thread-local cursors, relations, .df()) all exit cleanly.
    • It is intermittent for us. The same single-question run printed the warning on some runs and not on others, with the same code and the same dependency set.

    So it looks like the leak check can be tripped by something other than the overload registry, which matches the polars and parquet-import reports above. I can't yet say which dependency is holding the reference. Since the warning is printed by the nanobind shutdown check and the connections are closed, it appears harmless, but it is noisy for CLI tools.

    Happy to test a patch or a nightly build.

  5. transferred this issue fromduckdb/duckdbon Oct 30, 2026
  6. stnatter commented on Nov 3, 2026

    @stnatter

    Same warning on duckdb 2.0.0, Python 3.15.2, macOS (arm64), without numpy or any typing.overload — a plain pytest suite that opens/closes module-scoped duckdb.connect() connections through a persistence layer. Explicit close() doesn't prevent it.

    nanobind: leaked 1 instances!
    nanobind: leaked 1 keep_alive records!
    nanobind: leaked 4 types!
     - leaked type "FunctionNullHandling"
     - leaked type "PythonExceptionHandling"
     - leaked type "PythonUDFType"
     - leaked type "_duckdb.DuckDBPyConnection"
    nanobind: leaked 74 functions!
     - leaked function "commit"
     - ... skipped remainder
    

    Intermittent (GC/shutdown ordering), and the count stays at 1 instance regardless of how many connections the suite opens — consistent with one connection held at shutdown plus the module-level type/function registrations nanobind can't free.

  7. added a commit that references this issue on Nov 4, 2026
  8. warfl0p commented on Nov 19, 2026

    @warfl0p

    Another trigger, with no Python reference left at all: a thread that ran a query and is still alive at interpreter exit (e.g. a library's daemon worker thread). The cursor is closed and deleted inside the thread, and nothing else references it.

    import duckdb, threading, time
    
    root = duckdb.connect()
    ev = threading.Event()
    
    def worker():
        c = root.cursor()
        c.execute("select 1")
        c.close()
        del c
        ev.wait()  # thread stays alive until exit, holds no reference
    
    threading.Thread(target=worker, daemon=True).start()
    time.sleep(0.5)
    nanobind: leaked 28 instances!
    nanobind: leaked 1 keep_alive records!
    nanobind: leaked 6 types!
     - leaked type "_duckdb._sqltypes.DuckDBPyType"
     - leaked type "_duckdb.DuckDBPyConnection"
     - leaked type "FunctionNullHandling"
     - leaked type "PythonUDFType"
     - leaked type "ExplainType"
     - leaked type "PythonExceptionHandling"
    nanobind: leaked 84 functions!
    
    • No warning if the thread has finished before exit, or with duckdb 1.5.4.
    • Reproduces on 2.0.0, 2.0.1.dev2611181018 and 2.1.0.dev2611161157 (Python 3.14, Linux x86_64).

    We hit this at the end of every Prefect flow run, since Prefect keeps daemon event-loop threads alive until shutdown.

  9. added a commit that references this issue on Nov 19, 2026
    de8eed7
  10. evertlammerts commented on Nov 20, 2026

    @evertlammerts
    Member

    Thanks all, this should be fixed in #784 and shipped today in v2.0.1.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions