Skip to content

Merge v2.0-cyanoptera into main with its fixes since 2026-10-29 - #803

Merged
evertlammerts merged 97 commits into
duckdb:mainfrom
ewoerd:merge-v2.0-cyanoptera-into-main
Dec 1, 2026
Merged

evertlammerts merged 97 commits into
duckdb:mainfrom
ewoerd:merge-v2.0-cyanoptera-into-main

Conversation

@evertlammerts

Copy link
Copy Markdown
Member

Since the last merge on 2026-10-29: 28 pull requests, among them the conversion of object columns into declared types (#739), views that own their file-like readers (#741), the polars filter pushdown rules (#740, #794) and the fixes around interpreter exit and held connections (#784, #792, #793, #802). Two tests of TestOpenResultIsExclusive fail on main in some runs; here one passes (#802) and the other is skipped under polars 2.2.0 (#794).

Main keeps its engine pin, its release version 2.1.0 and its benchmark baseline. Where both lines changed one function, the merge keeps both changes:

A second commit follows main's engine where the merged code meets it:

  • File system registration goes through VirtualFileSystem::Get(), as in Move the pin to f09095cd, support DECIMAL beyond 38 digits #797.
  • The cast cache of the numpy scan passes its client context directly, since the engine made the member it read private.
  • The polars scan counts a collated text column as text. This engine prints its type as VARCHAR('NOCASE'), and without the change a filter on it is no longer pushed.
  • Main's shutdown test that reads through fsspec turns nanobind's leak report on, as Silence nanobind exit leak report #784 asks of every test that checks for leaks.

Tests that main removed on purpose stay removed: the refusals of DECIMAL beyond 38 digits (#797) and of relation writes to names with more than three parts (#764).

JelteF and others added 30 commits November 1, 2026 21:55
The engine's v2.0 branch moved to 910c73dabea (v2.0.1-alpha52096, whose
extensions are published). The nightly of 2026-11-01 built against it and
failed 2 tests, both because of intended engine fixes:

duckdb/duckdb `94fe8ecf377` renders every finite timestamp, also those
before the first midnight of the range, so `TRY_CAST(t AS VARCHAR)` of
such an Arrow timestamp now returns `'290309-12-21 (BC) 23:59:59.999999'`
instead of throwing an internal error. The strict xfail of
`test_a_timestamp_before_the_date_range_try_casts_to_null` is replaced by
a test that expects the text.

duckdb/duckdb `1033ecbe776` makes `read_json` read a DECIMAL column from
the number's text instead of through a double, so `1.005` read as
`decimal(10,2)` now rounds to `1.01` like Spark does.
`TestJsonWithASchema::test_decimals` now expects that.
The engine's v2.0 branch moved to 910c73dabea (v2.0.1-alpha52096, whose
extensions are published). The nightly of 2026-11-01 built against it
and
failed 2 tests, both because of intended engine fixes:

duckdb/duckdb `94fe8ecf377` renders every finite timestamp, also those
before the first midnight of the range, so `TRY_CAST(t AS VARCHAR)` of
such an Arrow timestamp now returns `'290309-12-21 (BC)
23:59:59.999999'`
instead of throwing an internal error. The strict xfail of
`test_a_timestamp_before_the_date_range_try_casts_to_null` is replaced
by
a test that expects the text.

duckdb/duckdb `1033ecbe776` makes `read_json` read a DECIMAL column from
the number's text instead of through a double, so `1.005` read as
`decimal(10,2)` now rounds to `1.01` like Spark does.
`TestJsonWithASchema::test_decimals` now expects that.
…ared types (duckdb#739)

A pandas object column is typed from a sample of its rows, and a value
on a row the sample skipped is cast into that type whatever it is. For
`con.append` and for Spark `createDataFrame` with a schema the caller
has already said what type every column has, yet that type never reached
the scan: `con.append` runs an INSERT SELECT over the registered frame
and the INSERT casts whatever the sample produced, and the Spark layer
casts the scanned column after the fact.

```python
import duckdb, pandas as pd
con = duckdb.connect()
con.execute("CREATE TABLE t (a DOUBLE)")
values = [1] * 2999 + [2.5]
con.append("t", pd.DataFrame({"a": pd.Series(values, dtype=object)}))
con.execute("SELECT a FROM t ORDER BY rowid OFFSET 2999").fetchall()
```

```
[(2.0,)]
```

The analyzer reads every third row of three thousand, sees integers and
binds INTEGER; the scan writes 2.5 as 2 and the INSERT turns 2 into 2.0.
The same column with the appender writes 2.5, because `con.appender`
converts each value with the type it has in Python and then casts it
into the column's type with the connection's cast.

A pandas frame can now be registered with a declared type per column.
`PandasScanInfo` carries the types, so every bind of a copy of the table
reference sees them; `Pandas::Bind` takes the declared type for an
object column in place of the analyzer and marks the column, and the
scan converts each cell of such a column the way the appender converts a
value: `TransformPythonValue` with no target type and NaN as NULL, then
the engine's cast into the column type, which reads the session time
zone and raises the cast's own exception where the value does not fit. A
value of a kind without a DuckDB type of its own, a Path or an Enum
member, reads as its text in a VARCHAR column, as the string scan read
it before, and a numpy scalar reads as its Python value, a datetime64 or
timedelta64 at the microsecond unit, where the appender still refuses
one. The cells of one vector that share a source type are cast with one
engine call: they are staged compacted, cast into a temporary vector,
and moved into the output with `VectorOperations::Copy`, so a NULL row
never enters a cast and the output owns its strings; a vector of mixed
source types casts cell by cell through a bounded cache of cast
functions. The map key check that ran on the top level now recurses to
every depth, for the declared and the sampled object scan alike, since a
STRUCT to MAP cast does not check that text keys stay distinct once
cast.

`con.append` resolves the target table first, through the same
`Binder::BindTableName` lookup an INSERT binds through, with the name as
one identifier and generated columns left out, maps the frame's columns
to the table's by position or, with `by_name`, by name as identifiers,
and registers the frame with those types; a frame column without a table
column stays undeclared, so a count mismatch is still the INSERT's
error. The Spark layer registers through the private connection method
`_register_declared(view_name, df, types)` with the schema's types,
after taking a shallow copy of the frame whose object values have the
form pyspark gives a field: text for a string field, the wall time of an
aware datetime for a timestamp field without a zone, and a dict in field
order for a struct field from a tuple, a Row, a list or an object with
attributes, inside arrays and map values too. The caller's frame is not
changed. Columns of other dtypes, frames backed by pyarrow,
`register()`, `duckdb.sql` over a frame and the dict and numpy paths are
untouched, and a registered frame still types its object columns from
the sample. Appending a million object cells costs two to three times
what it did (ints into BIGINT 0.062 s against 0.030 s, strings 0.125 s
against 0.041 s, timestamps at parity), the price of one Value per cell.

Not built, by decision: a value outside the sample of an undeclared
column is still cast into the sampled type. The 54 strict xfails that
pin the exact conversion in `test_object_column_conversion.py`, the
`test_map.py` case and the Spark tests without a schema now say so in
their reason.

The tests are the 43 strict xfails in `test_append_df.py` and four in
`test_spark_pandas_dataframe.py`, written with the rules in October and
flipped here, plus the cases the review rounds added: None and pandas NA
rows, a NULL row among struct values whose text fields cast into INTEGER
with the field's statistics checked, a NULL row of an ARRAY column with
its element statistics, a NULL row of a UNION column, a NULL STRUCT
whose field is a UNION, ENUM values into VARCHAR with a label longer
than an inline string, keys that collapse in a nested MAP, a Path with a
lone surrogate, an int column into DATE, a bool and a nanosecond
datetime64 in a Spark string field, numpy int, float, bool and
datetime64 scalars into typed columns through both `con.append` and a
Spark schema, and two tests of the private method. The protection cases
pin that the INSERT still refuses a count mismatch, that a temporary
table shadows a persistent one, that the search path and a dotted name
resolve as the INSERT resolves them, and that a Spark frame's struct
values stay as given. All of them fail on the merge base and pass here;
the full fast suite, pandas 2.3.3 and an asserting ASan and UBSan build
pass.
…mes and SQL text, fix the removed method message and the reader stubs
…ame the column in Arrow refusals, read pandas 2 dictionary strings
… NULL chunk as the bound type (duckdb#746)

A map() function that calls sys.exit() ends the process, or hangs it.

```python
import sys, duckdb
duckdb.sql("SELECT 1").map(lambda df: sys.exit(3)).fetchall()
```

The call printed the exception with PyErr_PrintEx, whose handling of
SystemExit is to finalize the interpreter, from inside an engine task:
on the calling thread the process exits with code 3, on a worker thread
it hangs while finalization waits for the engine. Every other exception
reached the caller as the text "Python error. See above for a stack
trace." with the traceback on stderr. The error is now captured as a
Python exception and raised as the engine error "Python error in the map
function: TypeName: message", through the formatter scalar UDFs already
use; nothing is printed and the connection answers afterwards, for
sys.exit at bind, on the calling thread and on a worker thread alike.
The one other place with the same pattern, the Python file system's
seek, checked the error indicator after a call nanobind had already
turned into an exception; that branch cannot be reached and is removed.

map() also rejects its own output when a whole chunk of an object column
is NULL.

```python
con.sql("SELECT CASE WHEN i < 3000 THEN NULL ELSE 'x' END AS s FROM range(4000) t(i)").map(lambda df: df).fetchall()
```

```
duckdb.InvalidInputException: UDF column type mismatch, expected [VARCHAR], got ["NULL"]
```

The function's returned frame is analyzed per chunk, and a chunk whose
values are all missing is typed NULL, which the exact type comparison
against the types fixed at bind refused; a sparse VARCHAR, BLOB, UUID,
LIST, STRUCT or BOOLEAN column hits it on any build back to 1.5. A
returned column the analyzer reads as NULL now matches any bound type
and contributes a column of NULLs, instead of being scanned through the
bound type's scanner, which would read some of those values as data (a
numpy NaT as the text 'NaT'); every other mismatch still fails. The
reported case of the row, an integer column with a NULL in a chunk,
which pandas widens to float64, is a separate change that waits for a
decision on where it ships, since it changes the dtype the function
sees.

The tests pin ValueError, MemoryError, KeyboardInterrupt and a
BaseException subclass at bind and at execution with the type and
message in the error and nothing on stderr, sys.exit in a child process
for the three stages with the connection answering afterwards, the
identity map round tripping six column types with NULL chunks under an
inferred and an explicit schema, None, duckdb.NullValue(), a numpy NaT
and a Value typed NULL all coming back as NULL, and a value of another
type still mismatching. All fail on the merge base except the mismatch
guard.
…he constant NULL column, the declared bind stands
duckdb#749)

The loader's CMake interface target forces a macOS 10.7 deployment
minimum onto every object of the Python module.

```
elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
  target_compile_options(${target_name} INTERFACE -stdlib=libc++ -mmacosx-version-min=10.7)
```

The line was copied from the engine's old setup.py when the build moved
to CMake in July 2025, and the engine itself dropped it years ago. The
wheels declare a deployment target of 10.15 (11.0 on arm64, where
cibuildwheel raises it), which CMake passes to every compile and to the
link as `-mmacosx-version-min=10.15`; the interface target then appends
`-mmacosx-version-min=10.7`, and clang takes the last one. In the macOS
seed jobs of the release workflow 43 compile lines carry both minimums,
the binding objects and two generated extension loaders, so those
objects record a 10.7 floor inside a module whose link and wheel tag say
10.15. On arm64 clang clamps any minimum below 11.0, so only the x86_64
wheel and the x86_64 slice of universal2 are affected. The shipped tag
is right, but the bindings sit on a 10.7 availability floor, where C++17
aligned allocation does not compile and a later libc++ or runtime
feature would break only the macOS x86_64 build; `-stdlib=libc++`
existed only to go with the 10.7 target, since libc++ is clang's default
on macOS from 10.9 on.

The Darwin branch is deleted, nothing else changes; the Windows branch
stays. Verified without a Mac by configuring the project for Darwin on
Linux with the clang here for x86_64 at 10.15, arm64 at 11.0 and
universal2 at 10.15, and reading every compile command: before the
change 43 of 471 objects carried a later 10.7 minimum, after it none,
and the module link flags are unchanged; a Linux configure gives the
same 531 compile commands before and after. The macOS wheel jobs of this
pull request build and test the result. An editable or source build
without a deployment target in its environment uses the compiler's
default floor, as it did before.
…base file, drop the object store through the shutdown gate
… pandas 2 in CI, name a narrowed column by its bound name
…stub check in CI, cache each numpy scalar class's type
…onds of a fine datetime64, cast only units finer than a microsecond
…isor's sign, boolean And and Or, exact decimals, byte collation, and refuse types polars widens
… UNION a guess, confirm a guess by lossless widening, and cast MAP keys as values
duckdblabs-bot and others added 28 commits November 18, 2026 05:41
Bump duckdb submodule:
- Target branch: v2.0-cyanoptera
- Date: 2026-11-18 05:41:44
- DuckDB SHA: fe5c8b29a066f32be6eca4d7b2072d54a081c735
- Trigger:
https://github.com/duckdb/duckdb-python/actions/runs/44241982871
Bump duckdb submodule:
- Target branch: v2.0-cyanoptera
- Date: 2026-11-18 12:52:37
- DuckDB SHA: 90dcc2834cd5dfcfff3dced2f15f657e69736e29
- Trigger:
https://github.com/duckdb/duckdb-python/actions/runs/44303066433
Fixes duckdb#732, duckdb#736

A program that keeps a duckdb connection or type past interpreter
finalization prints at exit:

```
nanobind: leaked 27 instances!
 - leaked instance 0x64c7922f1c50 of type "_duckdb._sqltypes.DuckDBPyType"
nanobind: leaked 6 types!
 - leaked type "_duckdb.DuckDBPyConnection"
nanobind: leaked 84 functions!
nanobind: this is likely caused by a reference counting issue in the binding code.
```

Triggers include a `typing.overload` signature naming a duckdb type with
numpy imported, and a polars frame built from a relation.

nanobind checks at exit that every module object was freed and prints
the rest. What another package keeps past finalization is a fixed set,
not a growing leak.

- Builds without assertions now turn the report off; Debug and
FORCE_ASSERT builds keep it.
- `_duckdb._assertions` tells which way a build went; the wheel, sdist
and assertion jobs check it.
- A private `_duckdb._set_leak_report()` turns it on in test children,
so CI keeps its exit leak checks.
- duckdb gets its own nanobind domain, so its setting stays out of other
nanobind extensions.

Release wheels print nothing at exit, also for a daemon thread still
alive at exit, which keeps its module's globals and with them any
connection there; with the report switched on that case prints the full
list, which a follow-up on the type constants the module keeps will
shorten.
Move release_version past the version just released:
- Target branch: v2.0-cyanoptera
- Released: 2.0.1
- Next: 2.0.2
- Date: 2026-11-20 13:36:13
- Trigger:
https://github.com/duckdb/duckdb-python/actions/runs/44618384791
…ad holds (duckdb#792)

Fixes duckdb#789

A daemon thread's query stuck on a silent read holds up the exit. Since
2.0.1 the exit waits until the read fails (two minutes by default) and
can abort. 2.0.0 exits at once.

```python
con = duckdb.connect()
query = "SELECT * FROM read_text('http://stalled.example/x.txt')"
threading.Thread(target=lambda: con.sql(query).fetchall(), daemon=True).start()
# the main thread returns here
```

The atexit hook that ends open results asked the engine whether one
still runs, under the context lock, which the daemon thread holds during
a read that ignores the interrupt. Its one second wait for a busy
connection was also counted per result.

The hook first interrupts every running result's query, which takes no
lock. It then retries each connection's claim without blocking, for one
second in total. It closes each result still running once its claim is
taken, clears that connection's interrupt, and leaves the rest open; as
in 2.0.0, those are not checkpointed. A query the interrupt reaches is
interrupted and closed.

A result the main thread left open over an engine worker stuck in a read
still waits, as on 2.0.1: the engine's close waits for every running
task.

Cases in tests/slow/test_exit_with_open_results.py stall reads on one
and on twelve daemon connections, time the exit with a sort left open,
and check that a later exit handler can still use an interrupted or idle
connection.
…b#794)

Since polars 2.2.0, a lazy frame filter comparing an integer column with
a float no value equals is no longer pushed. Fixes six of the seven
failures of the v2.0 Release nightly since polars 2.2.0.

```python
pl.col("a") == 1.5  # a TINYINT column
# polars 2.1 sends the scan: Cast(a, Float64) == 1.5
# polars 2.2 sends the scan: Ternary(IsNotNull(a), false, NULL), that is when(a.is_not_null()).then(False)
```

[pola-rs/polars#30311](pola-rs/polars#30311)
folds such a comparison, or one outside the column's range, into a
when/then alike for every non-null row; the translator refused it and
polars filtered every row.

- A Ternary whose parts polars types Boolean now becomes `CASE WHEN p
THEN t ELSE f END`; both send a NULL condition to the last branch.
- A Boolean NULL now translates, also as the cast ending a when/then
without otherwise.

A when/then with integer parts stays refused: polars raises on it, the
engine reads nonzero as true. So do a Ternary inside a comparison and
other NULLs. Out of range integer comparisons, which polars 2.1 already
folded, are now pushed too.

New cases in `test_polars_pushdown_literals.py` cover each shape; the
pushed ones fail on the merge base with 2.2.0.

The seventh, joining two lazy frames of one connection, is a separate
polars 2.2.0 regression, reproducible without duckdb: a failed collect()
leaves a source still in its first call open until the frame is dropped.
…kdb#793)

Follows duckdb#792.

A streaming fetch that fails, such as an interrupted DB-API fetch or
Arrow reader, left its result counted as running after the engine ended
the query. A later query on that connection gave the exit hook two
running results, and the second waited because the hook cleared the
interrupt in between.

The streaming fetch now ends its result on the engine's error, as other
driving paths do. Later fetches raise the same error as before, with two
exceptions that now raise it too: `fetch_df_chunk(0)`, which returned an
empty frame, as for a query that failed before streaming, and a further
read of a failed Arrow reader whose connection is closed or in use by
another call, which reported that instead.

Tests bound the exit with a sort beside either failed fetch, and check
that later fetches on both routes raise the error.
Fixes duckdb#795

`import duckdb` fails when the host has removed `__main__` from
`sys.modules`, as the Azure Functions Python 3.13 worker does:

```python
import sys
del sys.modules["__main__"]
import duckdb
# ImportError: Encountered an error while initializing the extension.
```

At import the client checks whether `__main__` has a `__file__` to tell
an interactive session from a script. It got `__main__` by importing it,
so with the module gone the import searches `sys.path` and raises
`ModuleNotFoundError`, which fails the extension's initialization. With
a `__main__.py` on `sys.path`, the import runs that file instead.

`DetectEnvironment()` now reads `__main__` from `sys.modules` and treats
a missing or `None` entry as a session that is not interactive and not a
Jupyter kernel. An interactive session still enables the progress bar,
and a kernel is still detected for the progress widget.

The new child process test in `tests/fast/api/test_query_progress.py`
imports duckdb with `__main__` removed from `sys.modules` (once with a
`__main__.py` on `sys.path` that must not run), set to `None`, and
replaced by a module without `__file__`, and checks the progress bar
default: off in the first three, on in the last. The first three cases
fail on the merge base.
Brings back the change of duckdb#765, approved there, onto the current
v2.0-cyanoptera.

When two threads share a connection, a call from the second can land
after `execute()` submits a statement and before it settles it. The
worst outcome is a hang with the GIL held: the assertion job of duckdb#801
hung in `test_a_lazy_polars_frame_scanned_on_its_own_connection_errors`.
The others:

- a flush or relation on the other thread gets the engine's open result
message for a result it never held, or runs beside the half run
statement;
- a second `execute()` waits for the first, then replaces its result, so
the first thread reads the other thread's row;
- a DB-API `to_arrow_table()` refused by the race has already taken the
rows, and a retry returns nothing.

```python
import threading

import duckdb

con = duckdb.connect()
inside, done = threading.Event(), threading.Event()


class Params:
    def __len__(self):
        return 1

    def __iter__(self):
        inside.set()  # the first execute is reading its parameters
        done.wait(5)  # until the second thread's execute has returned
        return iter([1])


def second():
    inside.wait()
    try:
        con.execute("SELECT 2")
        print("second thread: ran")
    except duckdb.ResourceInUseException as error:
        print("second thread:", error)
    finally:
        done.set()


thread = threading.Thread(target=second)
thread.start()
con.execute("SELECT ?::INTEGER", Params())
thread.join()
print("first thread reads:", con.fetchall())

# v2.0-cyanoptera, after 5 s:
#   second thread: ran
#   first thread reads: [(2,)]
# with this change, at once:
#   second thread: Resource In Use Error: connection is busy with another call; it refuses instead of waiting, ...
#   first thread reads: [(1,)]
```

A statement should hold the connection claim, the client's
per-connection busy flag, from submission until it is settled.
`execute()`, `executemany()` and the DB-API Arrow fetch claimed twice,
once to submit and once to settle, while the engine already ran the
statement on its worker threads. A refused second claim left the pending
result to be destroyed with the GIL held, and its close waited for a
task that needed the GIL.

The three paths now hold one claim from submission through settling, as
`StatementGroup::RunAllButLast` already did, and close a refused or
failed result with the GIL released. Only the claimed submit, settle and
retain remain, each asserting the claim in a debug build.

In a program that shares a connection between threads, `execute()`,
`executemany()`, the DB-API Arrow fetches and the methods built on
`execute()`, such as `begin()` and `append()`, are refused as busy when
another thread's call of that set is in flight, instead of waiting.
Fetches of rows already in the client, `description` and `close()`
behave as before. A statement that a parameter object runs during
`execute()` no longer makes the outer call fail: the outer call
supersedes its result.

The tests in `tests/fast/api/test_appender.py` and
`tests/fast/api/test_execute_contract.py` contend from a second thread
while a Python UDF holds the statement, the hang cases in a child
process; the flush and second `execute()` tests fail on the merge base.
@evertlammerts evertlammerts added the submodule-bump Intentional DuckDB submodule pin move label Dec 1, 2026
@evertlammerts
evertlammerts merged commit 09d6df7 into duckdb:main Dec 1, 2026
28 of 31 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

submodule-bump Intentional DuckDB submodule pin move

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants