From 72506dbab71cc310000562f690a33682797d397f Mon Sep 17 00:00:00 2001 From: Jelte Fennema-Nio Date: Sun, 1 Nov 2026 21:55:56 +0000 Subject: [PATCH 01/61] engine bump 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. --- external/duckdb | 2 +- tests/fast/arrow/scan/test_arrow_scan_streams.py | 9 ++------- tests/fast/spark/test_spark_readjson.py | 4 ++-- 3 files changed, 5 insertions(+), 10 deletions(-) diff --git a/external/duckdb b/external/duckdb index fbd180f3a..910c73dab 160000 --- a/external/duckdb +++ b/external/duckdb @@ -1 +1 @@ -Subproject commit fbd180f3a40ca04d7165aa589771b8ea8110d693 +Subproject commit 910c73dabeafc0290907a0c37e09f6abed8e9446 diff --git a/tests/fast/arrow/scan/test_arrow_scan_streams.py b/tests/fast/arrow/scan/test_arrow_scan_streams.py index f02effebc..f1f0486ff 100644 --- a/tests/fast/arrow/scan/test_arrow_scan_streams.py +++ b/tests/fast/arrow/scan/test_arrow_scan_streams.py @@ -1108,14 +1108,9 @@ def test_a_coarse_timestamp_beyond_microseconds_try_casts_to_null(self, con, uni assert rows(con, f"SELECT TRY_CAST(t AS {target}) FROM far") == [(None,)] assert rows(con, "SELECT 42") == [(42,)] - @pytest.mark.xfail( - strict=True, - raises=duckdb.InternalException, - reason="the engine's text form of a timestamp before its date range throws an internal error", - ) - def test_a_timestamp_before_the_date_range_try_casts_to_null(self, con): + def test_a_timestamp_before_the_first_midnight_of_the_range_casts_to_text(self, con): con.register("early", pa.table({"t": pa.array([-106_751_991 * 86_400_000_000 - 1], pa.timestamp("us"))})) - assert rows(con, "SELECT TRY_CAST(t AS VARCHAR) FROM early") == [(None,)] + assert rows(con, "SELECT TRY_CAST(t AS VARCHAR) FROM early") == [("290309-12-21 (BC) 23:59:59.999999",)] assert rows(con, "SELECT 42") == [(42,)] def test_the_first_day_of_nanoseconds_reads_as_text(self, con): diff --git a/tests/fast/spark/test_spark_readjson.py b/tests/fast/spark/test_spark_readjson.py index cb677fd46..006b61ea5 100644 --- a/tests/fast/spark/test_spark_readjson.py +++ b/tests/fast/spark/test_spark_readjson.py @@ -131,9 +131,9 @@ def test_decimals(self, spark, tmp_path): thousand, one = (Decimal("1000.00"), None) if USE_ACTUAL_SPARK else (None, Decimal("1.00")) expected = [Decimal("1.00"), Decimal("1.70"), Decimal("1.00"), thousand, one, None, None] assert _field(spark, tmp_path, "decimal(10,2)", *values) == expected - # Spark rounds the decimal text, DuckDB the double it reads. + # Both round the decimal text, but only DuckDB reads a boolean as a number. values = _field(spark, tmp_path, "decimal(10,2)", "1.005", "true") - assert values == ([Decimal("1.01"), None] if USE_ACTUAL_SPARK else [Decimal("1.00"), Decimal("1.00")]) + assert values == ([Decimal("1.01"), None] if USE_ACTUAL_SPARK else [Decimal("1.01"), Decimal("1.00")]) def test_booleans(self, spark, tmp_path): assert _field(spark, tmp_path, "boolean", "true", "false") == [True, False] From a8c7ee4cd8596b1b47324794ce02ce36bd1eb551 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Thu, 5 Nov 2026 16:47:47 +0000 Subject: [PATCH 02/61] Convert object columns appended or given a Spark schema into the declared types --- _duckdb-stubs/__init__.pyi | 3 + duckdb/experimental/spark/sql/session.py | 109 ++++++++- .../duckdb_python/numpy/numpy_scan.hpp | 3 + .../duckdb_python/pandas/pandas_bind.hpp | 7 +- .../duckdb_python/pandas/pandas_scan.hpp | 5 +- .../pyconnection/pyconnection.hpp | 4 + .../duckdb_python/pyconnection/seam.hpp | 5 +- .../duckdb_python/python_replacement_scan.hpp | 9 +- src/numpy/numpy_scan.cpp | 228 +++++++++++++++++- src/pandas/bind.cpp | 24 +- src/pandas/scan.cpp | 2 +- src/pyconnection.cpp | 66 ++++- src/pyconnection/seam.cpp | 31 ++- src/python_replacement_scan.cpp | 14 +- tests/fast/pandas/test_append_df.py | 138 +++++++---- .../pandas/test_object_column_conversion.py | 120 ++++----- .../fast/spark/test_spark_pandas_dataframe.py | 58 ++--- tests/fast/test_map.py | 2 +- 18 files changed, 650 insertions(+), 178 deletions(-) diff --git a/_duckdb-stubs/__init__.pyi b/_duckdb-stubs/__init__.pyi index b03f407d8..d1e06b547 100644 --- a/_duckdb-stubs/__init__.pyi +++ b/_duckdb-stubs/__init__.pyi @@ -406,6 +406,9 @@ class DuckDBPyConnection: ) -> DuckDBPyRelation: ... def register(self, view_name: str, python_object: object) -> DuckDBPyConnection: ... def _register_arrow_source(self, view_name: str, source: object) -> DuckDBPyConnection: ... + def _register_declared( + self, view_name: str, df: object, types: list[sqltypes.DuckDBPyType | None] + ) -> DuckDBPyConnection: ... @typing.overload def _bind( self, diff --git a/duckdb/experimental/spark/sql/session.py b/duckdb/experimental/spark/sql/session.py index 8a7efb41f..9ceec7f6a 100644 --- a/duckdb/experimental/spark/sql/session.py +++ b/duckdb/experimental/spark/sql/session.py @@ -30,6 +30,7 @@ FractionalType, IntegralType, MapType, + StringType, StructField, StructType, TimestampMillisecondNTZType, @@ -45,6 +46,7 @@ _parse_datatype_string, _python_to_duckdb, _replace_types, + _to_string, ) from .udf import UDFRegistration @@ -85,13 +87,23 @@ def _is_missing(value: Any) -> bool: # noqa: ANN401 return value is None or type(value).__name__ in ("NAType", "NaTType") +def _numpy_value(value: Any) -> Any: # noqa: ANN401 + """The Python value of a NumPy value; a datetime64 or timedelta64 at nanoseconds would list as an int.""" + kind = getattr(getattr(value, "dtype", None), "kind", "") + if kind == "M": + return value.astype("datetime64[us]").tolist() + if kind == "m": + return value.astype("timedelta64[us]").tolist() + return value.tolist() + + def _python_value(value: Any) -> Any: # noqa: ANN401 """A value of a pandas column as the Python value DuckDB reads, at any depth, which Spark's verifier can check. A pandas missing value is None, and NumPy values and pandas timestamps and durations are Python values. """ if _is_numpy(value): - value = value.tolist() + value = _numpy_value(value) if _is_missing(value): return None if isinstance(value, datetime.datetime) and hasattr(value, "to_pydatetime"): @@ -105,6 +117,87 @@ def _python_value(value: Any) -> Any: # noqa: ANN401 return value +_WALL_TIME_TIMESTAMPS = ( + TimestampNTZType, + TimestampSecondNTZType, + TimestampMillisecondNTZType, + TimestampNanosecondNTZType, +) + + +def _reads_through_the_schema(data_type: DataType) -> bool: + """Whether a value of an object column takes a form from ``data_type`` before DuckDB reads it.""" + if isinstance(data_type, (StringType, StructType, *_WALL_TIME_TIMESTAMPS)): + return True + if isinstance(data_type, ArrayType): + return _reads_through_the_schema(data_type.elementType) + if isinstance(data_type, MapType): + return _reads_through_the_schema(data_type.valueType) + return False + + +def _value_through_the_schema(value: Any, data_type: DataType) -> Any: # noqa: ANN401 + """The value of an object column as pyspark hands it to a field of ``data_type``. + + A string field takes the text of any value, a timestamp field without a zone takes the wall time of an aware + datetime, and a struct field takes a tuple, a Row or an object with attributes as a dict in field order; the same + applies inside arrays and map values. A missing value is None. + """ + if _is_numpy(value): + value = _numpy_value(value) + if _is_missing(value): + return None + if isinstance(data_type, StringType): + return _to_string(value) + if isinstance(data_type, _WALL_TIME_TIMESTAMPS): + if isinstance(value, datetime.datetime) and value.tzinfo is not None: + return value.replace(tzinfo=None) + return value + if isinstance(data_type, StructType): + if isinstance(value, dict): + items = value + elif hasattr(value, "__fields__"): + items = dict(zip(value.__fields__, value, strict=False)) + elif isinstance(value, (tuple, list)): + items = dict(zip((field.name for field in data_type.fields), value, strict=False)) + elif hasattr(value, "__dict__"): + items = vars(value) + else: + return value + return { + field.name: _value_through_the_schema(items.get(field.name), field.dataType) for field in data_type.fields + } + if isinstance(data_type, ArrayType) and isinstance(value, (list, tuple)): + return [_value_through_the_schema(element, data_type.elementType) for element in value] + if isinstance(data_type, MapType) and isinstance(value, dict): + return {key: _value_through_the_schema(element, data_type.valueType) for key, element in value.items()} + return value + + +def _column_conforms(series: Any, data_type: DataType) -> bool: # noqa: ANN401 + """Whether every value of an object column already has the form its field takes, so the column stays as it is. + + Only a string field can be settled from the values' types alone; a struct field's dicts need their keys and + nested values looked at, which is the conversion itself. + """ + if isinstance(data_type, StringType): + return bool(series.map(type).isin([str, type(None)]).all()) + return False + + +def _frame_through_the_schema(data: "PandasDataFrame", schema: StructType) -> "PandasDataFrame": + """A shallow copy of ``data`` whose object columns hold their values as the fields of ``schema`` read them.""" + frame = data.copy(deep=False) + for position, ((name, series), field) in enumerate(zip(data.items(), schema.fields, strict=True)): + if series.dtype != object or not _reads_through_the_schema(field.dataType): + continue + if _column_conforms(series, field.dataType): + continue + values = [_value_through_the_schema(value, field.dataType) for value in series] + frame.isetitem(position, type(series)(values, index=series.index, dtype=object, name=name)) + return frame + + def _verify_pandas_values(data: "PandasDataFrame", schema: StructType) -> None: """Raise where Spark rejects a value of ``data`` for ``schema``, which it reads through the rows of ``data``. @@ -191,10 +284,17 @@ def _inferSchemaFromList(self, data: list[Any], names: list[str] | None = None) return schema def _createDataFrameFromPandas( - self, data: "PandasDataFrame", types: list[str] | None, names: list[str] | None + self, data: "PandasDataFrame", schema: StructType | None, names: list[str] | None ) -> DataFrame: unique_name = f"pyspark_pandas_df_{uuid.uuid1()}" - self.conn.register(unique_name, data) + types = None + if schema is not None: + types, names = schema.extract_types_and_names() + if schema is not None and len(schema.fields) == len(data.columns): + frame = _frame_through_the_schema(data, schema) + self.conn._register_declared(unique_name, frame, [field.dataType.duckdb_type for field in schema.fields]) + else: + self.conn.register(unique_name, data) df = DataFrame(self.conn.sql(f'select * from "{unique_name}"'), self) # Cast to types @@ -243,8 +343,7 @@ def createDataFrame( # noqa: D102 if isinstance(schema, StructType): if verifySchema: _verify_pandas_values(data, schema) - types, names = schema.extract_types_and_names() - return self._createDataFrameFromPandas(data, types, names) + return self._createDataFrameFromPandas(data, schema, None) if isinstance(schema, DataType): msg = "A pandas DataFrame with a schema that is not a StructType is not supported" raise ContributionsAcceptedError(msg) diff --git a/src/include/duckdb_python/numpy/numpy_scan.hpp b/src/include/duckdb_python/numpy/numpy_scan.hpp index 9cf4c0e82..2fdd8410a 100644 --- a/src/include/duckdb_python/numpy/numpy_scan.hpp +++ b/src/include/duckdb_python/numpy/numpy_scan.hpp @@ -12,6 +12,9 @@ struct NumpyScan { //! masked holds one numpy bool per row of the whole column, read as a byte, or is null when the column has no mask static void ScanObjectColumn(ClientContext &context, PyObject **col, idx_t stride, const uint8_t *masked, idx_t count, idx_t offset, Vector &out); + //! Converts each cell into the declared type of the column as the appender converts a value + static void ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t stride, const uint8_t *masked, + idx_t count, idx_t offset, Vector &out); }; } // namespace duckdb diff --git a/src/include/duckdb_python/pandas/pandas_bind.hpp b/src/include/duckdb_python/pandas/pandas_bind.hpp index 12ed21b8b..7a9fce9c0 100644 --- a/src/include/duckdb_python/pandas/pandas_bind.hpp +++ b/src/include/duckdb_python/pandas/pandas_bind.hpp @@ -38,12 +38,15 @@ struct PandasColumnBindData { string internal_categorical_type; //! Hold ownership of objects created during scanning PythonObjectContainer object_str_val; + //! The caller declared the column's type: each value converts into it as the appender converts a row + bool declared = false; }; struct Pandas { - //! Returns the frame's row count + //! Returns the frame's row count; declared_types, when given, hold one type per column, INVALID where none static idx_t Bind(ClientContext &config, nb::handle df, vector &out, - vector &return_types, vector &names); + vector &return_types, vector &names, + const vector &declared_types = {}); }; } // namespace duckdb diff --git a/src/include/duckdb_python/pandas/pandas_scan.hpp b/src/include/duckdb_python/pandas/pandas_scan.hpp index 8465acfcd..4c1edcaaa 100644 --- a/src/include/duckdb_python/pandas/pandas_scan.hpp +++ b/src/include/duckdb_python/pandas/pandas_scan.hpp @@ -19,9 +19,12 @@ namespace duckdb { //! Carried through the bind input so that SQL text can never name the dataframe struct PandasScanInfo : public TableFunctionInfo { - explicit PandasScanInfo(nb::object df_p) : df(std::move(df_p)) { + explicit PandasScanInfo(nb::object df_p, vector declared_types_p = {}) + : df(std::move(df_p)), declared_types(std::move(declared_types_p)) { } PyObjectHolder df; + //! One type per frame column the caller declared, read by every bind of a copy of the reference, so never changed + const vector declared_types; }; struct PandasScanFunction : public TableFunction { diff --git a/src/include/duckdb_python/pyconnection/pyconnection.hpp b/src/include/duckdb_python/pyconnection/pyconnection.hpp index eb7c71ca9..00ad18ceb 100644 --- a/src/include/duckdb_python/pyconnection/pyconnection.hpp +++ b/src/include/duckdb_python/pyconnection/pyconnection.hpp @@ -388,6 +388,10 @@ struct DuckDBPyConnection : public std::enable_shared_from_this &source); std::shared_ptr RegisterPythonObject(const string &name, const nb::object &python_object); + //! Registers a pandas DataFrame whose object columns take the given types, one per column in frame order, in place + //! of a type sampled from the values; None declares no type for that column + std::shared_ptr RegisterDeclared(const string &name, const PandasDataFrame &df, + const nb::list &types); std::shared_ptr RegisterArrowSource(const string &name, const nb::object &source); void InstallExtension(const string &extension, bool force_install = false, diff --git a/src/include/duckdb_python/pyconnection/seam.hpp b/src/include/duckdb_python/pyconnection/seam.hpp index 3cbb6ac5c..2ea8e1de5 100644 --- a/src/include/duckdb_python/pyconnection/seam.hpp +++ b/src/include/duckdb_python/pyconnection/seam.hpp @@ -72,7 +72,10 @@ struct DuckDBPySeam { static void InitializeConnectionMethods(nb::class_ &connection); //! Registers obj under a generated name; subject names the object in errors, an empty one makes it nameless static std::shared_ptr RegisterSource(DuckDBPyConnection &connection, const nb::object &obj, - const string &subject); + const string &subject, vector declared_types = {}); + //! The name and type of each column a value can be inserted into, of the table the name resolves to as one + //! identifier; empty when no table has the name + static vector> InsertableColumns(DuckDBPyConnection &connection, const string &name); //! Registers a table reference built in C++ under a generated name static std::shared_ptr RegisterTableRef(ClientContext &context, unique_ptr table, const string &subject); diff --git a/src/include/duckdb_python/python_replacement_scan.hpp b/src/include/duckdb_python/python_replacement_scan.hpp index a84522be2..f4f472497 100644 --- a/src/include/duckdb_python/python_replacement_scan.hpp +++ b/src/include/duckdb_python/python_replacement_scan.hpp @@ -22,10 +22,13 @@ struct PythonReplacementScan { //! from_arrow (NAMELESS) reads a pyarrow MessageReader static unique_ptr TryReplacementObject(const nb::object &entry, const string &name, ClientContext &context, - ArrowSourceKind kind = ArrowSourceKind::REGISTERED); - //! Perform a replacement or throw if it failed + ArrowSourceKind kind = ArrowSourceKind::REGISTERED, + vector declared_types = {}); + //! Perform a replacement or throw if it failed; declared_types, one per column of a pandas DataFrame, make + //! its object columns convert into those types instead of a type sampled from their values static unique_ptr ReplacementObject(const nb::object &entry, const string &name, ClientContext &context, - ArrowSourceKind kind = ArrowSourceKind::REGISTERED); + ArrowSourceKind kind = ArrowSourceKind::REGISTERED, + vector declared_types = {}); }; } // namespace duckdb diff --git a/src/numpy/numpy_scan.cpp b/src/numpy/numpy_scan.cpp index aac3fdb29..afaa3d07f 100644 --- a/src/numpy/numpy_scan.cpp +++ b/src/numpy/numpy_scan.cpp @@ -6,6 +6,8 @@ #include "duckdb/common/swar.hpp" #include "duckdb/common/types/timestamp.hpp" #include "duckdb/common/vector/struct_vector.hpp" +#include "duckdb/common/vector/list_vector.hpp" +#include "duckdb/common/vector/array_vector.hpp" #include "duckdb/common/vector/map_vector.hpp" #include "duckdb/common/case_insensitive_map.hpp" #include "duckdb_python/pandas/pandas_bind.hpp" @@ -17,6 +19,10 @@ #include "duckdb_python/exceptions.hpp" #include "duckdb_python/numpy/numpy_array.hpp" #include "duckdb_python/pandas/column/pandas_numpy_column.hpp" +#include "duckdb/function/cast/cast_function_set.hpp" +#include "duckdb/function/cast/default_casts.hpp" +#include "duckdb/common/vector_operations/vector_operations.hpp" +#include "duckdb_python/staged_rows.hpp" namespace duckdb { @@ -214,21 +220,198 @@ static void VerifyMapConstraints(Vector &vec, idx_t count) { } } +//! A MAP's keys must be unique at every depth; a cast of a STRUCT into a MAP, as of a dict whose keys collapse into +//! one key, does not check them void VerifyTypeConstraints(Vector &vec, idx_t count) { - switch (vec.GetType().id()) { - case LogicalTypeId::MAP: { + auto &type = vec.GetType(); + if (type.id() == LogicalTypeId::MAP) { VerifyMapConstraints(vec, count); - break; } + switch (type.InternalType()) { + case PhysicalType::LIST: + VerifyTypeConstraints(ListVector::GetEntry(vec), ListVector::GetListSize(vec)); + break; + case PhysicalType::ARRAY: + VerifyTypeConstraints(ArrayVector::GetEntry(vec), count * ArrayType::GetSize(type)); + break; + case PhysicalType::STRUCT: + for (auto &child : StructVector::GetEntries(vec)) { + VerifyTypeConstraints(child, count); + } + break; default: - return; + break; + } +} + +//! The casts one declared column needs, looked up once per source type for the vector, since the lookup costs more +//! than casting one value. The cache is bounded: dicts give a STRUCT type per key set, and past the bound a lookup +//! per value beats a search through them. +class DeclaredCasts { +public: + DeclaredCasts(ClientContext &context, const LogicalType &target) + : context(context), target(target), set(CastFunctionSet::Get(context)), get_input(context) { + } + + Value Cast(const Value &value) { + if (value.type() == target) { + return value; + } + auto cast = For(value.type()); + if (!cast) { + return CastToColumn(context, value, target); + } + Vector input(value, count_t(1)); + Vector result(target, 1); + // Without an error string the cast raises its own exception, as the appender's cast does + CastParameters parameters(cast->function.GetCastData().get(), false, nullptr, cast->local_state.get()); + cast->function.Cast(input, result, 1, parameters); + return result.GetValue(0); + } + +private: + static constexpr idx_t CACHED_SOURCE_TYPES = 16; + + struct Entry { + LogicalType source; + BoundCastInfo function; + unique_ptr local_state; + }; + + optional_ptr For(const LogicalType &source) { + for (auto &entry : casts) { + if (entry.source == source) { + return &entry; + } + } + if (casts.size() >= CACHED_SOURCE_TYPES) { + return nullptr; + } + Entry entry {source, set.GetCastFunction(source, target, get_input), nullptr}; + if (entry.function.HasInitLocalState()) { + CastLocalStateParameters parameters(get_input.context, entry.function.GetCastData()); + entry.local_state = entry.function.InitLocalState(parameters); + } + casts.push_back(std::move(entry)); + return &casts.back(); + } + + ClientContext &context; + const LogicalType ⌖ + CastFunctionSet &set; + GetCastFunctionInput get_input; + vector casts; +}; + +//! A declared column converts a cell as the appender converts a value of a row: with the type the value has in +//! Python, then the engine's cast into the column's type, which reads the connection's settings; NaN reads NULL at +//! every depth, and a value without a DuckDB type of its own reads as its text in a text column +//! A numpy scalar reads as its Python value; a datetime64 or timedelta64 at nanoseconds would read as an integer, +//! so those take the microsecond unit first, as the frame's own datetime columns do +static nb::object NumpyScalarValue(nb::handle scalar) { + auto kind = nb::cast(scalar.attr("dtype").attr("kind")); + if (kind == "M") { + return scalar.attr("astype")("datetime64[us]").attr("item")(); } + if (kind == "m") { + return scalar.attr("astype")("timedelta64[us]").attr("item")(); + } + return scalar.attr("item")(); +} + +static Value DeclaredValue(ClientContext &context, const LogicalType &target, nb::handle cell) { + if (cell.ptr() == Py_None) { + return Value(); + } + auto &import_cache = *DuckDBPyConnection::ImportCache(); + if (nb::isinstance(cell, import_cache.numpy.generic())) { + auto value = NumpyScalarValue(cell); + return DeclaredValue(context, target, value); + } + if (target.id() == LogicalTypeId::VARCHAR && GetPythonObjectType(cell) == PythonObjectType::Other) { + return Value(TransformPythonString(nb::str(cell))); + } + return TransformPythonValue(context, cell, LogicalType::UNKNOWN, true); } +//! The values of one vector of a declared column, written once the cells are read: a vector whose values share one +//! type is cast by the engine in one call, which costs a fraction of a cast per value. Only the values present +//! enter the cast and its result is copied into the output, so a NULL row never meets a cast that would give it a +//! shape of its own (a UNION member that is NULL), and the output owns every string the cast produced. +class DeclaredVector { +public: + explicit DeclaredVector(idx_t count) : values(count), source(LogicalTypeId::SQLNULL) { + } + + void Set(idx_t row, Value value) { + if (value.IsNull()) { + return; + } + if (source.id() == LogicalTypeId::SQLNULL) { + source = value.type(); + } else if (uniform && value.type() != source) { + uniform = false; + } + values[row] = std::move(value); + } + + void Write(ClientContext &context, Vector &out, idx_t count) { + auto &target = out.GetType(); + if (uniform && source.id() != LogicalTypeId::SQLNULL && source != target) { + idx_t present = 0; + for (idx_t row = 0; row < count; row++) { + present += !values[row].IsNull(); + } + Vector staged(source, present); + idx_t staged_row = 0; + for (idx_t row = 0; row < count; row++) { + if (!values[row].IsNull()) { + staged.SetValue(staged_row++, values[row]); + } + } + // A vector built with a capacity has no rows, and the fallback cast reads the row count to decide whether + // any value is present + FlatVector::SetSize(staged, present); + Vector casted(target, present); + // Without an error string the cast raises its own exception, as the appender's cast does + VectorOperations::TryCast(context, staged, casted, present, nullptr); + idx_t copied = 0; + for (idx_t row = 0; row < count;) { + if (values[row].IsNull()) { + FlatVector::SetNull(out, row, true); + row++; + continue; + } + idx_t run = 1; + while (row + run < count && !values[row + run].IsNull()) { + run++; + } + VectorOperations::Copy(casted, out, copied + run, copied, row); + copied += run; + row += run; + } + return; + } + DeclaredCasts casts(context, target); + for (idx_t row = 0; row < count; row++) { + if (values[row].IsNull()) { + FlatVector::SetNull(out, row, true); + } else { + out.SetValue(row, casts.Cast(values[row])); + } + } + } + +private: + vector values; + LogicalType source; + bool uniform = true; +}; + // A column without a mask takes the instantiation that tests no mask bits, so it reads like the plain array -template -static void ScanObjectRows(ClientContext &context, PyObject **col, idx_t stride, const uint8_t *masked, idx_t count, - idx_t offset, Vector &out) { +template +static void ScanObjectRows(PyObject **col, idx_t stride, const uint8_t *masked, idx_t count, idx_t offset, Vector &out, + CONVERT &&convert) { for (idx_t block_row = 0; block_row < count; block_row += MASK_BLOCK_ROWS) { auto block_end = MinValue(block_row + MASK_BLOCK_ROWS, count); // A masked cell can hold a value of another type, or no object at all @@ -239,26 +422,43 @@ static void ScanObjectRows(ClientContext &context, PyObject **col, idx_t stride, } // Converting can run Python, which lets another thread replace the cell and free the object it held auto cell = nb::borrow(col[stride / sizeof(PyObject *) * (i + offset)]); - ScanNumpyObject(context, cell.ptr(), i, out); + convert(cell, i); } } } -void NumpyScan::ScanObjectColumn(ClientContext &context, PyObject **col, idx_t stride, const uint8_t *masked, - idx_t count, idx_t offset, Vector &out) { +template +static void ScanObjectCells(ClientContext &context, PyObject **col, idx_t stride, const uint8_t *masked, idx_t count, + idx_t offset, Vector &out, CONVERT &&convert) { // numpy_col is a sequential list of objects, that make up one "column" (Vector) out.SetVectorType(VectorType::FLAT_VECTOR); PyUtil::QueryGil gil(context); // We're creating python objects here, so we need the GIL try { if (masked) { - ScanObjectRows(context, col, stride, masked, count, offset, out); + ScanObjectRows(col, stride, masked, count, offset, out, convert); } else { - ScanObjectRows(context, col, stride, masked, count, offset, out); + ScanObjectRows(col, stride, masked, count, offset, out, convert); } } catch (nb::python_error &error) { throw AsDuckDBError(error); } +} + +void NumpyScan::ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t stride, const uint8_t *masked, + idx_t count, idx_t offset, Vector &out) { + DeclaredVector staged(count); + auto &target = out.GetType(); + ScanObjectCells(context, col, stride, masked, count, offset, out, + [&](nb::handle cell, idx_t row) { staged.Set(row, DeclaredValue(context, target, cell)); }); + staged.Write(context, out, count); + VerifyTypeConstraints(out, count); +} + +void NumpyScan::ScanObjectColumn(ClientContext &context, PyObject **col, idx_t stride, const uint8_t *masked, + idx_t count, idx_t offset, Vector &out) { + ScanObjectCells(context, col, stride, masked, count, offset, out, + [&](nb::handle cell, idx_t row) { ScanNumpyObject(context, cell.ptr(), row, out); }); VerifyTypeConstraints(out, count); } @@ -526,6 +726,10 @@ void NumpyScan::Scan(ClientContext &context, PandasColumnBindData &bind_data, id // Get the source pointer of the numpy array auto src_ptr = (PyObject **)array.Data(); // NOLINT const bool is_object_col = bind_data.numpy_type.type == NumpyNullableType::OBJECT; + if (is_object_col && bind_data.declared) { + return NumpyScan::ScanDeclaredColumn(context, src_ptr, numpy_col.stride, MaskedRows(bind_data), count, + offset, out); + } if (is_object_col && out.GetType().id() != LogicalTypeId::VARCHAR) { //! We have determined the underlying logical type of this object column return NumpyScan::ScanObjectColumn(context, src_ptr, numpy_col.stride, MaskedRows(bind_data), count, offset, diff --git a/src/pandas/bind.cpp b/src/pandas/bind.cpp index e0aab3489..73b202055 100644 --- a/src/pandas/bind.cpp +++ b/src/pandas/bind.cpp @@ -120,7 +120,7 @@ std::unique_ptr RegisterMask(nb::handle mask) { } static LogicalType BindColumn(ClientContext &context, PandasBindColumn &column_p, PandasColumnBindData &bind_data, - idx_t row_count) { + idx_t row_count, const LogicalType &declared_type) { const string counted_from = "the frame"; LogicalType column_type; auto &column = column_p.handle; @@ -206,11 +206,15 @@ static LogicalType BindColumn(ClientContext &context, PandasBindColumn &column_p } CheckColumnArray(bind_data.name, data, row_count, counted_from); auto numpy_column = std::make_unique(NumpyArray(std::move(data))); - // Analyze the inner data type of the 'object' column if (bind_data.numpy_type.type == NumpyNullableType::OBJECT) { - PandasAnalyzer analyzer(context); - if (analyzer.Analyze(*numpy_column, row_count, bind_data.mask.get())) { - column_type = analyzer.AnalyzedType(); + if (declared_type.id() != LogicalTypeId::INVALID) { + bind_data.declared = true; + column_type = declared_type; + } else { + PandasAnalyzer analyzer(context); + if (analyzer.Analyze(*numpy_column, row_count, bind_data.mask.get())) { + column_type = analyzer.AnalyzedType(); + } } } bind_data.pandas_col = std::move(numpy_column); @@ -218,13 +222,18 @@ static LogicalType BindColumn(ClientContext &context, PandasBindColumn &column_p } idx_t Pandas::Bind(ClientContext &context, nb::handle df_p, vector &bind_columns, - vector &return_types, vector &names) { + vector &return_types, vector &names, + const vector &declared_types) { PandasDataFrameBind df(df_p); idx_t column_count = nb::len(df.names); if (column_count == 0) { throw InvalidInputException("Need a DataFrame with at least one column"); } + if (!declared_types.empty() && declared_types.size() != column_count) { + throw InternalException("declared types: %d types for a DataFrame of %d columns", declared_types.size(), + column_count); + } idx_t row_count = nb::len(nb::object(df_p.attr("index"))); auto column_names = ColumnNamesFromLabels(df.names); @@ -247,7 +256,8 @@ idx_t Pandas::Bind(ClientContext &context, nb::handle df_p, vector PandasScanFunction::PandasScanBind(ClientContext &conte if (nb::isinstance(df)) { row_count = NumpyBind::Bind(context, df, pandas_bind_data, return_types, names); } else { - row_count = Pandas::Bind(context, df, pandas_bind_data, return_types, names); + row_count = Pandas::Bind(context, df, pandas_bind_data, return_types, names, info->declared_types); } return make_uniq(std::move(info), row_count, std::move(pandas_bind_data), return_types); } diff --git a/src/pyconnection.cpp b/src/pyconnection.cpp index 6ff11149f..b6704efaf 100644 --- a/src/pyconnection.cpp +++ b/src/pyconnection.cpp @@ -328,6 +328,10 @@ static void InitializeConnectionMethods(nb::class_ &m) { "Synchronizes data in the write-ahead log (WAL) to the database data file (no-op for in-memory connections)"); m.def("append", &DuckDBPyConnection::Append, "Append the passed DataFrame to the named table", nb::arg("table_name"), nb::arg("df"), nb::kw_only(), nb::arg("by_name") = false); + m.def("_register_declared", &DuckDBPyConnection::RegisterDeclared, + "Register a DataFrame as a view whose object columns take the given types instead of types sampled from the " + "values", + nb::arg("view_name"), nb::arg("df"), nb::arg("types")); m.def( "appender", &DuckDBPyConnection::CreateAppender, "Create an appender that buffers rows and inserts, upserts, updates or deletes them in the named table at each " @@ -923,16 +927,45 @@ std::unique_ptr DuckDBPyConnection::CreateQueryAppender(const return DuckDBPyAppender::ForQuery(shared_from_this(), dml, columns, source); } +//! The table column each frame column is inserted into: by position over the insertable columns, or by the name +//! the INSERT matches, as an identifier; a frame column without a table column stays undeclared and the INSERT +//! reports the mismatch +static vector AppendTargetTypes(const vector> &table_columns, + const vector &frame_columns, bool by_name) { + vector types(frame_columns.size(), LogicalType::INVALID); + for (idx_t i = 0; i < frame_columns.size(); i++) { + if (!by_name) { + if (i < table_columns.size()) { + types[i] = table_columns[i].second; + } + continue; + } + for (auto &column : table_columns) { + if (Identifier(column.first) == Identifier(frame_columns[i])) { + types[i] = column.second; + break; + } + } + } + return types; +} + std::shared_ptr DuckDBPyConnection::Append(const string &name, const PandasDataFrame &value, bool by_name) { - RegisterPythonObject("__append_df", value); + vector column_names; + for (auto column : value.attr("columns")) { + column_names.push_back(nb::cast(nb::str(column))); + } + vector declared_types; + auto table_columns = DuckDBPySeam::InsertableColumns(*this, name); + if (!table_columns.empty()) { + declared_types = AppendTargetTypes(table_columns, column_names, by_name); + } + con.GetConnection(); + auto source = DuckDBPySeam::RegisterSource(*this, value, "__append_df", std::move(declared_types)); + RegisterSourceView("__append_df", *source); string columns = ""; if (by_name) { - auto df_columns = value.attr("columns"); - vector column_names; - for (auto column : df_columns) { - column_names.push_back(nb::cast(nb::str(column))); - } columns += "("; for (idx_t i = 0; i < column_names.size(); i++) { auto &column = column_names[i]; @@ -990,6 +1023,27 @@ std::shared_ptr DuckDBPyConnection::RegisterPythonObject(con return shared_from_this(); } +std::shared_ptr DuckDBPyConnection::RegisterDeclared(const string &name, const PandasDataFrame &df, + const nb::list &types) { + nb::object columns = df.attr("columns"); + if (nb::len(types) != nb::len(columns)) { + throw InvalidInputException("declared types: %d types given for a DataFrame of %d columns", nb::len(types), + nb::len(columns)); + } + vector declared_types; + for (auto type : types) { + if (type.is_none()) { + declared_types.push_back(LogicalType::INVALID); + } else { + declared_types.push_back(nb::cast(type).Type()); + } + } + con.GetConnection(); + auto source = DuckDBPySeam::RegisterSource(*this, df, name, std::move(declared_types)); + RegisterSourceView(name, *source); + return shared_from_this(); +} + std::shared_ptr DuckDBPyConnection::RegisterArrowSource(const string &name, const nb::object &source) { auto &client = *con.GetConnection().context; diff --git a/src/pyconnection/seam.cpp b/src/pyconnection/seam.cpp index a6f8fd43d..0e6e0d038 100644 --- a/src/pyconnection/seam.cpp +++ b/src/pyconnection/seam.cpp @@ -2,6 +2,7 @@ #include "duckdb/catalog/catalog.hpp" #include "duckdb/catalog/catalog_entry.hpp" +#include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/view_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry_retriever.hpp" #include "duckdb/catalog/entry_lookup_info.hpp" @@ -758,7 +759,7 @@ static bool ReadOnce(const nb::handle &obj) { } std::shared_ptr DuckDBPySeam::RegisterSource(DuckDBPyConnection &self, const nb::object &obj, - const string &subject) { + const string &subject, vector declared_types) { auto &context = *OpenConnection(self).context; if (!self.source_identity) { self.source_identity = std::make_shared(); @@ -777,7 +778,8 @@ std::shared_ptr DuckDBPySeam::RegisterSource(DuckDBPyConnection &s { // Classifying and adapting the object runs its own Python, which must not close or use this connection engine::ConnectionClaim claim(context); - table = PythonReplacementScan::ReplacementObject(obj, subject.empty() ? "source" : subject, context, kind); + table = PythonReplacementScan::ReplacementObject(obj, subject.empty() ? "source" : subject, context, kind, + std::move(declared_types)); } auto handle = RegisterTable(context, std::move(table), subject); if (once) { @@ -832,6 +834,31 @@ static string TableKind(DuckDBPyConnection &self, const nb::object &name) { return kind; } +vector> DuckDBPySeam::InsertableColumns(DuckDBPyConnection &self, const string &name) { + auto session = OpenSession(self); + auto &context = session.Context(); + DUCKDB_PY_ASSERT_GIL_HELD(); + nb::gil_scoped_release release; + auto claim = session.Claim(); + vector> columns; + // The same lookup an INSERT INTO binds through, so the temporary schema and the search path shadow as they do there + context.RunFunctionInTransaction([&]() { + CatalogEntryRetriever retriever(context); + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, + Binder::BindTableName(retriever, QualifiedName(Identifier(name)))); + auto entry = Catalog::GetEntry(context, lookup, OnEntryNotFound::RETURN_NULL); + if (!entry || entry->type != CatalogType::TABLE_ENTRY) { + return; + } + for (auto &column : entry->Cast().GetColumns().Logical()) { + if (!column.Generated()) { + columns.emplace_back(column.Name(), column.Type()); + } + } + }); + return columns; +} + //! Mirrors Binder::BindSchemaOrCatalog: a lone qualifier is a database's name when one has it, a schema otherwise static string NameScope(DuckDBPyConnection &self, const string &name) { // The session owns the context, as in TableKind diff --git a/src/python_replacement_scan.cpp b/src/python_replacement_scan.cpp index 10db51222..9fd7a180e 100644 --- a/src/python_replacement_scan.cpp +++ b/src/python_replacement_scan.cpp @@ -221,8 +221,9 @@ static unique_ptr PythonRelationRef(ClientContext &context, const nb:: } unique_ptr PythonReplacementScan::ReplacementObject(const nb::object &entry, const string &name, - ClientContext &context, ArrowSourceKind kind) { - auto replacement = TryReplacementObject(entry, name, context, kind); + ClientContext &context, ArrowSourceKind kind, + vector declared_types) { + auto replacement = TryReplacementObject(entry, name, context, kind, std::move(declared_types)); if (!replacement) { ThrowScanFailureError(entry, name); } @@ -230,7 +231,7 @@ unique_ptr PythonReplacementScan::ReplacementObject(const nb::object & } static unique_ptr ReplacementFor(const nb::object &entry, const string &name, ClientContext &context, - ArrowSourceKind kind) { + ArrowSourceKind kind, vector declared_types = {}) { auto table_function = make_uniq(); vector> children; NumpyObjectType numpytype; @@ -241,7 +242,7 @@ static unique_ptr ReplacementFor(const nb::object &entry, const string string name = "df_" + StringUtil::GenerateRandomName(); auto new_df = PandasScanFunction::PandasReplaceCopiedNames(entry); table_function->function = make_uniq("pandas_scan", std::move(children)); - table_function->bind_info = make_shared_ptr(std::move(new_df)); + table_function->bind_info = make_shared_ptr(std::move(new_df), std::move(declared_types)); auto dependency = make_uniq(); dependency->AddDependency("replacement_cache", PythonDependencyItem::Create(entry)); table_function->external_dependency = std::move(dependency); @@ -315,8 +316,9 @@ static unique_ptr ReplacementFor(const nb::object &entry, const string } unique_ptr PythonReplacementScan::TryReplacementObject(const nb::object &entry, const string &name, - ClientContext &context, ArrowSourceKind kind) { - return ReplacementFor(entry, name, context, kind); + ClientContext &context, ArrowSourceKind kind, + vector declared_types) { + return ReplacementFor(entry, name, context, kind, std::move(declared_types)); } static bool IsBuiltinFunction(const nb::object &object) { diff --git a/tests/fast/pandas/test_append_df.py b/tests/fast/pandas/test_append_df.py index 1a98abca0..da6dbcb23 100644 --- a/tests/fast/pandas/test_append_df.py +++ b/tests/fast/pandas/test_append_df.py @@ -82,6 +82,8 @@ def test_append_by_name_no_exact_match(self): NAIVE = datetime.datetime(2024, 5, 7, 7, 8, 9) AWARE = NAIVE.replace(tzinfo=P2) PATH = pathlib.PurePosixPath("/x") +LABEL = "a label longer than a string the engine keeps inline" +ENUM_VALUE = duckdb.Value(LABEL, f"ENUM('{LABEL}')") class _Color(enum.Enum): @@ -109,10 +111,6 @@ def _append_rows(con, table, values): appender.append_row(value) -NOT_YET_DECLARED = "the object column is typed from its sample, not from the table column" -CONVERTED_BY_THE_SCAN = "a value of an object column converts by the scan's own rules, not as the appender converts it" - - class TestAppendObjectColumnsToDeclaredTypes: @pytest.mark.parametrize( ("target", "column", "expected_first", "expected_last"), @@ -123,7 +121,6 @@ class TestAppendObjectColumnsToDeclaredTypes: 1.0, 2.5, id="int_sample_float_into_double", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "DECIMAL(10,2)", @@ -131,7 +128,6 @@ class TestAppendObjectColumnsToDeclaredTypes: Decimal("1.50"), Decimal("1.25"), id="narrow_decimal_sample_into_wider_decimal", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "TIMESTAMP", @@ -139,7 +135,6 @@ class TestAppendObjectColumnsToDeclaredTypes: datetime.datetime(2024, 5, 6), NAIVE, id="date_sample_datetime_into_timestamp", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "VARCHAR", @@ -147,7 +142,6 @@ class TestAppendObjectColumnsToDeclaredTypes: "1", "2.5", id="int_sample_float_into_varchar", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "VARCHAR", @@ -155,7 +149,6 @@ class TestAppendObjectColumnsToDeclaredTypes: "1", "x", id="int_sample_str_into_varchar", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "VARCHAR", @@ -163,7 +156,6 @@ class TestAppendObjectColumnsToDeclaredTypes: "1", "2.5", id="fully_sampled_int_and_float_into_varchar", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "VARCHAR", @@ -171,7 +163,6 @@ class TestAppendObjectColumnsToDeclaredTypes: "a", "ab", id="str_sample_bytes_into_varchar", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "VARCHAR", _outside_the_sample("a", PATH), "a", str(PATH), id="path_into_varchar_reads_as_its_text" @@ -203,7 +194,6 @@ class TestAppendObjectColumnsToDeclaredTypes: 1, 2**40, id="small_int_sample_large_int_into_bigint", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "UBIGINT", @@ -211,7 +201,6 @@ class TestAppendObjectColumnsToDeclaredTypes: 1, 2**63, id="int_past_the_signed_range_into_ubigint", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "HUGEINT", @@ -219,7 +208,6 @@ class TestAppendObjectColumnsToDeclaredTypes: 1, 2**70, id="int_past_64_bits_into_hugeint", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "DOUBLE", @@ -227,7 +215,6 @@ class TestAppendObjectColumnsToDeclaredTypes: 1.0, float(2**70), id="int_past_64_bits_into_double", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "UNION(i INTEGER, s VARCHAR)", @@ -235,7 +222,6 @@ class TestAppendObjectColumnsToDeclaredTypes: 1, "x", id="int_sample_str_into_union", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "MAP(VARCHAR, INTEGER)", @@ -243,7 +229,6 @@ class TestAppendObjectColumnsToDeclaredTypes: {"a": 1}, {"b": 2}, id="dict_with_other_key_into_map", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "JSON", @@ -251,7 +236,6 @@ class TestAppendObjectColumnsToDeclaredTypes: "1", '{"a":1}', id="int_sample_dict_into_json", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "INTEGER", @@ -259,7 +243,6 @@ class TestAppendObjectColumnsToDeclaredTypes: 1, 1, id="int_sample_bool_into_integer", - marks=pytest.mark.xfail(strict=True, reason=CONVERTED_BY_THE_SCAN), ), pytest.param( "DOUBLE", @@ -267,7 +250,6 @@ class TestAppendObjectColumnsToDeclaredTypes: 1.0, 1.0, id="int_sample_bool_into_double", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param("BOOLEAN", _outside_the_sample(True, 1), True, True, id="bool_sample_int_into_boolean"), pytest.param( @@ -278,6 +260,41 @@ class TestAppendObjectColumnsToDeclaredTypes: id="lists_into_array", ), pytest.param("DOUBLE", _outside_the_sample(1.5, float("nan")), 1.5, None, id="nan_into_double_is_null"), + pytest.param("DOUBLE", _outside_the_sample(1.5, None), 1.5, None, id="none_into_double_is_null"), + pytest.param("INTEGER", _outside_the_sample(1, np.int64(2)), 1, 2, id="numpy_int_into_integer"), + pytest.param("DOUBLE", _outside_the_sample(1.5, np.float32(2.5)), 1.5, 2.5, id="numpy_float_into_double"), + pytest.param( + "BOOLEAN", _outside_the_sample(True, np.bool_(False)), True, False, id="numpy_bool_into_boolean" + ), + pytest.param( + "TIMESTAMP", + _outside_the_sample(NAIVE, np.datetime64("2024-05-08T01:02:03.123456789", "ns")), + NAIVE, + datetime.datetime(2024, 5, 8, 1, 2, 3, 123456), + id="numpy_datetime_into_timestamp", + ), + pytest.param( + "STRUCT(x VARCHAR)", + _outside_the_sample({"x": "abc"}, None), + {"x": "abc"}, + None, + id="none_into_struct_of_text_is_null", + ), + pytest.param( + "STRUCT(x UNION(i INTEGER, s VARCHAR))", + _outside_the_sample({"x": 1}, None), + {"x": 1}, + None, + id="none_into_struct_of_union_is_null", + ), + pytest.param( + "VARCHAR", + pd.Series([ENUM_VALUE] * ROWS, dtype=object), + LABEL, + LABEL, + id="enum_values_into_varchar_keep_their_text", + ), + pytest.param("DOUBLE", _outside_the_sample(1.5, pd.NA), 1.5, None, id="pandas_na_into_double_is_null"), pytest.param("VARCHAR", _outside_the_sample("a", float("nan")), "a", None, id="nan_into_varchar_is_null"), pytest.param("INTEGER", _outside_the_sample(1, float("nan")), 1, None, id="nan_into_integer_is_null"), pytest.param( @@ -314,7 +331,6 @@ class TestAppendObjectColumnsToDeclaredTypes: "a", None, id="datetime64_nat_into_varchar_is_null", - marks=pytest.mark.xfail(strict=True, reason=CONVERTED_BY_THE_SCAN), ), ], ) @@ -334,47 +350,42 @@ def test_object_value_converts_into_the_table_column_type( _outside_the_sample(1, "x"), "Malformed JSON", id="text_that_is_not_json", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "INTEGER", _outside_the_sample(1, "x"), "'x'", id="text_into_integer", - marks=pytest.mark.xfail(strict=True, reason=CONVERTED_BY_THE_SCAN), ), pytest.param( "INTEGER", _outside_the_sample(1, 2**40), "1099511627776", id="int_out_of_range", - marks=pytest.mark.xfail(strict=True, reason=CONVERTED_BY_THE_SCAN), ), pytest.param( "FLOAT", _outside_the_sample(1, 1e300), "out of range", id="float_out_of_range", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "STRUCT(x INTEGER)", _outside_the_sample({"x": 1}, (2,)), "STRUCT", id="tuple_into_struct", - marks=pytest.mark.xfail(strict=True, reason=CONVERTED_BY_THE_SCAN), ), pytest.param( "TIME", _outside_the_sample(datetime.time(1, 2, 3), AWARE), "TIME", id="aware_datetime_into_time", - marks=pytest.mark.xfail(strict=True, reason=CONVERTED_BY_THE_SCAN), ), pytest.param("ENUM('a', 'b')", _outside_the_sample("a", "c"), "'c'", id="text_outside_the_enum"), pytest.param("INTEGER", pd.Series(["duck", "db"], dtype=object), "'duck'", id="text_column_into_integer"), pytest.param("UTINYINT", _outside_the_sample(1, -1), "out of range", id="negative_int_into_utinyint"), pytest.param("TINYINT", _outside_the_sample(1, 200), "out of range", id="int_out_of_tinyint_range"), + pytest.param("DATE", _outside_the_sample(1, 2), "DATE", id="int_column_into_date"), ], ) def test_object_value_the_table_column_type_refuses(self, duckdb_cursor, target, column, match): @@ -383,6 +394,45 @@ def test_object_value_the_table_column_type_refuses(self, duckdb_cursor, target, with pytest.raises(duckdb.ConversionException, match=match): duckdb_cursor.append("t", frame) + def test_keys_that_collapse_in_a_nested_map_are_refused(self, duckdb_cursor): + duckdb_cursor.execute("CREATE TABLE t (a STRUCT(m MAP(INTEGER, INTEGER)))") + # The same key set in every row, so one cast runs over the whole vector + frame = pd.DataFrame({"a": _outside_the_sample({"m": {"01": 1, "1": 2}}, {"m": {"01": 10, "1": 20}})}) + with pytest.raises(duckdb.InvalidInputException, match=r"(?i)duplicat|unique"): + duckdb_cursor.append("t", frame) + + def test_text_with_a_lone_surrogate_names_it(self, duckdb_cursor): + duckdb_cursor.execute("CREATE TABLE t (a VARCHAR)") + frame = pd.DataFrame({"a": _outside_the_sample("a", pathlib.PurePosixPath("/\udcff"))}) + with pytest.raises(duckdb.InvalidInputException, match="surrogate"): + duckdb_cursor.append("t", frame) + + def test_null_row_among_struct_values_the_cast_converts(self, duckdb_cursor): + duckdb_cursor.execute("CREATE TABLE t (a STRUCT(x INTEGER))") + # Text fields cast into INTEGER, so the whole vector goes through one cast with the NULL row inside it + values = [{"x": "1"}] * 1000 + [None] + [{"x": "2"}] * 1000 + duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series(values, dtype=object)})) + rows = duckdb_cursor.execute("SELECT a FROM t ORDER BY rowid OFFSET 999 LIMIT 3").fetchall() + assert rows == [({"x": 1},), (None,), ({"x": 2},)] + stats = duckdb_cursor.execute("SELECT stats(a) FROM t LIMIT 1").fetchall()[0][0] + assert stats["child_stats"]["x"]["has_null"] is True + + def test_null_row_of_a_union_column_is_null(self, duckdb_cursor): + duckdb_cursor.execute("CREATE TABLE t (a UNION(i INTEGER, s VARCHAR))") + duckdb_cursor.append("t", pd.DataFrame({"a": _outside_the_sample(1, None)})) + rows = duckdb_cursor.execute("SELECT a IS NULL, union_tag(a) FROM t ORDER BY rowid OFFSET 2998").fetchall() + assert rows == [(False, "i"), (True, None)] + + def test_null_row_of_an_array_column_has_null_elements(self, duckdb_cursor): + duckdb_cursor.execute("CREATE TABLE t (a INTEGER[3])") + # A vector of rows before the NULL, so the NULL row's element slots hold values from an earlier chunk + values = [[777, 777, 777]] * 2048 + [None] + [[5, 5, 5]] * 100 + duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series(values, dtype=object)})) + rows = duckdb_cursor.execute("SELECT a FROM t ORDER BY rowid OFFSET 2047 LIMIT 3").fetchall() + assert rows == [((777, 777, 777),), (None,), ((5, 5, 5),)] + stats = duckdb_cursor.execute("SELECT stats(a) FROM t LIMIT 1").fetchall()[0][0] + assert stats["child_stats"]["has_null"] is True + @pytest.mark.parametrize( ("zone", "expected"), [ @@ -390,14 +440,12 @@ def test_object_value_the_table_column_type_refuses(self, duckdb_cursor, target, "UTC", datetime.datetime(2024, 5, 7, 5, 8, 9), id="UTC", - marks=pytest.mark.xfail(strict=True, reason="an aware datetime outside the sample keeps its wall time"), ), pytest.param("Europe/Amsterdam", datetime.datetime(2024, 5, 7, 7, 8, 9), id="Europe_Amsterdam"), pytest.param( "America/New_York", datetime.datetime(2024, 5, 7, 1, 8, 9), id="America_New_York", - marks=pytest.mark.xfail(strict=True, reason="an aware datetime outside the sample keeps its wall time"), ), ], ) @@ -410,7 +458,6 @@ def test_aware_datetime_into_timestamp_reads_in_the_session_time_zone(self, duck @pytest.mark.parametrize("zone", ["UTC", "Europe/Amsterdam"], ids=["UTC", "Europe_Amsterdam"]) @pytest.mark.parametrize("naive", [NAIVE, pd.Timestamp(NAIVE)], ids=["datetime", "Timestamp"]) - @pytest.mark.xfail(strict=True, reason="a naive datetime outside an aware sample is refused") def test_naive_datetime_into_timestamptz_reads_in_the_session_time_zone(self, duckdb_cursor, zone, naive): duckdb_cursor.execute(f"SET TimeZone = '{zone}'") duckdb_cursor.execute("CREATE TABLE t (a TIMESTAMPTZ)") @@ -425,12 +472,10 @@ def test_naive_datetime_into_timestamptz_reads_in_the_session_time_zone(self, du pytest.param( "Europe/Amsterdam", id="Europe_Amsterdam", - marks=pytest.mark.xfail(strict=True, reason="a date outside an aware sample reads as midnight UTC"), ), pytest.param( "America/New_York", id="America_New_York", - marks=pytest.mark.xfail(strict=True, reason="a date outside an aware sample reads as midnight UTC"), ), ], ) @@ -441,21 +486,18 @@ def test_date_into_timestamptz_reads_as_midnight_in_the_session_time_zone(self, values = _column(duckdb_cursor) assert (values[0], values[-1]) == (AWARE, datetime.datetime(2024, 5, 6, tzinfo=zoneinfo.ZoneInfo(zone))) - @pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED) def test_by_name_declares_each_column_from_its_name(self, duckdb_cursor): duckdb_cursor.execute("CREATE TABLE t (a DOUBLE, b VARCHAR)") frame = pd.DataFrame({"b": _outside_the_sample(1, "x"), "A": _outside_the_sample(1, 2.5)}) duckdb_cursor.append("t", frame, by_name=True) assert duckdb_cursor.execute("SELECT a, b FROM t ORDER BY rowid OFFSET 2999").fetchall() == [(2.5, "x")] - @pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED) def test_by_position_skips_generated_columns(self, duckdb_cursor): duckdb_cursor.execute("CREATE TABLE t (a DOUBLE, g DOUBLE AS (a * 2), b VARCHAR)") frame = pd.DataFrame({"x": _outside_the_sample(1, 2.5), "y": _outside_the_sample(1, "x")}) duckdb_cursor.append("t", frame) assert duckdb_cursor.execute("SELECT a, g, b FROM t ORDER BY rowid OFFSET 2999").fetchall() == [(2.5, 5.0, "x")] - @pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED) def test_temporary_table_shadows_the_table_of_the_same_name(self, duckdb_cursor): duckdb_cursor.execute("CREATE TABLE t (a INTEGER)") duckdb_cursor.execute("CREATE TEMPORARY TABLE t (a DOUBLE)") @@ -465,7 +507,6 @@ def test_temporary_table_shadows_the_table_of_the_same_name(self, duckdb_cursor) untouched = duckdb_cursor.execute("SELECT count(*) FROM memory.main.t").fetchall() assert (written, untouched) == ([(2.5,)], [(0,)]) - @pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED) def test_table_is_found_through_the_search_path(self, duckdb_cursor): duckdb_cursor.execute("CREATE SCHEMA s") duckdb_cursor.execute("CREATE TABLE s.t (a DOUBLE)") @@ -476,7 +517,6 @@ def test_table_is_found_through_the_search_path(self, duckdb_cursor): untouched = duckdb_cursor.execute("SELECT count(*) FROM memory.main.t").fetchall() assert (written, untouched) == ([(2.5,)], [(0,)]) - @pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED) def test_table_name_with_a_dot_is_one_identifier(self, duckdb_cursor): duckdb_cursor.execute("CREATE SCHEMA s") duckdb_cursor.execute('CREATE TABLE "s.t" (a DOUBLE)') @@ -508,43 +548,36 @@ class TestAppendMatchesTheAppender: "DOUBLE", _outside_the_sample(1, 2.5), id="int_sample_float_into_double", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "DECIMAL(10,2)", _outside_the_sample(Decimal("1.5"), Decimal("1.25")), id="decimals", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "VARCHAR", _outside_the_sample(1, 2.5), id="numbers_into_varchar", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "TIMESTAMP", _outside_the_sample(NAIVE, AWARE), id="aware_datetime_into_timestamp", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "TIMESTAMPTZ", _outside_the_sample(AWARE, NAIVE), id="naive_datetime_into_timestamptz", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "UNION(i INTEGER, s VARCHAR)", _outside_the_sample(1, "x"), id="union", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "INTEGER", _outside_the_sample(1, True), id="bool_into_integer", - marks=pytest.mark.xfail(strict=True, reason=CONVERTED_BY_THE_SCAN), ), pytest.param("BOOLEAN", _outside_the_sample(True, 1), id="int_into_boolean"), pytest.param("INTEGER[3]", _outside_the_sample([1, 2, 3], [4, 5, 6]), id="lists_into_array"), @@ -568,19 +601,16 @@ def test_append_writes_what_the_appender_writes(self, duckdb_cursor, target, col "JSON", _outside_the_sample(1, "x"), id="text_that_is_not_json", - marks=pytest.mark.xfail(strict=True, reason=NOT_YET_DECLARED), ), pytest.param( "INTEGER", _outside_the_sample(1, 2**40), id="int_out_of_range", - marks=pytest.mark.xfail(strict=True, reason=CONVERTED_BY_THE_SCAN), ), pytest.param( "STRUCT(x INTEGER)", _outside_the_sample({"x": 1}, (2,)), id="tuple_into_struct", - marks=pytest.mark.xfail(strict=True, reason=CONVERTED_BY_THE_SCAN), ), pytest.param("ENUM('a', 'b')", _outside_the_sample("a", "c"), id="text_outside_the_enum"), ], @@ -593,3 +623,17 @@ def test_append_refuses_what_the_appender_refuses(self, duckdb_cursor, target, c frame = pd.DataFrame({"a": column}) with pytest.raises(type(refused.value)): duckdb_cursor.append("t", frame) + + +class TestRegisterDeclared: + def test_declared_type_replaces_the_sampled_type(self, duckdb_cursor): + frame = pd.DataFrame({"a": _outside_the_sample(1, 2.5), "b": _outside_the_sample("x", "y")}) + duckdb_cursor._register_declared("declared", frame, [duckdb.sqltypes.DOUBLE, None]) + rel = duckdb_cursor.sql("SELECT a, b FROM declared WHERE a = 2.5") + assert rel.types == [duckdb.sqltypes.DOUBLE, duckdb.sqltypes.VARCHAR] + assert rel.fetchall() == [(2.5, "y")] + + def test_one_type_per_column_or_refused(self, duckdb_cursor): + frame = pd.DataFrame({"a": [1], "b": [2]}) + with pytest.raises(duckdb.InvalidInputException, match="1 types given for a DataFrame of 2 columns"): + duckdb_cursor._register_declared("declared", frame, [duckdb.sqltypes.DOUBLE]) diff --git a/tests/fast/pandas/test_object_column_conversion.py b/tests/fast/pandas/test_object_column_conversion.py index bd9fafc96..36c57b543 100644 --- a/tests/fast/pandas/test_object_column_conversion.py +++ b/tests/fast/pandas/test_object_column_conversion.py @@ -27,8 +27,9 @@ JAN_FIRST = datetime.datetime(2024, 1, 1) -def not_yet(reason): - return pytest.mark.xfail(strict=True, reason=reason) +def not_built(reason): + # Exact conversion of a value outside the sample is not built (Evert, 2026-11-05); these pin what it would do + return pytest.mark.xfail(strict=True, reason=f"not built: {reason}") def quiet_child_env(): @@ -116,7 +117,7 @@ def as_tuple(self): ] -@not_yet(MISMATCH_NOT_RAISED) +@not_built(MISMATCH_NOT_RAISED) @pytest.mark.parametrize( "value", [ @@ -135,7 +136,7 @@ def test_fractional_value_outside_the_sample_raises(duckdb_cursor, value): assert_names(message, "amount", UNSAMPLED, python_type_name(value), "INTEGER") -@not_yet(MISMATCH_NOT_RAISED) +@not_built(MISMATCH_NOT_RAISED) @pytest.mark.parametrize( ("rows", "at", "sample"), [ @@ -150,7 +151,7 @@ def test_fractional_value_outside_a_small_sample_raises(duckdb_cursor, rows, at, assert_names(message, "amount", at, "float", "INTEGER") -@not_yet(MISMATCH_NOT_RAISED) +@not_built(MISMATCH_NOT_RAISED) def test_fractional_values_deep_in_a_long_column_raise(duckdb_cursor): values = [1] * 100000 values[77777] = 2.5 @@ -161,7 +162,7 @@ def test_fractional_values_deep_in_a_long_column_raise(duckdb_cursor): assert re.search(r"(? None: self.x = x -_typed_from_the_sample = pytest.mark.xfail( - not USE_ACTUAL_SPARK, strict=True, reason="the object column is typed from its sample before the schema applies" -) -_not_turned_into_dicts = pytest.mark.xfail( - not USE_ACTUAL_SPARK, - strict=True, - reason="lists, tuples and objects in a struct field are not turned into dicts in field order before the scan", -) -_not_turned_into_text = pytest.mark.xfail( - not USE_ACTUAL_SPARK, strict=True, reason="values in a string field are not turned into text before the scan" -) - - class TestPandasObjectColumnsWithASchema: @pytest.mark.parametrize( ("column", "schema", "expected_first", "expected_last"), @@ -309,7 +297,6 @@ class TestPandasObjectColumnsWithASchema: Decimal("1.50"), Decimal("1.25"), id="wider_decimal_into_decimal", - marks=_typed_from_the_sample, ), pytest.param( _outside_the_sample(1, "x"), @@ -317,7 +304,6 @@ class TestPandasObjectColumnsWithASchema: "1", "x", id="str_among_ints_into_string", - marks=_typed_from_the_sample, ), pytest.param( _outside_the_sample(1, 2**40), @@ -325,7 +311,6 @@ class TestPandasObjectColumnsWithASchema: 1, 2**40, id="large_int_into_bigint", - marks=_typed_from_the_sample, ), pytest.param( _outside_the_sample(b"ab", bytearray(b"cd")), @@ -343,9 +328,37 @@ class TestPandasObjectColumnsWithASchema: "b'ab'", "b'cd'", id="fully_sampled_bytes_into_string_read_as_their_text", - marks=_not_turned_into_text, ), pytest.param(_outside_the_sample([1, 2], (3, 4)), "a array", [1, 2], [3, 4], id="tuple_into_array"), + pytest.param(_outside_the_sample(1, np.int64(2)), "a int", 1, 2, id="numpy_int_into_int"), + pytest.param(_outside_the_sample(1.5, np.float32(2.5)), "a double", 1.5, 2.5, id="numpy_float_into_double"), + pytest.param( + _outside_the_sample(True, np.bool_(False)), "a boolean", True, False, id="numpy_bool_into_boolean" + ), + pytest.param( + _outside_the_sample(NAIVE, np.datetime64("2024-05-08T01:02:03.123456789", "ns")), + "a timestamp_ntz", + NAIVE, + datetime.datetime(2024, 5, 8, 1, 2, 3, 123456), + id="numpy_datetime_into_timestamp_ntz", + ), + pytest.param( + _outside_the_sample("a", True), "a string", "a", "true", id="bool_into_string_reads_as_spark_text" + ), + pytest.param( + _outside_the_sample("a", np.datetime64("NaT", "us")), + "a string", + "a", + None, + id="datetime64_nat_into_string_is_null", + ), + pytest.param( + _outside_the_sample("a", np.datetime64("2024-01-01T00:00:00.123456789", "ns")), + "a string", + "a", + "2024-01-01 00:00:00.123456", + id="datetime64_ns_into_string_reads_as_its_text", + ), ], ) def test_object_value_outside_the_sample_with_a_schema(self, spark, column, schema, expected_first, expected_last): @@ -368,7 +381,6 @@ def test_object_value_outside_the_sample_with_a_schema(self, spark, column, sche Row(x=1), Row(x=2), id="list_among_dicts", - marks=_not_turned_into_dicts, ), pytest.param( _outside_the_sample({"x": 1}, _Point(2)), @@ -376,7 +388,6 @@ def test_object_value_outside_the_sample_with_a_schema(self, spark, column, sche Row(x=1), Row(x=2), id="object_among_dicts", - marks=_not_turned_into_dicts, ), pytest.param( pd.Series([(1,), (2,)], dtype=object), @@ -384,7 +395,6 @@ def test_object_value_outside_the_sample_with_a_schema(self, spark, column, sche Row(x=1), Row(x=2), id="tuples_only", - marks=_not_turned_into_dicts, ), pytest.param( _outside_the_sample([{"x": 1}], [(2,)]), @@ -413,7 +423,6 @@ def test_object_value_outside_the_sample_with_a_schema(self, spark, column, sche Row(s=Row(x=1)), Row(s=Row(x=2)), id="tuple_fields_only", - marks=_not_turned_into_dicts, ), pytest.param( _outside_the_sample({"y": 2, "x": 1}, (3, 4)), @@ -421,7 +430,6 @@ def test_object_value_outside_the_sample_with_a_schema(self, spark, column, sche Row(x=1, y=2), Row(x=3, y=4), id="tuple_among_dicts_of_another_key_order", - marks=_not_turned_into_dicts, ), ], ) @@ -440,7 +448,6 @@ def test_struct_values_of_the_frame_stay_as_given(self, spark): assert repr(list(frame["a"])) == given @pytest.mark.skipif(USE_ACTUAL_SPARK, reason="sets the session time zone through the DuckDB connection") - @pytest.mark.xfail(strict=True, reason="an aware datetime outside a naive sample keeps its wall time") def test_aware_datetime_outside_the_sample_of_a_timestamp_field(self, spark): spark.conn.execute("SET TimeZone = 'UTC'") df = spark.createDataFrame(pd.DataFrame({"t": _outside_the_sample(NAIVE, AWARE)}), "t timestamp") @@ -455,9 +462,6 @@ def test_aware_datetime_outside_the_sample_of_a_timestamp_field(self, spark): pytest.param( pd.Series([AWARE, AWARE], dtype=object), id="only_aware_values", - marks=pytest.mark.xfail( - strict=True, reason="an aware datetime in a timestamp_ntz field reads in the session time zone" - ), ), ], ) @@ -481,7 +485,7 @@ class TestPandasObjectColumnsWithoutASchema: ), ], ) - @pytest.mark.xfail(strict=True, reason="a value outside the sample is converted into the sampled type") + @pytest.mark.xfail(strict=True, reason="not built: a value outside the sample is converted into the sampled type") def test_object_value_outside_the_sample_that_does_not_fit_raises(self, spark, column, match): df = spark.createDataFrame(pd.DataFrame({"a": column})) with pytest.raises(duckdb.InvalidInputException, match=match): diff --git a/tests/fast/test_map.py b/tests/fast/test_map.py index c056e53ff..926f0b368 100644 --- a/tests/fast/test_map.py +++ b/tests/fast/test_map.py @@ -394,7 +394,7 @@ def replace(df): @MAP_SCHEMAS @pytest.mark.xfail( - strict=True, reason="a fractional value outside the chunk's sample is converted with loss into INTEGER" + strict=True, reason="not built: a fractional value outside the chunk's sample is converted with loss into INTEGER" ) def test_map_fractional_value_outside_the_chunk_sample_raises(duckdb_cursor, schema): duckdb_cursor.execute("set threads = 1") From 9e12946a4359f6e869003aa965c454dabefa758b Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Thu, 5 Nov 2026 17:31:33 +0000 Subject: [PATCH 03/61] Read numpy scalars and every map key form through the declared types --- duckdb/experimental/spark/sql/session.py | 38 +++++++++++--- src/numpy/numpy_scan.cpp | 22 ++++++-- tests/fast/pandas/test_append_df.py | 21 ++++++++ .../fast/spark/test_spark_pandas_dataframe.py | 50 +++++++++++++++++++ 4 files changed, 120 insertions(+), 11 deletions(-) diff --git a/duckdb/experimental/spark/sql/session.py b/duckdb/experimental/spark/sql/session.py index 9ceec7f6a..8ff6b721e 100644 --- a/duckdb/experimental/spark/sql/session.py +++ b/duckdb/experimental/spark/sql/session.py @@ -127,12 +127,11 @@ def _python_value(value: Any) -> Any: # noqa: ANN401 def _reads_through_the_schema(data_type: DataType) -> bool: """Whether a value of an object column takes a form from ``data_type`` before DuckDB reads it.""" - if isinstance(data_type, (StringType, StructType, *_WALL_TIME_TIMESTAMPS)): + # A map always does: a dict whose keys are not text would otherwise read as a struct of the keys' text + if isinstance(data_type, (StringType, StructType, MapType, *_WALL_TIME_TIMESTAMPS)): return True if isinstance(data_type, ArrayType): return _reads_through_the_schema(data_type.elementType) - if isinstance(data_type, MapType): - return _reads_through_the_schema(data_type.valueType) return False @@ -170,10 +169,26 @@ def _value_through_the_schema(value: Any, data_type: DataType) -> Any: # noqa: if isinstance(data_type, ArrayType) and isinstance(value, (list, tuple)): return [_value_through_the_schema(element, data_type.elementType) for element in value] if isinstance(data_type, MapType) and isinstance(value, dict): - return {key: _value_through_the_schema(element, data_type.valueType) for key, element in value.items()} + # DuckDB's own map form, a list of keys beside a list of values: a converted key may be a dict or a list, which + # no dict can hold as a key, and two keys that collapse into one stay two for DuckDB's uniqueness check + return { + "key": [_value_through_the_schema(key, data_type.keyType) for key in value], + "value": [_value_through_the_schema(element, data_type.valueType) for element in value.values()], + } return value +def _holds_numpy(value: Any) -> bool: # noqa: ANN401 + """Whether ``value`` is a NumPy value or holds one at any depth of its dicts, lists and tuples.""" + if _is_numpy(value): + return True + if isinstance(value, dict): + return any(_holds_numpy(key) or _holds_numpy(element) for key, element in value.items()) + if isinstance(value, (list, tuple)): + return any(_holds_numpy(element) for element in value) + return False + + def _column_conforms(series: Any, data_type: DataType) -> bool: # noqa: ANN401 """Whether every value of an object column already has the form its field takes, so the column stays as it is. @@ -185,11 +200,20 @@ def _column_conforms(series: Any, data_type: DataType) -> bool: # noqa: ANN401 return False +def _is_pyarrow_backed(data: "PandasDataFrame") -> bool: + """Whether any column of ``data`` has a pyarrow dtype, which makes DuckDB read the whole frame through Arrow.""" + import pandas + + return any(isinstance(dtype, pandas.ArrowDtype) for dtype in data.dtypes) + + def _frame_through_the_schema(data: "PandasDataFrame", schema: StructType) -> "PandasDataFrame": """A shallow copy of ``data`` whose object columns hold their values as the fields of ``schema`` read them.""" frame = data.copy(deep=False) for position, ((name, series), field) in enumerate(zip(data.items(), schema.fields, strict=True)): - if series.dtype != object or not _reads_through_the_schema(field.dataType): + if series.dtype != object: + continue + if not _reads_through_the_schema(field.dataType) and not series.map(_holds_numpy).any(): continue if _column_conforms(series, field.dataType): continue @@ -290,7 +314,9 @@ def _createDataFrameFromPandas( types = None if schema is not None: types, names = schema.extract_types_and_names() - if schema is not None and len(schema.fields) == len(data.columns): + # A frame with a pyarrow backed column is read through Arrow, which takes no declared types, so it keeps + # the path it had: register as it is and cast below + if schema is not None and len(schema.fields) == len(data.columns) and not _is_pyarrow_backed(data): frame = _frame_through_the_schema(data, schema) self.conn._register_declared(unique_name, frame, [field.dataType.duckdb_type for field in schema.fields]) else: diff --git a/src/numpy/numpy_scan.cpp b/src/numpy/numpy_scan.cpp index afaa3d07f..ec3cc6159 100644 --- a/src/numpy/numpy_scan.cpp +++ b/src/numpy/numpy_scan.cpp @@ -306,8 +306,18 @@ class DeclaredCasts { //! A declared column converts a cell as the appender converts a value of a row: with the type the value has in //! Python, then the engine's cast into the column's type, which reads the connection's settings; NaN reads NULL at //! every depth, and a value without a DuckDB type of its own reads as its text in a text column -//! A numpy scalar reads as its Python value; a datetime64 or timedelta64 at nanoseconds would read as an integer, -//! so those take the microsecond unit first, as the frame's own datetime columns do +//! A numpy scalar, or an array of no dimensions, reads as its Python value; a datetime64 or timedelta64 at +//! nanoseconds would read as an integer, so those take the microsecond unit first, as the frame's own datetime +//! columns do +static bool IsNumpyScalar(nb::handle cell) { + auto &import_cache = *DuckDBPyConnection::ImportCache(); + if (nb::isinstance(cell, import_cache.numpy.generic())) { + return true; + } + // A subclass is not taken: numpy.ma.masked and a masked array of no dimensions carry a payload under their mask + return cell.type().is(import_cache.numpy.ndarray()) && nb::cast(cell.attr("ndim")) == 0; +} + static nb::object NumpyScalarValue(nb::handle scalar) { auto kind = nb::cast(scalar.attr("dtype").attr("kind")); if (kind == "M") { @@ -323,10 +333,12 @@ static Value DeclaredValue(ClientContext &context, const LogicalType &target, nb if (cell.ptr() == Py_None) { return Value(); } - auto &import_cache = *DuckDBPyConnection::ImportCache(); - if (nb::isinstance(cell, import_cache.numpy.generic())) { + if (IsNumpyScalar(cell)) { auto value = NumpyScalarValue(cell); - return DeclaredValue(context, target, value); + // A long double's item() is a numpy scalar again; one step, then the conversion refuses what is left + if (!IsNumpyScalar(value)) { + return DeclaredValue(context, target, value); + } } if (target.id() == LogicalTypeId::VARCHAR && GetPythonObjectType(cell) == PythonObjectType::Other) { return Value(TransformPythonString(nb::str(cell))); diff --git a/tests/fast/pandas/test_append_df.py b/tests/fast/pandas/test_append_df.py index da6dbcb23..4360a8bc8 100644 --- a/tests/fast/pandas/test_append_df.py +++ b/tests/fast/pandas/test_append_df.py @@ -261,6 +261,14 @@ class TestAppendObjectColumnsToDeclaredTypes: ), pytest.param("DOUBLE", _outside_the_sample(1.5, float("nan")), 1.5, None, id="nan_into_double_is_null"), pytest.param("DOUBLE", _outside_the_sample(1.5, None), 1.5, None, id="none_into_double_is_null"), + pytest.param("DOUBLE", _outside_the_sample(1.5, np.ma.masked), 1.5, None, id="masked_into_double_is_null"), + pytest.param( + "DOUBLE", + _outside_the_sample(1.5, np.ma.array(42.0, mask=True)), + 1.5, + None, + id="masked_zero_dimensional_array_into_double_is_null", + ), pytest.param("INTEGER", _outside_the_sample(1, np.int64(2)), 1, 2, id="numpy_int_into_integer"), pytest.param("DOUBLE", _outside_the_sample(1.5, np.float32(2.5)), 1.5, 2.5, id="numpy_float_into_double"), pytest.param( @@ -273,6 +281,13 @@ class TestAppendObjectColumnsToDeclaredTypes: datetime.datetime(2024, 5, 8, 1, 2, 3, 123456), id="numpy_datetime_into_timestamp", ), + pytest.param( + "TIMESTAMP", + _outside_the_sample(NAIVE, np.array("2024-05-08T01:02:03.123456789", dtype="datetime64[ns]")), + NAIVE, + datetime.datetime(2024, 5, 8, 1, 2, 3, 123456), + id="numpy_zero_dimensional_datetime_into_timestamp", + ), pytest.param( "STRUCT(x VARCHAR)", _outside_the_sample({"x": "abc"}, None), @@ -394,6 +409,12 @@ def test_object_value_the_table_column_type_refuses(self, duckdb_cursor, target, with pytest.raises(duckdb.ConversionException, match=match): duckdb_cursor.append("t", frame) + def test_numpy_long_double_is_refused_like_the_appender(self, duckdb_cursor): + duckdb_cursor.execute("CREATE TABLE t (a DOUBLE)") + frame = pd.DataFrame({"a": _outside_the_sample(1.5, np.longdouble("2.5"))}) + with pytest.raises(duckdb.NotImplementedException, match="longdouble"): + duckdb_cursor.append("t", frame) + def test_keys_that_collapse_in_a_nested_map_are_refused(self, duckdb_cursor): duckdb_cursor.execute("CREATE TABLE t (a STRUCT(m MAP(INTEGER, INTEGER)))") # The same key set in every row, so one cast runs over the whole vector diff --git a/tests/fast/spark/test_spark_pandas_dataframe.py b/tests/fast/spark/test_spark_pandas_dataframe.py index 413c3a7ac..f8fcc7ea5 100644 --- a/tests/fast/spark/test_spark_pandas_dataframe.py +++ b/tests/fast/spark/test_spark_pandas_dataframe.py @@ -330,6 +330,30 @@ class TestPandasObjectColumnsWithASchema: id="fully_sampled_bytes_into_string_read_as_their_text", ), pytest.param(_outside_the_sample([1, 2], (3, 4)), "a array", [1, 2], [3, 4], id="tuple_into_array"), + pytest.param( + _outside_the_sample([1], [np.int64(2)]), "a array", [1], [2], id="numpy_int_in_a_list_into_array" + ), + pytest.param( + _outside_the_sample({1: 10}, {np.int64(2): 20}), + "a map", + {1: 10}, + {2: 20}, + id="numpy_int_as_a_map_key", + ), + pytest.param( + _outside_the_sample({"x": 1}, {True: 2}), + "a map", + {"x": 1}, + {"true": 2}, + id="bool_as_a_text_map_key_reads_as_spark_text", + ), + pytest.param( + _outside_the_sample({(1,): 10}, {Row(a=2): 20}), + "a map,int>", + {Row(a=1): 10}, + {Row(a=2): 20}, + id="tuple_and_row_as_struct_map_keys", + ), pytest.param(_outside_the_sample(1, np.int64(2)), "a int", 1, 2, id="numpy_int_into_int"), pytest.param(_outside_the_sample(1.5, np.float32(2.5)), "a double", 1.5, 2.5, id="numpy_float_into_double"), pytest.param( @@ -342,6 +366,13 @@ class TestPandasObjectColumnsWithASchema: datetime.datetime(2024, 5, 8, 1, 2, 3, 123456), id="numpy_datetime_into_timestamp_ntz", ), + pytest.param( + _outside_the_sample(1, np.array(2, dtype="int64")), + "a int", + 1, + 2, + id="numpy_zero_dimensional_int_into_int", + ), pytest.param( _outside_the_sample("a", True), "a string", "a", "true", id="bool_into_string_reads_as_spark_text" ), @@ -440,6 +471,25 @@ def test_struct_field_takes_each_value_the_schema_check_accepts( rows = df.collect() assert (rows[0].a, rows[-1].a) == (expected_first, expected_last) + def test_map_keys_that_collapse_are_refused(self, spark): + frame = pd.DataFrame({"m": _outside_the_sample({"x": 1}, {True: 1, "true": 2})}) + with pytest.raises(duckdb.InvalidInputException, match=r"(?i)unique|duplicat"): + spark.createDataFrame(frame, "m map").collect() + + def test_array_keys_of_a_map_reach_the_engine(self, spark): + # A dict cannot hold a list as a key, so the keys and values are read apart instead of the map + frame = pd.DataFrame({"m": _outside_the_sample({("a",): 1}, {("b", "c"): 2})}) + df = spark.createDataFrame(frame, "m map,int>") + rows = df.relation.project("map_keys(m), map_values(m)").fetchall() + assert (rows[0], rows[-1]) == (([["a"]], [1]), ([["b", "c"]], [2])) + + def test_frame_with_a_pyarrow_column_keeps_the_arrow_path(self, spark): + pytest.importorskip("pyarrow") + maps = pd.Series([{"a": 1}, {"a": 2}], dtype=object) + frame = pd.DataFrame({"m": maps, "n": pd.Series([1, 2], dtype="int64[pyarrow]")}) + rows = spark.createDataFrame(frame, "m map, n long").collect() + assert [(row.m, row.n) for row in rows] == [({"a": 1}, 1), ({"a": 2}, 2)] + def test_struct_values_of_the_frame_stay_as_given(self, spark): frame = pd.DataFrame({"a": _outside_the_sample({"y": 2, "x": 1}, (3, 4))}) # repr keeps the key order, which dict equality ignores. From 287e582b60a983509f9a86e8bfeca8c5b96c544b Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Thu, 5 Nov 2026 18:01:12 +0000 Subject: [PATCH 04/61] Keep a polars filter that casts a column out of the pushed predicate --- duckdb/polars_io.py | 15 +-- tests/fast/arrow/test_polars.py | 27 ++--- .../arrow/test_polars_pushdown_literals.py | 106 ++++++++++++++++++ 3 files changed, 123 insertions(+), 25 deletions(-) diff --git a/duckdb/polars_io.py b/duckdb/polars_io.py index b6497255c..dce362d24 100644 --- a/duckdb/polars_io.py +++ b/duckdb/polars_io.py @@ -251,19 +251,16 @@ def _pl_tree_to_sql(tree: _ExpressionTree) -> str: cast_tree = tree[node_type] assert isinstance(cast_tree, dict), f"A {node_type} should be a dict but got {type(cast_tree)}" options = cast_tree.get("options") - if options == "Strict": - # Strict casts on literals (e.g. pl.lit(1, dtype=pl.Int8)) are safe to unwrap — - # the value is known at expression creation time. Strict casts on columns - # (e.g. pl.col("a").cast(pl.Int64)) are semantically meaningful and must not be dropped. - cast_expr = cast_tree.get("expr", {}) - if not isinstance(cast_expr, dict) or "Literal" not in cast_expr: - msg = "Strict cast on non-literal expression cannot be pushed down" - raise NotImplementedError(msg) - elif options != "NonStrict": + if options not in ("Strict", "NonStrict"): msg = f"Only NonStrict/Strict casts can be safely unwrapped, got {options!r}" raise NotImplementedError(msg) cast_expr = cast_tree["expr"] assert isinstance(cast_expr, dict), f"A {node_type} should be a dict but got {type(cast_expr)}" + # polars folds a cast of a literal before the source sees it; a cast of a column can truncate, turn an + # overflow into NULL or change the type the comparison runs in, and the bare column carries none of that + if "Literal" not in cast_expr: + msg = "A cast of a column or an expression cannot be pushed down" + raise NotImplementedError(msg) return _pl_tree_to_sql(cast_expr) if node_type == "Scalar": diff --git a/tests/fast/arrow/test_polars.py b/tests/fast/arrow/test_polars.py index 487a8beb6..1052652ad 100644 --- a/tests/fast/arrow/test_polars.py +++ b/tests/fast/arrow/test_polars.py @@ -776,25 +776,20 @@ def test_decimal_scale(self): """ assert _pl_tree_to_sql(json.loads(scalar_decimal_scale)) == "1" - def test_cast_node_unwraps_inner_expression(self): - """Cast nodes should be unwrapped to process the inner expression.""" - # A Cast wrapping a Column reference + def test_cast_node_unwraps_a_literal_and_refuses_a_column(self): + """A cast of a literal goes, the literal renders with its own type; a cast of a column keeps its semantics.""" + cast_literal = json.loads( + '{"Cast": {"expr": {"Literal": {"Int": 1}}, "dtype": {"Decimal": [20, 0]}, "options": "NonStrict"}}' + ) + assert _pl_tree_to_sql(cast_literal) == "1" + + # A cast polars inserted to reconcile types, or one that cannot fail, arrives NonStrict; it can still truncate, + # turn an overflow into NULL or change the type the comparison runs in, so the predicate stays with polars cast_column = json.loads( '{"Cast": {"expr": {"Column": "a"}, "dtype": {"Decimal": [20, 0]}, "options": "NonStrict"}}' ) - assert _pl_tree_to_sql(cast_column) == '"a"' - - # A Cast wrapping a full binary expression - cast_expr = json.loads(""" - { - "BinaryExpr": { - "left": {"Cast": {"expr": {"Column": "a"}, "dtype": {"Decimal": [20, 0]}, "options": "NonStrict"}}, - "op": "Eq", - "right": {"Literal": {"Int": 1}} - } - } - """) - assert _pl_tree_to_sql(cast_expr) == '("a" = 1)' + with pytest.raises(NotImplementedError, match="cast of a column"): + _pl_tree_to_sql(cast_column) def test_cast_node_predicate_pushdown(self): """Predicates with Cast nodes should be successfully pushed down.""" diff --git a/tests/fast/arrow/test_polars_pushdown_literals.py b/tests/fast/arrow/test_polars_pushdown_literals.py index 68f6b6720..4edcf3ab4 100644 --- a/tests/fast/arrow/test_polars_pushdown_literals.py +++ b/tests/fast/arrow/test_polars_pushdown_literals.py @@ -257,3 +257,109 @@ def test_untyped_non_finite_literal_is_not_pushed_down_without_assertions(self): [sys.executable, "-I", "-O", "-c", script], capture_output=True, text=True, timeout=60, check=False ) assert result.returncode == 0, result.stderr + + +class TestColumnCastPushdown: + # A cast of the column, whether the user wrote it or polars inserted it to reconcile types, truncates, turns an + # overflow into NULL or changes the type the comparison runs in; the bare column carries none of that, so the + # predicate stays with polars and the source must say so. + ROWS = """ + INSERT INTO t VALUES + ('2024-01-01 12:00:00+00'), ('2024-01-01 12:00:00.0005+00'), ('2024-01-01 12:00:00.001+00'), + ('2024-01-01 12:00:00.000999+00'), (NULL) + """ + + @pytest.mark.parametrize("session_zone", ["UTC", "America/New_York"]) + @pytest.mark.parametrize("zone", [None, "UTC", "Asia/Tokyo"]) + def test_column_cast_to_coarser_unit_matches_polars(self, zone, session_zone, duckdb_cursor, pushdowns): + duckdb_cursor.execute(f"SET TimeZone = '{session_zone}'") + duckdb_cursor.execute(f"CREATE TABLE t (a {'TIMESTAMP' if zone is None else 'TIMESTAMPTZ'})") + duckdb_cursor.execute(self.ROWS) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + noon = datetime.datetime(2024, 1, 1, 12, tzinfo=datetime.timezone.utc) + value = noon.replace(tzinfo=None) if zone is None else noon.astimezone(ZoneInfo(zone)) + literal = pl.lit(value, dtype=pl.Datetime("ms", zone)) + for compare in ORDERINGS: + predicate = compare(pl.col("a").cast(pl.Datetime("ms", zone)), literal) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) + + @pytest.mark.parametrize("unit", POLARS_UNITS) + def test_column_cast_to_other_units_matches_polars(self, unit, duckdb_cursor, pushdowns): + duckdb_cursor.execute("SET TimeZone = 'UTC'") + duckdb_cursor.execute("CREATE TABLE t (a TIMESTAMPTZ)") + duckdb_cursor.execute(self.ROWS) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + literal = pl.lit( + datetime.datetime(2024, 1, 1, 12, 0, 0, 500, tzinfo=datetime.timezone.utc), dtype=pl.Datetime(unit, "UTC") + ) + for compare in ORDERINGS: + predicate = compare(pl.col("a").cast(pl.Datetime(unit, "UTC")), literal) + # polars drops a cast to the column's own unit and zone before the source sees the predicate + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=unit == "us") + + def test_numeric_column_cast_matches_polars(self, duckdb_cursor, pushdowns): + duckdb_cursor.execute("CREATE TABLE t (i INTEGER)") + duckdb_cursor.execute("INSERT INTO t VALUES (1), (127), (200), (NULL)") + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + # A non strict cast of 200 into Int8 is NULL for polars, where the engine's cast would raise + for compare in ORDERINGS: + predicate = compare(pl.col("i").cast(pl.Int8, strict=False), pl.lit(127, dtype=pl.Int8)) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) + + def test_two_column_comparisons(self, duckdb_cursor, pushdowns): + duckdb_cursor.execute("CREATE TABLE t (i INTEGER, j BIGINT, d20 DECIMAL(20,0), d38 DECIMAL(38,0))") + duckdb_cursor.execute("INSERT INTO t VALUES (1, 2, 1, 2), (3, 1, 3, 1), (2, 2, 2, 2), (NULL, 1, NULL, 1)") + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + for compare in ORDERINGS: + # polars widens the narrower column with a NonStrict cast, which the source does not push + assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("i"), pl.col("j")), pushed=False) + assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("d20"), pl.col("d38")), pushed=True) + + def test_cast_of_an_expression_matches_polars(self, duckdb_cursor, pushdowns): + duckdb_cursor.execute("CREATE TABLE t (i INTEGER)") + duckdb_cursor.execute("INSERT INTO t VALUES (1), (127), (200), (NULL)") + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + predicate = (pl.col("i") % 256).cast(pl.Int8, strict=False).is_null() + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) + assert lazy_df.filter(predicate).collect()["i"].to_list() == [200, None] + + def test_fallback_filters_every_batch(self, duckdb_cursor, pushdowns): + # The source hands polars Arrow batches of about 120 thousand rows: a match in the first, none in the second, + # one in the third, so a read that stopped at an empty batch would lose the last match + duckdb_cursor.execute( + "CREATE TABLE t AS SELECT range AS id, CASE WHEN range IN (100, 250000) THEN 100 ELSE 200 END AS i " + "FROM range(300000)" + ) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + predicate = pl.col("i").cast(pl.Int8, strict=False).is_between(100, 127) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) + assert lazy_df.filter(predicate).collect()["id"].to_list() == [100, 250000] + + def test_float_column_against_a_double_literal_matches_polars(self, duckdb_cursor, pushdowns): + # polars widens the FLOAT column with a cast; pushed bare, the engine compared 0.1 as a FLOAT and dropped a row + duckdb_cursor.execute("CREATE TABLE t (f FLOAT)") + duckdb_cursor.execute("INSERT INTO t VALUES (0.1), (1), (127), (200), (NULL)") + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + for compare in ORDERINGS: + predicate = compare(pl.col("f"), pl.lit(0.1, dtype=pl.Float64)) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) + + def test_date_column_against_a_zoned_literal_matches_polars(self, duckdb_cursor, pushdowns): + # polars casts the DATE column to the literal's zoned datetime; pushed bare, the engine read the date in the + # session zone and kept a day polars drops + duckdb_cursor.execute("SET TimeZone = 'America/New_York'") + duckdb_cursor.execute("CREATE TABLE t (d DATE)") + duckdb_cursor.execute("INSERT INTO t VALUES ('2023-12-31'), ('2024-01-01'), ('2024-01-02'), (NULL)") + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + literal = pl.lit(datetime.datetime(2024, 1, 1, tzinfo=datetime.timezone.utc), dtype=pl.Datetime("us", "UTC")) + for compare in ORDERINGS: + assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("d"), literal), pushed=False) + + def test_decimal_column_against_a_literal_is_still_pushed(self, duckdb_cursor, pushdowns): + # polars folds the literal into the column's decimal type before the source sees it, so no Cast node arrives + duckdb_cursor.execute("CREATE TABLE t (a DECIMAL(20,0))") + duckdb_cursor.execute("INSERT INTO t VALUES (1), (10), (100), (NULL)") + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + for compare in ORDERINGS: + tree = assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("a"), pl.lit(10)), pushed=True) + assert "Cast" not in json.dumps(tree) From cb4870a4b9eadc406e973cf12b1ff5e025233ed3 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Thu, 5 Nov 2026 18:55:19 +0000 Subject: [PATCH 05/61] Let a view over a file-like reader own its data, and one object store per database --- _duckdb-stubs/__init__.pyi | 8 +- duckdb/_relation.py | 7 +- duckdb/_seam.py | 12 +- src/include/duckdb_python/pyfilesystem.hpp | 23 +++ src/pyconnection.cpp | 56 +++++-- src/pyconnection/seam.cpp | 62 ++++++- tests/fast/api/test_read_csv.py | 186 +++++++++++++++++++++ 7 files changed, 329 insertions(+), 25 deletions(-) diff --git a/_duckdb-stubs/__init__.pyi b/_duckdb-stubs/__init__.pyi index b03f407d8..d44929ca2 100644 --- a/_duckdb-stubs/__init__.pyi +++ b/_duckdb-stubs/__init__.pyi @@ -484,7 +484,13 @@ class DuckDBPyConnection: def _own_sources(self, name: str, handles: lst[SourceHandle]) -> None: ... def _catalog_version(self) -> int: ... def _create_view( - self, name: str | tuple[str, ...] | lst[str], sql: str, *, temporary: bool = False, replace: bool = False + self, + name: str | tuple[str, ...] | lst[str], + sql: str, + *, + temporary: bool = False, + replace: bool = False, + sources: lst[SourceHandle] = ..., ) -> None: ... def _table_kind(self, name: str | tuple[str, ...] | lst[str]) -> str: ... def _name_scope(self, name: str) -> str: ... diff --git a/duckdb/_relation.py b/duckdb/_relation.py index 7088f6eca..d0804d3e0 100644 --- a/duckdb/_relation.py +++ b/duckdb/_relation.py @@ -2836,9 +2836,10 @@ def update(self, set: object, *, condition: object = None) -> None: def create_view(self, view_name: str, replace: bool = True) -> DuckDBPyRelation: # noqa: FBT001 """Creates a view named view_name that refers to the relation object.""" body, _ = _render(self, literals=True, wrap_text=True) - # The view holds the table reference of every registry name it reads, so its catalog entry owns its sources - # and its transaction decides when they go; a Python object in a database file is refused there. - _seam.create_view(self._con, view_name, body, replace=replace) + # The view holds the table reference of every registry name it reads and the handles of every source the + # relation reads, so its catalog entry owns its sources and its transaction decides when they go; a Python + # object in a database file is refused there. + _seam.create_view(self._con, view_name, body, replace=replace, sources=self._sources()) return self to_view = create_view diff --git a/duckdb/_seam.py b/duckdb/_seam.py index 953d4ffd5..25e238be9 100644 --- a/duckdb/_seam.py +++ b/duckdb/_seam.py @@ -184,9 +184,15 @@ def register_filelike(con: _duckdb.DuckDBPyConnection, obj: object) -> SourceHan return con._register_filelike(obj) -def create_view(con: _duckdb.DuckDBPyConnection, name: str, sql: str, *, replace: bool) -> None: - """Create the persistent view `name` over the SELECT in `sql`, the view owning what the registry names it reads.""" - con._create_view(name, sql, replace=replace) +def create_view( + con: _duckdb.DuckDBPyConnection, name: str, sql: str, *, replace: bool, sources: Sequence[SourceHandle] = () +) -> None: + """Create the persistent view `name` over the SELECT in `sql`. + + The view owns what the registry names it reads and the `sources` handles of the relation it was made from, among + them the file-like objects the SELECT reads by their object store path, for as long as it exists. + """ + con._create_view(name, sql, replace=replace, sources=list(sources)) def check_text(con: _duckdb.DuckDBPyConnection, text: str, shape: str) -> int: diff --git a/src/include/duckdb_python/pyfilesystem.hpp b/src/include/duckdb_python/pyfilesystem.hpp index 104b1a603..85a61143b 100644 --- a/src/include/duckdb_python/pyfilesystem.hpp +++ b/src/include/duckdb_python/pyfilesystem.hpp @@ -5,6 +5,7 @@ #include "duckdb_python/nb/casters.hpp" #include "duckdb/common/vector.hpp" #include "duckdb/common/types/timestamp.hpp" +#include "duckdb/storage/object_cache.hpp" namespace duckdb { @@ -121,4 +122,26 @@ class PythonFilesystem : public FileSystem { idx_t SeekPosition(FileHandle &handle) override; }; +//! The in-memory file system that holds file-like objects, one per database: a cursor registers nothing of its own, +//! since the database's virtual file system takes the name once. Found through the database's object cache, so every +//! connection and cursor of the database reads the same entries. +class ObjectStore : public ObjectCacheEntry { +public: + ~ObjectStore() override; + + static string ObjectType() { + return "python_object_store"; + } + string GetObjectType() override { + return ObjectType(); + } + optional_idx GetEstimatedCacheMemory() const override { + return optional_idx(); + } + +public: + //! Read and written with the GIL held, which is what serialises the connections of a database here + std::shared_ptr filesystem; +}; + } // namespace duckdb diff --git a/src/pyconnection.cpp b/src/pyconnection.cpp index 6ff11149f..86ddbbb7b 100644 --- a/src/pyconnection.cpp +++ b/src/pyconnection.cpp @@ -365,10 +365,9 @@ void DuckDBPyConnection::UnregisterFilesystem(const nb::str &name) { fs.ExtractSubSystem(nb::cast(name)); } -void DuckDBPyConnection::RegisterFilesystem(nb::object filesystem) { - nb::gil_scoped_acquire gil; - - auto &database = con.GetDatabase(); +//! The engine side file system over an fsspec object, with the Python reads done: the registration itself then runs +//! no Python +static unique_ptr WrapFilesystem(const nb::object &filesystem) { // Import fsspec here (a normal, throwing context) so a missing install surfaces as ModuleNotFoundError, rather // than terminating inside the noexcept AbstractFileSystem type check (which nanobind cannot let throw). auto abstract_filesystem = nb::module_::import_("fsspec").attr("AbstractFileSystem"); @@ -376,8 +375,6 @@ void DuckDBPyConnection::RegisterFilesystem(nb::object filesystem) { throw InvalidInputException("Bad filesystem instance"); } - auto &fs = database.GetFileSystem(); - // nb::object (not auto, which deduces an accessor): nb::str(protocol) below is an ambiguous overload on MSVC. nb::object protocol = filesystem.attr("protocol"); if (protocol.is_none() || nb::str("abstract").equal(protocol)) { @@ -392,8 +389,13 @@ void DuckDBPyConnection::RegisterFilesystem(nb::object filesystem) { protocols.push_back(nb::cast(nb::str(sub_protocol))); } } + return make_uniq(std::move(protocols), nb::borrow(filesystem)); +} - fs.RegisterSubSystem(make_uniq(std::move(protocols), nb::borrow(filesystem))); +void DuckDBPyConnection::RegisterFilesystem(nb::object filesystem) { + nb::gil_scoped_acquire gil; + auto wrapped = WrapFilesystem(filesystem); + con.GetDatabase().GetFileSystem().RegisterSubSystem(std::move(wrapped)); } nb::list DuckDBPyConnection::ListFilesystems() { @@ -1736,18 +1738,40 @@ nb::object DuckDBPyConnection::ArrowSourcesNodes() { return ArrowSourcesPart(GetModuleState().arrow_sources_nodes); } +ObjectStore::~ObjectStore() { + // The Python file system dies with the database, on whatever thread drops the last connection, so the reference + // goes under the guard; during interpreter teardown it is left to the interpreter, as every held Python object is + if (nb::detail::cleanup_guard guard {}) { + filesystem.reset(); + } else if (filesystem) { + filesystem->release(); + } +} + ModifiedMemoryFileSystem &DuckDBPyConnection::GetObjectFileSystem() { if (!internal_object_filesystem) { - D_ASSERT(!FileSystemIsRegistered("DUCKDB_INTERNAL_OBJECTSTORE")); - auto &import_cache_py = *ImportCache(); - auto modified_memory_fs = import_cache_py.duckdb.filesystem.ModifiedMemoryFileSystem(); - if (modified_memory_fs.ptr() == nullptr) { - throw InvalidInputException( - "This operation could not be completed because required module 'fsspec' is not installed"); + auto &context = *con.GetConnection().context; + auto store = ObjectCache::GetObjectCache(context).GetOrCreate(ObjectStore::ObjectType()); + // The GIL is the lock here: a mutex held while the Python file system is built would deadlock against a + // connection that took the GIL and waits for it. Building runs Python, which can hand the GIL to another + // connection doing the same, so every Python step comes first and the entry is checked again right before + // the engine registration, which runs no Python. + if (!store->filesystem) { + auto &import_cache_py = *ImportCache(); + auto modified_memory_fs = import_cache_py.duckdb.filesystem.ModifiedMemoryFileSystem(); + if (modified_memory_fs.ptr() == nullptr) { + throw InvalidInputException( + "This operation could not be completed because required module 'fsspec' is not installed"); + } + auto built = std::make_shared(modified_memory_fs()); + auto wrapped = WrapFilesystem(*built); + if (!store->filesystem) { + D_ASSERT(!FileSystemIsRegistered("DUCKDB_INTERNAL_OBJECTSTORE")); + con.GetDatabase().GetFileSystem().RegisterSubSystem(std::move(wrapped)); + store->filesystem = std::move(built); + } } - internal_object_filesystem = std::make_shared(modified_memory_fs()); - auto &abstract_fs = reinterpret_cast(*internal_object_filesystem); - RegisterFilesystem(abstract_fs); + internal_object_filesystem = store->filesystem; } return *internal_object_filesystem; } diff --git a/src/pyconnection/seam.cpp b/src/pyconnection/seam.cpp index a6f8fd43d..356d6bee5 100644 --- a/src/pyconnection/seam.cpp +++ b/src/pyconnection/seam.cpp @@ -629,15 +629,72 @@ bool DuckDBPySeam::IsRegisteredView(ClientContext &context, const string &name) return registered; } +//! The FROM of the first SELECT a query reaches, through its CTEs and set operations +static unique_ptr &FirstFrom(QueryNode &node) { + switch (node.type) { + case QueryNodeType::SELECT_NODE: + return node.Cast().from_table; + case QueryNodeType::CTE_NODE: + return FirstFrom(*node.Cast().child); + case QueryNodeType::RECURSIVE_CTE_NODE: + return FirstFrom(*node.Cast().left); + case QueryNodeType::SET_OPERATION_NODE: + return FirstFrom(*node.Cast().children[0]); + default: + throw InternalException("a view body renders as a SELECT, which carries its sources on its FROM"); + } +} + +//! The reference of a FROM whose copy keeps its dependency: a join's or a pivot's copy drops it, so the leftmost +//! leaf under them carries it, and a copy of the view (its rename) keeps owning its sources +static unique_ptr &OwningReference(unique_ptr &ref) { + switch (ref->type) { + case TableReferenceType::JOIN: + return OwningReference(ref->Cast().left); + case TableReferenceType::PIVOT: + return OwningReference(ref->Cast().source); + default: + return ref; + } +} + +//! The view's query keeps the handles on a FROM: the catalog entry owns the query and a bound copy shares the +//! dependency, so an object store entry the query names by its path lives as long as the view +static void OwnSourcesInView(SQLStatement &statement, shared_ptr sources) { + auto &info = statement.Cast().info->Cast(); + auto &first = FirstFrom(*info.query->node); + if (!first) { + throw InternalException("a view body renders as a SELECT with a FROM, which carries its sources"); + } + auto &from = OwningReference(first); + // A FROM the inliner copied out of the registry shares its dependency with the registry's entry, which must not + // come to hold the handles; the view's own reference gets a dependency of its own with the entry's items + auto owned = make_shared_ptr(); + if (from->external_dependency) { + from->external_dependency->ScanDependencies( + [&](const string &name, shared_ptr item) { owned->AddDependency(name, std::move(item)); }); + } + owned->AddDependency("sources", std::move(sources)); + from->external_dependency = std::move(owned); +} + static void CreateView(DuckDBPyConnection &self, const nb::object &name, const string &sql, bool temporary, - bool replace) { + bool replace, const nb::list &sources) { auto qualified = NameFromParts(name); auto session = OpenSession(self); DUCKDB_PY_ASSERT_GIL_HELD(); + // Built while the GIL is held: the item keeps a reference to the Python list of handles + shared_ptr owned; + if (nb::len(sources) > 0) { + owned = PythonDependencyItem::Create(sources); + } nb::gil_scoped_release release; // One claim from reading the registry to creating the view, so no other call changes either in between auto claim = session.Claim(); auto statement = DuckDBPySeam::ViewStatement(session.Context(), qualified, sql, temporary, replace, false); + if (owned) { + OwnSourcesInView(*statement, std::move(owned)); + } session.RunClaimed(std::move(statement), DuckDBPyConnection::CheckSignals); } @@ -1451,7 +1508,8 @@ void DuckDBPySeam::InitializeConnectionMethods(nb::class_ &m m.def("_create_view", &CreateView, "Create a view of the SELECT in sql, the Python objects it reads held by the view itself, so the view " "reads them for as long as it exists and its transaction decides when they go", - nb::arg("name"), nb::arg("sql"), nb::kw_only(), nb::arg("temporary") = false, nb::arg("replace") = false); + nb::arg("name"), nb::arg("sql"), nb::kw_only(), nb::arg("temporary") = false, nb::arg("replace") = false, + nb::arg("sources") = nb::list()); m.def("_catalog_version", &CatalogVersion, "How many statements that can change what a name binds to have run on this connection's database"); m.def("_own_sources", &OwnSources, diff --git a/tests/fast/api/test_read_csv.py b/tests/fast/api/test_read_csv.py index 4cc81e125..fd610b3d7 100644 --- a/tests/fast/api/test_read_csv.py +++ b/tests/fast/api/test_read_csv.py @@ -1,6 +1,11 @@ import datetime +import gc import platform +import re import sys +import threading +import time +import weakref from io import BytesIO, StringIO from pathlib import Path from typing import NoReturn @@ -733,3 +738,184 @@ def test_files_to_sniff_option(self, tmp_path): rel.fetchall() rel = con.read_csv(file_path, files_to_sniff=-1) assert rel.fetchall() == [("2025-05-12", "baz"), ("bar", "baz")] + + +def _object_store_path(relation): + return re.search(r"DUCKDB_INTERNAL_OBJECTSTORE://[0-9a-f]+", relation.sql_query()).group(0) + + +class TestFilelikeViews: + # The object store entry of a file-like reader must live as long as a view that reads it, not as long as the + # relation the view was made from. + + @pytest.mark.parametrize("make_view", ["to_view", "create_view"]) + @pytest.mark.parametrize("reader", ["read_csv", "read_json"]) + def test_view_outlives_the_relation(self, duckdb_cursor, reader, make_view): + _ = pytest.importorskip("fsspec") + source = StringIO('[{"c1": "a"}]') if reader == "read_json" else StringIO("c1\na") + getattr(getattr(duckdb_cursor, reader)(source), make_view)("v") + gc.collect() + assert duckdb_cursor.sql("SELECT * FROM v").fetchall() == [("a",)] + assert duckdb_cursor.sql("SELECT * FROM v").fetchall() == [("a",)] + + def test_view_over_a_derived_relation(self, duckdb_cursor): + _ = pytest.importorskip("fsspec") + duckdb_cursor.read_csv(StringIO("c1\n1\n2\n3")).filter("c1 > 1").project("c1 * 10 AS c").to_view("v") + gc.collect() + assert duckdb_cursor.sql("SELECT c FROM v ORDER BY c").fetchall() == [(20,), (30,)] + + def test_view_over_two_filelikes(self, duckdb_cursor): + _ = pytest.importorskip("fsspec") + left = duckdb_cursor.read_csv(StringIO("c1\n1")) + right = duckdb_cursor.read_csv(StringIO("c1\n2")) + left.union(right).to_view("v") + del left, right + gc.collect() + assert duckdb_cursor.sql("SELECT c1 FROM v ORDER BY c1").fetchall() == [(1,), (2,)] + + def test_views_share_the_entry(self, duckdb_cursor): + _ = pytest.importorskip("fsspec") + rel = duckdb_cursor.read_csv(StringIO("c1\na")) + path = _object_store_path(rel) + rel.to_view("v1") + rel.to_view("v2") + del rel + gc.collect() + duckdb_cursor.execute("DROP VIEW v1") + gc.collect() + assert duckdb_cursor.sql("SELECT * FROM v2").fetchall() == [("a",)] + duckdb_cursor.execute("DROP VIEW v2") + gc.collect() + with pytest.raises(duckdb.IOException, match="No files found"): + duckdb_cursor.sql(f"SELECT * FROM read_csv('{path}')").fetchall() + + def test_replaced_view_releases_its_entry(self, duckdb_cursor): + _ = pytest.importorskip("fsspec") + first = duckdb_cursor.read_csv(StringIO("c1\na")) + first_path = _object_store_path(first) + first.to_view("v") + del first + duckdb_cursor.read_csv(StringIO("c1\nb")).to_view("v") + gc.collect() + assert duckdb_cursor.sql("SELECT * FROM v").fetchall() == [("b",)] + with pytest.raises(duckdb.IOException, match="No files found"): + duckdb_cursor.sql(f"SELECT * FROM read_csv('{first_path}')").fetchall() + + @pytest.mark.parametrize("shape", ["frame_alone", "frame_union_filelike"]) + def test_view_over_a_registered_frame_releases_the_frame(self, duckdb_cursor, shape): + _ = pytest.importorskip("fsspec") + pd = pytest.importorskip("pandas") + frame = pd.DataFrame({"c1": [1]}) + alive = weakref.ref(frame) + rel = duckdb_cursor.from_df(frame) + if shape == "frame_union_filelike": + rel = rel.union(duckdb_cursor.read_csv(StringIO("c1\n2"))) + # A frame alone puts the registry's own reference, with its shared dependency, in the view's FROM; the union + # puts a CTE there. The registry entry must not come to hold the view's handles, or the frame outlives the view + rel.to_view("v") + del rel, frame + gc.collect() + assert duckdb_cursor.sql("SELECT c1 FROM v ORDER BY c1").fetchall()[0] == (1,) + duckdb_cursor.execute("DROP VIEW v") + gc.collect() + assert alive() is None + + def test_renamed_view_over_a_join_keeps_its_sources(self, duckdb_cursor): + _ = pytest.importorskip("fsspec") + # The engine copies the view to rename it, and a join reference's copy drops what hangs on the join itself + left = duckdb_cursor.read_csv(StringIO("a\n1")) + right = duckdb_cursor.read_csv(StringIO("b\n2")) + left.cross(right).to_view("v") + del left, right + gc.collect() + duckdb_cursor.execute("ALTER VIEW v RENAME TO renamed") + gc.collect() + assert duckdb_cursor.sql("SELECT * FROM renamed").fetchall() == [(1, 2)] + + def test_view_reads_from_a_cursor(self, duckdb_cursor): + _ = pytest.importorskip("fsspec") + duckdb_cursor.read_csv(StringIO("c1\na")).to_view("v") + gc.collect() + assert duckdb_cursor.cursor().sql("SELECT * FROM v").fetchall() == [("a",)] + + +class TestObjectStoreAcrossConnections: + @pytest.mark.parametrize("first", ["cursor", "parent"]) + def test_filelike_reads_on_cursor_and_parent(self, first): + _ = pytest.importorskip("fsspec") + con = duckdb.connect() + cursor = con.cursor() + order = [cursor, con] if first == "cursor" else [con, cursor] + for number, connection in enumerate(order, start=1): + assert connection.read_csv(StringIO(f"c1\n{number}")).fetchall() == [(number,)] + assert con.cursor().read_csv(StringIO("c1\n3")).fetchall() == [(3,)] + + def test_database_closes_after_the_registering_cursor_is_gone(self): + _ = pytest.importorskip("fsspec") + con = duckdb.connect() + cursor = con.cursor() + assert cursor.read_csv(StringIO("c1\n1")).fetchall() == [(1,)] + cursor.close() + del cursor + gc.collect() + # The store's Python object dies with the database, dropped by a connection that never built it + con.close() + + def test_two_connections_to_one_database_file(self, tmp_path): + _ = pytest.importorskip("fsspec") + path = str(tmp_path / "shared.db") + first = duckdb.connect(path) + second = duckdb.connect(path) + assert first.read_csv(StringIO("c1\n1")).fetchall() == [(1,)] + assert second.read_csv(StringIO("c1\n2")).fetchall() == [(2,)] + first.close() + assert second.read_csv(StringIO("c1\n3")).fetchall() == [(3,)] + second.close() + + def test_another_connection_registers_inside_the_fsspec_import(self, monkeypatch): + _ = pytest.importorskip("fsspec") + import builtins + + import duckdb.filesystem + + con = duckdb.connect() + sibling = con.cursor() + original = builtins.__import__ + armed = [True] + + def reenter(name, *args, **kwargs): + # The import the registration runs hands the GIL over; the sibling registers the store meanwhile + if name == "fsspec" and armed[0]: + armed[0] = False + assert sibling.read_csv(StringIO("c1\n2")).fetchall() == [(2,)] + return original(name, *args, **kwargs) + + monkeypatch.setattr(builtins, "__import__", reenter) + assert con.read_csv(StringIO("c1\n1")).fetchall() == [(1,)] + + @pytest.mark.timeout(20) + def test_two_connections_build_the_store_at_once(self, monkeypatch): + _ = pytest.importorskip("fsspec") + from duckdb.filesystem import ModifiedMemoryFileSystem + + original = ModifiedMemoryFileSystem.__init__ + building = threading.Event() + + def slow_init(self, *args, **kwargs): + # Hands the GIL to the other connection in the middle of building the store + building.set() + time.sleep(0.5) + original(self, *args, **kwargs) + + # fsspec hands out a cached instance per thread without calling __init__; a fresh one per build is needed + monkeypatch.setattr(ModifiedMemoryFileSystem, "cachable", False) + monkeypatch.setattr(ModifiedMemoryFileSystem, "__init__", slow_init) + con = duckdb.connect() + cursor = con.cursor() + results = [] + worker = threading.Thread(target=lambda: results.append(cursor.read_csv(StringIO("c1\n1")).fetchall())) + worker.start() + assert building.wait(10) + results.append(con.read_csv(StringIO("c1\n2")).fetchall()) + worker.join() + assert sorted(results) == [[(1,)], [(2,)]] From ed606d92d8dfeed6bc2dedfa53ab2517072ddd17 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Thu, 5 Nov 2026 19:38:05 +0000 Subject: [PATCH 06/61] Read numpy scalars in the appender as the declared object columns read them --- .../duckdb_python/python_conversion.hpp | 4 + src/native/python_conversion.cpp | 52 +++++++ src/numpy/numpy_scan.cpp | 43 +----- src/pyappender.cpp | 6 +- tests/fast/api/test_appender_values.py | 142 +++++++++++++++++- 5 files changed, 209 insertions(+), 38 deletions(-) diff --git a/src/include/duckdb_python/python_conversion.hpp b/src/include/duckdb_python/python_conversion.hpp index ac4fa11a7..7ae4a69f7 100644 --- a/src/include/duckdb_python/python_conversion.hpp +++ b/src/include/duckdb_python/python_conversion.hpp @@ -58,6 +58,10 @@ void TransformPythonObject(optional_ptr context, nb::handle ele, Value TransformPythonValue(optional_ptr context, nb::handle ele, const LogicalType &target_type = LogicalType::UNKNOWN, bool nan_as_null = true); string TransformPythonString(nb::handle str); +//! A numpy scalar, or an array of no dimensions, as its Python value, a datetime64 or timedelta64 at the microsecond +//! unit; one step, so a long double, whose item() is a numpy scalar again, comes back as it is for the conversion to +//! refuse; any other object comes back as it is +nb::object PythonValueOfNumpyScalar(nb::handle cell); //! Needs no GIL InvalidInputException UnencodableStrError(uint32_t codepoint, idx_t position); //! Raises the pending UnicodeEncodeError of a failed UTF-8 conversion of str as the typed error above diff --git a/src/native/python_conversion.cpp b/src/native/python_conversion.cpp index 5a86ae445..fdca84284 100644 --- a/src/native/python_conversion.cpp +++ b/src/native/python_conversion.cpp @@ -71,6 +71,58 @@ void ThrowUnencodableStr(nb::handle str) { throw UnencodableStrError(PyUnicode_ReadChar(str.ptr(), start), NumericCast(start)); } +//! Whether numpy is imported, asked of the module dict without importing it: a numpy scalar cannot exist before +static bool NumpyIsImported(PythonImportCache &import_cache) { + if (import_cache.numpy.LoadSucceeded()) { + return true; + } + static PyObject *const name = PyUnicode_InternFromString("numpy"); + if (!name) { + PyErr_Clear(); + return false; + } + auto module = PyDict_GetItemWithError(PyImport_GetModuleDict(), name); + if (!module && PyErr_Occurred()) { + PyErr_Clear(); + } + return module && module != Py_None; +} + +//! Decided from the object's type, which runs no code of the object's; numpy is optional and loaded by nothing here, +//! so an ordinary value costs no import and no retried import of a missing numpy +static bool IsNumpyScalar(nb::handle cell) { + auto &import_cache = *DuckDBPyConnection::ImportCache(); + if (!NumpyIsImported(import_cache)) { + return false; + } + auto generic = import_cache.numpy.generic(); + auto type = Py_TYPE(cell.ptr()); + if (generic.ptr() != nullptr && PyType_IsSubtype(type, reinterpret_cast(generic.ptr()))) { + return true; + } + // A subclass is not taken: numpy.ma.masked and a masked array of no dimensions carry a payload under their mask + auto ndarray = import_cache.numpy.ndarray(); + return ndarray.ptr() != nullptr && reinterpret_cast(type) == ndarray.ptr() && + nb::cast(cell.attr("ndim")) == 0; +} + +nb::object PythonValueOfNumpyScalar(nb::handle cell) { + if (!IsNumpyScalar(cell)) { + return nb::borrow(cell); + } + auto kind = nb::cast(cell.attr("dtype").attr("kind")); + nb::object value; + if (kind == "M") { + // A nanosecond datetime64 lists as an integer; the microsecond unit lists as a datetime, NaT as None + value = cell.attr("astype")("datetime64[us]").attr("item")(); + } else if (kind == "m") { + value = cell.attr("astype")("timedelta64[us]").attr("item")(); + } else { + value = cell.attr("item")(); + } + return IsNumpyScalar(value) ? nb::borrow(cell) : value; +} + string TransformPythonString(nb::handle str) { Py_ssize_t size; const char *data = PyUnicode_AsUTF8AndSize(str.ptr(), &size); diff --git a/src/numpy/numpy_scan.cpp b/src/numpy/numpy_scan.cpp index ec3cc6159..607f5bfef 100644 --- a/src/numpy/numpy_scan.cpp +++ b/src/numpy/numpy_scan.cpp @@ -305,45 +305,18 @@ class DeclaredCasts { //! A declared column converts a cell as the appender converts a value of a row: with the type the value has in //! Python, then the engine's cast into the column's type, which reads the connection's settings; NaN reads NULL at -//! every depth, and a value without a DuckDB type of its own reads as its text in a text column -//! A numpy scalar, or an array of no dimensions, reads as its Python value; a datetime64 or timedelta64 at -//! nanoseconds would read as an integer, so those take the microsecond unit first, as the frame's own datetime -//! columns do -static bool IsNumpyScalar(nb::handle cell) { - auto &import_cache = *DuckDBPyConnection::ImportCache(); - if (nb::isinstance(cell, import_cache.numpy.generic())) { - return true; - } - // A subclass is not taken: numpy.ma.masked and a masked array of no dimensions carry a payload under their mask - return cell.type().is(import_cache.numpy.ndarray()) && nb::cast(cell.attr("ndim")) == 0; -} - -static nb::object NumpyScalarValue(nb::handle scalar) { - auto kind = nb::cast(scalar.attr("dtype").attr("kind")); - if (kind == "M") { - return scalar.attr("astype")("datetime64[us]").attr("item")(); - } - if (kind == "m") { - return scalar.attr("astype")("timedelta64[us]").attr("item")(); - } - return scalar.attr("item")(); -} - +//! every depth, a numpy scalar reads as its Python value, and a value without a DuckDB type of its own reads as its +//! text in a text column static Value DeclaredValue(ClientContext &context, const LogicalType &target, nb::handle cell) { - if (cell.ptr() == Py_None) { + auto plain = PythonValueOfNumpyScalar(cell); + nb::handle value = plain; + if (value.ptr() == Py_None) { return Value(); } - if (IsNumpyScalar(cell)) { - auto value = NumpyScalarValue(cell); - // A long double's item() is a numpy scalar again; one step, then the conversion refuses what is left - if (!IsNumpyScalar(value)) { - return DeclaredValue(context, target, value); - } - } - if (target.id() == LogicalTypeId::VARCHAR && GetPythonObjectType(cell) == PythonObjectType::Other) { - return Value(TransformPythonString(nb::str(cell))); + if (target.id() == LogicalTypeId::VARCHAR && GetPythonObjectType(value) == PythonObjectType::Other) { + return Value(TransformPythonString(nb::str(value))); } - return TransformPythonValue(context, cell, LogicalType::UNKNOWN, true); + return TransformPythonValue(context, value, LogicalType::UNKNOWN, true); } //! The values of one vector of a declared column, written once the cells are read: a vector whose values share one diff --git a/src/pyappender.cpp b/src/pyappender.cpp index aeb5d4734..963f8214e 100644 --- a/src/pyappender.cpp +++ b/src/pyappender.cpp @@ -484,7 +484,8 @@ void DuckDBPyAppender::ThrowIfBroken() const { } Value DuckDBPyAppender::Convert(ClientContext &context, const nb::handle &object, const LogicalType &type) { - return CastToColumn(context, TransformPythonValue(context, object, LogicalType::UNKNOWN, false), type); + auto plain = PythonValueOfNumpyScalar(object); + return CastToColumn(context, TransformPythonValue(context, plain, LogicalType::UNKNOWN, false), type); } void DuckDBPyAppender::Stage(const vector &row) { @@ -637,7 +638,8 @@ idx_t DuckDBPyAppender::BufferedRows() const { void DuckDBPyAppender::Initialize(nb::handle &m) { auto appender = nb::class_(m, "Appender", nb::is_weak_referenceable()); appender.def("append_row", &DuckDBPyAppender::AppendRow, - "Buffer one row, one value per column, each converted as an executemany parameter would be"); + "Buffer one row, one value per column; a numpy scalar is read as its Python value, then each value is " + "converted as an executemany parameter would be"); appender.def("append_rows", &DuckDBPyAppender::AppendRows, "Buffer each row of an iterable of sequences, stopping at the first bad row and keeping the rows " "before it", diff --git a/tests/fast/api/test_appender_values.py b/tests/fast/api/test_appender_values.py index d0e96ceaf..7f5da0b3f 100644 --- a/tests/fast/api/test_appender_values.py +++ b/tests/fast/api/test_appender_values.py @@ -1,5 +1,9 @@ import datetime as dt import decimal +import os +import subprocess +import sys +import textwrap import uuid from concurrent.futures import ThreadPoolExecutor @@ -241,13 +245,35 @@ def cells(column_type): return VALUES +def python_value_of_numpy_scalar(value): + """The value the appender converts: a numpy scalar, or an array of no dimensions, as its Python value.""" + if not (isinstance(value, np.generic) or (type(value) is np.ndarray and value.ndim == 0)): + return value + kind = value.dtype.kind + if kind == "M": + item = value.astype("datetime64[us]").tolist() + elif kind == "m": + item = value.astype("timedelta64[us]").tolist() + else: + item = value.item() + return value if isinstance(item, np.generic) else item + + def reference_failures(con, values): cursors = [con.cursor() for _ in range(REFERENCE_THREADS)] def share(thread): cursor = cursors[thread] + # The appender reads a numpy scalar as its Python value and converts that as executemany converts it, so the + # reference takes the value the appender reads; for a datetime64 that differs from executemany's own reading + # (its integer), for an int64 or bool executemany refuses the scalar return [ - (i, failure(cursor.executemany, "INSERT INTO ref VALUES (?, ?)", [[i, value]])) + ( + i, + failure( + cursor.executemany, "INSERT INTO ref VALUES (?, ?)", [[i, python_value_of_numpy_scalar(value)]] + ), + ) for i, (_, value) in enumerate(values) if i % REFERENCE_THREADS == thread ] @@ -307,3 +333,117 @@ def test_strings_past_the_inline_length_survive_several_flushes(con, column_type app.flush() assert outcomes(con, "tgt", column_type, values, appended) == expected + + +class TestNumpyScalars: + # The appender reads a numpy scalar as con.append reads one in a declared object column: its Python value, a + # datetime64 or timedelta64 at the microsecond unit. + + @pytest.mark.parametrize( + ("column_type", "value", "expected"), + [ + pytest.param("INTEGER", np.int64(2), 2, id="int64_into_integer"), + pytest.param("DOUBLE", np.float32(2.5), 2.5, id="float32_into_double"), + pytest.param("BOOLEAN", np.bool_(False), False, id="bool_into_boolean"), + pytest.param( + "TIMESTAMP", + np.datetime64("2024-05-08T01:02:03.123456789", "ns"), + dt.datetime(2024, 5, 8, 1, 2, 3, 123456), + id="datetime64_ns_into_timestamp", + ), + pytest.param("INTERVAL", np.timedelta64(1500, "us"), dt.timedelta(microseconds=1500), id="timedelta64_us"), + pytest.param("INTERVAL", np.timedelta64(1501, "ns"), dt.timedelta(microseconds=1), id="timedelta64_ns"), + pytest.param("INTERVAL", np.timedelta64("NaT", "ns"), None, id="timedelta64_nat_is_null"), + pytest.param("VARCHAR", np.str_("a\x00b"), "a\x00b", id="str_scalar_into_varchar"), + pytest.param("BLOB", np.bytes_(b"\x00\xff"), b"\x00\xff", id="bytes_scalar_into_blob"), + pytest.param( + "STRUCT(a INTEGER)", + np.array({"a": 1}, dtype=object), + {"a": 1}, + id="zero_dimensional_object_array_into_struct", + ), + pytest.param("INTEGER", np.array(2), 2, id="zero_dimensional_array_into_integer"), + pytest.param("DOUBLE", np.float64("nan"), float("nan"), id="float64_nan_stays_a_value"), + pytest.param("DOUBLE", np.ma.masked, None, id="masked_singleton_is_null"), + pytest.param("TIMESTAMP", np.datetime64("NaT", "ns"), None, id="datetime64_nat_is_null"), + ], + ) + def test_numpy_scalars_append_as_their_python_values(self, con, column_type, value, expected): + con.execute(f"CREATE OR REPLACE TABLE t (x {column_type})") + with con.appender("t") as appender: + appender.append_row(value) + (stored,) = con.execute("SELECT x FROM t").fetchall()[0] + if isinstance(expected, float) and expected != expected: + assert stored != stored + else: + assert stored == expected + + def test_datetime64_reads_as_a_datetime_not_its_integer(self, con): + # The appender used to hand a datetime64 to the conversion, which read a nanosecond one as its integer + con.execute("CREATE OR REPLACE TABLE t (b BIGINT, v VARCHAR)") + stamp = np.datetime64("2024-05-08T01:02:03.123456789", "ns") + with con.appender("t") as appender: + appender.append_row(None, stamp) + assert con.execute("SELECT v FROM t").fetchall() == [("2024-05-08 01:02:03.123456",)] + with pytest.raises(duckdb.ConversionException), con.appender("t") as appender: + appender.append_row(stamp, None) + + def test_rows_of_a_two_dimensional_array_append(self, con): + con.execute("CREATE OR REPLACE TABLE t (x INTEGER, y DOUBLE)") + with con.appender("t") as appender: + appender.append_rows(np.array([[1, 1.5], [2, 2.5]])) + assert con.execute("SELECT x, y FROM t ORDER BY x").fetchall() == [(1, 1.5), (2, 2.5)] + + def test_nested_numpy_values_keep_their_existing_conversion(self, con): + # A numpy value inside a list keeps the conversion it had, in the appender, executemany and con.append alike: + # a nested int64 is refused, a nested float64 is read as a float + con.execute("CREATE OR REPLACE TABLE t (x DOUBLE[])") + with con.appender("t") as appender: + appender.append_row([np.float64(1.5)]) + assert con.execute("SELECT x FROM t").fetchall() == [([1.5],)] + with pytest.raises(duckdb.NotImplementedException, match=r"numpy\.int64"), con.appender("t") as appender: + appender.append_row([np.int64(1)]) + + def test_an_ordinary_append_imports_no_numpy(self): + # With numpy installed but not imported, an ordinary append must not import it (40 ms) or, without numpy, + # retry the failed import for every value + script = textwrap.dedent( + """ + import sys + import duckdb + con = duckdb.connect() + con.execute("CREATE TABLE t (x INTEGER, s VARCHAR)") + with con.appender("t") as appender: + appender.append_row(1, "a") + print("numpy" in sys.modules, con.execute("SELECT x, s FROM t").fetchall()) + """ + ) + env = {**os.environ, "SKBUILD_EDITABLE_VERBOSE": "0"} + result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=120, env=env) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "False [(1, 'a')]" + + def test_ordinary_values_append_without_numpy(self): + # numpy is optional; the scalar reading must not touch its types when it cannot be imported + script = textwrap.dedent( + """ + import sys + sys.modules["numpy"] = None + import duckdb + con = duckdb.connect() + con.execute("CREATE TABLE t (x INTEGER, s VARCHAR)") + with con.appender("t") as appender: + appender.append_row(1, "a") + print(con.execute("SELECT x, s FROM t").fetchall()) + """ + ) + # An editable install that rebuilds on import otherwise prints its cmake command into the child's stdout + env = {**os.environ, "SKBUILD_EDITABLE_VERBOSE": "0"} + result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=120, env=env) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "[(1, 'a')]" + + def test_numpy_long_double_is_refused(self, con): + con.execute("CREATE OR REPLACE TABLE t (x DOUBLE)") + with pytest.raises(duckdb.NotImplementedException, match="longdouble"), con.appender("t") as appender: + appender.append_row(np.longdouble("2.5")) From b01dc1841e62727992dfa4c9dbae5599800a052d Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Thu, 5 Nov 2026 21:15:36 +0000 Subject: [PATCH 07/61] Pin the classic S3 client for the staging upload and give the h2oai data download real backoff --- .github/workflows/release.yml | 13 ++++++++++++- tests/slow/test_h2oai_arrow.py | 27 ++++++++++++++++----------- 2 files changed, 28 insertions(+), 12 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5fc6fcf7c..49ec9083e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -379,7 +379,18 @@ jobs: AWS_SECRET_ACCESS_KEY: ${{ secrets.S3_DUCKDB_STAGING_KEY }} run: | - aws s3 cp artifacts ${{ needs.workflow_state.outputs.s3_url }} --recursive + # AWS CLI 2.38 made the CRT transfer client the default on every host, and against + # the staging endpoint it failed uploads that the classic client never failed. + aws configure set default.s3.preferred_transfer_client classic + for attempt in 1 2 3; do + if aws s3 cp artifacts "${{ needs.workflow_state.outputs.s3_url }}" --recursive; then + exit 0 + fi + echo "::warning::S3 upload attempt ${attempt} of 3 failed" + if [[ ${attempt} -lt 3 ]]; then sleep $((attempt * 30)); fi + done + echo "::error::S3 upload failed 3 times" + exit 1 publish_pypi: name: Publish Artifacts to PyPI diff --git a/tests/slow/test_h2oai_arrow.py b/tests/slow/test_h2oai_arrow.py index 2831f8520..401bcaeed 100644 --- a/tests/slow/test_h2oai_arrow.py +++ b/tests/slow/test_h2oai_arrow.py @@ -1,5 +1,4 @@ import math -from pathlib import Path import pytest @@ -196,32 +195,38 @@ def test_join(self, threads, function, large_data): @pytest.fixture(scope="module") -def arrow_dataset_register(): +def arrow_dataset_register(tmp_path_factory): """Single fixture to download files and register them on the given connection.""" session = requests.Session() retries = urllib3_util.Retry( allowed_methods={"GET"}, # only retry on GETs (all we do) total=None, # disable to make the below take effect redirect=10, # Don't follow more than 10 redirects in a row - connect=3, # try 3 times before giving up on connection errors - read=3, # try 3 times before giving up on read errors - status=3, # try 3 times before giving up on status errors (see forcelist below) + connect=6, # try 6 times before giving up on connection errors + read=6, # try 6 times before giving up on read errors + status=6, # try 6 times before giving up on status errors (see forcelist below) status_forcelist=[429, *list(range(500, 512))], other=0, # whatever else may cause an error should break - backoff_factor=0.1, # [0.0s, 0.2s, 0.4s] + backoff_factor=2, # [0s, 4s, 8s, 16s, 32s, 64s] outlasts a CI runner losing DNS for a minute raise_on_redirect=True, # raise exception when redirect error retries are exhausted raise_on_status=True, # raise exception when status error retries are exhausted respect_retry_after_header=True, # respect Retry-After headers ) session.mount("https://", requests_adapters.HTTPAdapter(max_retries=retries)) + # Per worker under xdist, so parallel workers never read each other's partial downloads. + data_dir = tmp_path_factory.mktemp("h2oai") saved_filepaths = set() def _register(url, filename, con, tablename) -> None: - r = session.get(url) - filepath = Path(filename) - filepath.write_bytes(r.content) - con.register(tablename, read_csv(filename)) - saved_filepaths.add(filepath) + filepath = data_dir / filename + with session.get(url, stream=True, timeout=(30, 60)) as r: + r.raise_for_status() + # Recorded before the body streams, so a download that breaks halfway is still removed at teardown. + saved_filepaths.add(filepath) + with filepath.open("wb") as f: + for chunk in r.iter_content(chunk_size=1 << 20): + f.write(chunk) + con.register(tablename, read_csv(filepath)) yield _register From 9c07d164fbc57eaf347991911d46f35f9ba39671 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Thu, 5 Nov 2026 22:33:19 +0000 Subject: [PATCH 08/61] Raise a map() function's exception as an engine error and take an all NULL chunk as the bound type --- src/map.cpp | 24 +++++- src/pyfilesystem.cpp | 4 - tests/fast/test_map.py | 180 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 201 insertions(+), 7 deletions(-) diff --git a/src/map.cpp b/src/map.cpp index e97242434..80f7379f8 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -43,8 +43,9 @@ static nb::object FunctionCall(NumpyResultConversion &conversion, const vector(df_obj); @@ -188,6 +189,18 @@ static string TypeVectorToString(const vector &types) { return StringUtil::Join(types, types.size(), ", ", [](const LogicalType &argument) { return argument.ToString(); }); } +//! A returned column the analyzer reads as all NULL binds as NULL, which holds for any type, as OverrideNullType +//! assumes at bind +static bool MatchesBoundTypes(const vector &returned, const vector &bound) { + D_ASSERT(returned.size() == bound.size()); + for (idx_t col_idx = 0; col_idx < returned.size(); col_idx++) { + if (returned[col_idx] != bound[col_idx] && returned[col_idx].id() != LogicalTypeId::SQLNULL) { + return false; + } + } + return true; +} + static OperatorResultType ExecuteMap(ExecutionContext &context, TableFunctionInput &data_p, DataChunk &input, DataChunk &output) { if (input.size() == 0) { @@ -213,7 +226,7 @@ static OperatorResultType ExecuteMap(ExecutionContext &context, TableFunctionInp pandas_return_types.size()); } D_ASSERT(output.GetTypes() == data.out_types); - if (pandas_return_types != output.GetTypes()) { + if (!MatchesBoundTypes(pandas_return_types, output.GetTypes())) { throw InvalidInputException("UDF column type mismatch, expected [%s], got [%s]", TypeVectorToString(data.out_types), TypeVectorToString(pandas_return_types)); } @@ -227,6 +240,11 @@ static OperatorResultType ExecuteMap(ExecutionContext &context, TableFunctionInp } for (idx_t col_idx = 0; col_idx < output.ColumnCount(); col_idx++) { + if (pandas_return_types[col_idx].id() == LogicalTypeId::SQLNULL) { + // The bound type's scanner would read some of these values as data, such as NaT as the text 'NaT'. + ConstantVector::SetNull(output.data[col_idx], count_t(row_count)); + continue; + } auto &bind_data = pandas_bind_data[col_idx]; Vector temp(output.data[col_idx].GetType(), row_count); PandasScanFunction::PandasBackendScanSwitch(context.client, bind_data, row_count, 0, temp); diff --git a/src/pyfilesystem.cpp b/src/pyfilesystem.cpp index 88c6d60be..62a4a44d4 100644 --- a/src/pyfilesystem.cpp +++ b/src/pyfilesystem.cpp @@ -208,10 +208,6 @@ void PythonFilesystem::Seek(duckdb::FileHandle &handle, uint64_t location) { CallPython([&]() -> void { auto seek = PythonFileHandle::GetHandle(handle).attr("seek"); seek(location); - if (PyErr_Occurred()) { - PyErr_PrintEx(1); - throw InvalidInputException("Python exception occurred!"); - } }); } bool PythonFilesystem::CanHandleFile(const string &fpath) { diff --git a/tests/fast/test_map.py b/tests/fast/test_map.py index 926f0b368..6fab9c8f4 100644 --- a/tests/fast/test_map.py +++ b/tests/fast/test_map.py @@ -1,6 +1,7 @@ import gc import itertools import json +import os import re import subprocess import sys @@ -603,3 +604,182 @@ def test_map_result_column_of_another_length_is_refused(kind, rows, length, expl if "words" in outcome: outcome["words"] = named & set(outcome["words"]) assert outcome == {"error": "InvalidInputException", "words": named, "answers": [[[42]], [[42]]]} + + +@pytest.mark.parametrize("explicit_schema", [False, True], ids=["inferred", "explicit_schema"]) +@pytest.mark.parametrize( + ("sql_type", "value"), + [ + pytest.param("BOOLEAN", "i % 2 = 0", id="BOOLEAN"), + pytest.param("VARCHAR", "i::VARCHAR", id="VARCHAR"), + pytest.param("BLOB", "i::VARCHAR::BLOB", id="BLOB"), + pytest.param("UUID", "md5(i::VARCHAR)::UUID", id="UUID"), + pytest.param("INTEGER[]", "[i::INTEGER]", id="LIST"), + pytest.param("STRUCT(a INTEGER)", "{'a': i::INTEGER}", id="STRUCT"), + ], +) +def test_map_identity_round_trips_a_column_with_null_chunks(duckdb_cursor, sql_type, value, explicit_schema): + duckdb_cursor.execute("set threads = 1") + # Of the four 2048 row chunks of a, the first holds no NULL, the second one, the third only NULLs and the fourth + # none again, so a chunk follows the one whose column came back as a constant NULL; n has no NULL at all. + source = duckdb_cursor.sql( + f"select (case when (i < 4096 and i != 3000) or i >= 6144 then {value} end)::{sql_type} as a, i as n " + "from range(8192) t(i)" + ) + mapped = source.map(lambda df: df, schema={"a": sql_type, "n": "BIGINT"} if explicit_schema else None) + assert mapped.types == source.types + assert mapped.fetchall() == source.fetchall() + + +@pytest.mark.parametrize("explicit_schema", [False, True], ids=["inferred", "explicit_schema"]) +@pytest.mark.parametrize( + ("sql_type", "make_missing"), + [ + pytest.param("BIGINT", lambda: None, id="None_for_BIGINT"), + pytest.param("VARCHAR", duckdb.NullValue, id="NullValue_for_VARCHAR"), + pytest.param("VARCHAR", lambda: np.datetime64("NaT", "us"), id="NaT_for_VARCHAR"), + pytest.param("BIGINT", lambda: duckdb.Value(True, duckdb.sqltypes.SQLNULL), id="NULL_typed_Value_for_BIGINT"), + ], +) +def test_map_returned_column_the_analyzer_reads_as_null_is_null(duckdb_cursor, sql_type, make_missing, explicit_schema): + def missing_on_rows(df): + if not len(df): + return df + return df.assign(a=pd.Series([make_missing() for _ in range(len(df))], dtype=object)) + + source = duckdb_cursor.sql(f"select i::{sql_type} as a from range(3) t(i)") + mapped = source.map(missing_on_rows, schema={"a": sql_type} if explicit_schema else None) + assert mapped.types == source.types + assert mapped.fetchall() == [(None,), (None,), (None,)] + + +def test_map_returned_object_column_with_a_value_of_another_type_still_mismatches(duckdb_cursor): + def text_on_rows(df): + return df.assign(a=pd.Series(["x"] + [None] * (len(df) - 1), dtype=object)) if len(df) else df + + mapped = duckdb_cursor.sql("select i as a from range(3) t(i)").map(text_on_rows) + with pytest.raises( + duckdb.InvalidInputException, match=re.escape("UDF column type mismatch, expected [BIGINT], got [VARCHAR]") + ): + mapped.fetchall() + + +MAP_FUNCTION_ERROR = "Python error in the map function: " + + +class CustomBaseException(BaseException): + pass + + +@pytest.mark.parametrize("stage", ["bind", "execution"]) +@pytest.mark.parametrize( + "exc", + [pytest.param(cls, id=cls.__name__) for cls in [ValueError, MemoryError, KeyboardInterrupt, CustomBaseException]], +) +def test_map_function_exception_reaches_the_caller_with_its_type_and_message(duckdb_cursor, capfd, exc, stage): + def boom(df): + if stage == "bind" or len(df): + msg = "boom in map" + raise exc(msg) + return df + + with pytest.raises( + duckdb.InvalidInputException, match=re.escape(f"{MAP_FUNCTION_ERROR}{exc.__name__}: boom in map") + ): + duckdb_cursor.sql("select i as a from range(3) t(i)").map(boom).fetchall() + assert capfd.readouterr().err == "" + _assert_connection_answers(duckdb_cursor) + + +_SYS_EXIT_CHILD = """ +import json +import sys +import threading + +import duckdb + +stage = sys.argv[1] +submitting = threading.get_ident() +exited = threading.Event() +lock = threading.Lock() +exited_on = [] + + +def exit_always(df): + exited_on.append(threading.get_ident()) + sys.exit(3) + + +def exit_on_rows(df): + if len(df): + exited_on.append(threading.get_ident()) + sys.exit(3) + return df + + +def exit_once_off_the_submitting_thread(df): + if not len(df): + return df + if threading.get_ident() == submitting: + # Waiting releases the GIL and holds this task, so a worker thread takes another one and exits. + exited.wait(timeout=10) + return df + with lock: + if exited_on: + return df + exited_on.append(threading.get_ident()) + exited.set() + sys.exit(3) + + +con = duckdb.connect(config={"threads": 4}) if stage == "worker_thread" else duckdb.default_connection() +if stage == "calling_thread": + # One thread runs every task on the thread that fetches. + con.execute("set threads = 1") +try: + if stage == "bind": + con.sql("select i as a from range(10) t(i)").map(exit_always) + elif stage == "calling_thread": + con.sql("select i as a from range(10) t(i)").map(exit_on_rows).fetchall() + else: + # Five row groups give the scan several tasks, where range() gives one. + con.execute("create table t as select range a from range(500000)") + con.table("t").map(exit_once_off_the_submitting_thread).fetchall() + outcome = {"error": None} +except duckdb.Error as error: + outcome = {"error": type(error).__name__, "message": str(error)} +outcome["raised_on_the_submitting_thread"] = [ident == submitting for ident in exited_on] +outcome["answers"] = con.sql("select 42").fetchall() +print("outcome " + json.dumps(outcome), flush=True) +""" + +SYS_EXIT_CHILD_TIMEOUT = 60 + + +@pytest.mark.timeout(2 * SYS_EXIT_CHILD_TIMEOUT) +@pytest.mark.parametrize("stage", ["bind", "calling_thread", "worker_thread"]) +def test_map_function_calling_sys_exit_raises_instead_of_ending_the_process(stage): + # sys.exit in a map function can end or hang the process, so the case runs in a child. + try: + child = subprocess.run( + [sys.executable, "-I", "-c", _SYS_EXIT_CHILD, stage], + capture_output=True, + text=True, + timeout=SYS_EXIT_CHILD_TIMEOUT, + check=False, + # An editable install that rebuilds on import otherwise prints its build output to stderr. + env={**os.environ, "SKBUILD_EDITABLE_VERBOSE": "0"}, + ) + except subprocess.TimeoutExpired as hang: + pytest.fail(f"the child did not finish within {SYS_EXIT_CHILD_TIMEOUT} seconds: {hang.stderr!r}") + assert child.returncode == 0, child.stdout[-2000:] + child.stderr[-2000:] + assert child.stderr == "", child.stderr[-2000:] + outcomes = [ + json.loads(line.removeprefix("outcome ")) for line in child.stdout.splitlines() if line.startswith("outcome ") + ] + assert len(outcomes) == 1, child.stdout[-2000:] + outcome = outcomes[0] + assert outcome["error"] == "InvalidInputException", outcome + assert f"{MAP_FUNCTION_ERROR}SystemExit: 3" in outcome["message"], outcome + assert outcome["raised_on_the_submitting_thread"] == [stage != "worker_thread"] + assert outcome["answers"] == [[42]] From 5b36cbde4250f2213b51da84b461ce7fee64f826 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Thu, 5 Nov 2026 22:51:13 +0000 Subject: [PATCH 09/61] Stop calling classes in type conversion, refuse lone surrogates in names and SQL text, fix the removed method message and the reader stubs --- _duckdb-stubs/__init__.pyi | 24 ++- duckdb/_relation.py | 4 +- scripts/cache_data.json | 63 +++++++ scripts/imports.py | 9 + .../import_cache/modules/numpy_module.hpp | 14 +- src/include/duckdb_python/pytype.hpp | 4 +- src/include/duckdb_python/pyutil.hpp | 11 +- src/native/python_conversion.cpp | 2 +- src/pyconnection.cpp | 2 +- src/python_udf.cpp | 6 + src/pyutil.cpp | 11 ++ src/typing/pytype.cpp | 74 ++++++-- tests/fast/api/test_reader_path_lists.py | 51 ++++++ tests/fast/relational_api/test_rapi_lazy.py | 22 +++ tests/fast/test_type.py | 170 ++++++++++++++++++ tests/fast/test_unencodable_strings.py | 77 +++++++- tests/fast/udf/test_udf_type_names.py | 23 ++- 17 files changed, 523 insertions(+), 44 deletions(-) create mode 100644 tests/fast/api/test_reader_path_lists.py diff --git a/_duckdb-stubs/__init__.pyi b/_duckdb-stubs/__init__.pyi index d1e06b547..fc0a3b4fe 100644 --- a/_duckdb-stubs/__init__.pyi +++ b/_duckdb-stubs/__init__.pyi @@ -233,7 +233,13 @@ class DuckDBPyConnection: def from_arrow(self, arrow_object: object) -> DuckDBPyRelation: ... def from_csv_auto( self, - path_or_buffer: str | bytes | os.PathLike[str] | os.PathLike[bytes] | typing.IO[bytes] | typing.IO[str], + path_or_buffer: str + | bytes + | os.PathLike[str] + | os.PathLike[bytes] + | typing.IO[bytes] + | typing.IO[str] + | Sequence[str | bytes | os.PathLike[str] | os.PathLike[bytes] | typing.IO[bytes] | typing.IO[str]], header: bool | int | None = None, compression: CsvCompression | None = None, sep: str | None = None, @@ -320,7 +326,13 @@ class DuckDBPyConnection: def query_progress(self) -> float: ... def read_csv( self, - path_or_buffer: str | bytes | os.PathLike[str] | os.PathLike[bytes] | typing.IO[bytes] | typing.IO[str], + path_or_buffer: str + | bytes + | os.PathLike[str] + | os.PathLike[bytes] + | typing.IO[bytes] + | typing.IO[str] + | Sequence[str | bytes | os.PathLike[str] | os.PathLike[bytes] | typing.IO[bytes] | typing.IO[str]], header: bool | int | None = None, compression: CsvCompression | None = None, sep: str | None = None, @@ -365,7 +377,13 @@ class DuckDBPyConnection: ) -> DuckDBPyRelation: ... def read_json( self, - path_or_buffer: str | bytes | os.PathLike[str] | os.PathLike[bytes] | typing.IO[bytes] | typing.IO[str], + path_or_buffer: str + | bytes + | os.PathLike[str] + | os.PathLike[bytes] + | typing.IO[bytes] + | typing.IO[str] + | Sequence[str | bytes | os.PathLike[str] | os.PathLike[bytes] | typing.IO[bytes] | typing.IO[str]], *, columns: ColumnsTypes | None = None, sample_size: int | None = None, diff --git a/duckdb/_relation.py b/duckdb/_relation.py index 7088f6eca..381b450dc 100644 --- a/duckdb/_relation.py +++ b/duckdb/_relation.py @@ -1803,7 +1803,7 @@ def _column(self, name: str) -> DuckDBPyRelation: if replacement is not None: msg = ( f"Relations no longer have {name}(): a relation keeps no result between calls, so every call " - f"runs it again. Use {replacement} instead." + f"runs it again. Use {replacement} instead" ) raise AttributeError(msg) msg = f"This relation does not contain a column by the name of '{name}'" @@ -3540,6 +3540,8 @@ def _catalog_relation(con: _duckdb.DuckDBPyConnection, name: str, step_class: ty A dotted name is qualified when its first part names a schema or a database, as SQL reads it, and is one name otherwise. """ + if isinstance(name, str): + _encodable(name) parts = _name_parts(name) if len(parts) > 1 and _seam.name_scope(con, parts[0]) == "none": relation = _catalog_source(con, (name,), step_class, qualified=False) diff --git a/scripts/cache_data.json b/scripts/cache_data.json index 97e26642f..ac797a32a 100644 --- a/scripts/cache_data.json +++ b/scripts/cache_data.json @@ -337,6 +337,15 @@ "numpy.ndarray", "numpy.datetime64", "numpy.generic", + "numpy.number", + "numpy.integer", + "numpy.signedinteger", + "numpy.unsignedinteger", + "numpy.inexact", + "numpy.floating", + "numpy.complexfloating", + "numpy.flexible", + "numpy.character", "numpy.int64", "numpy.bool_", "numpy.byte", @@ -866,5 +875,59 @@ "full_path": "zoneinfo.ZoneInfo", "name": "ZoneInfo", "children": [] + }, + "numpy.number": { + "type": "attribute", + "full_path": "numpy.number", + "name": "number", + "children": [] + }, + "numpy.integer": { + "type": "attribute", + "full_path": "numpy.integer", + "name": "integer", + "children": [] + }, + "numpy.signedinteger": { + "type": "attribute", + "full_path": "numpy.signedinteger", + "name": "signedinteger", + "children": [] + }, + "numpy.unsignedinteger": { + "type": "attribute", + "full_path": "numpy.unsignedinteger", + "name": "unsignedinteger", + "children": [] + }, + "numpy.inexact": { + "type": "attribute", + "full_path": "numpy.inexact", + "name": "inexact", + "children": [] + }, + "numpy.floating": { + "type": "attribute", + "full_path": "numpy.floating", + "name": "floating", + "children": [] + }, + "numpy.complexfloating": { + "type": "attribute", + "full_path": "numpy.complexfloating", + "name": "complexfloating", + "children": [] + }, + "numpy.flexible": { + "type": "attribute", + "full_path": "numpy.flexible", + "name": "flexible", + "children": [] + }, + "numpy.character": { + "type": "attribute", + "full_path": "numpy.character", + "name": "character", + "children": [] } } \ No newline at end of file diff --git a/scripts/imports.py b/scripts/imports.py index b21ab9023..4de973ac2 100644 --- a/scripts/imports.py +++ b/scripts/imports.py @@ -84,6 +84,15 @@ numpy.ndarray numpy.datetime64 numpy.generic +numpy.number +numpy.integer +numpy.signedinteger +numpy.unsignedinteger +numpy.inexact +numpy.floating +numpy.complexfloating +numpy.flexible +numpy.character numpy.int64 numpy.bool_ numpy.byte diff --git a/src/include/duckdb_python/import_cache/modules/numpy_module.hpp b/src/include/duckdb_python/import_cache/modules/numpy_module.hpp index e67ae8935..4da8872d8 100644 --- a/src/include/duckdb_python/import_cache/modules/numpy_module.hpp +++ b/src/include/duckdb_python/import_cache/modules/numpy_module.hpp @@ -41,7 +41,10 @@ struct NumpyCacheItem : public PythonImportCacheItem { public: NumpyCacheItem() : PythonImportCacheItem("numpy"), ma(this), ndarray("ndarray", this), datetime64("datetime64", this), - generic("generic", this), int64("int64", this), bool_("bool_", this), byte("byte", this), + generic("generic", this), number("number", this), integer("integer", this), + signedinteger("signedinteger", this), unsignedinteger("unsignedinteger", this), inexact("inexact", this), + floating("floating", this), complexfloating("complexfloating", this), flexible("flexible", this), + character("character", this), int64("int64", this), bool_("bool_", this), byte("byte", this), ubyte("ubyte", this), short_("short", this), ushort_("ushort", this), intc("intc", this), uintc("uintc", this), int_("int_", this), uint("uint", this), longlong("longlong", this), ulonglong("ulonglong", this), half("half", this), float16("float16", this), single("single", this), @@ -55,6 +58,15 @@ struct NumpyCacheItem : public PythonImportCacheItem { PythonImportCacheItem ndarray; PythonImportCacheItem datetime64; PythonImportCacheItem generic; + PythonImportCacheItem number; + PythonImportCacheItem integer; + PythonImportCacheItem signedinteger; + PythonImportCacheItem unsignedinteger; + PythonImportCacheItem inexact; + PythonImportCacheItem floating; + PythonImportCacheItem complexfloating; + PythonImportCacheItem flexible; + PythonImportCacheItem character; PythonImportCacheItem int64; PythonImportCacheItem bool_; PythonImportCacheItem byte; diff --git a/src/include/duckdb_python/pytype.hpp b/src/include/duckdb_python/pytype.hpp index f62005042..dffc18480 100644 --- a/src/include/duckdb_python/pytype.hpp +++ b/src/include/duckdb_python/pytype.hpp @@ -40,8 +40,8 @@ class DuckDBPyType { //! Convert a Python object (an existing DuckDBPyType, a type string, a Python type object such as `int`, or a //! dict describing a struct) into an owned DuckDBPyType. An existing DuckDBPyType is copied (value semantics); //! anything else is routed through the registered Python constructor, which drives the same factories as the - //! registered implicit conversions. Returns false (clearing any pending Python error) when the object can't be - //! converted, so a caller can raise a context-specific message. + //! registered implicit conversions. Returns false, with no Python error left set, when converting raises an + //! Exception, so a caller can raise a context-specific message; any other BaseException propagates. static bool TryConvert(const nb::object &object, std::unique_ptr &result); //! Converts any form TryConvert accepts, resolving type names against the connection, or the default connection //! when it is null. Raises the conversion's own error instead of returning false. diff --git a/src/include/duckdb_python/pyutil.hpp b/src/include/duckdb_python/pyutil.hpp index def1f84e0..a934929e0 100644 --- a/src/include/duckdb_python/pyutil.hpp +++ b/src/include/duckdb_python/pyutil.hpp @@ -47,15 +47,8 @@ struct PyUtil { // Lenient string conversion: str as is, bytes UTF-8 decoded, anything else via str(). // nanobind's cast rejects bytes/scalars. For identifier/param-key/separator sites. - static std::string CastToString(nb::handle obj) { - if (nb::bytes::check_(obj)) { - return nb::cast(obj.attr("decode")("utf-8")); - } - if (nb::str::check_(obj)) { - return nb::cast(obj); - } - return nb::cast(nb::str(obj)); - } + // A str that UTF-8 cannot encode raises the InvalidInputException naming its first surrogate. + static std::string CastToString(nb::handle obj); #ifndef Py_LIMITED_API // Whether this thread holds the GIL. The stable ABI has no way to ask, so the asserts below exist only in diff --git a/src/native/python_conversion.cpp b/src/native/python_conversion.cpp index 5a86ae445..56d6b0892 100644 --- a/src/native/python_conversion.cpp +++ b/src/native/python_conversion.cpp @@ -91,7 +91,7 @@ static vector TransformStructKeys(nb::handle keys, idx_t size) { for (idx_t i = 0; i < size; i++) { // str() accepts non-string keys, such as the integer keys of a MAP that DuckDB returns as a plain {1: 10} // dict, which nanobind's nb::cast rejects. - res.emplace_back(Identifier(nb::cast(nb::str(keys.attr("__getitem__")(i))))); + res.emplace_back(Identifier(TransformPythonString(nb::str(keys.attr("__getitem__")(i))))); } return res; } diff --git a/src/pyconnection.cpp b/src/pyconnection.cpp index b6704efaf..19a38ef67 100644 --- a/src/pyconnection.cpp +++ b/src/pyconnection.cpp @@ -841,7 +841,7 @@ engine::StatementGroup DuckDBPyConnection::GetStatements(const nb::object &query return engine::StatementGroup(EngineSession(), statement_obj.GetStatement()); } if (nb::isinstance(query)) { - auto sql_query = nb::cast(nb::str(query)); + auto sql_query = TransformPythonString(nb::str(query)); return engine::StatementGroup(EngineSession(), sql_query); } throw InvalidInputException("Please provide either a DuckDBPyStatement or a string representing the query"); diff --git a/src/python_udf.cpp b/src/python_udf.cpp index 79b9686c5..80856721d 100644 --- a/src/python_udf.cpp +++ b/src/python_udf.cpp @@ -563,6 +563,12 @@ struct PythonUDFData { } PyErr_Clear(); return false; + } catch (nb::python_error &error) { + // An interrupt or exit raised while the annotation converted belongs to the caller. + if (!error.matches(PyExc_Exception)) { + throw; + } + return false; } catch (...) { PyErr_Clear(); return false; diff --git a/src/pyutil.cpp b/src/pyutil.cpp index 623912d80..8f1e13270 100644 --- a/src/pyutil.cpp +++ b/src/pyutil.cpp @@ -3,6 +3,7 @@ #include "duckdb/common/exception.hpp" #include "duckdb_python/engine/connection.hpp" #include "duckdb_python/pyconnection/pyconnection.hpp" +#include "duckdb_python/python_conversion.hpp" namespace duckdb { @@ -48,6 +49,16 @@ bool PyUtil::GilCheck() { } #endif +std::string PyUtil::CastToString(nb::handle obj) { + if (nb::bytes::check_(obj)) { + return nb::cast(obj.attr("decode")("utf-8")); + } + if (nb::str::check_(obj)) { + return TransformPythonString(obj); + } + return TransformPythonString(nb::str(obj)); +} + bool PyUtil::IsListLike(nb::handle obj) { if (nb::isinstance(obj) || nb::isinstance(obj)) { return false; diff --git a/src/typing/pytype.cpp b/src/typing/pytype.cpp index 23c7d7aac..4583b075b 100644 --- a/src/typing/pytype.cpp +++ b/src/typing/pytype.cpp @@ -4,6 +4,7 @@ #include "duckdb/common/exception.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb_python/pyconnection/pyconnection.hpp" +#include "duckdb_python/python_conversion.hpp" #include "duckdb/main/connection.hpp" #include "duckdb/common/vector.hpp" @@ -132,15 +133,65 @@ static LogicalType FromString(const string &type_str, std::shared_ptrcon.GetConnection().context, type_str); } +static bool IsAbstractNumpyScalar(const nb::handle &type, NumpyCacheItem &numpy) { + for (auto *base : {&numpy.generic, &numpy.number, &numpy.integer, &numpy.signedinteger, &numpy.unsignedinteger, + &numpy.inexact, &numpy.floating, &numpy.complexfloating, &numpy.flexible, &numpy.character}) { + if (type.is((*base)())) { + return true; + } + } + return false; +} + +//! Whether the numpy class a type is or derives from first is concrete; numpy 1.x gives an abstract base, and a class +//! derived from one, a dtype with a DeprecationWarning, so numpy.dtype must never see them +static bool DerivesFromConcreteNumpyScalar(const nb::handle &type, NumpyCacheItem &numpy) { + nb::tuple mro = type.attr("__mro__"); + auto numpy_module = nb::str("numpy"); + for (auto ancestor : mro) { + if (nb::getattr(ancestor, "__module__", nb::none()).equal(numpy_module)) { + return !IsAbstractNumpyScalar(ancestor, numpy); + } + } + return false; +} + +static bool IsSubclass(const nb::handle &type, const nb::handle &base) { + auto is_subclass = PyObject_IsSubclass(type.ptr(), base.ptr()); + if (is_subclass < 0) { + throw nb::python_error(); + } + return is_subclass != 0; +} + static bool FromNumpyType(const nb::object &type, LogicalType &result) { - // Since this is a type, we have to create an instance from it first. - auto obj = type(); - // We convert these to string because the underlying physical - // types of a numpy type aren't consistent on every platform - if (!nb::hasattr(obj, "dtype")) { + // Only a concrete numpy scalar type is read, through numpy.dtype, so converting a class never calls it. + if (!ModuleIsLoaded()) { + return false; + } + auto &import_cache = *DuckDBPyConnection::ImportCache(); + auto generic = import_cache.numpy.generic(); + if (!generic || !IsSubclass(type, generic) || !DerivesFromConcreteNumpyScalar(type, import_cache.numpy)) { return false; } - string type_str = nb::cast(nb::str(nb::object(obj.attr("dtype")))); + nb::object dtype; + try { + dtype = import_cache.numpy().attr("dtype")(type); + } catch (nb::python_error &error) { + // A scalar class numpy refuses a dtype for is no type either. + if (!error.matches(PyExc_Exception)) { + throw; + } + return false; + } + // numpy maps a class onto the dtype of the scalar type it derives from, and only such a class is that type + nb::object dtype_type = dtype.attr("type"); + if (!IsSubclass(type, dtype_type)) { + return false; + } + // We convert these to string because the underlying physical + // types of a numpy type aren't consistent on every platform + string type_str = nb::cast(nb::str(dtype)); if (type_str == "bool") { result = LogicalType::BOOLEAN; } else if (type_str == "int8") { @@ -311,7 +362,7 @@ static LogicalType FromObject(const nb::object &object, const std::shared_ptr(nb::str(object)); + auto string_value = TransformPythonString(nb::str(object)); return FromString(string_value, connection); } case PythonTypeObject::TYPE: { @@ -365,10 +416,11 @@ bool DuckDBPyType::TryConvert(const nb::object &object, std::unique_ptr()(object); result = MakeType(nb::cast(converted).Type()); return true; - } catch (...) { - // A failed construction (e.g. an unannotated parameter) leaves the Python error indicator set; clear it - // so the caller's subsequent Python operations don't trip on a stale error. - PyErr_Clear(); + } catch (nb::python_error &error) { + // Only an Exception says the object is no type; an interrupt or exit raised meanwhile belongs to the caller. + if (!error.matches(PyExc_Exception)) { + throw; + } return false; } } diff --git a/tests/fast/api/test_reader_path_lists.py b/tests/fast/api/test_reader_path_lists.py new file mode 100644 index 000000000..8d5bcac13 --- /dev/null +++ b/tests/fast/api/test_reader_path_lists.py @@ -0,0 +1,51 @@ +"""A connection's readers take a list of paths, and their annotations say so.""" + +import json +import re + +import pytest + +import duckdb + +READERS = ("read_json", "read_csv", "from_csv_auto") +#: Every path shape the readers take at runtime: one path, a list literal, a list[str] variable, a list of +#: pathlib.Path and a list of a file like object. +ACCEPTED_ARGUMENTS = ('"a"', '["a", "b"]', "paths", '[pathlib.Path("a")]', '[io.BytesIO(b"")]') + + +def annotated_calls(): + """The snippet mypy checks, and the line of each reader's call with a number.""" + lines = ["import io", "import pathlib", "", "import duckdb", "", "con = duckdb.connect()"] + lines.append('paths: list[str] = ["a", "b"]') + refused = {} + for reader in READERS: + lines.extend(f"con.{reader}({argument})" for argument in ACCEPTED_ARGUMENTS) + lines.append(f"con.{reader}(42)") + refused[reader] = len(lines) + return "\n".join(lines) + "\n", refused + + +def test_read_json_reads_every_file_of_a_list(tmp_path): + paths = [] + for name in ("a", "b"): + path = tmp_path / f"{name}.jsonl" + path.write_text(json.dumps({"x": name}) + "\n") + paths.append(path) + con = duckdb.connect() + assert con.read_json([str(p) for p in paths]).order("x").fetchall() == [("a",), ("b",)] + assert con.read_json(paths, format="newline_delimited").order("x").fetchall() == [("a",), ("b",)] + + +def test_mypy_accepts_every_path_shape_and_refuses_a_number(tmp_path): + api = pytest.importorskip("mypy.api") + text, refused = annotated_calls() + snippet = tmp_path / "calls.py" + snippet.write_text(text) + dash = "-" * 2 + flags = [f"{dash}{flag}" for flag in ("strict", "no-incremental", "follow-imports=silent", "no-pretty")] + report, errors, _ = api.run([str(snippet), *flags, f"{dash}cache-dir", str(tmp_path / "cache")]) + found = {int(line): message for line, message in re.findall(r"calls\.py:(\d+): error: (.*)", report)} + assert sorted(found) == sorted(refused.values()), report + errors + for reader, line in refused.items(): + expected = f'Argument 1 to "{reader}" of "DuckDBPyConnection" has incompatible type "int"' + assert expected in found[line], report diff --git a/tests/fast/relational_api/test_rapi_lazy.py b/tests/fast/relational_api/test_rapi_lazy.py index 3e0c634af..00e5f3db2 100644 --- a/tests/fast/relational_api/test_rapi_lazy.py +++ b/tests/fast/relational_api/test_rapi_lazy.py @@ -1,4 +1,7 @@ import re +import subprocess +import sys +import traceback import pytest @@ -99,6 +102,25 @@ def test_a_removed_method_names_its_replacement(self, con, method, replacement): with pytest.raises(AttributeError, match=pattern): getattr(rel, method) + @pytest.mark.parametrize("method", ["fetchone", "fetchmany", "fetch_df_chunk", "execute"]) + def test_a_removed_method_message_reads_on_with_the_suggestion_python_adds(self, con, method): + # Python appends ". Did you mean: 'fetchall'?" when it shows this error and a close name exists. + rel = con.sql("SELECT 1 AS a") + with pytest.raises(AttributeError) as raised: + getattr(rel, method) + assert not str(raised.value).endswith(".") + assert ".." not in "".join(traceback.format_exception_only(raised.value)) + + def test_the_interpreter_shows_the_suggestion_after_one_period(self, tmp_path): + # The interpreter's own display adds the suggestion on every version, traceback formatting only from 3.12. + script = "import duckdb\nduckdb.connect().sql('SELECT 1 AS a').fetchone\n" + # Run outside the checkout, so the child imports the duckdb this process imported. + shown = subprocess.run( + [sys.executable, "-c", script], capture_output=True, text=True, timeout=120, check=False, cwd=tmp_path + ) + assert shown.returncode == 1, shown.stdout + shown.stderr + assert "Use rel.limit(1).fetchall() instead. Did you mean: 'fetchall'?" in shown.stderr, shown.stderr + def test_a_column_named_like_a_removed_method_is_still_reachable(self, con): rel = con.sql("SELECT 1 AS execute, 2 AS fetchone") assert rel["execute"].fetchall() == [(1,)] diff --git a/tests/fast/test_type.py b/tests/fast/test_type.py index 9d2b5b8cb..1637cd2aa 100644 --- a/tests/fast/test_type.py +++ b/tests/fast/test_type.py @@ -1,4 +1,6 @@ +import datetime import sys +import warnings import pytest @@ -260,3 +262,171 @@ def test_children_attribute(self): assert DuckDBPyType("INTEGER[2]").children == [("child", DuckDBPyType("INTEGER")), ("size", 2)] assert DuckDBPyType("INTEGER[2][3]").children == [("child", DuckDBPyType("INTEGER[2]")), ("size", 3)] assert DuckDBPyType("ENUM('a', 'b', 'c')").children == [("values", ["a", "b", "c"])] + + +CONSTRUCTED = [] + + +class Interrupting: + def __init__(self) -> None: + CONSTRUCTED.append(type(self).__name__) + raise KeyboardInterrupt + + +class Failing: + def __init__(self) -> None: + CONSTRUCTED.append(type(self).__name__) + msg = "raised by the constructor" + raise RuntimeError(msg) + + +class Plain: + def __init__(self) -> None: + CONSTRUCTED.append(type(self).__name__) + + +class WithADtype: + """An instance would carry a dtype as a numpy scalar does, which is no reason to read the class as one.""" + + dtype = "int32" + + def __init__(self) -> None: + CONSTRUCTED.append(type(self).__name__) + + +class RaisingName: + """A dict key whose str() raises, so converting a dict that holds it runs code that raises.""" + + def __init__(self, error: type[BaseException]) -> None: + self.error = error + + def __str__(self) -> str: + raise self.error + + +def annotated(annotation): + """A function whose one parameter carries the annotation, for create_function to convert.""" + + def identity(x): + return x + + identity.__annotations__ = {"x": annotation} + return identity + + +def outcome(call): + """What a call returned or raised, so an interrupt that escapes fails the test instead of ending the session.""" + try: + return call() + except BaseException as error: + return error + + +UNKNOWN_CLASSES = [Interrupting, Failing, Plain, WithADtype] + + +class TestAClassThatIsNoType: + """A class that is neither a builtin the conversion knows nor a numpy scalar type is refused without a call.""" + + @pytest.mark.parametrize("cls", UNKNOWN_CLASSES) + @pytest.mark.parametrize( + ("compare", "expected"), + [ + pytest.param(lambda cls: INTEGER == cls, False, id="eq"), # noqa: SIM300 + pytest.param(lambda cls: INTEGER != cls, True, id="ne"), # noqa: SIM300 + pytest.param(lambda cls: INTEGER == {"a": cls}, False, id="eq_struct_field"), # noqa: SIM300 + ], + ) + def test_comparing_with_it_does_not_call_it(self, cls, compare, expected): + CONSTRUCTED.clear() + assert outcome(lambda: compare(cls)) is expected + assert CONSTRUCTED == [] + + @pytest.mark.parametrize("cls", UNKNOWN_CLASSES) + @pytest.mark.parametrize( + ("convert", "error"), + [ + pytest.param(lambda con, cls: DuckDBPyType(cls), TypeError, id="constructor"), + pytest.param(lambda con, cls: con.list_type(cls), TypeError, id="list_type"), + pytest.param(lambda con, cls: con.struct_type({"a": cls}), duckdb.InvalidInputException, id="struct_type"), + pytest.param( + lambda con, cls: con.execute("SELECT ?", [duckdb.Value(1, cls)]), + duckdb.InvalidInputException, + id="value_type", + ), + pytest.param( + lambda con, cls: con.create_function("f", lambda x: x, [cls], BIGINT), TypeError, id="udf_parameter" + ), + ], + ) + def test_converting_it_is_refused_without_calling_it(self, cls, convert, error): + con = duckdb.connect() + CONSTRUCTED.clear() + assert isinstance(outcome(lambda: convert(con, cls)), error) + assert CONSTRUCTED == [] + + def test_a_class_whose_constructor_needs_arguments_gets_the_conversion_s_refusal(self): + with pytest.raises(TypeError, match="Could not convert from unknown 'type' to DuckDBPyType"): + DuckDBPyType(datetime.date) + + def test_a_numpy_scalar_type_still_converts(self): + np = pytest.importorskip("numpy") + + class Subclassed(np.int32): + pass + + assert DuckDBPyType(np.int32) == INTEGER + assert DuckDBPyType(Subclassed) == INTEGER + assert INTEGER == np.int32 # noqa: SIM300 + assert INTEGER != np.int64 # noqa: SIM300 + + @pytest.mark.parametrize( + ("name", "subclassed"), + [ + pytest.param("str_", False, id="str_"), + pytest.param("object_", False, id="object_"), + pytest.param("datetime64", False, id="datetime64"), + pytest.param("void", False, id="void"), + pytest.param("generic", False, id="generic"), + pytest.param("integer", False, id="integer"), + pytest.param("integer", True, id="subclass_of_integer"), + pytest.param("generic", True, id="subclass_of_generic"), + ], + ) + def test_a_numpy_scalar_type_without_a_duckdb_type_is_refused(self, name, subclassed): + np = pytest.importorskip("numpy") + scalar = getattr(np, name) + if subclassed: + scalar = type(f"SubclassOf{name}", (scalar,), {}) + # Warnings are recorded, not raised, so a numpy that converts these with a warning (1.x) fails on either. + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + with pytest.raises(TypeError, match="Could not convert from unknown 'type' to DuckDBPyType"): + DuckDBPyType(scalar) + assert [str(warning.message) for warning in caught] == [] + + +class TestConvertingATypeOperand: + """Converting an operand to a type refuses on an Exception and lets every other BaseException through.""" + + @pytest.mark.parametrize("error", [KeyboardInterrupt, SystemExit]) + @pytest.mark.parametrize( + "convert", + [ + pytest.param(lambda con, fields: INTEGER == fields, id="eq"), # noqa: SIM300 + pytest.param(lambda con, fields: INTEGER != fields, id="ne"), # noqa: SIM300 + pytest.param(lambda con, fields: con.struct_type({"a": fields}), id="struct_type_field"), + pytest.param(lambda con, fields: con.execute("SELECT ?", [duckdb.Value(1, fields)]), id="value_type"), + pytest.param(lambda con, fields: con.create_function("f", annotated(fields)), id="udf_annotation"), + ], + ) + def test_an_interrupt_reaches_the_caller(self, convert, error): + con = duckdb.connect() + with pytest.raises(error): + convert(con, {RaisingName(error): int}) + assert con.execute("SELECT 42").fetchone() == (42,) + + def test_an_exception_makes_the_comparison_false(self): + fields = {RaisingName(RuntimeError): int} + assert (INTEGER == fields) is False # noqa: SIM300 + assert (INTEGER != fields) is True # noqa: SIM300 diff --git a/tests/fast/test_unencodable_strings.py b/tests/fast/test_unencodable_strings.py index 1e6e6dcb3..be9c34665 100644 --- a/tests/fast/test_unencodable_strings.py +++ b/tests/fast/test_unencodable_strings.py @@ -11,7 +11,7 @@ import duckdb import numpy as np import pandas as pd -from duckdb.sqltypes import BIGINT, VARCHAR +from duckdb.sqltypes import BIGINT, VARCHAR, DuckDBPyType def execute_positional(con, text): @@ -149,7 +149,7 @@ def write_csv_na_rep(con, path, text): def refusal(escaped_char, position): - return re.escape(f"cannot encode str as UTF-8, surrogate '{escaped_char}' at position {position}") + return re.escape(f"cannot encode str as UTF-8, surrogate '{escaped_char}' at position {position}") + r"(?!\d)" # A value converted as a Python value, which is every reader option, every parameter and every frame column, reports @@ -267,3 +267,76 @@ def test_object_column_round_trips_inline_and_heap_lengths(kind, encoded_bytes): def test_value_construction_does_not_check(): assert duckdb.Value("\ud800", VARCHAR).object == "\ud800" + + +# Names and SQL text reach the engine as text of their own rather than as a value, and report the offset inside the +# string the caller gave: the SQL text, the key, the parameter name or the table name. +SQL_TEXT_PREFIX = len("SELECT '") + + +def table_with_a_column(con): + con.execute("CREATE TABLE named (x INTEGER)") + return "named" + + +def name_or_text(convert, position, name, *, refused_on="connection"): + return pytest.param(convert, position, refused_on, id=name) + + +#: The connection a conversion runs on, which must stay usable after it refuses; the module runs on the default one. +REFUSED_ON = {"connection": lambda con: con, "cursor": lambda con: con.cursor(), "default": lambda con: duckdb} + + +def execute_text(con, text): + return con.execute(f"SELECT '{text}'") + + +NAME_AND_TEXT_REFUSALS = [ + name_or_text(execute_text, SQL_TEXT_PREFIX, "execute_text"), + name_or_text(lambda con, text: con.executemany(f"SELECT '{text}'", [[]]), SQL_TEXT_PREFIX, "executemany_text"), + name_or_text(execute_text, SQL_TEXT_PREFIX, "cursor_text", refused_on="cursor"), + name_or_text( + lambda con, text: duckdb.execute(f"SELECT '{text}'", connection=con), SQL_TEXT_PREFIX, "module_execute_text" + ), + name_or_text(lambda con, text: con.sql(f"SELECT '{text}'"), SQL_TEXT_PREFIX, "sql_text"), + name_or_text(lambda con, text: con.execute("SELECT ?", [{text: 1}]), 0, "struct_key"), + name_or_text(lambda con, text: con.execute("SELECT ?", [[{"a": {text: 1}}]]), 0, "nested_struct_key"), + name_or_text(lambda con, text: con.executemany("SELECT ?", [[{text: 1}]]), 0, "executemany_struct_key"), + name_or_text(lambda con, text: con.sql("SELECT ?", params=[{text: 1}]).fetchall(), 0, "sql_params_struct_key"), + name_or_text(lambda con, text: con.execute("SELECT $x", {text: 1}), 0, "execute_parameter_name"), + name_or_text(lambda con, text: con.executemany("SELECT $x", [{text: 1}]), 0, "executemany_parameter_name"), + name_or_text(lambda con, text: con.struct_type({text: BIGINT}), 0, "struct_type_field_name"), + name_or_text( + lambda con, text: con.create_function("f", lambda x: x, [{text: int}], int), 0, "type_from_dict_field_name" + ), + name_or_text(lambda con, text: con.create_function("f", lambda x: x, [text], int), 0, "type_name"), + name_or_text( + lambda con, text: con.create_function("f", lambda x: x, [{"a": text}], int), 0, "type_name_of_a_field" + ), + name_or_text(lambda con, text: DuckDBPyType(text), 0, "type_name_on_the_default_connection", refused_on="default"), + name_or_text(lambda con, text: con.appender(table_with_a_column(con), columns=[text]), 0, "appender_column_name"), + name_or_text(lambda con, text: con.table(text), 0, "table_name"), + name_or_text(lambda con, text: con.view(text), 0, "view_name"), + name_or_text(lambda con, text: con.table(f"main.{text}"), len("main."), "qualified_table_name"), + name_or_text(lambda con, text: con.view(f"main.{text}"), len("main."), "qualified_view_name"), +] + + +@pytest.mark.parametrize(("convert", "position", "refused_on"), NAME_AND_TEXT_REFUSALS) +def test_surrogate_in_a_name_or_sql_text_is_refused(convert, position, refused_on): + con = duckdb.connect() + connection = REFUSED_ON[refused_on](con) + with pytest.raises(duckdb.InvalidInputException, match=refusal("\\ud800", position)): + convert(connection, "\ud800") + assert connection.execute("SELECT 42").fetchone() == (42,) + + +@pytest.mark.parametrize("text", ["\u00e9", "\U0001f600"], ids=["two_byte_utf8", "four_byte_utf8"]) +def test_encodable_names_and_sql_text_round_trip(text): + con = duckdb.connect() + assert con.execute(f"SELECT '{text}'").fetchone() == (text,) + assert list(con.execute("SELECT ?", [{text: 1}]).fetchone()[0]) == [text] + assert con.execute(f"SELECT ${text}", {text: 1}).fetchone() == (1,) + assert con.struct_type({text: BIGINT}).children == [(text, BIGINT)] + con.execute(f'CREATE TABLE "{text}" AS SELECT 1 AS x') + assert con.table(text).fetchall() == [(1,)] diff --git a/tests/fast/udf/test_udf_type_names.py b/tests/fast/udf/test_udf_type_names.py index dba4a41f1..f8b9b5859 100644 --- a/tests/fast/udf/test_udf_type_names.py +++ b/tests/fast/udf/test_udf_type_names.py @@ -313,23 +313,21 @@ def query(): target.create_function("block", block, [INTEGER], INTEGER, side_effects=True) worker = threading.Thread(target=query) - # Converting a class annotation instantiates it, so the annotations around y hold and free the connection + # Converting a dict annotation takes str() of its keys, so the annotations around y hold and free the connection class HoldTheConnection: - dtype = "int32" - - def __init__(self) -> None: + def __str__(self) -> str: worker.start() held.append(entered.wait(10)) + return "a" class FreeTheConnection: - dtype = "int32" - - def __init__(self) -> None: + def __str__(self) -> str: freed.append(True) release.set() worker.join(10) + return "a" - def f(x: HoldTheConnection, y: list["INTEGER"], z: FreeTheConnection) -> int: + def f(x: {HoldTheConnection(): int}, y: list["INTEGER"], z: {FreeTheConnection(): int}) -> int: return len(y) try: @@ -352,14 +350,13 @@ def test_a_name_in_an_annotation_inside_an_aborted_transaction_refuses(self, def with pytest.raises(duckdb.BinderException): target.execute("SELECT missing") - # Converting a class annotation instantiates it, so a later annotation can end the aborted transaction + # Converting a dict annotation takes str() of its keys, so a later annotation can end the aborted transaction class RollBack: - dtype = "int32" - - def __init__(self) -> None: + def __str__(self) -> str: target.rollback() + return "a" - def f(x: list["INTEGER"], y: RollBack) -> int: + def f(x: list["INTEGER"], y: {RollBack(): int}) -> int: return len(x) with pytest.raises(duckdb.TransactionException, match="transaction is aborted"): From 3bb144ac79a017c932409facb652668f9203254a Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Thu, 5 Nov 2026 22:53:33 +0000 Subject: [PATCH 10/61] Prune row groups for zoned and time constants in the column's unit, name the column in Arrow refusals, read pandas 2 dictionary strings --- duckdb/_sources/to_arrow.py | 49 +++++-- src/arrow/arrow_importer.cpp | 94 +++++++------ src/arrow/python_arrow_scan.cpp | 9 +- .../duckdb_python/arrow/arrow_importer.hpp | 2 +- src/pandas/bind.cpp | 36 +++-- .../arrow/scan/test_arrow_scan_row_ranges.py | 8 +- .../fast/arrow/scan/test_arrow_scan_rules.py | 6 +- .../arrow/scan/test_python_arrow_scan_core.py | 121 ++++++++++++++--- tests/fast/arrow/scan/test_translators.py | 106 +++++++++++++++ .../arrow/test_dictionary_filter_pushdown.py | 127 ++++++++++++++++-- tests/fast/pandas/test_pandas_string.py | 50 +++++++ 11 files changed, 510 insertions(+), 98 deletions(-) diff --git a/duckdb/_sources/to_arrow.py b/duckdb/_sources/to_arrow.py index 50dd3fe53..310de8b81 100644 --- a/duckdb/_sources/to_arrow.py +++ b/duckdb/_sources/to_arrow.py @@ -1,8 +1,9 @@ """A predicate tree as a pyarrow compute expression that a Dataset scanner evaluates exactly as the engine would. -A constant becomes a scalar of its own engine type, never of the column's Arrow type, so a value between two points -of a coarser column keeps its meaning; a zoned scalar is labelled with the column's zone, since pyarrow compares -across units but not across zones. +A constant becomes a scalar of its own engine type, except a zoned timestamp or time constant, which is compared as a +scalar of the column's own type, the form pyarrow tests against Parquet row group statistics; one between two points +of a coarser column is compared with the point below it, under the operator that keeps its meaning, since no row of +the column equals it. """ from __future__ import annotations @@ -76,7 +77,7 @@ def _translate(node: Node, schema: pa.Schema) -> pc.Expression: return _column(schema, parts)[0].is_valid() case Binary(op=op, left=Col(parts=parts), right=Lit() as constant) if op in _COMPARISONS: field, kind = _column(schema, parts) - compared = _COMPARISONS[op](field, _scalar(constant, kind)) + compared = _compare(op, field, kind, _scalar(constant, kind)) if op in (">", ">=") and pa.types.is_floating(kind): # The engine orders NaN above every number; NaN alone is unequal to itself, also in a dictionary, # where pyarrow has no is_nan kernel. @@ -236,6 +237,24 @@ def _scalar(constant: Lit, kind: pa.DataType) -> pa.Scalar: return pa.scalar(constant.value, own) +def _compare(op: str, field: pc.Expression, kind: pa.DataType, scalar: pa.Scalar) -> pc.Expression: + """`field op scalar`, with a zoned timestamp or time constant in the column's own unit.""" + import pyarrow as pa + import pyarrow.compute as pc + + if not _in_column_unit(kind): + return _COMPARISONS[op](field, scalar) + point, exact = _point_below(scalar.value, kind.unit) + below = pa.scalar(point, kind) + if exact: + return _COMPARISONS[op](field, below) + if op in (">", ">="): + return field > below + if op in ("<", "<="): + return field <= below + return pc.if_else(field.is_valid(), pa.scalar(op == "!="), pa.scalar(None, pa.bool_())) + + def _membership(field: pc.Expression, kind: pa.DataType, values: Sequence[Node]) -> pc.Expression: """Membership of `field` in the constants, each converted exactly to the column's own type.""" import pyarrow as pa @@ -264,17 +283,23 @@ def _held(scalar: pa.Scalar, kind: pa.DataType) -> object: """The scalar's value as a value of the column's type, or None when no row of the column can hold it.""" import pyarrow as pa - if pa.types.is_timestamp(kind) and kind.tz is not None: - return _on_grid(scalar.value, kind.unit) - if pa.types.is_time(kind): - return _on_grid(scalar.value, kind.unit) + if _in_column_unit(kind): + point, exact = _point_below(scalar.value, kind.unit) + return point if exact else None value = scalar.as_py() if pa.types.is_fixed_size_binary(kind) and len(value) != kind.byte_width: return None return value -def _on_grid(count: int, unit: str) -> int | None: - """A count of microseconds as a count of `unit`, or None when it lies between two of them.""" - step = 1_000_000 // _PER_SECOND[unit] - return count // step if count % step == 0 else None +def _in_column_unit(kind: pa.DataType) -> bool: + """Whether a constant arrives in microseconds and is converted into the column's unit: a zoned timestamp or time.""" + import pyarrow as pa + + return pa.types.is_time(kind) or (pa.types.is_timestamp(kind) and kind.tz is not None) + + +def _point_below(count: int, unit: str) -> tuple[int, bool]: + """A count of microseconds as the count of `unit` at or below it, and whether it is exactly that point.""" + point, rest = divmod(count, 1_000_000 // _PER_SECOND[unit]) + return point, rest == 0 diff --git a/src/arrow/arrow_importer.cpp b/src/arrow/arrow_importer.cpp index 7067bc6fd..9c52478d5 100644 --- a/src/arrow/arrow_importer.cpp +++ b/src/arrow/arrow_importer.cpp @@ -37,36 +37,38 @@ bool ValidRange(int64_t offset, int64_t length) { // Arrow buffers need not be aligned to their value type, so a scalar is copied out instead of read through a pointer. template -T LoadAt(const void *buffer, int64_t index) { +T LoadAt(const void *buffer, int64_t index, const string &column) { if (index < 0 || index > NumericLimits::Maximum() / static_cast(sizeof(T))) { - throw InvalidInputException("an Arrow batch addresses row %d of a buffer, beyond what a buffer can hold", - index); + throw InvalidInputException( + "an Arrow batch carried column '%s' that addresses row %d of a buffer, beyond what a buffer can hold", + column, index); } T value; memcpy(&value, static_cast(buffer) + index * static_cast(sizeof(T)), sizeof(T)); return value; } -void CheckNested(const ArrowArray &array, const ArrowType &type, idx_t column) { +void CheckNested(const ArrowArray &array, const ArrowType &type, const string &column) { if (!ValidRange(array.offset, array.length)) { - throw InvalidInputException("an Arrow batch carried column %d with a nested array of offset %d and length %d, " - "which do not describe a range of rows", - column, array.offset, array.length); + throw InvalidInputException( + "an Arrow batch carried column '%s' with a nested array of offset %d and length %d, " + "which do not describe a range of rows", + column, array.offset, array.length); } // The engine reads validity only through the bitmap, so NULL rows would read as values. if (array.null_count > 0 && array.n_buffers > 0 && (!array.buffers || !array.buffers[0])) { throw InvalidInputException( - "an Arrow batch carried column %d with a non-zero null count but no validity bitmap", column); + "an Arrow batch carried column '%s' with a non-zero null count but no validity bitmap", column); } // The engine reads every child its format names, so a missing one would be read through a null pointer. auto child_of = [&](idx_t index) -> const ArrowArray & { if (!array.children || array.n_children <= NumericCast(index) || !array.children[index]) { - throw InvalidInputException("an Arrow batch carried column %d with a nested array missing its child %d", + throw InvalidInputException("an Arrow batch carried column '%s' with a nested array missing its child %d", column, index); } if (!array.children[index]->release) { throw InvalidInputException( - "an Arrow batch carried column %d with a nested array whose child %d is released already", column, + "an Arrow batch carried column '%s' with a nested array whose child %d is released already", column, index); } return *array.children[index]; @@ -76,12 +78,12 @@ void CheckNested(const ArrowArray &array, const ArrowType &type, idx_t column) { const auto rows = array.offset + array.length; const auto width = NumericCast(factor); if (width > 0 && rows > NumericLimits::Maximum() / width) { - throw InvalidInputException("an Arrow batch carried column %d with a nested array too long to address", + throw InvalidInputException("an Arrow batch carried column '%s' with a nested array too long to address", column); } const auto needed = rows * width; if (child.length < needed) { - throw InvalidInputException("Arrow array child length does not match the array length: column %d holds a " + throw InvalidInputException("Arrow array child length does not match the array length: column '%s' holds a " "nested array of %d rows where %d were expected", column, child.length, needed); } @@ -89,15 +91,16 @@ void CheckNested(const ArrowArray &array, const ArrowType &type, idx_t column) { switch (type.GetPhysicalType()) { case ArrowArrayPhysicalType::DICTIONARY_ENCODED: if (!array.dictionary) { - throw InvalidInputException("an Arrow batch carried column %d with a dictionary-encoded array that has no " - "dictionary", - column); - } - if (!array.dictionary->release) { throw InvalidInputException( - "an Arrow batch carried column %d with a dictionary-encoded array whose dictionary is released already", + "an Arrow batch carried column '%s' with a dictionary-encoded array that has no " + "dictionary", column); } + if (!array.dictionary->release) { + throw InvalidInputException("an Arrow batch carried column '%s' with a dictionary-encoded array whose " + "dictionary is released already", + column); + } CheckNested(*array.dictionary, type.GetDictionary(), column); return; case ArrowArrayPhysicalType::RUN_END_ENCODED: { @@ -105,9 +108,10 @@ void CheckNested(const ArrowArray &array, const ArrowType &type, idx_t column) { auto &run_ends = child_of(0); auto &values = child_of(1); if (run_ends.length != values.length) { - throw InvalidInputException("an Arrow batch carried column %d with a run end encoded array of %d run ends " - "and %d values", - column, run_ends.length, values.length); + throw InvalidInputException( + "an Arrow batch carried column '%s' with a run end encoded array of %d run ends " + "and %d values", + column, run_ends.length, values.length); } CheckNested(run_ends, info.GetChild(0), column); CheckNested(values, info.GetChild(1), column); @@ -116,31 +120,32 @@ void CheckNested(const ArrowArray &array, const ArrowType &type, idx_t column) { if (run_ends.length > 0) { if (run_ends.n_buffers < 2 || !run_ends.buffers || !run_ends.buffers[1]) { throw InvalidInputException( - "an Arrow batch carried column %d with a run end encoded array whose run ends have no values", + "an Arrow batch carried column '%s' with a run end encoded array whose run ends have no values", column); } const auto index = run_ends.offset + run_ends.length - 1; switch (info.GetChild(0).GetDuckType().id()) { case LogicalTypeId::SMALLINT: - last_end = LoadAt(run_ends.buffers[1], index); + last_end = LoadAt(run_ends.buffers[1], index, column); break; case LogicalTypeId::INTEGER: - last_end = LoadAt(run_ends.buffers[1], index); + last_end = LoadAt(run_ends.buffers[1], index, column); break; case LogicalTypeId::BIGINT: - last_end = LoadAt(run_ends.buffers[1], index); + last_end = LoadAt(run_ends.buffers[1], index, column); break; default: throw InvalidInputException( - "an Arrow batch carried column %d with a run end encoded array whose run ends " + "an Arrow batch carried column '%s' with a run end encoded array whose run ends " "are %s, not SMALLINT, INTEGER or BIGINT", column, info.GetChild(0).GetDuckType().ToString()); } } if (array.length > 0 && last_end < array.offset + array.length) { - throw InvalidInputException("an Arrow batch carried column %d with a run end encoded array whose runs end " - "at %d before its %d rows", - column, last_end, array.offset + array.length); + throw InvalidInputException( + "an Arrow batch carried column '%s' with a run end encoded array whose runs end " + "at %d before its %d rows", + column, last_end, array.offset + array.length); } return; } @@ -156,7 +161,7 @@ void CheckNested(const ArrowArray &array, const ArrowType &type, idx_t column) { auto &info = type.GetTypeInfo(); // The engine converts every child the array has into vectors sized by the type. if (array.n_children != NumericCast(info.ChildCount())) { - throw InvalidInputException("an Arrow batch carried column %d with a struct or union of %d child arrays " + throw InvalidInputException("an Arrow batch carried column '%s' with a struct or union of %d child arrays " "where its type has %d", column, array.n_children, info.ChildCount()); } @@ -173,29 +178,30 @@ void CheckNested(const ArrowArray &array, const ArrowType &type, idx_t column) { auto &child = child_of(0); auto value_at = [&](idx_t buffer, int64_t index) -> int64_t { if (info.GetSizeType() == ArrowVariableSizeType::SUPER_SIZE) { - return LoadAt(array.buffers[buffer], index); + return LoadAt(array.buffers[buffer], index, column); } - return LoadAt(array.buffers[buffer], index); + return LoadAt(array.buffers[buffer], index, column); }; // The child's own range is checked first, so the offset checks below compare against a valid length. CheckNested(child, info.GetChild(), column); if (!info.IsView() && array.length > 0) { if (array.n_buffers < 2 || !array.buffers || !array.buffers[1]) { - throw InvalidInputException("an Arrow batch carried column %d with a list that has no offsets", column); + throw InvalidInputException("an Arrow batch carried column '%s' with a list that has no offsets", + column); } // The engine takes the child rows to read from the first and the last offset. const auto first = value_at(1, array.offset); const auto last = value_at(1, array.offset + array.length); if (first < 0 || first > last || last > child.length) { throw InvalidInputException( - "an Arrow batch carried column %d with a list whose offsets %d to %d do not " + "an Arrow batch carried column '%s' with a list whose offsets %d to %d do not " "fit its child of %d rows", column, first, last, child.length); } } else if (info.IsView() && array.length > 0) { if (array.n_buffers < 3 || !array.buffers || !array.buffers[1] || !array.buffers[2]) { throw InvalidInputException( - "an Arrow batch carried column %d with a list view that has no offsets or sizes", column); + "an Arrow batch carried column '%s' with a list view that has no offsets or sizes", column); } // The engine reads the child from the lowest offset to the highest end of every list with a size. for (int64_t row = array.offset; row < array.offset + array.length; row++) { @@ -203,7 +209,7 @@ void CheckNested(const ArrowArray &array, const ArrowType &type, idx_t column) { const auto start = value_at(1, row); if (size != 0 && (size < 0 || start < 0 || start > child.length - size)) { throw InvalidInputException( - "an Arrow batch carried column %d with a list view whose list at row %d " + "an Arrow batch carried column '%s' with a list view whose list at row %d " "reaches past its child of %d rows", column, row - array.offset, child.length); } @@ -275,6 +281,7 @@ ArrowBatchImporter::ArrowBatchImporter(ClientContext &context, shared_ptr ArrowBatchImporter::Adopt(ArrowArray &incoming) const { const auto expected = arrow_columns.size(); + auto &names = schema->GetNames(); if (incoming.n_children < 0 || NumericCast(incoming.n_children) != expected) { throw InvalidInputException("an Arrow batch carried %d columns where %d were expected", incoming.n_children, expected); @@ -291,24 +298,25 @@ shared_ptr ArrowBatchImporter::Adopt(ArrowArray &incoming) co for (idx_t i = 0; i < expected; i++) { auto child = incoming.children[i]; if (!child || !child->release) { - throw InvalidInputException("an Arrow batch carried column %d missing or released already", i); + throw InvalidInputException("an Arrow batch carried column '%s' missing or released already", names[i]); } if (!ValidRange(child->offset, child->length)) { - throw InvalidInputException("an Arrow batch carried column %d with offset %d and length %d, which do not " + throw InvalidInputException("an Arrow batch carried column '%s' with offset %d and length %d, which do not " "describe a range of rows", - i, child->offset, child->length); + names[i], child->offset, child->length); } if (child->length < rows_needed) { - throw InvalidInputException("Arrow array child length does not match the array length: column %d holds %d " - "rows where %d were expected", - i, child->length, rows_needed); + throw InvalidInputException( + "Arrow array child length does not match the array length: column '%s' holds %d " + "rows where %d were expected", + names[i], child->length, rows_needed); } } if (incoming.null_count > 0 && (incoming.n_buffers == 0 || !incoming.buffers || !incoming.buffers[0])) { throw InvalidInputException("an Arrow batch has a non-zero null count but no validity bitmap"); } for (auto column : columns) { - CheckNested(*incoming.children[column], *arrow_columns.at(column), column); + CheckNested(*incoming.children[column], *arrow_columns.at(column), names[column]); } auto owned = make_shared_ptr(); owned->arrow_array = incoming; diff --git a/src/arrow/python_arrow_scan.cpp b/src/arrow/python_arrow_scan.cpp index 326616666..ba74e3c1a 100644 --- a/src/arrow/python_arrow_scan.cpp +++ b/src/arrow/python_arrow_scan.cpp @@ -280,6 +280,8 @@ struct PythonArrowScanBindData : public TableFunctionData { shared_ptr info; //! The Arrow names of the declared columns, empty for a nameless array vector raw_names; + //! The names the scan binds the declared columns to + vector bound_names; vector types; ArrowTableSchema arrow_table; PredicateColumns predicate_columns; @@ -450,7 +452,8 @@ unique_ptr PythonArrowScanBind(ClientContext &context, TableFuncti for (idx_t i = 0; i < result->types.size(); i++) { auto raw = NameOf(arrow_schema, i); // A plain array has no column name of its own; the engine would call it v0. - names.emplace_back(schema->wrapped && raw.empty() ? string("value") : resolved_names[i]); + result->bound_names.push_back(schema->wrapped && raw.empty() ? string("value") : resolved_names[i]); + names.emplace_back(result->bound_names.back()); result->raw_names.push_back(std::move(raw)); } result->predicate_columns = PredicateColumns(arrow_schema, result->types); @@ -660,6 +663,9 @@ unique_ptr PythonArrowScanInitGlobal(ClientContext &co result->arrow_table = make_shared_ptr(); ResolveBatchSchema(context, *result->arrow_table, schema); auto &types = result->arrow_table->GetTypes(); + // The engine names a stream's nameless or repeated columns by their place in the stream, which a narrowed stream + // changes, so the stream's columns take the names the scan bound them to. + auto &stream_names = result->arrow_table->GetNames(); for (idx_t i = 0; i < fields; i++) { const auto expected = exported.projected ? requested[i] : i; const auto name = NameOf(schema, i); @@ -671,6 +677,7 @@ unique_ptr PythonArrowScanInitGlobal(ClientContext &co throw InvalidInputException("%s answered with column '%s' of type %s where %s was declared", source_subject, name, types[i].ToString(), bind_data.types[expected].ToString()); } + stream_names[i] = bind_data.bound_names[expected]; } // One vector ranges under verify_parallelism, as in the engine's own scans, so queries under it cross range ends. result->range_rows = diff --git a/src/include/duckdb_python/arrow/arrow_importer.hpp b/src/include/duckdb_python/arrow/arrow_importer.hpp index 1f028bd3a..ff6db8115 100644 --- a/src/include/duckdb_python/arrow/arrow_importer.hpp +++ b/src/include/duckdb_python/arrow/arrow_importer.hpp @@ -22,7 +22,7 @@ void ReadArrowColumn(Vector &vector, ArrowArray &array, const ArrowType &arrow_t //! share a batch by reading different ranges of it. class ArrowBatchImporter { public: - //! Output column i is read from batch column columns[i] + //! Output column i is read from batch column columns[i]; a refusal names a batch column by its name in `schema` ArrowBatchImporter(ClientContext &context, shared_ptr schema, vector columns); //! Checks the batch's shape against the schema and takes it over, clearing its release; a refused batch keeps it diff --git a/src/pandas/bind.cpp b/src/pandas/bind.cpp index 73b202055..3cbae125a 100644 --- a/src/pandas/bind.cpp +++ b/src/pandas/bind.cpp @@ -83,29 +83,49 @@ void CheckColumnArray(const string &column, nb::handle array, idx_t row_count, c //! a column whose chunks are shorter than this on average is cheaper to convert. static constexpr idx_t ARROW_ROWS_PER_CHUNK = 50; -//! The column read from its own chunks, or null when it is to be converted with to_numpy instead +//! The column read from its own chunks, decoded first when they are dictionary encoded, or null when it is to be +//! converted with to_numpy instead static unique_ptr BindArrowStringColumn(ClientContext &context, const string &name, nb::handle pandas_array, idx_t row_count, const string &counted_from) { nb::object chunked_array = pandas_array.attr("__arrow_array__")(); - nb::object pyarrow_type = chunked_array.attr("type"); // Before pyarrow 14 nothing exports through capsules. - if (!PyUtil::HasAttribute(pyarrow_type, "__arrow_c_schema__")) { + if (!PyUtil::HasAttribute(chunked_array.attr("type"), "__arrow_c_schema__")) { return nullptr; } - if (row_count < ARROW_ROWS_PER_CHUNK * nb::cast(chunked_array.attr("num_chunks"))) { + auto subject = StringUtil::Format("column '%s'", name); + auto resolve = [&]() { + nb::object schema = chunked_array.attr("type").attr("__arrow_c_schema__")(); + return ArrowType::GetArrowLogicalType(context, InCapsule(schema, "arrow_schema", subject)); + }; + auto arrow_type = resolve(); + const bool short_chunks = row_count < ARROW_ROWS_PER_CHUNK * nb::cast(chunked_array.attr("num_chunks")); + nb::object chunks; + if (arrow_type->GetPhysicalType() == ArrowArrayPhysicalType::DICTIONARY_ENCODED) { + // pandas 2 keeps the dictionary its array was built from, which pandas 2.2 cannot convert with to_numpy before + // pyarrow 25, so it is decoded and read here at any chunk length. + nb::object value_type = chunked_array.attr("type").attr("value_type"); + if (short_chunks) { + // A cast and an export per chunk would cost more than the conversion they replace, so the chunks are + // combined and decoded once. + chunked_array = chunked_array.attr("combine_chunks")().attr("cast")(value_type); + chunks = nb::make_tuple(chunked_array); + } else { + chunked_array = chunked_array.attr("cast")(value_type); + } + arrow_type = resolve(); + } else if (short_chunks) { return nullptr; } - auto subject = StringUtil::Format("column '%s'", name); - nb::object schema = pyarrow_type.attr("__arrow_c_schema__")(); - auto arrow_type = ArrowType::GetArrowLogicalType(context, InCapsule(schema, "arrow_schema", subject)); // Only a plain layout may be read without the engine adopting the chunks. if (arrow_type->GetDuckType().id() != LogicalTypeId::VARCHAR || arrow_type->GetPhysicalType() != ArrowArrayPhysicalType::DEFAULT) { return nullptr; } auto result = make_uniq(std::move(arrow_type)); - nb::object chunks = chunked_array.attr("chunks"); + if (!chunks.is_valid()) { + chunks = chunked_array.attr("chunks"); + } for (auto chunk : chunks) { auto exported = nb::cast(chunk.attr("__arrow_c_array__")()); result->AddChunk(InCapsule(exported[1], "arrow_array", subject)); diff --git a/tests/fast/arrow/scan/test_arrow_scan_row_ranges.py b/tests/fast/arrow/scan/test_arrow_scan_row_ranges.py index fbfd75a82..1b404bd98 100644 --- a/tests/fast/arrow/scan/test_arrow_scan_row_ranges.py +++ b/tests/fast/arrow/scan/test_arrow_scan_row_ranges.py @@ -663,7 +663,7 @@ def test_a_projected_column_of_large_batches_keeps_its_values(self, release_tabl pytest.param( core._shorten_first_column, "Arrow array child length does not match the array length:" - f" column 0 holds 1 rows where {LARGE_BATCH} were expected", + f" column 'i' holds 1 rows where {LARGE_BATCH} were expected", id="short_column", ), pytest.param( @@ -892,8 +892,9 @@ def hold_gil(x): def _list_of_dictionary(empty, valued): - indices = pa.array(np.arange(2 * valued, dtype=np.int32) % 3) - child = pa.DictionaryArray.from_arrays(indices, pa.array(["x", "y", "z"])) + # Every list element names its own dictionary entry, in reverse, so a decode shifted by any amount reads other text. + indices = pa.array(np.arange(2 * valued, dtype=np.int32)[::-1]) + child = pa.DictionaryArray.from_arrays(indices, pa.array([f"v{index}" for index in range(2 * valued)])) offsets = [0] * (empty + 1) + [2 * (i + 1) for i in range(valued)] return pa.ListArray.from_arrays(pa.array(offsets, pa.int32()), child) @@ -926,3 +927,4 @@ def test_a_list_of_dictionaries_after_a_vector_of_empty_lists_reads_its_lists(se assert con.execute("SELECT count(*), sum(len(l)) FROM src").fetchall() == expected assert con.execute(f"SELECT l FROM src LIMIT 5 OFFSET {empty - 2}").fetchall() == first_valued assert con.execute(f"SELECT l FROM src OFFSET {len(column) - 3}").fetchall() == last + assert con.execute("SELECT l FROM src").fetchall() == [(value,) for value in column.to_pylist()] diff --git a/tests/fast/arrow/scan/test_arrow_scan_rules.py b/tests/fast/arrow/scan/test_arrow_scan_rules.py index 49d3b50fc..d74c8dc59 100644 --- a/tests/fast/arrow/scan/test_arrow_scan_rules.py +++ b/tests/fast/arrow/scan/test_arrow_scan_rules.py @@ -616,12 +616,12 @@ def test_the_release_count_sees_an_array_still_held(self): ("mangle", "message"), [ pytest.param("child_count", "carried 3 columns where 2 were expected", id="child_count"), - pytest.param("null_child", "carried column 0 missing or released already", id="null_child_pointer"), - pytest.param("released_child", "carried column 0 missing or released already", id="released_child"), + pytest.param("null_child", "carried column 'i' missing or released already", id="null_child_pointer"), + pytest.param("released_child", "carried column 'i' missing or released already", id="released_child"), pytest.param("negative_length", "which do not describe a range of rows", id="negative_length"), pytest.param( "longer_than_children", - "column 0 holds 1000 rows where 10000 were expected", + "column 'i' holds 1000 rows where 10000 were expected", id="longer_than_children", ), ], diff --git a/tests/fast/arrow/scan/test_python_arrow_scan_core.py b/tests/fast/arrow/scan/test_python_arrow_scan_core.py index fc580a61e..92a88827c 100644 --- a/tests/fast/arrow/scan/test_python_arrow_scan_core.py +++ b/tests/fast/arrow/scan/test_python_arrow_scan_core.py @@ -1775,59 +1775,59 @@ def _drop_the_validity_bitmap(column, pokes): "short_struct_child": ( _struct_table, lambda column, pokes: pokes.set(ctypes.c_int64, _field(_child(column, 0), "length"), 1), - "column 0 holds a nested array of 1 rows where 2000 were expected", + "column 's' holds a nested array of 1 rows where 2000 were expected", ), "nested_offset_overflow": ( _struct_table, lambda column, pokes: pokes.set(ctypes.c_int64, _field(_child(column, 0), "offset"), 2**63 - 1), - "column 0 with a nested array of offset 9223372036854775807 and length 2000", + "column 's' with a nested array of offset 9223372036854775807 and length 2000", ), "missing_child": ( _struct_table, lambda column, pokes: pokes.set(ctypes.c_void_p, ctypes.cast(column.children, ctypes.c_void_p).value, None), - "column 0 with a nested array missing its child 0", + "column 's' with a nested array missing its child 0", ), "extra_child": ( _struct_table, lambda column, pokes: pokes.set(ctypes.c_int64, _field(column, "n_children"), 2), - "column 0 with a struct or union of 2 child arrays where its type has 1", + "column 's' with a struct or union of 2 child arrays where its type has 1", ), "released_child": ( _struct_table, lambda column, pokes: pokes.set(ctypes.c_void_p, _field(_child(column, 0), "release"), None), - "column 0 with a nested array whose child 0 is released already", + "column 's' with a nested array whose child 0 is released already", ), "released_dictionary": ( lambda: pa.table({"d": pa.array(["a", "b"] * 1_000).dictionary_encode()}), lambda column, pokes: pokes.set(ctypes.c_void_p, column.dictionary + _ArrowArray.release.offset, None), - "column 0 with a dictionary-encoded array whose dictionary is released already", + "column 'd' with a dictionary-encoded array whose dictionary is released already", ), "run_ends_out_of_range": ( _run_end_table, lambda column, pokes: pokes.set(ctypes.c_int64, _field(_child(column, 0), "offset"), -1), - "column 0 with a nested array of offset -1 and length 2", + "column 'r' with a nested array of offset -1 and length 2", ), "run_ends_and_values_unequal": ( _run_end_table, lambda column, pokes: pokes.set(ctypes.c_int64, _field(_child(column, 1), "length"), 1), - "column 0 with a run end encoded array of 2 run ends and 1 values", + "column 'r' with a run end encoded array of 2 run ends and 1 values", ), "list_offsets_beyond_child": ( lambda: pa.table({"l": pa.array([[i] for i in range(2_000)])}), lambda column, pokes: pokes.set(ctypes.c_int64, _field(_child(column, 0), "length"), 1_999), - "column 0 with a list whose offsets 0 to 2000 do not fit its child of 1999 rows", + "column 'l' with a list whose offsets 0 to 2000 do not fit its child of 1999 rows", ), "list_view_without_sizes": ( lambda: pa.table({"l": pa.array([[1], [2, 3]] * 1_000, type=pa.list_view(pa.int64()))}), lambda column, pokes: pokes.set(ctypes.c_void_p, column.buffers + 2 * ctypes.sizeof(ctypes.c_void_p), None), - "column 0 with a list view that has no offsets or sizes", + "column 'l' with a list view that has no offsets or sizes", ), "run_ends_stop_before_the_rows": ( lambda: pa.table({"l": pa.FixedSizeListArray.from_arrays(_run_end_array(6), 2).slice(1)}), lambda column, pokes: [ pokes.set(ctypes.c_int64, _field(_child(_child(column, 0), index), "length"), 1) for index in (0, 1) ], - "column 0 with a run end encoded array whose runs end at 3 before its 6 rows", + "column 'l' with a run end encoded array whose runs end at 3 before its 6 rows", ), "list_view_past_its_child": ( lambda: pa.table( @@ -1838,35 +1838,118 @@ def _drop_the_validity_bitmap(column, pokes): } ), lambda column, pokes: pokes.set(ctypes.c_int64, _field(_child(column, 0), "length"), 1), - "column 0 with a list view whose list at row 0 reaches past its child of 1 rows", + "column 'l' with a list view whose list at row 0 reaches past its child of 1 rows", ), "run_ends_of_tinyint": ( lambda: pa.table( {"r": pa.RunEndEncodedArray.from_arrays(pa.array([4], pa.int16()), pa.array([7], pa.int64()))} ), None, - "column 0 with a run end encoded array whose run ends are TINYINT, not SMALLINT, INTEGER or BIGINT", + "column 'r' with a run end encoded array whose run ends are TINYINT, not SMALLINT, INTEGER or BIGINT", # The one int16 run end of 4 reads as the int8 run end 4 on a little endian machine. lambda field: ctypes.memmove(_ArrowSchemaHead.from_address(field.children[0]).format, b"c", 1), ), "null_count_without_bitmap": ( lambda: pa.table({"i": pa.array([1, None] * 1_000)}), _drop_the_validity_bitmap, - "column 0 with a non-zero null count but no validity bitmap", + "column 'i' with a non-zero null count but no validity bitmap", ), "struct_child_null_count_without_bitmap": ( lambda: pa.table({"s": pa.StructArray.from_arrays([pa.array([1, None] * 1_000)], ["x"])}), lambda column, pokes: _drop_the_validity_bitmap(_child(column, 0), pokes), - "column 0 with a non-zero null count but no validity bitmap", + "column 's' with a non-zero null count but no validity bitmap", ), "list_child_null_count_without_bitmap": ( lambda: pa.table({"l": pa.array([[1, None]] * 1_000)}), lambda column, pokes: _drop_the_validity_bitmap(_child(column, 0), pokes), - "column 0 with a non-zero null count but no validity bitmap", + "column 'l' with a non-zero null count but no validity bitmap", ), } +class NarrowingPokingSource(PythonStreamSource): + """One batch of the requested columns, narrowed as a projecting source does, whose column `name` `poke` changes.""" + + def __init__(self, table, name, poke) -> None: + super().__init__(table, max_chunksize=table.num_rows) + self.name = name + self.poke = poke + + def stream(self, columns, filters): + table = self.table if columns is None else self.table.select(list(columns)) + stream = PokingStream(table.schema, table.to_batches(max_chunksize=table.num_rows), None) + index = table.schema.get_field_index(self.name) + stream.corrupt = lambda array: self.poke(array.children[index].contents, stream.pokes) + self.streams.append(stream) + return stream.capsule(), columns is not None + + +class PlainArrayPokingSource(PythonStreamSource): + """A stream of one plain array, which the scan reads as a column of its own, changed by `poke` after the export.""" + + def __init__(self, array, poke) -> None: + super().__init__(pa.table({"unused": array})) + self.array = array + self.poke = poke + + def __arrow_c_schema__(self) -> object: + return self.array.type.__arrow_c_schema__() + + def stream(self, columns, filters): + stream = PokingStream(self.array.type, [self.array], None) + stream.corrupt = lambda array: self.poke(array, stream.pokes) + self.streams.append(stream) + return stream.capsule(), False + + +def _one_field_struct(): + return pa.StructArray.from_arrays([pa.array(range(2_000))], ["i"]) + + +# The column s of a table k, x, s, the change to it after the export, and the refusal text that follows its name. +REFUSALS_BY_COLUMN = { + "released_struct_child": ( + _one_field_struct, + lambda column, pokes: pokes.set(ctypes.c_void_p, _field(_child(column, 0), "release"), None), + "with a nested array whose child 0 is released already", + ), + "overflowing_column_offset": ( + _one_field_struct, + lambda column, pokes: pokes.set(ctypes.c_int64, _field(column, "offset"), 2**63 - 1), + "with offset 9223372036854775807 and length 2000", + ), + "run_ends_beyond_a_buffer": ( + lambda: _run_end_array(2_000), + lambda column, pokes: pokes.set(ctypes.c_int64, _field(_child(column, 0), "offset"), 2**62), + f"that addresses row {2**62 + 1} of a buffer, beyond what a buffer can hold", + ), +} + + +class TestRefusalsNameTheColumn: + @pytest.mark.timeout(60) + @pytest.mark.parametrize("query", ["SELECT s FROM t", "SELECT x, s FROM t", "SELECT * FROM t"]) + @pytest.mark.parametrize("case", list(REFUSALS_BY_COLUMN)) + def test_a_refusal_names_the_column_the_query_reads(self, case, query): + make, poke, message = REFUSALS_BY_COLUMN[case] + table = pa.table({"k": range(2_000), "x": range(2_000), "s": make()}) + source = NarrowingPokingSource(table, "s", poke) + with duckdb.connect() as con: + con._register_arrow_source("t", source) + with pytest.raises(duckdb.InvalidInputException, match=re.escape(f"column 's' {message}")): + con.execute(query).fetchall() + + @pytest.mark.timeout(60) + def test_a_refusal_names_a_plain_array_by_its_column_name(self): + source = PlainArrayPokingSource(pa.array([1, None] * 1_000), _drop_the_validity_bitmap) + with duckdb.connect() as con: + con._register_arrow_source("t", source) + assert [name for name, *_ in con.execute("SELECT * FROM t LIMIT 0").description] == ["value"] + message = "column 'value' with a non-zero null count but no validity bitmap" + with pytest.raises(duckdb.InvalidInputException, match=re.escape(message)): + con.execute("SELECT value FROM t").fetchall() + + class TestMalformedAndUnusualInput: @pytest.mark.timeout(60) @pytest.mark.parametrize( @@ -1884,7 +1967,7 @@ class TestMalformedAndUnusualInput: ), pytest.param( _overflowing_column_offset, - "an Arrow batch carried column 0 with offset 9223372036854775807 and length 1000", + "an Arrow batch carried column 'i' with offset 9223372036854775807 and length 1000", id="column_offset_overflow", ), ], @@ -2332,7 +2415,7 @@ def test_every_adopted_array_is_released_once(self, query, threads): ( _shorten_first_column, "Arrow array child length does not match the array length:" - " column 0 holds 1 rows where 1000 were expected", + " column 'i' holds 1 rows where 1000 were expected", ), (_wrong_column_count, "an Arrow batch carried 1 columns where 2 were expected"), ], @@ -2357,7 +2440,7 @@ def test_a_malformed_array_is_refused_and_released(self, corrupt, message): ( 400_000, "Arrow array child length does not match the array length:" - " column 0 holds 300000 rows where 400000 were expected", + " column 'a' holds 300000 rows where 400000 were expected", ), ], ids=["minus_one", "minus_several_ranges", "longer_than_its_column"], diff --git a/tests/fast/arrow/scan/test_translators.py b/tests/fast/arrow/scan/test_translators.py index a6aaadf61..d6525e48c 100644 --- a/tests/fast/arrow/scan/test_translators.py +++ b/tests/fast/arrow/scan/test_translators.py @@ -551,6 +551,112 @@ def test_a_nanosecond_zoned_column_is_refused(self): refused_by_arrow(arrow_table([0], kind).schema, cmp(">", "c", HALF, "TIMESTAMP WITH TIME ZONE")) +# The points base to base + 999 of the column's unit in ten Parquet row groups of 100, then one of NULLs. The constant +# is the point base + 299, or a third of a point past it. Parquet stores a column of seconds in milliseconds, so the +# millisecond kinds stand for both. +PRUNING_KINDS = [ + pytest.param(pa.timestamp("ms", tz="UTC"), 0, id="timestamp-ms-utc"), + pytest.param(pa.timestamp("ms", tz="UTC"), -500, id="timestamp-ms-utc-before-1970"), + pytest.param(pa.timestamp("ms", tz=NEW_YORK), 0, id="timestamp-ms-new-york"), + pytest.param(pa.time32("ms"), 0, id="time-ms"), +] +# Whether a row at `point` microseconds satisfies the predicate on the constant `at` microseconds, `step` one point. +PRUNING_PREDICATES = { + "gt": lambda point, at, step: point > at, + "ge": lambda point, at, step: point >= at, + "lt": lambda point, at, step: point < at, + "le": lambda point, at, step: point <= at, + "eq": lambda point, at, step: point == at, + "ne": lambda point, at, step: point != at, + "not_gt": lambda point, at, step: not point > at, + "not_eq": lambda point, at, step: point != at, + "not_ne": lambda point, at, step: point == at, + "between": lambda point, at, step: at <= point <= at + 100 * step, +} +PRUNED = { + "on_grid": { + "gt": 7, + "ge": 8, + "lt": 3, + "le": 3, + "eq": 1, + "ne": 10, + "not_gt": 3, + "not_eq": 10, + "not_ne": 1, + "between": 2, + }, + "off_grid": { + "gt": 7, + "ge": 7, + "lt": 3, + "le": 3, + "eq": 0, + "ne": 10, + "not_gt": 3, + "not_eq": 10, + "not_ne": 0, + "between": 1, + }, +} +PRUNING_OPS = {"gt": ">", "ge": ">=", "lt": "<", "le": "<=", "eq": "=", "ne": "!="} + + +def _pruning_constant(kind, micros): + if pa.types.is_time(kind): + whole, rest = divmod(micros, 1_000_000) + return Lit(datetime.time(whole // 3600, whole // 60 % 60, whole % 60, rest), "TIME") + return Lit(micros, "TIMESTAMP WITH TIME ZONE") + + +def _pruning_node(op, kind, at, step): + constant = _pruning_constant(kind, at) + if op in ("not_gt", "not_eq", "not_ne"): + return negate(Binary(PRUNING_OPS[op[4:]], col("c"), constant)) + if op == "between": + upper = _pruning_constant(kind, at + 100 * step) + return both(Binary(">=", col("c"), constant), Binary("<=", col("c"), upper)) + return Binary(PRUNING_OPS[op], col("c"), constant) + + +class TestArrowRowGroupPruning: + """A constant prunes the Parquet row groups its rows rule out, also between two points of a coarser column.""" + + @pytest.mark.parametrize("offset", list(PRUNED)) + @pytest.mark.parametrize("op", list(PRUNING_PREDICATES)) + @pytest.mark.parametrize(("kind", "base"), PRUNING_KINDS) + def test_row_groups_kept_and_rows(self, tmp_path, kind, base, op, offset): + from duckdb._sources.to_arrow import to_arrow + + pq = pytest.importorskip("pyarrow.parquet") + step = 1_000 + points = [base + index for index in range(1000)] + storage = pa.int64() if pa.types.is_timestamp(kind) else pa.int32() + column = pa.array([*points, *[None] * 100], storage).cast(kind) + path = tmp_path / "points.parquet" + pq.write_table(pa.table({"id": list(range(1100)), "c": column}), path, row_group_size=100) + dataset = ds.dataset(path) + at = (base + 299) * step + (step // 3 if offset == "off_grid" else 0) + expression = to_arrow(_pruning_node(op, kind, at, step), dataset.schema) + holds = PRUNING_PREDICATES[op] + assert sorted(dataset.to_table(filter=expression).column("id").to_pylist()) == [ + index for index, point in enumerate(points) if holds(point * step, at, step) + ] + assert next(iter(dataset.get_fragments())).subset(expression).num_row_groups == PRUNED[offset][op] + + @pytest.mark.parametrize(("op", "valid_row"), [("eq", False), ("ne", True), ("not_eq", True), ("not_ne", False)]) + @pytest.mark.parametrize("kind", [pa.timestamp("ms", tz=NEW_YORK), pa.time32("ms")], ids=["zoned", "time"]) + def test_an_equality_between_two_points_is_null_on_a_null_row(self, kind, op, valid_row): + from duckdb._sources.to_arrow import to_arrow + + table = pa.table( + {"c": pa.array([299, None], pa.int64() if pa.types.is_timestamp(kind) else pa.int32()).cast(kind)} + ) + expression = to_arrow(_pruning_node(op, kind, 299_333, 1_000), table.schema) + evaluated = ds.dataset(table).to_table(columns={"holds": expression}).column("holds").to_pylist() + assert evaluated == [valid_row, None] + + class TestArrowDecimals: VALUES = (D("1.25"), D("2.50"), None) diff --git a/tests/fast/arrow/test_dictionary_filter_pushdown.py b/tests/fast/arrow/test_dictionary_filter_pushdown.py index 1493e5678..c2187b127 100644 --- a/tests/fast/arrow/test_dictionary_filter_pushdown.py +++ b/tests/fast/arrow/test_dictionary_filter_pushdown.py @@ -663,7 +663,6 @@ def test_zoned_timestamp_parquet_dataset_matches_native(duckdb_cursor, tmp_path, assert_fully_pushed(duckdb_cursor, _arrow_query(predicate), len(expected)) -OFF_GRID_PRUNING = "per unit rounding: an off grid constant prunes only once it is rounded into the column's unit" PRUNING_CONSTANTS_MS = {"on_grid": 799, "off_grid": 799.5} @@ -699,15 +698,127 @@ def test_zoned_timestamp_parquet_pruning_filter_matches_hand_rows(duckdb_cursor, assert _pruning_count(duckdb_cursor, PRUNING_CONSTANTS_MS[constant]) == (200,) -@pytest.mark.parametrize( - "constant", - [ - pytest.param("on_grid"), - pytest.param("off_grid", marks=_xfail(OFF_GRID_PRUNING, AssertionError)), - ], -) +@pytest.mark.parametrize("constant", list(PRUNING_CONSTANTS_MS)) @pytest.mark.parametrize("column_zone", ["UTC", NEW_YORK]) def test_zoned_timestamp_parquet_row_group_pruning(duckdb_cursor, tmp_path, column_zone, constant): fragment, captured = _register_capturing_parquet(duckdb_cursor, tmp_path, column_zone) _pruning_count(duckdb_cursor, PRUNING_CONSTANTS_MS[constant]) assert fragment.subset(captured[-1]).num_row_groups == 2 + + +def _time_literal(micros): + return f"TIME '{dt.datetime(1970, 1, 1) + dt.timedelta(microseconds=micros):%H:%M:%S.%f}'" + + +# A column of the points base to base + 999 of its unit in ten row groups of 100, and a constant on the point +# base + 299 or a third of a point past it; > keeps the 700 rows above it and the seven row groups that hold them. +PRUNING_COLUMNS = { + "zoned_ms_off_grid": (pa.timestamp("ms", tz=NEW_YORK), 0, 333, _micros_literal), + "zoned_ms_on_grid_before_1970": (pa.timestamp("ms", tz="UTC"), -500, 0, _micros_literal), + "time_ms_on_grid": (pa.time32("ms"), 0, 0, _time_literal), + "time_ms_off_grid": (pa.time32("ms"), 0, 333, _time_literal), +} + + +# Constants on a point of the column, a third of a point above one, one microsecond below one, and a third of a point +# above one before 1970: the forms the comparison takes in the column's unit. +COLUMN_UNIT_CONSTANTS = { + "on_grid": lambda step: 10 * step, + "third_above": lambda step: 10 * step + step // 3, + "just_below": lambda step: 10 * step - 1, + "third_above_before_1970": lambda step: -10 * step + step // 3, +} +COLUMN_UNIT_PREDICATES = { + "eq": "p = {c}", + "ne": "p <> {c}", + "lt": "p < {c}", + "le": "p <= {c}", + "gt": "p > {c}", + "ge": "p >= {c}", + "not_eq": "NOT (p = {c})", + "not_ne": "NOT (p <> {c})", + "between": "p BETWEEN {c} AND {c3}", +} + + +COLUMN_UNIT_KINDS = { + "zoned_ms": pa.timestamp("ms", tz=NEW_YORK), + "zoned_s": pa.timestamp("s", tz="UTC"), + "time_ms": pa.time32("ms"), + "time_s": pa.time32("s"), +} + + +@pytest.mark.parametrize("op", list(COLUMN_UNIT_PREDICATES)) +@pytest.mark.parametrize("shape", ["column", "in_null_struct"]) +@pytest.mark.parametrize( + ("kind", "constant", "storage"), + [ + pytest.param(kind, constant, storage, id=f"{storage}-{name}-{constant}") + for name, kind in COLUMN_UNIT_KINDS.items() + for constant in COLUMN_UNIT_CONSTANTS + # Parquet reads a column of seconds back in milliseconds, so only a Dataset in memory keeps seconds. + for storage in (["in_memory"] if kind.unit == "s" else ["parquet", "in_memory"]) + if not (pa.types.is_time(kind) and constant.endswith("before_1970")) + ], +) +def test_dataset_rows_for_every_comparison_in_the_column_unit( + duckdb_cursor, tmp_path, kind, constant, storage, shape, op +): + # The dataset takes the whole filter, so the rows are those of the comparison built in the column's unit. + pq = pytest.importorskip("pyarrow.parquet") + pa_ds = pytest.importorskip("pyarrow.dataset") + is_time = pa.types.is_time(kind) + step = 1_000_000 // {"s": 1, "ms": 1_000}[kind.unit] + points = range(40) if is_time else range(-20, 20) + column = pa.array([*points, None, None], pa.int32() if is_time else pa.int64()).cast(kind) + if shape == "in_null_struct": + # A NULL parent makes its field NULL, also where the field's own array holds a value. + column = pa.StructArray.from_arrays([column], ["p"], mask=pa.array([index % 5 == 3 for index in range(42)])) + table = pa.table({"x": list(range(1, len(column) + 1)), "p" if shape == "column" else "s": column}) + if storage == "parquet": + pq.write_table(table, tmp_path / "points.parquet", row_group_size=4) + dataset = pa_ds.dataset(tmp_path / "points.parquet") + else: + dataset = pa_ds.dataset(table.to_batches(max_chunksize=4)) + assert ( + dataset.schema.field("p").type if shape == "column" else dataset.schema.field("s").type.field("p").type + ) == kind + duckdb_cursor.execute(f"SET TimeZone = '{NEW_YORK}'") + duckdb_cursor.register("arrow_t", dataset) + duckdb_cursor.execute("CREATE TABLE native_t AS SELECT * FROM arrow_t") + literal = _time_literal if is_time else _micros_literal + at = COLUMN_UNIT_CONSTANTS[constant](step) + predicate = COLUMN_UNIT_PREDICATES[op].format(c=literal(at), c3=literal(at + 3 * step)) + if shape == "in_null_struct": + predicate = predicate.replace("p ", "s.p ") + expected = _rows(duckdb_cursor, "native_t", predicate) + assert _arrow_rows(duckdb_cursor, predicate) == expected + assert_fully_pushed(duckdb_cursor, _arrow_query(predicate), len(expected)) + + +@pytest.mark.parametrize("column", list(PRUNING_COLUMNS)) +def test_parquet_row_group_pruning_in_the_column_unit(duckdb_cursor, tmp_path, column): + pq = pytest.importorskip("pyarrow.parquet") + pa_ds = pytest.importorskip("pyarrow.dataset") + kind, base, past, literal = PRUNING_COLUMNS[column] + step = 1_000 + storage = pa.int64() if pa.types.is_timestamp(kind) else pa.int32() + path = tmp_path / "points.parquet" + points = pa.array(range(base, base + 1000), storage).cast(kind) + pq.write_table(pa.table({"x": list(range(1000)), "p": points}), path, row_group_size=100) + source = pa_ds.dataset(path) + captured = [] + + class FilterCapturingDataset(pa_ds.FileSystemDataset): + def scanner(self, **kwargs): + captured.append(kwargs.get("filter")) + return super().scanner(**kwargs) + + duckdb_cursor.execute(f"SET TimeZone = '{NEW_YORK}'") + duckdb_cursor.register( + "arrow_t", FilterCapturingDataset(list(source.get_fragments()), source.schema, source.format, source.filesystem) + ) + predicate = f"p > {literal((base + 299) * step + past)}" + assert _rows(duckdb_cursor, "arrow_t", predicate) == [(x,) for x in range(300, 1000)] + assert next(iter(source.get_fragments())).subset(captured[-1]).num_row_groups == 7 diff --git a/tests/fast/pandas/test_pandas_string.py b/tests/fast/pandas/test_pandas_string.py index b775a1dcb..684d6f071 100644 --- a/tests/fast/pandas/test_pandas_string.py +++ b/tests/fast/pandas/test_pandas_string.py @@ -693,6 +693,56 @@ def test_str_chunks_outlive_the_frames_column_while_a_result_streams(pa, dtype): assert pa.total_allocated_bytes() == before +needs_dictionary_backed_strings = pytest.mark.skipif( + PANDAS_GE_3, + reason=( + "pandas 3 decodes a dictionary when it builds an ArrowStringArray and no CI job runs pandas 2; run it by hand " + "with pandas 2.2.3 and pyarrow 18.1.0 layered onto this environment through uv run's with option" + ), +) +DICTIONARY_LAYOUTS = { + "one_chunk_with_nulls": [["x", "y", None, "z"] * 250], + "two_chunks_with_different_dictionaries": [["a", "b"] * 60, ["c", None] * 60], + "one_chunk_without_nulls": [["x", "y"] * 60], + "below_the_chunk_length_threshold": [["x", None, "y"]], + "many_short_chunks": [["v", None]] * 30, + "many_one_row_chunks": [[("a", None, "b")[index % 3]] for index in range(100)], + "an_empty_chunk_between_two": [["a", None] * 50, [], ["b"] * 50], + "only_nulls": [[None] * 100], + "chunks_longer_than_a_vector": [ + [None if index % 7 == 0 else f"v{index % 100}" for index in range(2 * VECTOR_SIZE + 1)], + ["é", None, "", "nan", "a\x00b", "🦆"] * 700, + ], +} + + +def _dictionary_backed(pa, pieces, index_type): + kind = pa.dictionary(index_type, pa.large_string()) + chunks = [pa.array(piece, pa.large_string()).dictionary_encode().cast(kind) for piece in pieces] + array = pd.arrays.ArrowStringArray(pa.chunked_array(chunks, kind)) + assert array._pa_array.type == kind + return array + + +@needs_dictionary_backed_strings +@needs_arrow_chunk_export +@pytest.mark.parametrize("index_type", ["int8", "int32", "int64"]) +@pytest.mark.parametrize("layout", list(DICTIONARY_LAYOUTS)) +def test_dictionary_backed_string_column_reads_its_values_from_its_chunks( + duckdb_cursor, monkeypatch, pa, layout, index_type +): + pieces = DICTIONARY_LAYOUTS[layout] + values = [value for piece in pieces for value in piece] + frame = pd.DataFrame( # noqa: F841 + {"s": _dictionary_backed(pa, pieces, getattr(pa, index_type)()), "i": numpy.arange(len(values))} + ) + calls = _to_numpy_calls(monkeypatch, pd.arrays.ArrowStringArray, len(values)) + relation = duckdb_cursor.sql("SELECT s FROM frame ORDER BY i") + assert _types(relation) == ["VARCHAR"] + assert relation.fetchall() == _rows_of(values) + assert calls == [] + + @pytest.mark.parametrize("rows", [3, 3 * ARROW_ROWS_PER_CHUNK], ids=["short", "long"]) @pytest.mark.parametrize("dtype", PYARROW_STORAGE) def test_pyarrow_string_column_is_never_read_through_data(duckdb_cursor, monkeypatch, dtype, rows): From f9d0cef5430c8b03cd3e34febd94b3061a4c1349 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Thu, 5 Nov 2026 23:13:52 +0000 Subject: [PATCH 11/61] Stop forcing a macOS 10.7 deployment minimum onto the module's objects --- cmake/duckdb_loader.cmake | 6 ------ 1 file changed, 6 deletions(-) diff --git a/cmake/duckdb_loader.cmake b/cmake/duckdb_loader.cmake index 7ecca449f..5255c12eb 100644 --- a/cmake/duckdb_loader.cmake +++ b/cmake/duckdb_loader.cmake @@ -160,12 +160,6 @@ function(_duckdb_create_interface_target target_name) # functions /utf-8 # treat source files as UTF-8 encoded ) - elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin") - target_compile_options( - ${target_name} - INTERFACE -stdlib=libc++ # for libc++ in favor of older libstdc++ - -mmacosx-version-min=10.7 # minimum osx version compatibility - ) endif() # Link to the DuckDB static library From b2e0ea6115345b503ed10149c64f4cd42e2ad9a6 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 00:22:19 +0000 Subject: [PATCH 12/61] Accept Python 3.15's wording of the attribute suggestion in the removed method display test --- tests/fast/relational_api/test_rapi_lazy.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/fast/relational_api/test_rapi_lazy.py b/tests/fast/relational_api/test_rapi_lazy.py index 00e5f3db2..9ae7e2056 100644 --- a/tests/fast/relational_api/test_rapi_lazy.py +++ b/tests/fast/relational_api/test_rapi_lazy.py @@ -119,7 +119,12 @@ def test_the_interpreter_shows_the_suggestion_after_one_period(self, tmp_path): [sys.executable, "-c", script], capture_output=True, text=True, timeout=120, check=False, cwd=tmp_path ) assert shown.returncode == 1, shown.stdout + shown.stderr - assert "Use rel.limit(1).fetchall() instead. Did you mean: 'fetchall'?" in shown.stderr, shown.stderr + # The suggestion's wording differs by version ("Did you mean: 'fetchall'?" up to 3.14, "Did you mean + # '.fetchall' instead of '.fetchone'?" from 3.15); one period, then the suggestion naming fetchall. + assert re.search(r"Use rel\.limit\(1\)\.fetchall\(\) instead\. Did you mean[^\n]*fetchall", shown.stderr), ( + shown.stderr + ) + assert ".." not in shown.stderr, shown.stderr def test_a_column_named_like_a_removed_method_is_still_reachable(self, con): rel = con.sql("SELECT 1 AS execute, 2 AS fetchone") From c1802141e86aa8051b6d0108dae2890c80078c38 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 01:07:41 +0000 Subject: [PATCH 13/61] Make map() keep its column types, ENUMs included --- .../numpy/numpy_result_conversion.hpp | 3 + .../duckdb_python/pandas/pandas_bind.hpp | 12 +- src/include/duckdb_python/pyresult.hpp | 2 - src/map.cpp | 162 +++++-- src/numpy/numpy_result_conversion.cpp | 15 + src/numpy/numpy_scan.cpp | 27 +- src/pandas/bind.cpp | 22 +- src/pyresult.cpp | 25 +- tests/fast/pandas/test_append_df.py | 21 + tests/fast/test_map_types.py | 416 ++++++++++++++++++ 10 files changed, 630 insertions(+), 75 deletions(-) create mode 100644 tests/fast/test_map_types.py diff --git a/src/include/duckdb_python/numpy/numpy_result_conversion.hpp b/src/include/duckdb_python/numpy/numpy_result_conversion.hpp index f068dc79f..6425d9e6e 100644 --- a/src/include/duckdb_python/numpy/numpy_result_conversion.hpp +++ b/src/include/duckdb_python/numpy/numpy_result_conversion.hpp @@ -38,4 +38,7 @@ class NumpyResultConversion { bool pandas; }; +//! The dtype df() gives an ENUM column: a pandas CategoricalDtype over the enum's values in order, ordered +nb::object EnumCategoricalDtype(const LogicalType &enum_type); + } // namespace duckdb diff --git a/src/include/duckdb_python/pandas/pandas_bind.hpp b/src/include/duckdb_python/pandas/pandas_bind.hpp index 7a9fce9c0..ee5a6c3cf 100644 --- a/src/include/duckdb_python/pandas/pandas_bind.hpp +++ b/src/include/duckdb_python/pandas/pandas_bind.hpp @@ -42,11 +42,19 @@ struct PandasColumnBindData { bool declared = false; }; +//! The categories of a CategoricalDtype the caller built from an ENUM's values, in order +struct PandasEnumDtype { + nb::handle categories; + LogicalType type; +}; + struct Pandas { - //! Returns the frame's row count; declared_types, when given, hold one type per column, INVALID where none + //! Returns the frame's row count; declared_types, when given, hold one type per column, INVALID where none; a + //! categorical column whose categories are those of one of enum_dtypes, that very object, reads its codes as that + //! ENUM static idx_t Bind(ClientContext &config, nb::handle df, vector &out, vector &return_types, vector &names, - const vector &declared_types = {}); + const vector &declared_types = {}, const vector &enum_dtypes = {}); }; } // namespace duckdb diff --git a/src/include/duckdb_python/pyresult.hpp b/src/include/duckdb_python/pyresult.hpp index abad6e35f..50157de21 100644 --- a/src/include/duckdb_python/pyresult.hpp +++ b/src/include/duckdb_python/pyresult.hpp @@ -136,8 +136,6 @@ struct DuckDBPyResult { //! and whose originals the caller carries here. Empty means the result's own names. vector names_override; unique_ptr current_chunk; - // Holds the categories of Categorical/ENUM types - unordered_map categories; // Holds the categorical type of Categorical/ENUM types unordered_map categories_type; }; diff --git a/src/map.cpp b/src/map.cpp index e97242434..e3746f16d 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -26,15 +26,30 @@ struct MapFunctionData : public TableFunctionData { shared_ptr info; vector in_types, out_types; vector in_names, out_names; + //! Per output column, whether its type is only a guess from the typed input column of its name, which each chunk + //! must confirm, rather than imposed by the schema or an object input + vector guessed; + //! Per input column, the CategoricalDtype an ENUM column is handed over in, built once since it lists every value + vector enum_dtypes; + //! The categories of those dtypes with their ENUM types, by which a returned column of them reads its codes + vector enum_categories; + vector known_enums; }; -static nb::object FunctionCall(NumpyResultConversion &conversion, const vector &names, PyObject *function) { +static nb::object FunctionCall(const MapFunctionData &data, NumpyResultConversion &conversion) { + auto &import_cache = *DuckDBPyConnection::ImportCache(); nb::dict in_numpy_dict; - for (idx_t col_idx = 0; col_idx < names.size(); col_idx++) { - in_numpy_dict[names[col_idx].c_str()] = conversion.ToArray(col_idx); + for (idx_t col_idx = 0; col_idx < data.in_names.size(); col_idx++) { + auto column = conversion.ToArray(col_idx); + // As df() gives it: the codes alone bind back as TINYINT, a NULL as the code -1. + if (data.in_types[col_idx].id() == LogicalTypeId::ENUM) { + column = import_cache.pandas.Categorical().attr("from_codes")(column, nb::arg("dtype") = + data.enum_dtypes[col_idx].obj); + } + in_numpy_dict[data.in_names[col_idx].c_str()] = column; } + auto function = data.info->function.obj.ptr(); - auto &import_cache = *DuckDBPyConnection::ImportCache(); auto pandas_df = import_cache.pandas.DataFrame(); auto in_df = pandas_df(in_numpy_dict); D_ASSERT(in_df.ptr()); @@ -65,39 +80,37 @@ static nb::object FunctionCall(NumpyResultConversion &conversion, const vector &types) { - for (auto &type : types) { - if (type.id() == LogicalTypeId::SQLNULL) { - return true; +//! The input column of that name, the one at the same position first; the input names are deduplicated at bind +static optional_idx InputColumnNamed(const vector &input_names, const Identifier &name, idx_t position) { + if (position < input_names.size() && input_names[position] == name) { + return position; + } + for (idx_t col_idx = 0; col_idx < input_names.size(); col_idx++) { + if (input_names[col_idx] == name) { + return col_idx; } } - return false; + return optional_idx(); } +//! An object column of the empty bind frame has no values to type it, so it takes the type of the input column of its +//! name. That type is imposed when the function got the input as an object column too; from a typed input it is only +//! a guess, since the function may have moved the column to another type, and casting back would lose values. static void OverrideNullType(vector &return_types, const vector &return_names, - const vector &original_types, const vector &original_names) { - if (!ContainsNullType(return_types)) { - // Nothing to override, none of the returned types are NULL - return; - } - if (return_types.size() != original_types.size()) { - // FIXME: we can probably infer from the names in this case - // Cant infer what the type should be - return; - } - for (idx_t i = 0; i < return_types.size(); i++) { - auto &return_type = return_types[i]; - auto &original_type = original_types[i]; - - if (return_type != LogicalTypeId::SQLNULL) { + const vector &input_types, const vector &input_names, + vector &guessed) { + guessed.assign(return_types.size(), false); + for (idx_t col_idx = 0; col_idx < return_types.size(); col_idx++) { + if (return_types[col_idx].id() != LogicalTypeId::SQLNULL) { continue; } - if (return_names[i] != original_names[i]) { - throw InvalidInputException( - "Returned dataframe contains NULL type, and we could not infer the desired type"); + auto input = InputColumnNamed(input_names, return_names[col_idx], col_idx); + if (!input.IsValid()) { + continue; } - // Override the NULL with the original type - return_type = original_type; + auto &input_type = input_types[input.GetIndex()]; + return_types[col_idx] = input_type; + guessed[col_idx] = RawArrayWrapper::DuckDBToNumpyDtype(input_type) != "object"; } } @@ -135,6 +148,7 @@ unique_ptr BindExplicitSchema(unique_ptr function function_data->out_names = names; function_data->out_types = types; + function_data->guessed.assign(types.size(), false); return std::move(function_data); } @@ -146,22 +160,31 @@ static unique_ptr BindMap(ClientContext &context, shared_ptr &names) { auto data_uptr = make_uniq(std::move(info)); auto &data = *data_uptr; - auto function = data.info->function.obj.ptr(); auto explicit_schema = data.info->schema.obj.ptr(); data.in_names = input.input_table_names; + // The frame is keyed by name, so two input columns of one name would leave the function one of them + QueryResult::DeduplicateColumns(data.in_names); data.in_types = input.input_table_types; + for (auto &type : data.in_types) { + if (type.id() != LogicalTypeId::ENUM) { + data.enum_dtypes.emplace_back(); + continue; + } + data.enum_dtypes.emplace_back(EnumCategoricalDtype(type)); + data.enum_categories.emplace_back(data.enum_dtypes.back().obj.attr("categories")); + data.known_enums.push_back({data.enum_categories.back().obj, type}); + } if (explicit_schema != Py_None) { return BindExplicitSchema(std::move(data_uptr), explicit_schema, return_types, names); } NumpyResultConversion conversion(data.in_types, 0, context.GetClientProperties()); - auto df = PandasScanFunction::PandasWithBoundNames(FunctionCall(conversion, data.in_names, function)); + auto df = PandasScanFunction::PandasWithBoundNames(FunctionCall(data, conversion)); vector pandas_bind_data; // unused - Pandas::Bind(context, df, pandas_bind_data, return_types, names); + Pandas::Bind(context, df, pandas_bind_data, return_types, names, {}, data.known_enums); - // output types are potentially NULL, this happens for types that map to 'object' dtype - OverrideNullType(return_types, names, data.in_types, data.in_names); + OverrideNullType(return_types, names, data.in_types, data.in_names, data.guessed); data.out_names = names; data.out_types = return_types; @@ -184,6 +207,12 @@ unique_ptr MapFunction::MapFunctionBind(ClientContext &context, Ta } } +static InvalidInputException UntypedColumnError(const Identifier &name) { + return InvalidInputException( + "UDF column '%s' has no type: the function returned no values for it at bind time; pass its type with schema=", + name.c_str()); +} + static string TypeVectorToString(const vector &types) { return StringUtil::Join(types, types.size(), ", ", [](const LogicalType &argument) { return argument.ToString(); }); } @@ -200,18 +229,55 @@ static OperatorResultType ExecuteMap(ExecutionContext &context, TableFunctionInp NumpyResultConversion conversion(data.in_types, input.size(), context.client.GetClientProperties()); conversion.Append(input); - auto df = PandasScanFunction::PandasWithBoundNames( - FunctionCall(conversion, data.in_names, data.info->function.obj.ptr())); + auto df = PandasScanFunction::PandasWithBoundNames(FunctionCall(data, conversion)); + auto column_count = nb::len(nb::object(df.attr("columns"))); + if (column_count != output.ColumnCount()) { + throw InvalidInputException("Expected %llu columns from UDF, got %llu", output.ColumnCount(), column_count); + } + // Before anything types the frame, which could fail on a value it cannot read + for (idx_t col_idx = 0; col_idx < output.ColumnCount(); col_idx++) { + if (data.out_types[col_idx].id() != LogicalTypeId::SQLNULL) { + continue; + } + auto column = df.attr("__getitem__")(nb::object(df.attr("columns"))[nb::int_(col_idx)]); + auto has_value = PyObject_IsTrue(nb::object(column.attr("notna")().attr("any")()).ptr()); + if (has_value < 0) { + throw nb::python_error(); + } + if (has_value) { + throw UntypedColumnError(data.out_names[col_idx]); + } + } + // An object column has no type of its own, only values, so it is read into the type the schema or an object input + // imposed, whatever its values. A guessed type and a column bind could not type, which holds only missing values + // here, are left to the analyzer. + vector declared_types; + for (idx_t col_idx = 0; col_idx < output.ColumnCount(); col_idx++) { + auto &type = data.out_types[col_idx]; + auto imposed = type.id() != LogicalTypeId::SQLNULL && !data.guessed[col_idx]; + declared_types.push_back(imposed ? type : LogicalType::INVALID); + } vector pandas_bind_data; vector pandas_return_types; vector pandas_names; + auto row_count = Pandas::Bind(context.client, df, pandas_bind_data, pandas_return_types, pandas_names, + declared_types, data.known_enums); - auto row_count = Pandas::Bind(context.client, df, pandas_bind_data, pandas_return_types, pandas_names); - if (pandas_return_types.size() != output.ColumnCount()) { - throw InvalidInputException("Expected %llu columns from UDF, got %llu", output.ColumnCount(), - pandas_return_types.size()); + // A guess is only checked: a chunk of only missing values confirms nothing and reads NULL, any other type refutes + // it, and the analyzer's sample decides which, as it did before for every column. + vector missing_values(output.ColumnCount(), false); + for (idx_t col_idx = 0; col_idx < output.ColumnCount(); col_idx++) { + if (!data.guessed[col_idx] || pandas_return_types[col_idx] == data.out_types[col_idx]) { + continue; + } + if (pandas_return_types[col_idx].id() != LogicalTypeId::SQLNULL) { + throw UntypedColumnError(data.out_names[col_idx]); + } + pandas_return_types[col_idx] = data.out_types[col_idx]; + missing_values[col_idx] = true; } + D_ASSERT(output.GetTypes() == data.out_types); if (pandas_return_types != output.GetTypes()) { throw InvalidInputException("UDF column type mismatch, expected [%s], got [%s]", @@ -227,9 +293,23 @@ static OperatorResultType ExecuteMap(ExecutionContext &context, TableFunctionInp } for (idx_t col_idx = 0; col_idx < output.ColumnCount(); col_idx++) { + if (missing_values[col_idx]) { + ConstantVector::SetNull(output.data[col_idx], count_t(row_count)); + continue; + } auto &bind_data = pandas_bind_data[col_idx]; Vector temp(output.data[col_idx].GetType(), row_count); - PandasScanFunction::PandasBackendScanSwitch(context.client, bind_data, row_count, 0, temp); + try { + PandasScanFunction::PandasBackendScanSwitch(context.client, bind_data, row_count, 0, temp); + } catch (std::exception &ex) { + ErrorData error(ex); + // The cast's own message names no column; a Python error keeps the traceback its message starts with + if (!bind_data.declared || error.Type() == ExceptionType::INVALID || + error.Type() == ExceptionType::INTERRUPT) { + throw; + } + error.Throw(StringUtil::Format("UDF column '%s': ", data.out_names[col_idx].c_str())); + } VectorOperations::Copy(temp, output.data[col_idx], row_count, 0, 0); } output.SetChildCardinality(row_count); diff --git a/src/numpy/numpy_result_conversion.cpp b/src/numpy/numpy_result_conversion.cpp index f511baed5..db3315164 100644 --- a/src/numpy/numpy_result_conversion.cpp +++ b/src/numpy/numpy_result_conversion.cpp @@ -1,5 +1,6 @@ #include "duckdb_python/numpy/array_wrapper.hpp" #include "duckdb_python/numpy/numpy_result_conversion.hpp" +#include "duckdb_python/pyconnection/pyconnection.hpp" namespace duckdb { @@ -46,4 +47,18 @@ void NumpyResultConversion::Append(DataChunk &chunk) { #endif } +nb::object EnumCategoricalDtype(const LogicalType &enum_type) { + DUCKDB_PY_ASSERT_GIL_HELD(); + auto categorical_dtype = DuckDBPyConnection::ImportCache()->pandas.CategoricalDtype(); + if (!categorical_dtype) { + throw InvalidInputException("'pandas' is required for this operation but it was not installed"); + } + auto &values = EnumType::GetValuesInsertOrder(enum_type); + nb::list categories; + for (idx_t i = 0; i < EnumType::GetSize(enum_type); i++) { + categories.append(nb::cast(values.GetValue(i).ToString())); + } + return categorical_dtype(categories, true); +} + } // namespace duckdb diff --git a/src/numpy/numpy_scan.cpp b/src/numpy/numpy_scan.cpp index ec3cc6159..d9ff6fe90 100644 --- a/src/numpy/numpy_scan.cpp +++ b/src/numpy/numpy_scan.cpp @@ -352,7 +352,12 @@ static Value DeclaredValue(ClientContext &context, const LogicalType &target, nb //! shape of its own (a UNION member that is NULL), and the output owns every string the cast produced. class DeclaredVector { public: - explicit DeclaredVector(idx_t count) : values(count), source(LogicalTypeId::SQLNULL) { + explicit DeclaredVector(idx_t count) : values(count), written(count, false), source(LogicalTypeId::SQLNULL) { + } + + //! A row the scan wrote into the output itself, which Write leaves as it is + void MarkWritten(idx_t row) { + written[row] = true; } void Set(idx_t row, Value value) { @@ -389,6 +394,10 @@ class DeclaredVector { VectorOperations::TryCast(context, staged, casted, present, nullptr); idx_t copied = 0; for (idx_t row = 0; row < count;) { + if (written[row]) { + row++; + continue; + } if (values[row].IsNull()) { FlatVector::SetNull(out, row, true); row++; @@ -406,6 +415,9 @@ class DeclaredVector { } DeclaredCasts casts(context, target); for (idx_t row = 0; row < count; row++) { + if (written[row]) { + continue; + } if (values[row].IsNull()) { FlatVector::SetNull(out, row, true); } else { @@ -416,6 +428,7 @@ class DeclaredVector { private: vector values; + vector written; LogicalType source; bool uniform = true; }; @@ -461,8 +474,16 @@ void NumpyScan::ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t idx_t count, idx_t offset, Vector &out) { DeclaredVector staged(count); auto &target = out.GetType(); - ScanObjectCells(context, col, stride, masked, count, offset, out, - [&](nb::handle cell, idx_t row) { staged.Set(row, DeclaredValue(context, target, cell)); }); + // A str into plain VARCHAR reads as TransformPythonValue would read it, without building a Value per cell + const bool plain_text = target == LogicalType::VARCHAR; + ScanObjectCells(context, col, stride, masked, count, offset, out, [&](nb::handle cell, idx_t row) { + if (plain_text && PyUnicode_CheckExact(cell.ptr())) { + FlatVector::GetDataMutable(out)[row] = StringVector::AddString(out, TransformPythonString(cell)); + staged.MarkWritten(row); + return; + } + staged.Set(row, DeclaredValue(context, target, cell)); + }); staged.Write(context, out, count); VerifyTypeConstraints(out, count); } diff --git a/src/pandas/bind.cpp b/src/pandas/bind.cpp index 73b202055..e998558b3 100644 --- a/src/pandas/bind.cpp +++ b/src/pandas/bind.cpp @@ -120,7 +120,8 @@ std::unique_ptr RegisterMask(nb::handle mask) { } static LogicalType BindColumn(ClientContext &context, PandasBindColumn &column_p, PandasColumnBindData &bind_data, - idx_t row_count, const LogicalType &declared_type) { + idx_t row_count, const LogicalType &declared_type, + const vector &enum_dtypes) { const string counted_from = "the frame"; LogicalType column_type; auto &column = column_p.handle; @@ -137,6 +138,18 @@ static LogicalType BindColumn(ClientContext &context, PandasBindColumn &column_p nb::object data; if (bind_data.numpy_type.type == NumpyNullableType::CATEGORY) { + auto column_categories = enum_dtypes.empty() ? nb::object() : nb::object(column_p.type.attr("categories")); + for (auto &known : enum_dtypes) { + // A categories index is immutable, so this object still holds the enum's values, and reading them again + // would cost a string per category on every call; pandas 2 builds a new dtype around the same index + if (column_categories.is(known.categories)) { + data = column.attr("cat").attr("codes").attr("to_numpy")(); + bind_data.internal_categorical_type = nb::cast(nb::str(nb::object(data.attr("dtype")))); + CheckColumnArray(bind_data.name, data, row_count, counted_from); + bind_data.pandas_col = std::make_unique(NumpyArray(std::move(data))); + return known.type; + } + } // for category types, we create an ENUM type for string or use the converted numpy type for the rest D_ASSERT(nb::hasattr(column, "cat")); D_ASSERT(nb::hasattr(column.attr("cat"), "categories")); @@ -223,7 +236,7 @@ static LogicalType BindColumn(ClientContext &context, PandasBindColumn &column_p idx_t Pandas::Bind(ClientContext &context, nb::handle df_p, vector &bind_columns, vector &return_types, vector &names, - const vector &declared_types) { + const vector &declared_types, const vector &enum_dtypes) { PandasDataFrameBind df(df_p); idx_t column_count = nb::len(df.names); @@ -256,8 +269,9 @@ idx_t Pandas::Bind(ClientContext &context, nb::handle df_p, vector &types, unordered_map &categories) { - for (idx_t col_idx = 0; col_idx < types.size(); col_idx++) { - auto &type = types[col_idx]; - if (type.id() == LogicalTypeId::ENUM) { - // It's an ENUM type, in addition to converting the codes we must convert the categories - if (categories.find(col_idx) == categories.end()) { - auto &categories_list = EnumType::GetValuesInsertOrder(type); - auto categories_size = EnumType::GetSize(type); - for (idx_t i = 0; i < categories_size; i++) { - categories[col_idx].append(nb::cast(categories_list.GetValue(i).ToString())); - } - } - } - } -} - std::unique_ptr DuckDBPyResult::InitializeNumpyConversion(bool pandas) { if (Empty()) { throw InvalidInputException("result closed"); @@ -313,7 +293,6 @@ nb::dict DuckDBPyResult::FetchNumpyInternal(bool chunked, idx_t vectors_per_chun } conversion.Append(*chunk); } - InsertCategory(GetTypes(), categories); // now that we have materialized the result in contiguous arrays, construct the actual NumPy arrays or // categorical types diff --git a/tests/fast/pandas/test_append_df.py b/tests/fast/pandas/test_append_df.py index 4360a8bc8..0f3099f86 100644 --- a/tests/fast/pandas/test_append_df.py +++ b/tests/fast/pandas/test_append_df.py @@ -428,6 +428,27 @@ def test_text_with_a_lone_surrogate_names_it(self, duckdb_cursor): with pytest.raises(duckdb.InvalidInputException, match="surrogate"): duckdb_cursor.append("t", frame) + def test_text_column_mixing_str_with_other_cells_appends_each_as_text(self, duckdb_cursor): + duckdb_cursor.execute("CREATE TABLE t (a VARCHAR)") + cells = ["a", 5, 6, "b", None, 7, np.str_("c"), "\u00e9 \U0001f600"] + duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series(cells, dtype=object)})) + assert duckdb_cursor.table("t").fetchall() == [ + ("a",), + ("5",), + ("6",), + ("b",), + (None,), + ("7",), + ("c",), + ("\u00e9 \U0001f600",), + ] + + def test_text_with_a_lone_surrogate_in_a_str_names_it(self, duckdb_cursor): + duckdb_cursor.execute("CREATE TABLE t (a VARCHAR)") + frame = pd.DataFrame({"a": pd.Series(["a", "b\udcff"], dtype=object)}) + with pytest.raises(duckdb.InvalidInputException, match="surrogate"): + duckdb_cursor.append("t", frame) + def test_null_row_among_struct_values_the_cast_converts(self, duckdb_cursor): duckdb_cursor.execute("CREATE TABLE t (a STRUCT(x INTEGER))") # Text fields cast into INTEGER, so the whole vector goes through one cast with the NULL row inside it diff --git a/tests/fast/test_map_types.py b/tests/fast/test_map_types.py new file mode 100644 index 000000000..8672d4cac --- /dev/null +++ b/tests/fast/test_map_types.py @@ -0,0 +1,416 @@ +"""map() fixes one type per output column at bind and reads each chunk's returned column into it.""" + +import re + +import pytest +from conftest import PANDAS_GE_3 + +import duckdb +import numpy as np +import pandas as pd + +ENUM = "ENUM('a', 'b')" +SCHEMAS = pytest.mark.parametrize("explicit_schema", [False, True], ids=["inferred", "explicit_schema"]) + + +def _schema_of(relation, explicit_schema): + return dict(zip(relation.columns, relation.types, strict=True)) if explicit_schema else None + + +@pytest.mark.parametrize("with_null", [False, True], ids=["no_null", "a_null"]) +def test_map_enum_column_reaches_the_function_as_df_gives_it(duckdb_cursor, with_null): + second = "NULL" if with_null else f"'a'::{ENUM}" + source = duckdb_cursor.sql(f"select * from (values ('b'::{ENUM}), ({second})) t(e)") + seen = [] + + def record(df): + seen.append((len(df), df["e"].dtype, [None if pd.isna(v) else v for v in df["e"].tolist()])) + return df + + mapped = source.map(record) + assert mapped.types == source.types + assert mapped.fetchall() == source.fetchall() + categorical = pd.CategoricalDtype(["a", "b"], ordered=True) + assert source.df()["e"].dtype == categorical + assert all(dtype == categorical for _, dtype, _ in seen), seen + assert [values for rows, _, values in seen if rows] == [["b", None if with_null else "a"]] + + +def test_map_enum_column_reaches_every_call_with_the_dtype_built_at_bind(duckdb_cursor): + duckdb_cursor.execute("set threads = 1") + seen = [] + + def record(df): + if len(df): + seen.append(df["e"].dtype) + return df + + source = duckdb_cursor.sql(f"select (case when i % 3 = 0 then 'a' else 'b' end)::{ENUM} as e from range(4096) t(i)") + assert source.map(record).fetchall() == source.fetchall() + assert len(seen) == 2 + # pandas 3 keeps the dtype object; pandas 2 builds a new dtype around the same categories index + assert all(dtype.categories is seen[0].categories for dtype in seen) + if PANDAS_GE_3: + assert all(dtype is seen[0] for dtype in seen) + + +@pytest.mark.parametrize( + ("categories", "ordered", "result_type"), + [ + pytest.param(["a", "b"], True, ENUM, id="equal_categories"), + pytest.param(["a", "b"], False, ENUM, id="equal_categories_unordered"), + pytest.param(["b", "a"], True, "ENUM('b', 'a')", id="reordered_categories"), + ], +) +def test_map_enum_column_rebuilt_as_a_new_categorical_reads_by_its_categories( + duckdb_cursor, categories, ordered, result_type +): + def rebuild(df): + return df.assign(e=pd.Categorical(df["e"].astype(object), categories=categories, ordered=ordered)) + + source = duckdb_cursor.sql(f"select * from (values ('b'::{ENUM}), (NULL), ('a'::{ENUM})) t(e)") + mapped = source.map(rebuild) + assert mapped.types == [duckdb.sqltype(result_type)] + assert mapped.fetchall() == [("b",), (None,), ("a",)] + + +def test_map_enum_column_compares_with_its_text(duckdb_cursor): + source = duckdb_cursor.sql(f"select * from (values ('b'::{ENUM}), (NULL), ('a'::{ENUM})) t(e)") + mapped = source.map(lambda df: df.assign(is_b=df["e"] == "b")) + assert mapped.types == [source.types[0], duckdb.sqltypes.BOOLEAN] + assert mapped.fetchall() == [("b", True), (None, False), ("a", False)] + + +@SCHEMAS +@pytest.mark.parametrize( + ("sql_type", "value"), + [ + pytest.param("STRUCT(x BIGINT)", "{'x': i::BIGINT}", id="STRUCT_BIGINT_field"), + pytest.param("MAP(INTEGER, INTEGER)", "map([i::INTEGER], [i::INTEGER])", id="MAP_INTEGER_keys"), + pytest.param("MAP(VARCHAR, BIGINT)", "map([i::VARCHAR], [i::BIGINT])", id="MAP_BIGINT_values"), + pytest.param("INTEGER[2]", "[i, i]::INTEGER[2]", id="ARRAY"), + pytest.param("UNION(a INTEGER, b VARCHAR)", "i::INTEGER::UNION(a INTEGER, b VARCHAR)", id="UNION"), + pytest.param("TIME_NS", "'01:00:00'::TIME_NS", id="TIME_NS"), + pytest.param( + "STRUCT(a INTEGER[], b MAP(VARCHAR, INTEGER))", + "{'a': [i::INTEGER], 'b': map(['k'], [i::INTEGER])}", + id="nested", + ), + ], +) +def test_map_identity_returns_an_object_column_in_its_own_type(duckdb_cursor, sql_type, value, explicit_schema): + source = duckdb_cursor.sql( + f"select (case when i = 1 then NULL else {value} end)::{sql_type} as a from range(3) t(i)" + ) + mapped = source.map(lambda df: df, schema=_schema_of(source, explicit_schema)) + assert mapped.types == source.types + assert mapped.fetchall() == source.fetchall() + + +@SCHEMAS +def test_map_identity_returns_a_struct_whose_field_is_null_across_a_chunk(duckdb_cursor, explicit_schema): + duckdb_cursor.execute("set threads = 1") + # The field holds values in the first 2048 row chunk and only NULLs in the second. + source = duckdb_cursor.sql("select {'a': case when i < 2048 then i::INTEGER end} as s from range(4096) t(i)") + mapped = source.map(lambda df: df, schema=_schema_of(source, explicit_schema)) + assert mapped.types == source.types + assert mapped.fetchall() == source.fetchall() + + +@SCHEMAS +def test_map_identity_returns_an_enum_column_in_its_own_type(duckdb_cursor, explicit_schema): + source = duckdb_cursor.sql(f"select * from (values ('b'::{ENUM}), (NULL), ('a'::{ENUM})) t(e)") + mapped = source.map(lambda df: df, schema=_schema_of(source, explicit_schema)) + assert mapped.types == source.types + assert mapped.fetchall() == source.fetchall() + + +def test_map_column_takes_the_input_type_of_its_name_when_columns_are_added_or_reordered(duckdb_cursor): + source = duckdb_cursor.sql("select i as n, {'x': i::BIGINT} as s from range(3) t(i)") + mapped = source.map(lambda df: df[["s", "n"]].assign(k=1)) + assert mapped.types == [source.types[1], duckdb.sqltypes.BIGINT, duckdb.sqltypes.BIGINT] + assert mapped.fetchall() == [(s, n, 1) for n, s in source.fetchall()] + + +def _text_cells(values): + def replace(df): + return df.assign(a=pd.Series(values[: len(df)], dtype=object, index=df.index)) if len(df) else df + + return replace + + +MISSING_VALUES = [ + pytest.param(lambda: None, id="None"), + pytest.param(duckdb.NullValue, id="NullValue"), + pytest.param(lambda: np.datetime64("NaT", "us"), id="NaT"), + pytest.param(lambda: pd.NA, id="pd.NA"), + pytest.param(lambda: float("nan"), id="NaN"), +] + + +def _missing_cells(make_missing): + def missing(df): + return df.assign(a=pd.Series([make_missing() for _ in range(len(df))], dtype=object)) if len(df) else df + + return missing + + +@pytest.mark.parametrize("sql_type", ["BIGINT", "DOUBLE", "VARCHAR"]) +@pytest.mark.parametrize("make_missing", MISSING_VALUES) +def test_map_object_column_of_missing_values_reads_null_in_its_schema_type(duckdb_cursor, make_missing, sql_type): + source = duckdb_cursor.sql(f"select i::{sql_type} as a from range(3) t(i)") + mapped = source.map(_missing_cells(make_missing), schema=_schema_of(source, explicit_schema=True)) + assert mapped.types == source.types + assert mapped.fetchall() == [(None,), (None,), (None,)] + + +@pytest.mark.parametrize("make_missing", MISSING_VALUES) +def test_map_object_column_of_missing_values_keeps_an_object_input_type(duckdb_cursor, make_missing): + source = duckdb_cursor.sql("select i::VARCHAR as a from range(3) t(i)") + mapped = source.map(_missing_cells(make_missing)) + assert mapped.types == source.types + assert mapped.fetchall() == [(None,), (None,), (None,)] + + +def _odd_cell_at(row, value): + """Every cell of column a as its Python value, and value at row.""" + + def replace(df): + if not len(df): + return df + cells = df["a"].astype(object).tolist() + cells[row] = value + return df.assign(a=pd.Series(cells, dtype=object, index=df.index)) + + return replace + + +# In a 2048 row chunk the analyzer samples the even rows only, so the last row is outside its sample. +ODD_ROWS = pytest.mark.parametrize("row", [0, 2047], ids=["first_row", "row_outside_the_sample"]) +BIGINT_A = {"a": duckdb.sqltypes.BIGINT} + + +@ODD_ROWS +def test_map_object_column_cell_is_cast_into_the_bound_type(duckdb_cursor, row): + duckdb_cursor.execute("set threads = 1") + mapped = duckdb_cursor.sql("select i as a from range(2048) t(i)").map(_odd_cell_at(row, "5"), schema=BIGINT_A) + assert mapped.types == [duckdb.sqltypes.BIGINT] + assert mapped.fetchall() == [(5 if i == row else i,) for i in range(2048)] + + +@ODD_ROWS +def test_map_object_column_cell_the_cast_refuses_raises_the_casts_error(duckdb_cursor, row): + duckdb_cursor.execute("set threads = 1") + mapped = duckdb_cursor.sql("select i as a from range(2048) t(i)").map(_odd_cell_at(row, "x"), schema=BIGINT_A) + expected = "Conversion Error: UDF column 'a': Could not convert string 'x' to INT64" + with pytest.raises(duckdb.ConversionException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +@ODD_ROWS +def test_map_struct_cell_without_a_field_reads_it_as_null(duckdb_cursor, row): + duckdb_cursor.execute("set threads = 1") + source = duckdb_cursor.sql("select {'x': i::INTEGER, 'y': i::INTEGER} as a from range(2048) t(i)") + mapped = source.map(_odd_cell_at(row, {"x": 3})) + expected = [({"x": 3, "y": None} if i == row else {"x": i, "y": i},) for i in range(2048)] + assert mapped.types == source.types + assert mapped.fetchall() == expected + + +def test_map_object_column_of_zero_dimensional_arrays_reads_their_values(duckdb_cursor): + def arrays(df): + cells = np.empty(len(df), dtype=object) + for i, v in enumerate(df["a"]): + cells[i] = np.array(int(v), dtype=object) + return df.assign(a=pd.Series(cells, dtype=object, index=df.index)) + + mapped = duckdb_cursor.sql("select i as a from range(3) t(i)").map(arrays, schema={"a": duckdb.sqltypes.BIGINT}) + assert mapped.fetchall() == [(0,), (1,), (2,)] + + +def test_map_declared_column_read_error_names_the_column(duckdb_cursor): + source = duckdb_cursor.sql("select i as n, {'x': i::INTEGER} as s from range(3) t(i)") + mapped = source.map(lambda df: df.assign(n=df["s"]), schema=_schema_of(source, explicit_schema=True)) + expected = "Conversion Error: UDF column 'n': Unimplemented type for cast (STRUCT(x INTEGER) -> BIGINT)" + with pytest.raises(duckdb.ConversionException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +@pytest.mark.parametrize( + ("cells", "expected"), + [ + # Every staged value is an int, so one cast reads them; the str rows between them are written directly. + pytest.param(["a", 5, 6, "b", None, 7, "c"], ["a", "5", "6", "b", None, "7", "c"], id="str_int_and_null"), + pytest.param(["a", 5, np.str_("c"), None], ["a", "5", "c", None], id="with_a_str_subclass"), + ], +) +def test_map_text_column_mixing_str_with_other_cells_reads_each_as_text(duckdb_cursor, cells, expected): + source = duckdb_cursor.sql(f"select i::VARCHAR as a from range({len(cells)}) t(i)") + mapped = source.map(_text_cells(cells)) + assert mapped.fetchall() == [(value,) for value in expected] + + +def test_map_json_column_still_validates_its_text(duckdb_cursor): + schema = {"a": duckdb.sqltype("JSON")} + good = duckdb_cursor.sql("select 1 as a").map(_text_cells(['{"k": 1}']), schema=schema) + assert good.fetchall() == [('{"k": 1}',)] + bad = duckdb_cursor.sql("select 1 as a").map(_text_cells(["not json"]), schema=schema) + expected = ( + "Conversion Error: UDF column 'a': Malformed JSON at byte 0 of input: invalid literal. Input: \"not json\"" + ) + with pytest.raises(duckdb.ConversionException, match=f"^{re.escape(expected)}$"): + bad.fetchall() + + +@pytest.mark.parametrize( + ("projection", "names"), + [ + pytest.param("col0 as a, col1 as a", ["a", "a_1"], id="one_name"), + pytest.param('col0 as a, col1 as "A"', ["a", "A_1"], id="names_differing_in_case"), + ], +) +def test_map_identity_keeps_both_columns_of_one_name(duckdb_cursor, projection, names): + source = duckdb_cursor.values([1, "x"]).project(projection) + seen = [] + + def record(df): + seen.append(list(df.columns)) + return df + + mapped = source.map(record) + assert seen[0] == names == list(source.df().columns) + assert mapped.types == source.types + assert mapped.fetchall() == source.fetchall() + + +def _with_list_column(df): + return df.assign(s=pd.Series([[v] for v in df["a"]], dtype=object, index=df.index)) + + +def _with_text_column(df): + # An object column, as pandas 2 gives this expression on every frame and pandas 3 without pyarrow on the empty one. + return df.assign(s=pd.Series(("prefix " + df["a"].astype(str)).tolist(), dtype=object, index=df.index)) + + +NEW_COLUMNS = pytest.mark.parametrize( + ("function", "sql_type", "values"), + [ + pytest.param(_with_list_column, "BIGINT[]", [[0], [1], [2]], id="list"), + pytest.param(_with_text_column, "VARCHAR", ["prefix 0", "prefix 1", "prefix 2"], id="text"), + ], +) + + +@NEW_COLUMNS +def test_map_new_object_column_reads_into_the_schema_type(duckdb_cursor, function, sql_type, values): + schema = {"a": duckdb.sqltypes.BIGINT, "s": duckdb.sqltype(sql_type)} + mapped = duckdb_cursor.sql("select i as a from range(3) t(i)").map(function, schema=schema) + assert mapped.types == [duckdb.sqltypes.BIGINT, duckdb.sqltype(sql_type)] + assert mapped.fetchall() == list(enumerate(values)) + + +@NEW_COLUMNS +def test_map_new_object_column_the_bind_frame_cannot_type_names_the_column_and_schema( + duckdb_cursor, function, sql_type, values +): + mapped = duckdb_cursor.sql("select i as a from range(3) t(i)").map(function) + with pytest.raises(duckdb.InvalidInputException, match=_no_type("s")): + mapped.fetchall() + + +def _no_type(column): + message = f"UDF column '{column}' has no type: the function returned no values for it at bind time; pass its type" + return f"^{re.escape(f'Invalid Input Error: {message} with schema=')}$" + + +def test_map_new_object_column_with_a_cell_the_analyzer_cannot_read_names_the_column_and_schema(duckdb_cursor): + def array_cell(df): + cells = np.empty(len(df), dtype=object) + if len(df): + cells[-1] = np.array(1, dtype=object) + return df.assign(s=pd.Series(cells, dtype=object, index=df.index)) + + mapped = duckdb_cursor.sql("select i as a from range(2048) t(i)").map(array_cell) + with pytest.raises(duckdb.InvalidInputException, match=_no_type("s")): + mapped.fetchall() + + +@pytest.mark.parametrize( + ("function", "column"), + [ + pytest.param( + lambda df: df.assign(a=pd.Series(df["a"].astype(str).str.zfill(5).tolist(), dtype=object, index=df.index)), + "a", + id="typed_input_turned_into_text", + ), + pytest.param(lambda df: df.rename(columns={"a": "b", "b": "a"}), "a", id="names_swapped"), + ], +) +def test_map_typed_input_column_the_function_moved_to_another_type_is_refused(duckdb_cursor, function, column): + mapped = duckdb_cursor.sql("select i as a, i::VARCHAR as b from range(3) t(i)").map(function) + with pytest.raises(duckdb.InvalidInputException, match=_no_type(column)): + mapped.fetchall() + + +@pytest.mark.parametrize( + ("make_cell", "expected"), + [ + pytest.param(int, [(0,), (1,), (2,)], id="python_ints"), + pytest.param(lambda v: None, [(None,), (None,), (None,)], id="only_none"), + ], +) +def test_map_typed_input_column_the_function_turned_into_objects_keeps_a_confirmed_type( + duckdb_cursor, make_cell, expected +): + def objects(df): + return df.assign(a=pd.Series([make_cell(v) for v in df["a"]], dtype=object, index=df.index)) + + source = duckdb_cursor.sql("select i::INTEGER as a from range(3) t(i)") + mapped = source.map(objects) + assert mapped.types == source.types + assert mapped.fetchall() == expected + + +def test_map_new_object_column_fails_on_the_first_chunk_with_a_value(duckdb_cursor): + duckdb_cursor.execute("set threads = 1") + rows_per_call = [] + + def late_values(df): + rows_per_call.append(len(df)) + values = [None if i < 2048 else str(i) for i in df["a"]] + return df.assign(s=pd.Series(values, dtype=object, index=df.index)) + + mapped = duckdb_cursor.sql("select i as a from range(4096) t(i)").map(late_values) + with pytest.raises(duckdb.InvalidInputException, match=_no_type("s")): + mapped.fetchall() + # The first chunk, of only None, was read before the second one failed. + assert [rows for rows in rows_per_call if rows] == [2048, 2048] + + +@pytest.mark.parametrize( + "missing", + [ + pytest.param(None, id="None"), + pytest.param(float("nan"), id="NaN"), + pytest.param(pd.NA, id="pd.NA"), + pytest.param(pd.NaT, id="pandas_NaT"), + pytest.param(np.datetime64("NaT", "us"), id="numpy_NaT"), + ], +) +def test_map_new_object_column_of_only_missing_values_stays_null(duckdb_cursor, missing): + def note(df): + return df.assign(note=pd.Series([missing] * len(df), dtype=object, index=df.index)) + + mapped = duckdb_cursor.sql("select i as a from range(3) t(i)").map(note) + assert mapped.types == [duckdb.sqltypes.BIGINT, duckdb.sqltypes.SQLNULL] + assert mapped.fetchall() == [(0, None), (1, None), (2, None)] + + +def test_map_new_object_column_of_null_values_is_refused_as_untyped(duckdb_cursor): + # pandas does not read a duckdb.NullValue() as missing, so the column holds values bind could not type + def nulls(df): + return df.assign(s=pd.Series([duckdb.NullValue() for _ in range(len(df))], dtype=object, index=df.index)) + + mapped = duckdb_cursor.sql("select i as a from range(3) t(i)").map(nulls) + with pytest.raises(duckdb.InvalidInputException, match=_no_type("s")): + mapped.fetchall() From e4c2e1d6a5de7275cae53f79a785b96f8476e4e2 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 11:35:15 +0000 Subject: [PATCH 14/61] Push exact widening casts bare and the translatable conjuncts of an AND, keep the whole predicate on polars --- duckdb/polars_io.py | 104 ++++-- tests/fast/arrow/test_polars.py | 23 +- .../arrow/test_polars_pushdown_literals.py | 333 ++++++++++++++++-- 3 files changed, 406 insertions(+), 54 deletions(-) diff --git a/duckdb/polars_io.py b/duckdb/polars_io.py index dce362d24..9746233f9 100644 --- a/duckdb/polars_io.py +++ b/duckdb/polars_io.py @@ -1,8 +1,10 @@ from __future__ import annotations # noqa: D100 import datetime +import functools import io import json +import operator import typing from decimal import Decimal @@ -12,7 +14,7 @@ import duckdb if typing.TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Iterator, Mapping import typing_extensions @@ -38,13 +40,16 @@ def _predicate_to_expression(predicate: pl.Expr) -> duckdb.Expression | None: return _tree_to_sql_expression(tree) -def _tree_to_sql_expression(tree: _ExpressionTree) -> duckdb.Expression | None: +def _tree_to_sql_expression( + tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | None = None +) -> duckdb.Expression | None: """Convert an already-parsed Polars expression tree to a DuckDB expression. + ``schema`` is the polars schema of the scanned relation; without it no cast of a column translates. Returns None if the tree contains a node we cannot translate to SQL. """ try: - return duckdb.SQLExpression(_pl_tree_to_sql(tree)) + return duckdb.SQLExpression(_pl_tree_to_sql(tree, schema)) except Exception: # If the conversion fails, we return None return None @@ -119,6 +124,16 @@ def _strip_dynamic_predicates(tree: typing.Any) -> tuple[_ExpressionTree | None, return tree, False +def _conjuncts(tree: _ExpressionTree) -> list[_ExpressionTree]: + """The operands of a top level AND chain, nested on either side, or the tree itself.""" + bin_expr = tree.get("BinaryExpr") + if isinstance(bin_expr, dict) and bin_expr.get("op") == "And": + left, right = bin_expr.get("left"), bin_expr.get("right") + if isinstance(left, dict) and isinstance(right, dict): + return [*_conjuncts(left), *_conjuncts(right)] + return [tree] + + def _expression_from_tree(tree: _ExpressionTree) -> pl.Expr: """Rebuild a polars expression from a serialized tree (inverse of meta.serialize).""" return pl.Expr.deserialize(io.BytesIO(json.dumps(tree).encode()), format="json") @@ -157,11 +172,43 @@ def _escape_sql_identifier(identifier: str) -> str: return f'"{escaped}"' -def _pl_tree_to_sql(tree: _ExpressionTree) -> str: +_INTEGER_RANGES = { + f"{prefix}Int{bits}": (0, 2**bits - 1) if prefix else (-(2 ** (bits - 1)), 2 ** (bits - 1) - 1) + for prefix in ("", "U") + for bits in (8, 16, 32, 64, 128) +} + + +def _widens_exactly(column: pl.DataType | None, target: object) -> bool: + """Whether a cast of a column of dtype ``column`` to the serialized dtype ``target`` keeps every value. + + Only integer to integer and decimal to decimal count: the engine compares those bare columns exactly. An integer + to a decimal keeps every value too, but the engine raises where the common decimal type of a comparison needs more + than 38 digits, and polars casts a Date past 294247 or DATE 'infinity' to a NULL Datetime. + """ + kind = target.get("Literal") if isinstance(target, dict) else None + if isinstance(kind, str) and kind in _INTEGER_RANGES and str(column) in _INTEGER_RANGES: + low, high = _INTEGER_RANGES[str(column)] + target_low, target_high = _INTEGER_RANGES[kind] + return target_low <= low and high <= target_high + if isinstance(kind, dict) and isinstance(column, pl.Decimal) and column.precision is not None: + precision_scale = kind.get("Decimal") + if not (isinstance(precision_scale, list) and len(precision_scale) == 2): + return False + precision, scale = precision_scale + if not (isinstance(precision, int) and isinstance(scale, int)): + return False + return scale >= column.scale and precision - scale >= column.precision - column.scale + return False + + +def _pl_tree_to_sql(tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | None = None) -> str: """Recursively convert a Polars expression tree (as JSON) to a SQL string. Parameters: tree (dict): JSON-deserialized expression tree from Polars + schema (Mapping): the polars schema of the scanned relation, which decides whether a cast of a column widens + exactly; without it no cast of a column translates Returns: str: SQL expression string @@ -187,7 +234,7 @@ def _pl_tree_to_sql(tree: _ExpressionTree) -> str: assert isinstance(lhs, dict), f"LHS of a {node_type} should be a dict but got {type(lhs)}" assert isinstance(op, str), f"The op of a {node_type} should be a str but got {type(op)}" assert isinstance(rhs, dict), f"RHS of a {node_type} should be a dict but got {type(rhs)}" - return f"({_pl_tree_to_sql(lhs)} {_pl_operation_to_sql(op)} {_pl_tree_to_sql(rhs)})" + return f"({_pl_tree_to_sql(lhs, schema)} {_pl_operation_to_sql(op)} {_pl_tree_to_sql(rhs, schema)})" if node_type == "Column": # A reference to a column name # Wrap in quotes to handle special characters @@ -199,7 +246,7 @@ def _pl_tree_to_sql(tree: _ExpressionTree) -> str: # Recursively process dynamic or literal values val_tree = tree[node_type] assert isinstance(val_tree, dict), f"A {node_type} should be a dict but got {type(val_tree)}" - return _pl_tree_to_sql(val_tree) + return _pl_tree_to_sql(val_tree, schema) if node_type == "Int": # Direct integer literals @@ -235,7 +282,7 @@ def _pl_tree_to_sql(tree: _ExpressionTree) -> str: if "Boolean" in func_dict: func = func_dict["Boolean"] - arg_sql = _pl_tree_to_sql(inputs[0]) + arg_sql = _pl_tree_to_sql(inputs[0], schema) if func == "IsNull": return f"({arg_sql} IS NULL)" @@ -250,18 +297,28 @@ def _pl_tree_to_sql(tree: _ExpressionTree) -> str: if node_type == "Cast": cast_tree = tree[node_type] assert isinstance(cast_tree, dict), f"A {node_type} should be a dict but got {type(cast_tree)}" - options = cast_tree.get("options") - if options not in ("Strict", "NonStrict"): - msg = f"Only NonStrict/Strict casts can be safely unwrapped, got {options!r}" - raise NotImplementedError(msg) cast_expr = cast_tree["expr"] assert isinstance(cast_expr, dict), f"A {node_type} should be a dict but got {type(cast_expr)}" - # polars folds a cast of a literal before the source sees it; a cast of a column can truncate, turn an - # overflow into NULL or change the type the comparison runs in, and the bare column carries none of that + column = cast_expr.get("Column") + if ( + schema is not None + and isinstance(column, str) + and _widens_exactly(schema.get(column), cast_tree.get("dtype")) + ): + # No cast option changes a value the target type holds, so the bare column compares the same + return _pl_tree_to_sql(cast_expr, schema) + # Any other cast of a column can truncate, turn an overflow into NULL or change the type the comparison runs + # in, and the bare column carries none of that if "Literal" not in cast_expr: msg = "A cast of a column or an expression cannot be pushed down" raise NotImplementedError(msg) - return _pl_tree_to_sql(cast_expr) + options = cast_tree.get("options") + if options not in ("Strict", "NonStrict"): + msg = f"Only NonStrict/Strict casts can be safely unwrapped, got {options!r}" + raise NotImplementedError(msg) + # polars folds a cast of a literal before a scan sees it, so only unoptimized trees such as those + # _predicate_to_expression builds reach this, and the literal renders without the cast's target type + return _pl_tree_to_sql(cast_expr, schema) if node_type == "Scalar": # Detect format: old style (dtype/value) or new style (direct type key) @@ -395,12 +452,19 @@ def source_generator( tree = json.loads(predicate.meta.serialize(format="json")) real_tree, had_dynamic = _strip_dynamic_predicates(tree) if real_tree is not None: - # We have a real predicate; if possible, push it down to DuckDB. - duck_predicate = _tree_to_sql_expression(real_tree) - if duck_predicate is None: - # Could not push it down: re-apply it polars-side. Rebuild the - # expression from the stripped tree so we never hand polars the - # dynamic node it cannot lower. + # A row the predicate keeps satisfies every conjunct, so the engine may filter by the conjuncts that + # translate as long as polars applies the whole predicate when one does not. + conjuncts = _conjuncts(real_tree) + pushed = [ + expression + for expression in (_tree_to_sql_expression(conjunct, schema) for conjunct in conjuncts) + if expression is not None + ] + if pushed: + duck_predicate = functools.reduce(operator.and_, pushed) + if len(pushed) < len(conjuncts): + # Rebuild the expression from the stripped tree so we never hand polars the dynamic node it + # cannot lower. fallback_predicate = _expression_from_tree(real_tree) if had_dynamic else predicate # Try to pushdown filter, if one exists if duck_predicate is not None: diff --git a/tests/fast/arrow/test_polars.py b/tests/fast/arrow/test_polars.py index 1052652ad..3be1fb1b3 100644 --- a/tests/fast/arrow/test_polars.py +++ b/tests/fast/arrow/test_polars.py @@ -11,6 +11,7 @@ arrow = pytest.importorskip("pyarrow") pl_testing = pytest.importorskip("polars.testing") +from duckdb import polars_io # noqa: E402 from duckdb.polars_io import _pl_tree_to_sql, _predicate_to_expression # noqa: E402 pl_pre_1_35_0 = parse_version(pl.__version__) < parse_version("1.35.0") @@ -783,8 +784,8 @@ def test_cast_node_unwraps_a_literal_and_refuses_a_column(self): ) assert _pl_tree_to_sql(cast_literal) == "1" - # A cast polars inserted to reconcile types, or one that cannot fail, arrives NonStrict; it can still truncate, - # turn an overflow into NULL or change the type the comparison runs in, so the predicate stays with polars + # Without the source schema a cast that widens cannot be told from one that truncates, turns an overflow into + # NULL or changes the type the comparison runs in, so the predicate stays with polars cast_column = json.loads( '{"Cast": {"expr": {"Column": "a"}, "dtype": {"Decimal": [20, 0]}, "options": "NonStrict"}}' ) @@ -792,13 +793,22 @@ def test_cast_node_unwraps_a_literal_and_refuses_a_column(self): _pl_tree_to_sql(cast_column) def test_cast_node_predicate_pushdown(self): - """Predicates with Cast nodes should be successfully pushed down.""" - # A decimal with non-38 precision produces a Cast node in Polars + """A comparison with a decimal literal of a precision other than 38 translates.""" + # polars 2 serializes the literal as a typed decimal scalar, polars 1 as a cast of the literal expr = pl.col("a") == pl.lit(1, dtype=pl.Decimal(precision=20, scale=0)) valid_filter(expr) - def test_polars_lazy_pushdown_decimal_with_cast(self): - """End-to-end test: decimal columns with non-38 precision should push down filters.""" + def test_polars_lazy_pushdown_decimal_with_cast(self, monkeypatch): + """A DECIMAL(20,0) column compared with an integer is filtered by the engine.""" + pushed = [] + to_sql_expression = polars_io._tree_to_sql_expression + + def recording(*args): + expression = to_sql_expression(*args) + pushed.append(expression is not None) + return expression + + monkeypatch.setattr(polars_io, "_tree_to_sql_expression", recording) con = duckdb.connect() con.execute("CREATE TABLE test_cast (a DECIMAL(20,0))") con.execute("INSERT INTO test_cast VALUES (1), (10), (100), (NULL)") @@ -807,6 +817,7 @@ def test_polars_lazy_pushdown_decimal_with_cast(self): assert lazy_df.filter(pl.col("a") == 1).collect().to_dicts() == [{"a": 1}] assert lazy_df.filter(pl.col("a") > 1).collect().to_dicts() == [{"a": 10}, {"a": 100}] + assert pushed == [True, True] def test_explicit_cast_not_pushed_down(self): """Explicit user .cast() (Strict) should not be pushed down - falls back to Polars.""" diff --git a/tests/fast/arrow/test_polars_pushdown_literals.py b/tests/fast/arrow/test_polars_pushdown_literals.py index 4edcf3ab4..67fa7806b 100644 --- a/tests/fast/arrow/test_polars_pushdown_literals.py +++ b/tests/fast/arrow/test_polars_pushdown_literals.py @@ -1,4 +1,5 @@ import datetime +import decimal import json import operator import subprocess @@ -7,6 +8,7 @@ from zoneinfo import ZoneInfo import pytest +from packaging.version import parse as parse_version import duckdb @@ -24,6 +26,16 @@ UNIT_RESOLUTION = {"ms": 0, "us": 1, "ns": 2} COLUMN_UNITS = {"TIMESTAMP_S": "ms", "TIMESTAMP_MS": "ms", "TIMESTAMP": "us", "TIMESTAMP_NS": "ns"} SERIALIZED_UNITS = {"Milliseconds": "ms", "Microseconds": "us", "Nanoseconds": "ns"} +POLARS_2 = parse_version(pl.__version__) >= parse_version("2") +INTEGER_RANGES = { + "TINYINT": (-(2**7), 2**7 - 1), + "SMALLINT": (-(2**15), 2**15 - 1), + "INTEGER": (-(2**31), 2**31 - 1), + "BIGINT": (-(2**63), 2**63 - 1), + "UTINYINT": (0, 2**8 - 1), + "UINTEGER": (0, 2**32 - 1), + "UBIGINT": (0, 2**64 - 1), +} ZONE_MISMATCHES = [("America/New_York", "UTC"), ("UTC", "Asia/Tokyo"), ("America/New_York", "Asia/Tokyo")] ZONE_MISMATCH_ROWS = """ INSERT INTO t VALUES @@ -37,10 +49,10 @@ def pushdowns(monkeypatch): seen = [] to_sql_expression = polars_io._tree_to_sql_expression - def recording(tree): - expression = to_sql_expression(tree) + def recording(tree, *schema): + expression = to_sql_expression(tree, *schema) try: - polars_io._pl_tree_to_sql(tree) + polars_io._pl_tree_to_sql(tree, *schema) except Exception as error: seen.append((tree, expression, type(error))) else: @@ -52,18 +64,37 @@ def recording(tree): def assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, *, pushed, polars_predicate=None): + """`pushed` holds for every conjunct of a top level AND, or is "partly" when some reached the engine.""" pushdowns.clear() actual = lazy_df.filter(predicate).collect() - assert len(pushdowns) == 1, pushdowns - tree, expression, error = pushdowns[0] - if pushed: - assert expression is not None, (predicate, tree, error) - else: - assert expression is None, (predicate, tree, expression) - assert error is NotImplementedError, (predicate, tree, error) expected = lazy_df.collect().filter(predicate if polars_predicate is None else polars_predicate) pl_testing.assert_frame_equal(actual, expected) - return tree + assert pushdowns, predicate + states = [expression is not None for _, expression, _ in pushdowns] + if pushed == "partly": + assert any(states), (predicate, pushdowns) + assert not all(states), (predicate, pushdowns) + else: + assert all(state == pushed for state in states), (predicate, pushdowns) + for tree, expression, error in pushdowns: + if expression is None: + assert error is NotImplementedError, (predicate, tree, error) + return [tree for tree, _, _ in pushdowns] + + +def refused_columns(pushdowns): + return sorted(name for tree, expression, _ in pushdowns if expression is None for name in column_names(tree)) + + +def column_names(node): + if isinstance(node, dict): + if isinstance(node.get("Column"), str): + yield node["Column"] + for child in node.values(): + yield from column_names(child) + elif isinstance(node, list): + for child in node: + yield from column_names(child) def datetime_units(node): @@ -110,7 +141,9 @@ def test_naive_literal_matches_polars(self, data_type, unit, duckdb_cursor, push literal = pl.lit(value, dtype=pl.Datetime(unit)) for compare in ORDERINGS: pushed = column_unit != "ns" and not widened_to_range(compare, unit, column_unit) - tree = assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("a"), literal), pushed=pushed) + [tree] = assert_pushdown_matches_polars( + lazy_df, pushdowns, compare(pl.col("a"), literal), pushed=pushed + ) assert set(datetime_units(tree)) == {column_unit} @pytest.mark.parametrize("unit", POLARS_UNITS) @@ -133,7 +166,9 @@ def test_zoned_literal_in_session_zone_matches_polars(self, zone, unit, duckdb_c literal = pl.lit(instant.astimezone(ZoneInfo(zone)), dtype=pl.Datetime(unit, zone)) for compare in ORDERINGS: pushed = not widened_to_range(compare, unit, "us") - tree = assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("a"), literal), pushed=pushed) + [tree] = assert_pushdown_matches_polars( + lazy_df, pushdowns, compare(pl.col("a"), literal), pushed=pushed + ) assert set(datetime_units(tree)) == {"us"} # polars itself rejects comparing a column and a literal of different zones, but it hands such a predicate to the @@ -151,7 +186,7 @@ def test_zoned_literal_outside_session_zone_compares_instants( literal = pl.lit(instant.astimezone(ZoneInfo(literal_zone)), dtype=pl.Datetime(unit, literal_zone)) same_instant = pl.lit(instant.astimezone(ZoneInfo(session_zone)), dtype=pl.Datetime(unit, session_zone)) for compare in ORDERINGS: - tree = assert_pushdown_matches_polars( + [tree] = assert_pushdown_matches_polars( lazy_df, pushdowns, compare(pl.col("a"), literal), @@ -227,7 +262,7 @@ def test_non_finite_literal_inside_conjunction_matches_polars(self, duckdb_curso duckdb_cursor.execute("INSERT INTO t VALUES (1), ('inf'), ('-inf'), ('nan'), (NULL)") lazy_df = duckdb_cursor.table("t").pl(lazy=True) predicate = (pl.col("a") > 0) & (pl.col("a") < float("inf")) - assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed="partly") @pytest.mark.parametrize("value", [float("inf"), float("-inf"), float("nan")]) @pytest.mark.parametrize("dtype", [pl.Float32, pl.Float64]) @@ -260,9 +295,10 @@ def test_untyped_non_finite_literal_is_not_pushed_down_without_assertions(self): class TestColumnCastPushdown: - # A cast of the column, whether the user wrote it or polars inserted it to reconcile types, truncates, turns an - # overflow into NULL or changes the type the comparison runs in; the bare column carries none of that, so the - # predicate stays with polars and the source must say so. + # A cast of the column, whether the user wrote it or polars inserted it to reconcile types, can truncate, turn an + # overflow into NULL or change the type the comparison runs in, and the bare column carries none of that, so the + # predicate stays with polars; only a cast whose target type holds every value of the column's type reads the same + # as the bare column and is pushed. ROWS = """ INSERT INTO t VALUES ('2024-01-01 12:00:00+00'), ('2024-01-01 12:00:00.0005+00'), ('2024-01-01 12:00:00.001+00'), @@ -311,8 +347,8 @@ def test_two_column_comparisons(self, duckdb_cursor, pushdowns): duckdb_cursor.execute("INSERT INTO t VALUES (1, 2, 1, 2), (3, 1, 3, 1), (2, 2, 2, 2), (NULL, 1, NULL, 1)") lazy_df = duckdb_cursor.table("t").pl(lazy=True) for compare in ORDERINGS: - # polars widens the narrower column with a NonStrict cast, which the source does not push - assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("i"), pl.col("j")), pushed=False) + # polars widens the narrower column to Int64, which holds every INTEGER, so the bare column reads the same + assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("i"), pl.col("j")), pushed=True) assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("d20"), pl.col("d38")), pushed=True) def test_cast_of_an_expression_matches_polars(self, duckdb_cursor, pushdowns): @@ -323,17 +359,29 @@ def test_cast_of_an_expression_matches_polars(self, duckdb_cursor, pushdowns): assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) assert lazy_df.filter(predicate).collect()["i"].to_list() == [200, None] - def test_fallback_filters_every_batch(self, duckdb_cursor, pushdowns): - # The source hands polars Arrow batches of about 120 thousand rows: a match in the first, none in the second, - # one in the third, so a read that stopped at an empty batch would lose the last match + def test_fallback_filters_every_batch(self, duckdb_cursor, pushdowns, monkeypatch): + # One match in the first batch and one past it with empty batches between, so a read that stopped after the + # first batch or at an empty one would lose the last match duckdb_cursor.execute( "CREATE TABLE t AS SELECT range AS id, CASE WHEN range IN (100, 250000) THEN 100 ELSE 200 END AS i " "FROM range(300000)" ) lazy_df = duckdb_cursor.table("t").pl(lazy=True) - predicate = pl.col("i").cast(pl.Int8, strict=False).is_between(100, 127) + batches = [] + from_arrow = pl.from_arrow + + def counting(batch, *args, **kwargs): + batches.append(batch.num_rows) + return from_arrow(batch, *args, **kwargs) + + monkeypatch.setattr(pl, "from_arrow", counting) + # Pushed bare, the predicate kept every row; the non strict cast turns 200 into NULL + predicate = pl.col("i").cast(pl.Int8, strict=False).is_not_null() assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) + batches.clear() assert lazy_df.filter(predicate).collect()["id"].to_list() == [100, 250000] + assert len(batches) > 1, batches + assert batches[0] <= 250000, batches def test_float_column_against_a_double_literal_matches_polars(self, duckdb_cursor, pushdowns): # polars widens the FLOAT column with a cast; pushed bare, the engine compared 0.1 as a FLOAT and dropped a row @@ -356,10 +404,239 @@ def test_date_column_against_a_zoned_literal_matches_polars(self, duckdb_cursor, assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("d"), literal), pushed=False) def test_decimal_column_against_a_literal_is_still_pushed(self, duckdb_cursor, pushdowns): - # polars folds the literal into the column's decimal type before the source sees it, so no Cast node arrives + # polars 2 folds the literal into the column's decimal type; polars 1 widens the column to Decimal(38, 0) duckdb_cursor.execute("CREATE TABLE t (a DECIMAL(20,0))") - duckdb_cursor.execute("INSERT INTO t VALUES (1), (10), (100), (NULL)") + duckdb_cursor.execute("INSERT INTO t VALUES (1), (10), (100), (99999999999999999999), (NULL)") + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + for compare in ORDERINGS: + assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("a"), pl.lit(10)), pushed=True) + + @pytest.mark.parametrize( + ("left", "right"), + [ + ("TINYINT", "SMALLINT"), + ("SMALLINT", "INTEGER"), + ("INTEGER", "BIGINT"), + ("UTINYINT", "TINYINT"), + ("UINTEGER", "INTEGER"), + ("UTINYINT", "UINTEGER"), + pytest.param( + "UBIGINT", + "BIGINT", + marks=pytest.mark.skipif(not POLARS_2, reason="polars 1 compares UInt64 with Int64 as Float64"), + ), + ], + ) + def test_exact_widening_is_pushed(self, left, right, duckdb_cursor, pushdowns): + duckdb_cursor.execute(f"CREATE TABLE t (a {left}, b {right})") + (left_low, left_high), (right_low, right_high) = INTEGER_RANGES[left], INTEGER_RANGES[right] + rows = [ + (left_low, right_low), + (left_high, right_high), + (left_low, right_high), + (left_high, right_low), + (1, 1), + (None, 1), + (1, None), + ] + duckdb_cursor.executemany("INSERT INTO t VALUES (?, ?)", rows) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + for compare in ORDERINGS: + [tree] = assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("a"), pl.col("b")), pushed=True) + assert "Cast" in json.dumps(tree) + + @pytest.mark.parametrize( + ("left", "right", "rows"), + [ + ("DECIMAL(10,2)", "DECIMAL(12,2)", [("-99999999.99", "-9999999999.99"), ("99999999.99", "99999999.99")]), + ("DECIMAL(10,2)", "DECIMAL(12,4)", [("-99999999.99", "-99999999.9999"), ("99999999.99", "99999999.9900")]), + ("DECIMAL(20,0)", "DECIMAL(38,0)", [("-" + "9" * 20, "-" + "9" * 38), ("9" * 20, "9" * 20)]), + ], + ) + def test_decimal_widening_is_pushed(self, left, right, rows, duckdb_cursor, pushdowns): + # polars 2 compares the two decimals as they are, polars 1 widens the narrower one to the wider precision or + # scale, which keeps every digit + duckdb_cursor.execute(f"CREATE TABLE t (a {left}, b {right})") + duckdb_cursor.executemany("INSERT INTO t VALUES (?, ?)", [*rows, ("1", "1"), (None, "1"), ("1", None)]) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + for compare in ORDERINGS: + assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("a"), pl.col("b")), pushed=True) + + def test_written_widening_is_pushed(self, duckdb_cursor, pushdowns): + # polars 2 marks a cast that cannot fail Overflowing, polars 1 keeps the user's Strict + duckdb_cursor.execute("CREATE TABLE t (a INTEGER)") + duckdb_cursor.execute("INSERT INTO t VALUES (-2147483648), (5), (6), (2147483647), (NULL)") lazy_df = duckdb_cursor.table("t").pl(lazy=True) for compare in ORDERINGS: - tree = assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("a"), pl.lit(10)), pushed=True) - assert "Cast" not in json.dumps(tree) + predicate = compare(pl.col("a").cast(pl.Int64), pl.lit(5, dtype=pl.Int64)) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=True) + + @pytest.mark.parametrize( + ("columns", "rows", "predicate"), + [ + pytest.param( + "a BIGINT", [(2**53,), (2**53 + 1,), (None,)], pl.col("a") == 2.0**53, id="BIGINT to Float64 past 2**53" + ), + pytest.param( + "a UINTEGER", + [(1,), (4000000000,), (None,)], + pl.col("a").cast(pl.Int32, strict=False).is_null(), + id="UInt32 to Int32", + ), + pytest.param( + "a SMALLINT", + [(1,), (-1,), (None,)], + pl.col("a").cast(pl.UInt16, strict=False).is_null(), + id="Int16 to UInt16", + ), + pytest.param( + "a DECIMAL(10,2)", + [("1.25",), ("1234567.89",), (None,)], + pl.col("a").cast(pl.Decimal(10, 4), strict=False).is_null(), + id="Decimal(10,2) to Decimal(10,4)", + ), + pytest.param( + "a DECIMAL(10,4)", + [("1.2345",), ("1.2300",), (None,)], + pl.col("a").cast(pl.Decimal(10, 2), strict=False) == decimal.Decimal("1.23"), + id="Decimal(10,4) to Decimal(10,2)", + ), + pytest.param( + "a DATE", + [("2024-01-01",), ("infinity",), ("300000-01-01",), (None,)], + pl.col("a") >= datetime.datetime(2020, 1, 1), + id="DATE past the microsecond range against a naive datetime", + ), + pytest.param( + "a DATE", + [("2019-01-01",), ("-infinity",), (None,)], + pl.col("a") < datetime.datetime(2020, 1, 1), + id="DATE before the microsecond range against a naive datetime", + ), + pytest.param( + "a DATE, b TIMESTAMP", + [("infinity", "2020-01-01"), ("2020-01-02", "2020-01-01"), (None, "2020-01-01")], + pl.col("a") >= pl.col("b"), + id="DATE against a TIMESTAMP column", + ), + pytest.param( + "a DATE, b TIMESTAMP_NS", + [("2300-01-01", "2020-01-01"), ("2020-01-02", "2020-01-01"), (None, "2020-01-01")], + pl.col("a") >= pl.col("b"), + id="DATE against a TIMESTAMP_NS column", + ), + pytest.param( + "a BIGINT, b DECIMAL(38,20)", + [(2**63 - 1, 1), (1, 1), (None, 1)], + pl.col("a") == pl.col("b"), + id="BIGINT against a DECIMAL(38,20) column", + ), + ], + ) + def test_lossy_cast_is_not_pushed(self, columns, rows, predicate, duckdb_cursor, pushdowns): + # Each predicate carries a cast next to the widenings that changes a value or the comparison; pushed bare, the + # engine kept rows polars drops, dropped rows polars keeps, or raised + duckdb_cursor.execute(f"CREATE TABLE t ({columns})") + duckdb_cursor.executemany(f"INSERT INTO t VALUES ({', '.join('?' * len(rows[0]))})", rows) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + [tree] = assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) + assert "Cast" in json.dumps(tree) + + @pytest.mark.parametrize( + ("source", "target", "pushed"), + [ + pytest.param(pl.Int32, '"Int64"', True, id="Int32 to Int64"), + pytest.param(pl.UInt8, '"Int16"', True, id="UInt8 to Int16"), + pytest.param(pl.UInt64, '"Int128"', True, id="UInt64 to Int128"), + pytest.param(pl.UInt8, '"UInt32"', True, id="UInt8 to UInt32"), + pytest.param(pl.Int64, '"UInt64"', False, id="Int64 to UInt64"), + pytest.param(pl.UInt32, '"Int32"', False, id="UInt32 to Int32"), + pytest.param(pl.Int64, '"Int32"', False, id="Int64 to Int32"), + pytest.param(pl.Decimal(20, 0), '{"Decimal": [38, 0]}', True, id="Decimal(20,0) to Decimal(38,0)"), + pytest.param(pl.Decimal(10, 2), '{"Decimal": [12, 4]}', True, id="Decimal(10,2) to Decimal(12,4)"), + pytest.param(pl.Decimal(10, 2), '{"Decimal": [10, 4]}', False, id="Decimal(10,2) to Decimal(10,4)"), + pytest.param(pl.Decimal(10, 4), '{"Decimal": [10, 2]}', False, id="Decimal(10,4) to Decimal(10,2)"), + pytest.param(pl.Int64, '{"Decimal": [38, 0]}', False, id="Int64 to Decimal(38,0)"), + pytest.param(pl.Date, '{"Datetime": ["Microseconds", null]}', False, id="Date to Datetime(Microseconds)"), + pytest.param(pl.Date, '{"Datetime": ["Milliseconds", null]}', False, id="Date to Datetime(Milliseconds)"), + pytest.param(pl.Float32, '"Float64"', False, id="Float32 to Float64"), + pytest.param(pl.Int32, '"Float64"', False, id="Int32 to Float64"), + ], + ) + def test_cast_rule_on_hand_built_trees(self, source, target, pushed): + schema = pl.Schema({"a": source}) + for options in ("Strict", "NonStrict", "Overflowing"): + tree = json.loads( + f'{{"Cast": {{"expr": {{"Column": "a"}}, "dtype": {{"Literal": {target}}}, "options": "{options}"}}}}' + ) + if pushed: + assert _pl_tree_to_sql(tree, schema) == '"a"' + else: + with pytest.raises(NotImplementedError): + _pl_tree_to_sql(tree, schema) + # Without the source schema a widening cannot be told from a cast that truncates + with pytest.raises(NotImplementedError): + _pl_tree_to_sql(tree) + with pytest.raises(NotImplementedError): + _pl_tree_to_sql(tree, pl.Schema({"b": source})) + + +class TestConjunctPushdown: + # The source pushes the conjuncts of a top level AND that translate and, when one stays behind, applies the whole + # predicate in polars to every batch; a row the predicate keeps has every conjunct TRUE, which the engine keeps. + def test_tpch_q6_shape_pushes_the_translatable_conjuncts(self, duckdb_cursor, pushdowns): + duckdb_cursor.execute("CREATE TABLE t (id INTEGER, ship DATE, disc DECIMAL(15,2), qty DECIMAL(15,2))") + # Rows the pushed date and quantity bounds keep but a discount bound or a NULL discount removes, so only the + # polars pass over the batch can drop them + duckdb_cursor.execute( + """ + INSERT INTO t VALUES + (1, '1994-03-01', 0.06, 10), (2, '1994-03-01', 0.04, 10), (3, '1994-03-01', 0.08, 10), + (4, '1994-03-01', NULL, 10), (5, '1994-01-01', 0.05, 23), (6, '1994-12-31', 0.07, 23.99), + (7, '1994-03-01', 0.06, 24), (8, '1993-12-31', 0.06, 10), (9, '1995-01-01', 0.06, 10), + (10, NULL, 0.06, 10), (11, '1994-03-01', 0.06, NULL), (12, '1994-03-01', 0.06, 10) + """ + ) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + predicate = ( + (pl.col("ship") >= datetime.date(1994, 1, 1)) + & (pl.col("ship") < datetime.date(1995, 1, 1)) + & (pl.col("disc") >= 0.05) + & (pl.col("disc") <= 0.07) + & (pl.col("qty") < 24) + ) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed="partly") + # polars compares a DECIMAL with a Python float through a Float64 cast of the column, which is refused + assert refused_columns(pushdowns) == ["disc", "disc"] + assert lazy_df.filter(predicate).collect()["id"].to_list() == [1, 5, 6, 12] + + def test_refused_conjunct_inside_or_keeps_the_rest_pushed(self, duckdb_cursor, pushdowns): + duckdb_cursor.execute("CREATE TABLE t (id INTEGER, a INTEGER, b INTEGER, f FLOAT)") + duckdb_cursor.execute( + """ + INSERT INTO t VALUES + (1, 1, 1, 0.5), (2, 1, 2, 0.1), (3, 1, 2, 0.5), (4, 0, 1, 0.1), (5, 1, 3, 0.1), (6, 1, NULL, 0.1), + (7, NULL, 1, 0.1), (8, 1, 2, NULL) + """ + ) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + # Nested on the right, so the AND chain is split on both sides + predicate = (pl.col("a") > 0) & ( + ((pl.col("f") == pl.lit(0.1, dtype=pl.Float64)) | (pl.col("b") == 1)) & (pl.col("b") < 3) + ) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed="partly") + assert refused_columns(pushdowns) == ["b", "f"] + assert len(pushdowns) == 3 + + def test_partly_pushed_predicate_under_head_and_top_k(self, duckdb_cursor, pushdowns): + duckdb_cursor.execute("CREATE TABLE t AS SELECT range AS id, (range % 300)::INTEGER AS i FROM range(1000)") + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + predicate = (pl.col("id") >= 100) & (pl.col("i").cast(pl.Int8, strict=False).is_null()) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed="partly") + eager = lazy_df.collect().filter(predicate) + pl_testing.assert_frame_equal(lazy_df.filter(predicate).head(3).collect(), eager.head(3)) + pl_testing.assert_frame_equal( + lazy_df.filter(predicate).sort("id", descending=True).head(3).collect(), + eager.sort("id", descending=True).head(3), + ) + pl_testing.assert_frame_equal(lazy_df.filter(predicate).select("i").collect(), eager.select("i")) From 452d322fa7abd874dd568afdb28ea857c894d2ad Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 12:06:45 +0000 Subject: [PATCH 15/61] Own a view's sources on a subquery, refuse a file-like view in a database file, drop the object store through the shutdown gate --- src/include/duckdb_python/path_like.hpp | 3 + .../pyconnection/pyconnection.hpp | 4 +- src/include/duckdb_python/pyfilesystem.hpp | 5 +- src/path_like.cpp | 2 +- src/pyconnection.cpp | 28 +-- src/pyconnection/seam.cpp | 88 +++++----- tests/fast/api/test_read_csv.py | 165 ++++++++++++++++-- tests/fast/api/test_seam.py | 11 ++ 8 files changed, 232 insertions(+), 74 deletions(-) diff --git a/src/include/duckdb_python/path_like.hpp b/src/include/duckdb_python/path_like.hpp index aa1a429bc..d6ad76bab 100644 --- a/src/include/duckdb_python/path_like.hpp +++ b/src/include/duckdb_python/path_like.hpp @@ -10,6 +10,9 @@ namespace duckdb { struct DuckDBPyConnection; struct PathLike { + //! The protocol of the in-memory file system of this process that holds the file-like objects given to a reader + static constexpr const char *OBJECT_STORE_PROTOCOL = "DUCKDB_INTERNAL_OBJECTSTORE"; + static PathLike Create(const nb::object &object, DuckDBPyConnection &connection); // The file(s) extracted from object vector files; diff --git a/src/include/duckdb_python/pyconnection/pyconnection.hpp b/src/include/duckdb_python/pyconnection/pyconnection.hpp index eb7c71ca9..b72a4a7f2 100644 --- a/src/include/duckdb_python/pyconnection/pyconnection.hpp +++ b/src/include/duckdb_python/pyconnection/pyconnection.hpp @@ -298,8 +298,8 @@ struct DuckDBPyConnection : public std::enable_shared_from_this internal_object_filesystem; + //! The database's store of file-like objects for reading, kept once this connection has found it + shared_ptr object_store; case_insensitive_map_t> registered_functions; //! The names register() succeeded with on this connection, bounded oldest out. Only a hint: unregister() of a //! name it holds refuses beside an open DB-API result, and of one it does not hold, such as a view renamed in SQL, diff --git a/src/include/duckdb_python/pyfilesystem.hpp b/src/include/duckdb_python/pyfilesystem.hpp index 85a61143b..1b54fd43e 100644 --- a/src/include/duckdb_python/pyfilesystem.hpp +++ b/src/include/duckdb_python/pyfilesystem.hpp @@ -140,8 +140,9 @@ class ObjectStore : public ObjectCacheEntry { } public: - //! Read and written with the GIL held, which is what serialises the connections of a database here - std::shared_ptr filesystem; + //! The one owner of the Python file system's reference. Read and written with the GIL held, which is what + //! serialises the connections of a database here + unique_ptr filesystem; }; } // namespace duckdb diff --git a/src/path_like.cpp b/src/path_like.cpp index 292e4ccde..e1cb28d6d 100644 --- a/src/path_like.cpp +++ b/src/path_like.cpp @@ -47,7 +47,7 @@ void PathLikeProcessor::AddFile(const nb::object &object) { } // This is (assumed to be) a file-like object auto generated_name = - StringUtil::Format("%s://%s", "DUCKDB_INTERNAL_OBJECTSTORE", StringUtil::GenerateRandomName()); + StringUtil::Format("%s://%s", PathLike::OBJECT_STORE_PROTOCOL, StringUtil::GenerateRandomName()); all_files.push_back(generated_name); fs_files.push_back(generated_name); diff --git a/src/pyconnection.cpp b/src/pyconnection.cpp index 86ddbbb7b..969a3e336 100644 --- a/src/pyconnection.cpp +++ b/src/pyconnection.cpp @@ -1739,17 +1739,23 @@ nb::object DuckDBPyConnection::ArrowSourcesNodes() { } ObjectStore::~ObjectStore() { - // The Python file system dies with the database, on whatever thread drops the last connection, so the reference - // goes under the guard; during interpreter teardown it is left to the interpreter, as every held Python object is - if (nb::detail::cleanup_guard guard {}) { - filesystem.reset(); - } else if (filesystem) { - filesystem->release(); + if (!filesystem) { + return; } + // The store dies with the database, on whatever thread drops the last connection, so the reference goes through + // the shutdown gate as the PythonFilesystem over the same object does + try { + PyUtil::QueryGil gil(nullptr); + filesystem->dec_ref(); + } catch (...) { // NOLINT + } + // Leaked when the gate refused, as the reference can then no longer be dropped + filesystem->release(); } ModifiedMemoryFileSystem &DuckDBPyConnection::GetObjectFileSystem() { - if (!internal_object_filesystem) { + DUCKDB_PY_ASSERT_GIL_HELD(); + if (!object_store) { auto &context = *con.GetConnection().context; auto store = ObjectCache::GetObjectCache(context).GetOrCreate(ObjectStore::ObjectType()); // The GIL is the lock here: a mutex held while the Python file system is built would deadlock against a @@ -1763,17 +1769,17 @@ ModifiedMemoryFileSystem &DuckDBPyConnection::GetObjectFileSystem() { throw InvalidInputException( "This operation could not be completed because required module 'fsspec' is not installed"); } - auto built = std::make_shared(modified_memory_fs()); + auto built = make_uniq(modified_memory_fs()); auto wrapped = WrapFilesystem(*built); if (!store->filesystem) { - D_ASSERT(!FileSystemIsRegistered("DUCKDB_INTERNAL_OBJECTSTORE")); + D_ASSERT(!FileSystemIsRegistered(PathLike::OBJECT_STORE_PROTOCOL)); con.GetDatabase().GetFileSystem().RegisterSubSystem(std::move(wrapped)); store->filesystem = std::move(built); } } - internal_object_filesystem = store->filesystem; + object_store = std::move(store); } - return *internal_object_filesystem; + return *object_store->filesystem; } bool DuckDBPyConnection::IsInteractive() { diff --git a/src/pyconnection/seam.cpp b/src/pyconnection/seam.cpp index 356d6bee5..78d9defd4 100644 --- a/src/pyconnection/seam.cpp +++ b/src/pyconnection/seam.cpp @@ -13,6 +13,7 @@ #include "duckdb/main/database.hpp" #include "duckdb/main/database_manager.hpp" #include "duckdb/parser/expression/columnref_expression.hpp" +#include "duckdb/parser/expression/constant_expression.hpp" #include "duckdb/parser/expression/function_expression.hpp" #include "duckdb/parser/expression/star_expression.hpp" #include "duckdb/parser/parsed_data/create_view_info.hpp" @@ -290,6 +291,25 @@ static unique_ptr WithColumnAliases(unique_ptr copy, const v return std::move(subquery); } +//! Whether a table function's arguments name a file on the object store, which lives in this process's memory +static bool ReadsTheObjectStore(const ParsedExpression &function) { + const auto prefix = string(PathLike::OBJECT_STORE_PROTOCOL) + "://"; + vector pending {&function}; + while (!pending.empty()) { + auto &expression = *pending.back(); + pending.pop_back(); + if (expression.GetExpressionClass() == ExpressionClass::CONSTANT) { + auto &literal = expression.Cast().GetLiteral(); + if (literal.kind == LiteralKind::STRING && StringUtil::StartsWith(literal.text, prefix)) { + return true; + } + } + ParsedExpressionIterator::EnumerateChildren(expression, + [&](const ParsedExpression &child) { pending.push_back(&child); }); + } + return false; +} + class SourceInliner { public: SourceInliner(ClientContext &context_p, engine::SourceRegistry ®istry_p) @@ -322,7 +342,8 @@ class SourceInliner { } } - //! Whether something written in holds a Python object, which no database file can store + //! Whether the query reads a Python object or a file on the object store, which live only in this process and + //! which no database file can store bool HoldsProcessLocalInput() const { return process_local; } @@ -512,9 +533,14 @@ class SourceInliner { } break; } - case TableReferenceType::TABLE_FUNCTION: - steps.push_back(Task::OfExpression(ref->Cast().function)); + case TableReferenceType::TABLE_FUNCTION: { + auto &function = ref->Cast().function; + if (function && ReadsTheObjectStore(*function)) { + process_local = true; + } + steps.push_back(Task::OfExpression(function)); break; + } case TableReferenceType::EXPRESSION_LIST: for (auto &row : ref->Cast().values) { for (auto &value : row) { @@ -629,53 +655,19 @@ bool DuckDBPySeam::IsRegisteredView(ClientContext &context, const string &name) return registered; } -//! The FROM of the first SELECT a query reaches, through its CTEs and set operations -static unique_ptr &FirstFrom(QueryNode &node) { - switch (node.type) { - case QueryNodeType::SELECT_NODE: - return node.Cast().from_table; - case QueryNodeType::CTE_NODE: - return FirstFrom(*node.Cast().child); - case QueryNodeType::RECURSIVE_CTE_NODE: - return FirstFrom(*node.Cast().left); - case QueryNodeType::SET_OPERATION_NODE: - return FirstFrom(*node.Cast().children[0]); - default: - throw InternalException("a view body renders as a SELECT, which carries its sources on its FROM"); - } -} - -//! The reference of a FROM whose copy keeps its dependency: a join's or a pivot's copy drops it, so the leftmost -//! leaf under them carries it, and a copy of the view (its rename) keeps owning its sources -static unique_ptr &OwningReference(unique_ptr &ref) { - switch (ref->type) { - case TableReferenceType::JOIN: - return OwningReference(ref->Cast().left); - case TableReferenceType::PIVOT: - return OwningReference(ref->Cast().source); - default: - return ref; - } -} - -//! The view's query keeps the handles on a FROM: the catalog entry owns the query and a bound copy shares the -//! dependency, so an object store entry the query names by its path lives as long as the view +//! The view reads its query through a subquery that holds the handles: the catalog entry owns the query, and every +//! copy the engine makes of a subquery reference (a bind, a rename) keeps its dependency, whatever the query reads static void OwnSourcesInView(SQLStatement &statement, shared_ptr sources) { auto &info = statement.Cast().info->Cast(); - auto &first = FirstFrom(*info.query->node); - if (!first) { - throw InternalException("a view body renders as a SELECT with a FROM, which carries its sources"); - } - auto &from = OwningReference(first); - // A FROM the inliner copied out of the registry shares its dependency with the registry's entry, which must not - // come to hold the handles; the view's own reference gets a dependency of its own with the entry's items - auto owned = make_shared_ptr(); - if (from->external_dependency) { - from->external_dependency->ScanDependencies( - [&](const string &name, shared_ptr item) { owned->AddDependency(name, std::move(item)); }); - } - owned->AddDependency("sources", std::move(sources)); - from->external_dependency = std::move(owned); + auto subquery = make_uniq(std::move(info.query)); + auto dependency = make_shared_ptr(); + dependency->AddDependency("sources", std::move(sources)); + subquery->external_dependency = std::move(dependency); + auto select = make_uniq(); + select->select_list.push_back(make_uniq()); + select->from_table = std::move(subquery); + info.query = make_uniq(); + info.query->node = std::move(select); } static void CreateView(DuckDBPyConnection &self, const nb::object &name, const string &sql, bool temporary, diff --git a/tests/fast/api/test_read_csv.py b/tests/fast/api/test_read_csv.py index fd610b3d7..f3d55ca70 100644 --- a/tests/fast/api/test_read_csv.py +++ b/tests/fast/api/test_read_csv.py @@ -744,6 +744,28 @@ def _object_store_path(relation): return re.search(r"DUCKDB_INTERNAL_OBJECTSTORE://[0-9a-f]+", relation.sql_query()).group(0) +def _one_reader(con): + return con.read_csv(StringIO("c1\na")) + + +def _two_readers_in_a_union(con): + return con.read_csv(StringIO("c1\na")).union(con.read_csv(StringIO("c1\nb"))) + + +def _one_reader_of_two_filelikes(con): + return con.read_csv([StringIO("c1\na"), StringIO("c1\nb")]) + + +def _a_reader_beside_a_table(con): + con.execute("CREATE TABLE t AS SELECT 1 AS k") + return con.table("t").cross(con.read_csv(StringIO("c1\na"))) + + +def _a_reader_read_by_sql(con): + reader = con.read_csv(StringIO("c1\na")) # noqa: F841, read by name below + return con.sql("SELECT * FROM reader") + + class TestFilelikeViews: # The object store entry of a file-like reader must live as long as a view that reads it, not as long as the # relation the view was made from. @@ -801,8 +823,14 @@ def test_replaced_view_releases_its_entry(self, duckdb_cursor): with pytest.raises(duckdb.IOException, match="No files found"): duckdb_cursor.sql(f"SELECT * FROM read_csv('{first_path}')").fetchall() - @pytest.mark.parametrize("shape", ["frame_alone", "frame_union_filelike"]) - def test_view_over_a_registered_frame_releases_the_frame(self, duckdb_cursor, shape): + @pytest.mark.parametrize( + ("shape", "expected"), + [ + pytest.param("frame_alone", [(1,)], id="frame_alone"), + pytest.param("frame_union_filelike", [(1,), (2,)], id="frame_union_filelike"), + ], + ) + def test_view_over_a_registered_frame_releases_the_frame(self, duckdb_cursor, shape, expected): _ = pytest.importorskip("fsspec") pd = pytest.importorskip("pandas") frame = pd.DataFrame({"c1": [1]}) @@ -815,22 +843,103 @@ def test_view_over_a_registered_frame_releases_the_frame(self, duckdb_cursor, sh rel.to_view("v") del rel, frame gc.collect() - assert duckdb_cursor.sql("SELECT c1 FROM v ORDER BY c1").fetchall()[0] == (1,) + assert duckdb_cursor.sql("SELECT c1 FROM v ORDER BY c1").fetchall() == expected duckdb_cursor.execute("DROP VIEW v") gc.collect() assert alive() is None - def test_renamed_view_over_a_join_keeps_its_sources(self, duckdb_cursor): + @pytest.mark.parametrize( + ("build", "expected"), + [ + pytest.param( + lambda con: con.read_csv(StringIO("a\n1")).cross(con.read_csv(StringIO("b\n2"))), + [(1, 2)], + id="join_of_two_filelikes", + ), + pytest.param( + lambda con: con.sql("SELECT 1 AS a").cross(con.read_csv(StringIO("b\n2"))), + [(1, 2)], + id="join_with_a_constant_left_side", + ), + pytest.param( + lambda con: con.sql("SELECT 1 AS c1").union(con.read_csv(StringIO("c1\n2"))), + [(1,), (2,)], + id="union_with_a_constant_left_side", + ), + ], + ) + def test_renamed_view_keeps_its_sources(self, duckdb_cursor, build, expected): _ = pytest.importorskip("fsspec") - # The engine copies the view to rename it, and a join reference's copy drops what hangs on the join itself - left = duckdb_cursor.read_csv(StringIO("a\n1")) - right = duckdb_cursor.read_csv(StringIO("b\n2")) - left.cross(right).to_view("v") - del left, right + # The engine copies the view to rename it, and the copy of a join reference drops what hangs on the join + build(duckdb_cursor).to_view("v") gc.collect() duckdb_cursor.execute("ALTER VIEW v RENAME TO renamed") gc.collect() - assert duckdb_cursor.sql("SELECT * FROM renamed").fetchall() == [(1, 2)] + assert duckdb_cursor.sql("SELECT * FROM renamed ORDER BY ALL").fetchall() == expected + + def test_view_over_a_join_keeps_the_deduplicated_column_names(self, duckdb_cursor): + _ = pytest.importorskip("fsspec") + duckdb_cursor.read_csv(StringIO("a\n1")).cross(duckdb_cursor.read_csv(StringIO("a\n2"))).to_view("v") + gc.collect() + assert [row[0] for row in duckdb_cursor.execute("DESCRIBE v").fetchall()] == ["a", "a_1"] + assert duckdb_cursor.sql("SELECT * FROM v").fetchall() == [(1, 2)] + + def test_rolled_back_create_releases_the_entry(self, duckdb_cursor): + _ = pytest.importorskip("fsspec") + rel = duckdb_cursor.read_csv(StringIO("c1\na")) + path = _object_store_path(rel) + duckdb_cursor.execute("BEGIN") + rel.to_view("v") + del rel + gc.collect() + assert duckdb_cursor.sql("SELECT * FROM v").fetchall() == [("a",)] + duckdb_cursor.execute("ROLLBACK") + gc.collect() + assert duckdb_cursor.execute("SELECT view_name FROM duckdb_views() WHERE NOT internal").fetchall() == [] + with pytest.raises(duckdb.IOException, match="No files found"): + duckdb_cursor.sql(f"SELECT * FROM read_csv('{path}')").fetchall() + + def test_rolled_back_drop_keeps_the_view(self, duckdb_cursor): + _ = pytest.importorskip("fsspec") + duckdb_cursor.read_csv(StringIO("c1\na")).to_view("v") + gc.collect() + duckdb_cursor.execute("BEGIN") + duckdb_cursor.execute("DROP VIEW v") + gc.collect() + duckdb_cursor.execute("ROLLBACK") + gc.collect() + assert duckdb_cursor.sql("SELECT * FROM v").fetchall() == [("a",)] + + def test_rolled_back_replace_restores_the_view_and_releases_the_replacement(self, duckdb_cursor): + _ = pytest.importorskip("fsspec") + duckdb_cursor.read_csv(StringIO("c1\na")).to_view("v") + gc.collect() + duckdb_cursor.execute("BEGIN") + replacement = duckdb_cursor.read_csv(StringIO("c1\nb")) + path = _object_store_path(replacement) + replacement.to_view("v") + del replacement + gc.collect() + assert duckdb_cursor.sql("SELECT * FROM v").fetchall() == [("b",)] + duckdb_cursor.execute("ROLLBACK") + gc.collect() + assert duckdb_cursor.sql("SELECT * FROM v").fetchall() == [("a",)] + with pytest.raises(duckdb.IOException, match="No files found"): + duckdb_cursor.sql(f"SELECT * FROM read_csv('{path}')").fetchall() + + def test_create_over_a_taken_name_without_replace_releases_the_entry(self, duckdb_cursor): + _ = pytest.importorskip("fsspec") + duckdb_cursor.read_csv(StringIO("c1\na")).to_view("v") + gc.collect() + second = duckdb_cursor.read_csv(StringIO("c1\nb")) + path = _object_store_path(second) + with pytest.raises(duckdb.CatalogException, match="already exists"): + second.create_view("v", replace=False) + del second + gc.collect() + assert duckdb_cursor.sql("SELECT * FROM v").fetchall() == [("a",)] + with pytest.raises(duckdb.IOException, match="No files found"): + duckdb_cursor.sql(f"SELECT * FROM read_csv('{path}')").fetchall() def test_view_reads_from_a_cursor(self, duckdb_cursor): _ = pytest.importorskip("fsspec") @@ -838,6 +947,42 @@ def test_view_reads_from_a_cursor(self, duckdb_cursor): gc.collect() assert duckdb_cursor.cursor().sql("SELECT * FROM v").fetchall() == [("a",)] + @pytest.mark.parametrize( + ("build", "expected"), + [ + pytest.param(_one_reader, [("a",)], id="reader"), + pytest.param(_one_reader_of_two_filelikes, [("a",), ("b",)], id="reader_of_two_filelikes"), + pytest.param(_two_readers_in_a_union, [("a",), ("b",)], id="union_of_two_readers"), + pytest.param(_a_reader_beside_a_table, [(1, "a")], id="reader_beside_a_table"), + pytest.param(_a_reader_read_by_sql, [("a",)], id="reader_read_by_sql"), + ], + ) + def test_view_over_a_filelike_is_refused_in_a_database_file(self, tmp_path, build, expected): + _ = pytest.importorskip("fsspec") + # The object store is a file system in this process's memory, so a stored view would read nothing after a + # reopen + con = duckdb.connect(str(tmp_path / "saved.duckdb")) + rel = build(con) + match = r"cannot be stored in a database file\. Use register\(\) for a view that reads it in this session" + with pytest.raises(duckdb.InvalidInputException, match=match): + rel.to_view("v") + assert con.execute("SELECT view_name FROM duckdb_views() WHERE NOT internal").fetchall() == [] + con.register("v", rel) + del rel + gc.collect() + assert con.sql("SELECT * FROM v ORDER BY ALL").fetchall() == expected + con.close() + + def test_view_over_a_filelike_in_an_attached_memory_database_is_created(self, tmp_path): + _ = pytest.importorskip("fsspec") + con = duckdb.connect(str(tmp_path / "saved.duckdb")) + con.execute("ATTACH ':memory:' AS scratch") + con.execute("USE scratch") + con.read_csv(StringIO("c1\na")).to_view("v") + gc.collect() + assert con.sql("SELECT * FROM scratch.main.v").fetchall() == [("a",)] + con.close() + class TestObjectStoreAcrossConnections: @pytest.mark.parametrize("first", ["cursor", "parent"]) diff --git a/tests/fast/api/test_seam.py b/tests/fast/api/test_seam.py index 0b9628039..febb9391d 100644 --- a/tests/fast/api/test_seam.py +++ b/tests/fast/api/test_seam.py @@ -1751,6 +1751,17 @@ def test_a_python_object_cannot_be_stored_in_a_file(self, tmp_path): assert connection.execute("SELECT * FROM p").fetchall() == [(1,)] connection.close() + def test_a_renamed_view_keeps_its_sources_when_its_first_select_reads_no_table(self, con): + _ = pytest.importorskip("fsspec") + handle = con._register_filelike(io.StringIO("c1\n2")) + sql = f"SELECT 1 AS c1 UNION ALL SELECT * FROM read_csv('{handle.name}') ORDER BY c1" + con._create_view("w", sql, sources=[handle]) + del handle + gc.collect() + con.execute("ALTER VIEW w RENAME TO renamed") + gc.collect() + assert con.execute("SELECT * FROM renamed").fetchall() == [(1,), (2,)] + def test_in_memory_a_persistent_view_of_a_python_object_is_created(self, con): handle = con._register_source(pd.DataFrame({"a": [1]})) con._create_view("p", f'SELECT * FROM "{handle.name}"') From d5ddcb058a4b692cf4e8f544eb62c362db66b688 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 12:12:56 +0000 Subject: [PATCH 16/61] Decode a dictionary backed string column chunk by chunk, test it with pandas 2 in CI, name a narrowed column by its bound name --- .github/workflows/packaging_wheels.yml | 42 +++++++++++++++++++ src/pandas/bind.cpp | 33 ++++----------- .../arrow/scan/test_python_arrow_scan_core.py | 25 ++++++++--- .../arrow/test_dictionary_filter_pushdown.py | 4 -- tests/fast/pandas/test_pandas_string.py | 2 + 5 files changed, 73 insertions(+), 33 deletions(-) diff --git a/.github/workflows/packaging_wheels.yml b/.github/workflows/packaging_wheels.yml index 1e2275dd6..0f1e35c21 100644 --- a/.github/workflows/packaging_wheels.yml +++ b/.github/workflows/packaging_wheels.yml @@ -253,3 +253,45 @@ jobs: cd "$testrun" uv run --no-project --python "$venv" python -c "import duckdb, sys, os; print(duckdb.__version__, sys.version, os.getcwd())" uv run --no-project --python "$venv" pytest --confcutdir=. --rootdir . -c pyproject.toml ${{ inputs.testsuite == 'fast' && './tests/fast' || './tests' }} + + test_pandas_2: + name: 'Test pandas 2: py3.12-manylinux_x86_64' + # The test dependency group installs pandas 3, which decodes a dictionary when it builds a string column, so the + # dictionary backed string columns of pandas 2 are read only here. The package itself accepts any pandas. + if: ${{ !cancelled() && inputs.testsuite != 'none' }} + needs: seed_wheels + runs-on: ubuntu-24.04 + steps: + - name: Checkout DuckDB Python + uses: actions/checkout@v4 + with: + ref: ${{ inputs.duckdb-python-sha }} + + - name: Fetch the wheel + uses: actions/download-artifact@v4 + with: + name: wheel-cp312-manylinux_x86_64 + path: wheelhouse + + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - uses: astral-sh/setup-uv@v10.3.0 + with: + version: "0.12.23" + enable-cache: false + + # pandas 2.2 converts a dictionary backed string column with to_numpy only from pyarrow 25 on. + - name: Install the wheel with pandas 2.2 and run the pandas string tests + shell: bash + run: | + set -eo pipefail + uv venv --python 3.12 .venv-pandas-2 + uv pip install --python .venv-pandas-2 wheelhouse/*.whl "pandas==2.2.3" "pyarrow==18.1.0" pytest pytest-timeout packaging + venv="$PWD/.venv-pandas-2" + testrun=$(uv run --no-project --python "$venv" python -c 'import tempfile; print(tempfile.mkdtemp(prefix="duckdb-testrun-"))') + cp -r tests pyproject.toml "$testrun" + cd "$testrun" + uv run --no-project --python "$venv" python -c "import duckdb, pandas, pyarrow; print(duckdb.__version__, pandas.__version__, pyarrow.__version__)" + uv run --no-project --python "$venv" pytest --confcutdir=. --rootdir . -c pyproject.toml ./tests/fast/pandas/test_pandas_string.py diff --git a/src/pandas/bind.cpp b/src/pandas/bind.cpp index 3cbae125a..a37e96cde 100644 --- a/src/pandas/bind.cpp +++ b/src/pandas/bind.cpp @@ -93,39 +93,24 @@ static unique_ptr BindArrowStringColumn(ClientContext &contex if (!PyUtil::HasAttribute(chunked_array.attr("type"), "__arrow_c_schema__")) { return nullptr; } - auto subject = StringUtil::Format("column '%s'", name); - auto resolve = [&]() { - nb::object schema = chunked_array.attr("type").attr("__arrow_c_schema__")(); - return ArrowType::GetArrowLogicalType(context, InCapsule(schema, "arrow_schema", subject)); - }; - auto arrow_type = resolve(); - const bool short_chunks = row_count < ARROW_ROWS_PER_CHUNK * nb::cast(chunked_array.attr("num_chunks")); - nb::object chunks; - if (arrow_type->GetPhysicalType() == ArrowArrayPhysicalType::DICTIONARY_ENCODED) { + if (nb::cast(nb::module_::import_("pyarrow.types").attr("is_dictionary")(chunked_array.attr("type")))) { // pandas 2 keeps the dictionary its array was built from, which pandas 2.2 cannot convert with to_numpy before - // pyarrow 25, so it is decoded and read here at any chunk length. - nb::object value_type = chunked_array.attr("type").attr("value_type"); - if (short_chunks) { - // A cast and an export per chunk would cost more than the conversion they replace, so the chunks are - // combined and decoded once. - chunked_array = chunked_array.attr("combine_chunks")().attr("cast")(value_type); - chunks = nb::make_tuple(chunked_array); - } else { - chunked_array = chunked_array.attr("cast")(value_type); - } - arrow_type = resolve(); - } else if (short_chunks) { + // pyarrow 25, so it is decoded chunk by chunk and read here at any chunk length; combining the chunks first + // would merge their dictionaries into the original index type, which a few hundred values overflow. + chunked_array = chunked_array.attr("cast")(chunked_array.attr("type").attr("value_type")); + } else if (row_count < ARROW_ROWS_PER_CHUNK * nb::cast(chunked_array.attr("num_chunks"))) { return nullptr; } + auto subject = StringUtil::Format("column '%s'", name); + nb::object schema = chunked_array.attr("type").attr("__arrow_c_schema__")(); + auto arrow_type = ArrowType::GetArrowLogicalType(context, InCapsule(schema, "arrow_schema", subject)); // Only a plain layout may be read without the engine adopting the chunks. if (arrow_type->GetDuckType().id() != LogicalTypeId::VARCHAR || arrow_type->GetPhysicalType() != ArrowArrayPhysicalType::DEFAULT) { return nullptr; } auto result = make_uniq(std::move(arrow_type)); - if (!chunks.is_valid()) { - chunks = chunked_array.attr("chunks"); - } + nb::object chunks = chunked_array.attr("chunks"); for (auto chunk : chunks) { auto exported = nb::cast(chunk.attr("__arrow_c_array__")()); result->AddChunk(InCapsule(exported[1], "arrow_array", subject)); diff --git a/tests/fast/arrow/scan/test_python_arrow_scan_core.py b/tests/fast/arrow/scan/test_python_arrow_scan_core.py index 92a88827c..655a80f3d 100644 --- a/tests/fast/arrow/scan/test_python_arrow_scan_core.py +++ b/tests/fast/arrow/scan/test_python_arrow_scan_core.py @@ -1868,17 +1868,17 @@ def _drop_the_validity_bitmap(column, pokes): class NarrowingPokingSource(PythonStreamSource): - """One batch of the requested columns, narrowed as a projecting source does, whose column `name` `poke` changes.""" + """One batch of the requested columns, narrowed as a projecting source does; `poke` changes declared `position`.""" - def __init__(self, table, name, poke) -> None: + def __init__(self, table, position, poke) -> None: super().__init__(table, max_chunksize=table.num_rows) - self.name = name + self.position = position self.poke = poke def stream(self, columns, filters): table = self.table if columns is None else self.table.select(list(columns)) stream = PokingStream(table.schema, table.to_batches(max_chunksize=table.num_rows), None) - index = table.schema.get_field_index(self.name) + index = self.position if columns is None else list(columns).index(self.position) stream.corrupt = lambda array: self.poke(array.children[index].contents, stream.pokes) self.streams.append(stream) return stream.capsule(), columns is not None @@ -1933,12 +1933,27 @@ class TestRefusalsNameTheColumn: def test_a_refusal_names_the_column_the_query_reads(self, case, query): make, poke, message = REFUSALS_BY_COLUMN[case] table = pa.table({"k": range(2_000), "x": range(2_000), "s": make()}) - source = NarrowingPokingSource(table, "s", poke) + source = NarrowingPokingSource(table, 2, poke) with duckdb.connect() as con: con._register_arrow_source("t", source) with pytest.raises(duckdb.InvalidInputException, match=re.escape(f"column 's' {message}")): con.execute(query).fetchall() + @pytest.mark.timeout(60) + @pytest.mark.parametrize( + ("names", "bound"), + [pytest.param(["s", "x", "s"], "s_1", id="repeated"), pytest.param(["k", "x", ""], "v2", id="empty")], + ) + def test_a_refusal_names_a_narrowed_column_by_its_bound_name(self, names, bound): + # The engine names the one column of the narrowed stream 's' or 'v0', which is not how the query reads it. + make, poke, message = REFUSALS_BY_COLUMN["released_struct_child"] + table = pa.table([pa.array(range(2_000)), pa.array(range(2_000)), make()], names=names) + source = NarrowingPokingSource(table, 2, poke) + with duckdb.connect() as con: + con._register_arrow_source("t", source) + with pytest.raises(duckdb.InvalidInputException, match=re.escape(f"column '{bound}' {message}")): + con.execute(f"SELECT {bound} FROM t").fetchall() + @pytest.mark.timeout(60) def test_a_refusal_names_a_plain_array_by_its_column_name(self): source = PlainArrayPokingSource(pa.array([1, None] * 1_000), _drop_the_validity_bitmap) diff --git a/tests/fast/arrow/test_dictionary_filter_pushdown.py b/tests/fast/arrow/test_dictionary_filter_pushdown.py index c2187b127..1f6e81ab8 100644 --- a/tests/fast/arrow/test_dictionary_filter_pushdown.py +++ b/tests/fast/arrow/test_dictionary_filter_pushdown.py @@ -242,10 +242,6 @@ def _params(cases, ops, marks_for, shapes=SHAPES): return params -def _xfail(reason, raises): - return [pytest.mark.xfail(strict=True, raises=raises, reason=reason)] - - def _no_marks(case, op): return [] diff --git a/tests/fast/pandas/test_pandas_string.py b/tests/fast/pandas/test_pandas_string.py index 684d6f071..81b9c76a0 100644 --- a/tests/fast/pandas/test_pandas_string.py +++ b/tests/fast/pandas/test_pandas_string.py @@ -707,6 +707,8 @@ def test_str_chunks_outlive_the_frames_column_while_a_result_streams(pa, dtype): "below_the_chunk_length_threshold": [["x", None, "y"]], "many_short_chunks": [["v", None]] * 30, "many_one_row_chunks": [[("a", None, "b")[index % 3]] for index in range(100)], + # More distinct values than an int8 index addresses, in chunks too short to be read one by one. + "distinct_values_beyond_an_int8_index": [[f"v{index}"] for index in range(200)], "an_empty_chunk_between_two": [["a", None] * 50, [], ["b"] * 50], "only_nulls": [[None] * 100], "chunks_longer_than_a_vector": [ From 9683cde4efd8aed86ea110fe6534d84eb3db6d98 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 12:14:35 +0000 Subject: [PATCH 17/61] Say retry up to 6 times, and remove a download that never opened without a second error --- tests/slow/test_h2oai_arrow.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/slow/test_h2oai_arrow.py b/tests/slow/test_h2oai_arrow.py index 401bcaeed..195f04fed 100644 --- a/tests/slow/test_h2oai_arrow.py +++ b/tests/slow/test_h2oai_arrow.py @@ -202,9 +202,9 @@ def arrow_dataset_register(tmp_path_factory): allowed_methods={"GET"}, # only retry on GETs (all we do) total=None, # disable to make the below take effect redirect=10, # Don't follow more than 10 redirects in a row - connect=6, # try 6 times before giving up on connection errors - read=6, # try 6 times before giving up on read errors - status=6, # try 6 times before giving up on status errors (see forcelist below) + connect=6, # retry up to 6 times on connection errors + read=6, # retry up to 6 times on read errors + status=6, # retry up to 6 times on status errors (see forcelist below) status_forcelist=[429, *list(range(500, 512))], other=0, # whatever else may cause an error should break backoff_factor=2, # [0s, 4s, 8s, 16s, 32s, 64s] outlasts a CI runner losing DNS for a minute @@ -231,7 +231,7 @@ def _register(url, filename, con, tablename) -> None: yield _register for filepath in saved_filepaths: - filepath.unlink() + filepath.unlink(missing_ok=True) session.close() From 3ed9e9f83ecd8c620545f190b07d8b49e14e8dfe Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 12:19:08 +0000 Subject: [PATCH 18/61] Read a tuple of paths like a list, check pandas STRUCT keys, run the stub check in CI, cache each numpy scalar class's type --- duckdb/_relation.py | 2 +- pyproject.toml | 1 + .../pyconnection/pyconnection.hpp | 2 + src/pandas/analyzer.cpp | 2 +- src/pyconnection.cpp | 11 +++++ src/typing/pytype.cpp | 49 ++++++++++++------- tests/fast/api/test_reader_path_lists.py | 36 ++++++++++++-- tests/fast/test_unencodable_strings.py | 6 +++ 8 files changed, 87 insertions(+), 22 deletions(-) diff --git a/duckdb/_relation.py b/duckdb/_relation.py index 381b450dc..589983632 100644 --- a/duckdb/_relation.py +++ b/duckdb/_relation.py @@ -3650,7 +3650,7 @@ def one(item: object) -> str: handles.append(handle) return handle.name - if isinstance(source, list): + if isinstance(source, (list, tuple)): if not source: raise _error(_duckdb.InvalidInputException, "Please provide a non-empty list of paths or file-like objects") paths = [one(item) for item in source] diff --git a/pyproject.toml b/pyproject.toml index c14d2196c..f5fbd1a5d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -283,6 +283,7 @@ test = [ # dependencies used for running tests "pytest-xdist", # parallel test execution (-n auto); without this `uv sync --reinstall` prunes a manual install "pytest_codspeed", "coverage", + "mypy", "gcovr; sys_platform != 'win32' or platform_machine != 'ARM64'", "gcsfs; sys_platform != 'win32' or platform_machine != 'ARM64'", "packaging", diff --git a/src/include/duckdb_python/pyconnection/pyconnection.hpp b/src/include/duckdb_python/pyconnection/pyconnection.hpp index 00ad18ceb..0b41db3aa 100644 --- a/src/include/duckdb_python/pyconnection/pyconnection.hpp +++ b/src/include/duckdb_python/pyconnection/pyconnection.hpp @@ -338,6 +338,8 @@ struct DuckDBPyConnection : public std::enable_shared_from_this conn); static PythonImportCache *ImportCache(); static nb::object ConsumedArrowReaders(); + //! The dict of numpy scalar class to the id of the DuckDB type it converts to; call with the GIL held + static nb::object NumpyScalarTypes(); //! Keeps adapt and the nodes module of the duckdb._sources package the package passes in as it imports static void SetArrowSources(const nb::object &sources); //! duckdb._sources.adapt; call with the GIL held diff --git a/src/pandas/analyzer.cpp b/src/pandas/analyzer.cpp index 259c7206b..c5fa4c330 100644 --- a/src/pandas/analyzer.cpp +++ b/src/pandas/analyzer.cpp @@ -342,7 +342,7 @@ LogicalType PandasAnalyzer::DictToStruct(const PyDictionary &dict, bool &can_con //! Have to already transform here because the child_list needs a string as key. Stringify via str() so //! non-string keys (e.g. the integer keys of a hashable-key MAP, produced as a plain {1: 10} dict) are //! accepted (nb::cast rejects non-str objects). - auto key = Identifier(nb::cast(nb::str(dict_key))); + auto key = Identifier(TransformPythonString(nb::str(dict_key))); auto dict_val = dict.values.attr("__getitem__")(i); auto val = GetItemType(dict_val, can_convert); diff --git a/src/pyconnection.cpp b/src/pyconnection.cpp index 19a38ef67..61bcca98a 100644 --- a/src/pyconnection.cpp +++ b/src/pyconnection.cpp @@ -50,6 +50,8 @@ struct DuckDBPyModuleState { std::shared_ptr import_cache; //! The single-use Arrow readers that have handed out their stream, by identity and held weakly unique_ptr consumed_arrow_readers; + //! The DuckDB type id of each numpy scalar class converted so far; only Cleanup clears it, as such classes are few + unique_ptr numpy_scalar_types; //! Held rather than imported on use, since an import fails once the package has left sys.modules unique_ptr arrow_sources_adapt; unique_ptr arrow_sources_nodes; @@ -1758,6 +1760,14 @@ nb::object DuckDBPyConnection::ConsumedArrowReaders() { return readers->obj; } +nb::object DuckDBPyConnection::NumpyScalarTypes() { + auto &types = GetModuleState().numpy_scalar_types; + if (!types) { + types = make_uniq(nb::dict()); + } + return types->obj; +} + void DuckDBPyConnection::SetArrowSources(const nb::object &sources) { auto adapt = sources.attr("adapt"); auto nodes = sources.attr("nodes"); @@ -1828,6 +1838,7 @@ void DuckDBPyConnection::Cleanup() { GetModuleState().default_connection.Release(); GetModuleState().import_cache.reset(); GetModuleState().consumed_arrow_readers.reset(); + GetModuleState().numpy_scalar_types.reset(); GetModuleState().arrow_sources_adapt.reset(); GetModuleState().arrow_sources_nodes.reset(); } diff --git a/src/typing/pytype.cpp b/src/typing/pytype.cpp index 4583b075b..0b79f531b 100644 --- a/src/typing/pytype.cpp +++ b/src/typing/pytype.cpp @@ -156,22 +156,8 @@ static bool DerivesFromConcreteNumpyScalar(const nb::handle &type, NumpyCacheIte return false; } -static bool IsSubclass(const nb::handle &type, const nb::handle &base) { - auto is_subclass = PyObject_IsSubclass(type.ptr(), base.ptr()); - if (is_subclass < 0) { - throw nb::python_error(); - } - return is_subclass != 0; -} - -static bool FromNumpyType(const nb::object &type, LogicalType &result) { - // Only a concrete numpy scalar type is read, through numpy.dtype, so converting a class never calls it. - if (!ModuleIsLoaded()) { - return false; - } - auto &import_cache = *DuckDBPyConnection::ImportCache(); - auto generic = import_cache.numpy.generic(); - if (!generic || !IsSubclass(type, generic) || !DerivesFromConcreteNumpyScalar(type, import_cache.numpy)) { +static bool ReadNumpyScalarType(const nb::object &type, PythonImportCache &import_cache, LogicalType &result) { + if (!DerivesFromConcreteNumpyScalar(type, import_cache.numpy)) { return false; } nb::object dtype; @@ -186,7 +172,7 @@ static bool FromNumpyType(const nb::object &type, LogicalType &result) { } // numpy maps a class onto the dtype of the scalar type it derives from, and only such a class is that type nb::object dtype_type = dtype.attr("type"); - if (!IsSubclass(type, dtype_type)) { + if (!nb::issubclass(type, dtype_type)) { return false; } // We convert these to string because the underlying physical @@ -223,6 +209,35 @@ static bool FromNumpyType(const nb::object &type, LogicalType &result) { return true; } +static bool FromNumpyType(const nb::object &type, LogicalType &result) { + // Only a concrete numpy scalar type is read, through numpy.dtype, so converting a class never calls it. + if (!ModuleIsLoaded()) { + return false; + } + auto &import_cache = *DuckDBPyConnection::ImportCache(); + auto generic = import_cache.numpy.generic(); + if (!generic || !nb::issubclass(type, generic)) { + return false; + } + // Reading a class costs more than the rest of converting a value it types, so each class is read once. The + // type is kept as its id, which describes every type a numpy scalar maps to; a kept DuckDBPyType would be + // reported as leaked at exit. + auto known = nb::borrow(DuckDBPyConnection::NumpyScalarTypes()); + auto cached = PyDict_GetItemWithError(known.ptr(), type.ptr()); + if (cached) { + result = LogicalType(static_cast(nb::cast(nb::handle(cached)))); + return true; + } + if (PyErr_Occurred()) { + throw nb::python_error(); + } + if (!ReadNumpyScalarType(type, import_cache, result)) { + return false; + } + known[type] = nb::int_(static_cast(result.id())); + return true; +} + static LogicalType FromType(const nb::type_object &obj) { nb::module_ builtins = nb::module_::import_("builtins"); if (obj.is(builtins.attr("str"))) { diff --git a/tests/fast/api/test_reader_path_lists.py b/tests/fast/api/test_reader_path_lists.py index 8d5bcac13..204b19d7c 100644 --- a/tests/fast/api/test_reader_path_lists.py +++ b/tests/fast/api/test_reader_path_lists.py @@ -1,4 +1,4 @@ -"""A connection's readers take a list of paths, and their annotations say so.""" +"""A connection's readers take a list or a tuple of paths, and their annotations say so.""" import json import re @@ -9,8 +9,8 @@ READERS = ("read_json", "read_csv", "from_csv_auto") #: Every path shape the readers take at runtime: one path, a list literal, a list[str] variable, a list of -#: pathlib.Path and a list of a file like object. -ACCEPTED_ARGUMENTS = ('"a"', '["a", "b"]', "paths", '[pathlib.Path("a")]', '[io.BytesIO(b"")]') +#: pathlib.Path, a list of a file like object and a tuple. +ACCEPTED_ARGUMENTS = ('"a"', '["a", "b"]', "paths", '[pathlib.Path("a")]', '[io.BytesIO(b"")]', '("a", "b")') def annotated_calls(): @@ -36,6 +36,36 @@ def test_read_json_reads_every_file_of_a_list(tmp_path): assert con.read_json(paths, format="newline_delimited").order("x").fetchall() == [("a",), ("b",)] +def write_two_files(con, tmp_path, extension): + paths = [] + for name in ("a", "b"): + path = tmp_path / f"{name}.{extension}" + con.execute(f"COPY (SELECT '{name}' AS x) TO '{path}'") + paths.append(str(path)) + return tuple(paths) + + +@pytest.mark.parametrize( + ("reader", "extension"), + [ + ("read_json", "json"), + ("read_csv", "csv"), + ("from_csv_auto", "csv"), + ("read_parquet", "parquet"), + ("from_parquet", "parquet"), + ], +) +def test_every_reader_reads_every_file_of_a_tuple(tmp_path, reader, extension): + con = duckdb.connect() + paths = write_two_files(con, tmp_path, extension) + assert getattr(con, reader)(paths).order("x").fetchall() == [("a",), ("b",)] + + +def test_an_empty_tuple_is_refused_like_an_empty_list(): + with pytest.raises(duckdb.InvalidInputException, match="Please provide a non-empty list of paths"): + duckdb.connect().read_json(()) + + def test_mypy_accepts_every_path_shape_and_refuses_a_number(tmp_path): api = pytest.importorskip("mypy.api") text, refused = annotated_calls() diff --git a/tests/fast/test_unencodable_strings.py b/tests/fast/test_unencodable_strings.py index be9c34665..171a4dc1e 100644 --- a/tests/fast/test_unencodable_strings.py +++ b/tests/fast/test_unencodable_strings.py @@ -291,6 +291,11 @@ def execute_text(con, text): return con.execute(f"SELECT '{text}'") +def pandas_struct_key(con, text): + df = pd.DataFrame({"c": [{text: 1}]}) # noqa: F841 + return con.sql("SELECT * FROM df").fetchall() + + NAME_AND_TEXT_REFUSALS = [ name_or_text(execute_text, SQL_TEXT_PREFIX, "execute_text"), name_or_text(lambda con, text: con.executemany(f"SELECT '{text}'", [[]]), SQL_TEXT_PREFIX, "executemany_text"), @@ -303,6 +308,7 @@ def execute_text(con, text): name_or_text(lambda con, text: con.execute("SELECT ?", [[{"a": {text: 1}}]]), 0, "nested_struct_key"), name_or_text(lambda con, text: con.executemany("SELECT ?", [[{text: 1}]]), 0, "executemany_struct_key"), name_or_text(lambda con, text: con.sql("SELECT ?", params=[{text: 1}]).fetchall(), 0, "sql_params_struct_key"), + name_or_text(pandas_struct_key, 0, "pandas_object_column_struct_key"), name_or_text(lambda con, text: con.execute("SELECT $x", {text: 1}), 0, "execute_parameter_name"), name_or_text(lambda con, text: con.executemany("SELECT $x", [{text: 1}]), 0, "executemany_parameter_name"), name_or_text(lambda con, text: con.struct_type({text: BIGINT}), 0, "struct_type_field_name"), From 202992d4c45299a627428219d35b86a5f6c8b2b7 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 12:42:05 +0000 Subject: [PATCH 19/61] Read numpy float, str and bytes scalars as they are, keep the nanoseconds of a fine datetime64, cast only units finer than a microsecond --- .../duckdb_python/python_conversion.hpp | 10 +- src/native/python_conversion.cpp | 80 ++++--- src/numpy/numpy_scan.cpp | 14 +- src/pyappender.cpp | 12 +- tests/fast/api/test_appender_values.py | 200 +++++++++++++++--- tests/fast/pandas/test_append_df.py | 12 +- 6 files changed, 247 insertions(+), 81 deletions(-) diff --git a/src/include/duckdb_python/python_conversion.hpp b/src/include/duckdb_python/python_conversion.hpp index 7ae4a69f7..306cd3857 100644 --- a/src/include/duckdb_python/python_conversion.hpp +++ b/src/include/duckdb_python/python_conversion.hpp @@ -58,10 +58,12 @@ void TransformPythonObject(optional_ptr context, nb::handle ele, Value TransformPythonValue(optional_ptr context, nb::handle ele, const LogicalType &target_type = LogicalType::UNKNOWN, bool nan_as_null = true); string TransformPythonString(nb::handle str); -//! A numpy scalar, or an array of no dimensions, as its Python value, a datetime64 or timedelta64 at the microsecond -//! unit; one step, so a long double, whose item() is a numpy scalar again, comes back as it is for the conversion to -//! refuse; any other object comes back as it is -nb::object PythonValueOfNumpyScalar(nb::handle cell); +//! A numpy scalar, or an array of no dimensions, as its Python value through item(), one step, so a long double, whose +//! item() is a numpy scalar again, comes back as it is for the conversion to refuse; a timedelta64 finer than a +//! microsecond, whose item() is an integer, takes the microsecond unit first. A datetime64 finer than a microsecond +//! has no Python value: it reads into timestamp, and the result is a null handle. Any other object comes back as it +//! is. +nb::object PythonValueOfNumpyScalar(nb::handle cell, timestamp_ns_t ×tamp); //! Needs no GIL InvalidInputException UnencodableStrError(uint32_t codepoint, idx_t position); //! Raises the pending UnicodeEncodeError of a failed UTF-8 conversion of str as the typed error above diff --git a/src/native/python_conversion.cpp b/src/native/python_conversion.cpp index fdca84284..5ea5839d0 100644 --- a/src/native/python_conversion.cpp +++ b/src/native/python_conversion.cpp @@ -71,21 +71,34 @@ void ThrowUnencodableStr(nb::handle str) { throw UnencodableStrError(PyUnicode_ReadChar(str.ptr(), start), NumericCast(start)); } -//! Whether numpy is imported, asked of the module dict without importing it: a numpy scalar cannot exist before -static bool NumpyIsImported(PythonImportCache &import_cache) { - if (import_cache.numpy.LoadSucceeded()) { +// Importing the module here instead would run the import on whichever thread of the query converts the value, and a +// None entry in sys.modules is how a program blocks the import +static bool ModuleIsImported(PythonImportCacheItem &module, PyObject *name) { + if (module.LoadSucceeded()) { return true; } - static PyObject *const name = PyUnicode_InternFromString("numpy"); if (!name) { PyErr_Clear(); return false; } - auto module = PyDict_GetItemWithError(PyImport_GetModuleDict(), name); - if (!module && PyErr_Occurred()) { + auto entry = PyDict_GetItemWithError(PyImport_GetModuleDict(), name); + if (!entry && PyErr_Occurred()) { PyErr_Clear(); } - return module && module != Py_None; + return entry && entry != Py_None; +} + +bool PandasIsImported(PythonImportCache &import_cache) { + // Interned once: building the key on every call, or asking the import cache about a module it has not loaded, + // costs an allocation for every converted value + static PyObject *const name = PyUnicode_InternFromString("pandas"); + return ModuleIsImported(import_cache.pandas, name); +} + +//! A numpy scalar cannot exist before numpy is imported +static bool NumpyIsImported(PythonImportCache &import_cache) { + static PyObject *const name = PyUnicode_InternFromString("numpy"); + return ModuleIsImported(import_cache.numpy, name); } //! Decided from the object's type, which runs no code of the object's; numpy is optional and loaded by nothing here, @@ -106,16 +119,35 @@ static bool IsNumpyScalar(nb::handle cell) { nb::cast(cell.attr("ndim")) == 0; } -nb::object PythonValueOfNumpyScalar(nb::handle cell) { - if (!IsNumpyScalar(cell)) { +//! A datetime or a timedelta holds no unit finer than a microsecond, so item() gives an integer at these +static bool IsFinerThanAMicrosecond(nb::handle dtype) { + auto code = nb::cast(dtype.attr("str")); + return StringUtil::EndsWith(code, "ns]") || StringUtil::EndsWith(code, "ps]") || + StringUtil::EndsWith(code, "fs]") || StringUtil::EndsWith(code, "as]"); +} + +nb::object PythonValueOfNumpyScalar(nb::handle cell, timestamp_ns_t ×tamp) { + auto object = cell.ptr(); + // numpy's float, str and bytes scalars are a float, str and bytes the conversion reads as they are, where item() + // would drop the trailing NUL characters of a str or bytes; an int or None is never a numpy scalar + if (object == Py_None || PyLong_Check(object) || PyFloat_Check(object) || PyUnicode_Check(object) || + PyBytes_Check(object) || !IsNumpyScalar(cell)) { return nb::borrow(cell); } - auto kind = nb::cast(cell.attr("dtype").attr("kind")); + auto dtype = cell.attr("dtype"); + auto kind = nb::cast(dtype.attr("kind")); + if (kind == "M" && IsFinerThanAMicrosecond(dtype)) { + // No Python value holds the nanoseconds; the engine's cast into the column then treats them as it treats a + // datetime64[ns] column of a frame + auto nanoseconds = cell.attr("astype")("datetime64[ns]").attr("item")(); + if (nanoseconds.is_none()) { + return nanoseconds; + } + timestamp = timestamp_ns_t(nb::cast(nanoseconds)); + return nb::object(); + } nb::object value; - if (kind == "M") { - // A nanosecond datetime64 lists as an integer; the microsecond unit lists as a datetime, NaT as None - value = cell.attr("astype")("datetime64[us]").attr("item")(); - } else if (kind == "m") { + if (kind == "m" && IsFinerThanAMicrosecond(dtype)) { value = cell.attr("astype")("timedelta64[us]").attr("item")(); } else { value = cell.attr("item")(); @@ -560,26 +592,6 @@ struct ContiguousBuffer { Py_buffer view; }; -// Importing pandas here instead would run the import on whichever thread of the query converts the value, and a None -// entry in sys.modules is how a program blocks the import -bool PandasIsImported(PythonImportCache &import_cache) { - if (import_cache.pandas.LoadSucceeded()) { - return true; - } - // Interned once: building the key on every call, or asking the import cache about a module it has not loaded, - // costs an allocation for every converted value - static PyObject *const name = PyUnicode_InternFromString("pandas"); - if (!name) { - PyErr_Clear(); - return false; - } - auto module = PyDict_GetItemWithError(PyImport_GetModuleDict(), name); - if (!module && PyErr_Occurred()) { - PyErr_Clear(); - } - return module && module != Py_None; -} - bool NumpyMaIsImported() { nb::str name("numpy.ma"); auto module = nb::steal(PyImport_GetModule(name.ptr())); diff --git a/src/numpy/numpy_scan.cpp b/src/numpy/numpy_scan.cpp index 607f5bfef..554c996a3 100644 --- a/src/numpy/numpy_scan.cpp +++ b/src/numpy/numpy_scan.cpp @@ -305,11 +305,19 @@ class DeclaredCasts { //! A declared column converts a cell as the appender converts a value of a row: with the type the value has in //! Python, then the engine's cast into the column's type, which reads the connection's settings; NaN reads NULL at -//! every depth, a numpy scalar reads as its Python value, and a value without a DuckDB type of its own reads as its -//! text in a text column +//! every depth, a numpy scalar reads as its Python value (a datetime64 finer than a microsecond as a TIMESTAMP_NS), +//! and a value without a DuckDB type of its own reads as its text in a text column static Value DeclaredValue(ClientContext &context, const LogicalType &target, nb::handle cell) { - auto plain = PythonValueOfNumpyScalar(cell); + if (cell.ptr() == Py_None) { + return Value(); + } + timestamp_ns_t timestamp; + auto plain = PythonValueOfNumpyScalar(cell, timestamp); + if (!plain.is_valid()) { + return Value::TIMESTAMPNS(timestamp); + } nb::handle value = plain; + // A NaT reads as None if (value.ptr() == Py_None) { return Value(); } diff --git a/src/pyappender.cpp b/src/pyappender.cpp index 963f8214e..b81af42cb 100644 --- a/src/pyappender.cpp +++ b/src/pyappender.cpp @@ -484,8 +484,11 @@ void DuckDBPyAppender::ThrowIfBroken() const { } Value DuckDBPyAppender::Convert(ClientContext &context, const nb::handle &object, const LogicalType &type) { - auto plain = PythonValueOfNumpyScalar(object); - return CastToColumn(context, TransformPythonValue(context, plain, LogicalType::UNKNOWN, false), type); + timestamp_ns_t timestamp; + auto plain = PythonValueOfNumpyScalar(object, timestamp); + auto value = plain.is_valid() ? TransformPythonValue(context, plain, LogicalType::UNKNOWN, false) + : Value::TIMESTAMPNS(timestamp); + return CastToColumn(context, value, type); } void DuckDBPyAppender::Stage(const vector &row) { @@ -638,8 +641,9 @@ idx_t DuckDBPyAppender::BufferedRows() const { void DuckDBPyAppender::Initialize(nb::handle &m) { auto appender = nb::class_(m, "Appender", nb::is_weak_referenceable()); appender.def("append_row", &DuckDBPyAppender::AppendRow, - "Buffer one row, one value per column; a numpy scalar is read as its Python value, then each value is " - "converted as an executemany parameter would be"); + "Buffer one row, one value per column; a numpy scalar is read as its Python value (a datetime64 finer " + "than a microsecond as a TIMESTAMP_NS), then each value is converted as an executemany parameter " + "would be"); appender.def("append_rows", &DuckDBPyAppender::AppendRows, "Buffer each row of an iterable of sequences, stopping at the first bad row and keeping the rows " "before it", diff --git a/tests/fast/api/test_appender_values.py b/tests/fast/api/test_appender_values.py index 7f5da0b3f..1d26b8a91 100644 --- a/tests/fast/api/test_appender_values.py +++ b/tests/fast/api/test_appender_values.py @@ -13,7 +13,7 @@ import numpy as np import pandas as pd from duckdb.sqltypes import BIGINT -from duckdb.value.constant import IntegerValue, StringValue, Value +from duckdb.value.constant import IntegerValue, StringValue, TimestampNanosecondValue, Value TZ_PLUS_2 = dt.timezone(dt.timedelta(hours=2)) UUID_TEXT = "12345678-1234-5678-1234-567812345678" @@ -245,17 +245,21 @@ def cells(column_type): return VALUES +FINER_THAN_A_MICROSECOND = ("ns", "ps", "fs", "as") + + def python_value_of_numpy_scalar(value): """The value the appender converts: a numpy scalar, or an array of no dimensions, as its Python value.""" - if not (isinstance(value, np.generic) or (type(value) is np.ndarray and value.ndim == 0)): + if isinstance(value, (float, str, bytes)) or not ( + isinstance(value, np.generic) or (type(value) is np.ndarray and value.ndim == 0) + ): return value kind = value.dtype.kind - if kind == "M": - item = value.astype("datetime64[us]").tolist() - elif kind == "m": - item = value.astype("timedelta64[us]").tolist() - else: - item = value.item() + finer = kind in "Mm" and np.datetime_data(value.dtype)[0] in FINER_THAN_A_MICROSECOND + if kind == "M" and finer: + nanoseconds = value.astype("datetime64[ns]") + return None if np.isnat(nanoseconds) else TimestampNanosecondValue(np.datetime_as_string(nanoseconds)) + item = value.astype("timedelta64[us]").item() if kind == "m" and finer else value.item() return value if isinstance(item, np.generic) else item @@ -266,7 +270,8 @@ def share(thread): cursor = cursors[thread] # The appender reads a numpy scalar as its Python value and converts that as executemany converts it, so the # reference takes the value the appender reads; for a datetime64 that differs from executemany's own reading - # (its integer), for an int64 or bool executemany refuses the scalar + # (its integer), a nanosecond one is a TIMESTAMP_NS value since no Python value holds it, and for an int64 or + # bool executemany refuses the scalar return [ ( i, @@ -335,9 +340,19 @@ def test_strings_past_the_inline_length_survive_several_flushes(con, column_type assert outcomes(con, "tgt", column_type, values, appended) == expected +NANOSECOND_STAMP = np.datetime64("2024-05-08T01:02:03.123456789", "ns") + + +class _ItemRaises(np.int64): + def item(self): + msg = "no item" + raise ValueError(msg) + + class TestNumpyScalars: # The appender reads a numpy scalar as con.append reads one in a declared object column: its Python value, a - # datetime64 or timedelta64 at the microsecond unit. + # timedelta64 finer than a microsecond at microseconds, and a datetime64 finer than a microsecond as a + # TIMESTAMP_NS the engine casts into the column. @pytest.mark.parametrize( ("column_type", "value", "expected"), @@ -345,17 +360,25 @@ class TestNumpyScalars: pytest.param("INTEGER", np.int64(2), 2, id="int64_into_integer"), pytest.param("DOUBLE", np.float32(2.5), 2.5, id="float32_into_double"), pytest.param("BOOLEAN", np.bool_(False), False, id="bool_into_boolean"), + pytest.param("DATE", np.datetime64("2024-05-08", "D"), dt.date(2024, 5, 8), id="day_datetime64_into_date"), pytest.param( - "TIMESTAMP", - np.datetime64("2024-05-08T01:02:03.123456789", "ns"), - dt.datetime(2024, 5, 8, 1, 2, 3, 123456), - id="datetime64_ns_into_timestamp", + "TIMESTAMP_S", + np.datetime64("2024-05-08T01:02:03", "s"), + dt.datetime(2024, 5, 8, 1, 2, 3), + id="second_datetime64_into_timestamp_s", ), + pytest.param("INTERVAL", np.timedelta64(2, "D"), dt.timedelta(days=2), id="timedelta64_day"), pytest.param("INTERVAL", np.timedelta64(1500, "us"), dt.timedelta(microseconds=1500), id="timedelta64_us"), pytest.param("INTERVAL", np.timedelta64(1501, "ns"), dt.timedelta(microseconds=1), id="timedelta64_ns"), pytest.param("INTERVAL", np.timedelta64("NaT", "ns"), None, id="timedelta64_nat_is_null"), + # A month has no fixed length: item() gives the count, which stays an integer + pytest.param("BIGINT", np.timedelta64(1, "M"), 1, id="month_timedelta64_reads_as_its_integer"), pytest.param("VARCHAR", np.str_("a\x00b"), "a\x00b", id="str_scalar_into_varchar"), + pytest.param("VARCHAR", np.str_("ab\x00"), "ab\x00", id="str_scalar_keeps_a_trailing_nul"), + pytest.param("VARCHAR", np.str_("\x00\x00"), "\x00\x00", id="str_scalar_of_nuls_keeps_them"), pytest.param("BLOB", np.bytes_(b"\x00\xff"), b"\x00\xff", id="bytes_scalar_into_blob"), + pytest.param("BLOB", np.bytes_(b"\x01\x00"), b"\x01\x00", id="bytes_scalar_keeps_a_trailing_nul"), + pytest.param("BLOB", np.bytes_(b"\x00\x00"), b"\x00\x00", id="bytes_scalar_of_nuls_keeps_them"), pytest.param( "STRUCT(a INTEGER)", np.array({"a": 1}, dtype=object), @@ -366,6 +389,7 @@ class TestNumpyScalars: pytest.param("DOUBLE", np.float64("nan"), float("nan"), id="float64_nan_stays_a_value"), pytest.param("DOUBLE", np.ma.masked, None, id="masked_singleton_is_null"), pytest.param("TIMESTAMP", np.datetime64("NaT", "ns"), None, id="datetime64_nat_is_null"), + pytest.param("TIMESTAMP", np.datetime64("NaT", "D"), None, id="day_datetime64_nat_is_null"), ], ) def test_numpy_scalars_append_as_their_python_values(self, con, column_type, value, expected): @@ -378,21 +402,123 @@ def test_numpy_scalars_append_as_their_python_values(self, con, column_type, val else: assert stored == expected - def test_datetime64_reads_as_a_datetime_not_its_integer(self, con): - # The appender used to hand a datetime64 to the conversion, which read a nanosecond one as its integer - con.execute("CREATE OR REPLACE TABLE t (b BIGINT, v VARCHAR)") - stamp = np.datetime64("2024-05-08T01:02:03.123456789", "ns") + @pytest.mark.parametrize( + ("column_type", "value", "text"), + [ + pytest.param("VARCHAR", np.datetime64("2024-05-08", "D"), "2024-05-08", id="day_unit_reads_as_a_date"), + pytest.param("VARCHAR", np.datetime64("2024-05", "M"), "2024-05-01", id="month_unit_reads_as_a_date"), + pytest.param( + "VARCHAR", + np.datetime64("2024-05-08T01:02:03", "s"), + "2024-05-08 01:02:03", + id="second_unit_reads_as_a_datetime", + ), + pytest.param( + "VARCHAR", NANOSECOND_STAMP, "2024-05-08 01:02:03.123456789", id="nanosecond_unit_into_varchar" + ), + pytest.param( + "TIMESTAMP_NS", + NANOSECOND_STAMP, + "2024-05-08 01:02:03.123456789", + id="nanosecond_unit_into_timestamp_ns", + ), + # The engine's TIMESTAMP_NS cast rounds to the nearest microsecond, as for a datetime64[ns] frame column + pytest.param( + "TIMESTAMP", NANOSECOND_STAMP, "2024-05-08 01:02:03.123457", id="nanosecond_unit_rounds_into_timestamp" + ), + pytest.param( + "TIMESTAMP_NS", + np.datetime64(1500, "ps"), + "1970-01-01 00:00:00.000000001", + id="picosecond_unit_at_nanoseconds", + ), + ], + ) + def test_datetime64_stores_the_text_of_its_value(self, con, column_type, value, text): + con.execute(f"CREATE OR REPLACE TABLE t (x {column_type})") + with con.appender("t") as appender: + appender.append_row(value) + assert con.execute("SELECT x::VARCHAR FROM t").fetchall() == [(text,)] + + @pytest.mark.parametrize( + ("column_type", "value", "match"), + [ + pytest.param("TIME", np.datetime64("2024-05-08", "D"), r"DATE -> TIME\)", id="day_datetime64_into_time"), + pytest.param("INTERVAL", np.timedelta64(1, "M"), r"INT\w* -> INTERVAL", id="month_timedelta64"), + pytest.param("INTERVAL", np.timedelta64(1, "Y"), r"INT\w* -> INTERVAL", id="year_timedelta64"), + pytest.param("BIGINT", NANOSECOND_STAMP, r"TIMESTAMP_NS -> BIGINT", id="nanosecond_datetime64_into_bigint"), + ], + ) + def test_a_numpy_value_without_a_cast_into_the_column_is_refused(self, con, column_type, value, match): + con.execute(f"CREATE OR REPLACE TABLE t (x {column_type})") + with pytest.raises(duckdb.ConversionException, match=match), con.appender("t") as appender: + appender.append_row(value) + + @pytest.mark.parametrize( + "column_type", + [ + "TIMESTAMP", + "TIMESTAMP_MS", + "TIMESTAMP_NS", + "TIMESTAMPTZ", + "TIMESTAMPTZ_NS", + "DATE", + "TIME", + "TIME_NS", + "VARCHAR", + # The engine has no cast from TIMESTAMP_NS into these two, for a frame column as for the appender + "TIMESTAMP_S", + "TIMETZ", + ], + ) + def test_nanosecond_datetime64_stores_what_a_nanosecond_frame_column_stores(self, con, column_type): + # The engine's cast from TIMESTAMP_NS rounds to the nearest microsecond, so the last stamp, a nanosecond before + # 1970, stores 1970 in a microsecond column + stamps = [NANOSECOND_STAMP, np.datetime64("NaT", "ns"), np.datetime64(-1, "ns")] + con.execute(f"CREATE OR REPLACE TABLE t (i INTEGER, x {column_type})") + frame = pd.DataFrame({"i": range(len(stamps)), "x": pd.Series(stamps, dtype="datetime64[ns]")}) + frame_error = failure(con.append, "t", frame) + expected = con.execute("SELECT i, x::VARCHAR FROM t ORDER BY i").fetchall() + con.execute(f"CREATE OR REPLACE TABLE t (i INTEGER, x {column_type})") + with con.appender("t") as appender: + errors = [failure(appender.append_row, i, stamp) for i, stamp in enumerate(stamps)] + stored = con.execute("SELECT i, x::VARCHAR FROM t ORDER BY i").fetchall() + if frame_error is None: + assert (stored, errors) == (expected, [None, None, None]) + else: + # The frame refuses the whole column, the appender each stamp that is not NaT, with the same cast error + assert (stored, errors[1]) == ([(1, None)], None) + for name, message in (errors[0], errors[2]): + assert name == frame_error[0] == "ConversionException" + assert frame_error[1].startswith(message) + + def test_a_refused_numpy_value_keeps_the_rows_around_it(self, con): + con.execute("CREATE OR REPLACE TABLE t (i INTEGER, x TIMESTAMP)") with con.appender("t") as appender: - appender.append_row(None, stamp) - assert con.execute("SELECT v FROM t").fetchall() == [("2024-05-08 01:02:03.123456",)] - with pytest.raises(duckdb.ConversionException), con.appender("t") as appender: - appender.append_row(stamp, None) + appender.append_row(1, np.datetime64("2024-05-08", "D")) + # Past the range of a Python date item() gives the day count, which no cast takes into a TIMESTAMP + with pytest.raises(duckdb.ConversionException): + appender.append_row(2, np.datetime64("300000-01-01", "D")) + appender.append_row(3, np.datetime64("2024-05-09", "D")) + assert con.execute("SELECT i, x FROM t ORDER BY i").fetchall() == [ + (1, dt.datetime(2024, 5, 8)), + (3, dt.datetime(2024, 5, 9)), + ] + + def test_a_raising_reading_keeps_the_rows_around_it(self, con): + con.execute("CREATE OR REPLACE TABLE t (i INTEGER, x INTEGER)") + with con.appender("t") as appender: + appender.append_row(1, np.int64(1)) + with pytest.raises(ValueError, match="no item"): + appender.append_row(2, _ItemRaises(2)) + appender.append_row(3, np.int64(3)) + assert con.execute("SELECT i, x FROM t ORDER BY i").fetchall() == [(1, 1), (3, 3)] def test_rows_of_a_two_dimensional_array_append(self, con): - con.execute("CREATE OR REPLACE TABLE t (x INTEGER, y DOUBLE)") + con.execute("CREATE OR REPLACE TABLE t (x INTEGER, y INTEGER)") with con.appender("t") as appender: - appender.append_rows(np.array([[1, 1.5], [2, 2.5]])) - assert con.execute("SELECT x, y FROM t ORDER BY x").fetchall() == [(1, 1.5), (2, 2.5)] + appender.append_rows(np.array([[1, 2], [3, 4]])) + assert con.execute("SELECT x, y FROM t ORDER BY x").fetchall() == [(1, 2), (3, 4)] def test_nested_numpy_values_keep_their_existing_conversion(self, con): # A numpy value inside a list keeps the conversion it had, in the appender, executemany and con.append alike: @@ -412,16 +538,15 @@ def test_an_ordinary_append_imports_no_numpy(self): import sys import duckdb con = duckdb.connect() + import decimal con.execute("CREATE TABLE t (x INTEGER, s VARCHAR)") with con.appender("t") as appender: appender.append_row(1, "a") + appender.append_row(decimal.Decimal(2), None) print("numpy" in sys.modules, con.execute("SELECT x, s FROM t").fetchall()) """ ) - env = {**os.environ, "SKBUILD_EDITABLE_VERBOSE": "0"} - result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=120, env=env) - assert result.returncode == 0, result.stderr - assert result.stdout.strip() == "False [(1, 'a')]" + assert run_isolated(script) == "False [(1, 'a'), (2, None)]" def test_ordinary_values_append_without_numpy(self): # numpy is optional; the scalar reading must not touch its types when it cannot be imported @@ -432,18 +557,25 @@ def test_ordinary_values_append_without_numpy(self): import duckdb con = duckdb.connect() con.execute("CREATE TABLE t (x INTEGER, s VARCHAR)") + import decimal with con.appender("t") as appender: appender.append_row(1, "a") + appender.append_row(decimal.Decimal(2), None) print(con.execute("SELECT x, s FROM t").fetchall()) """ ) - # An editable install that rebuilds on import otherwise prints its cmake command into the child's stdout - env = {**os.environ, "SKBUILD_EDITABLE_VERBOSE": "0"} - result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=120, env=env) - assert result.returncode == 0, result.stderr - assert result.stdout.strip() == "[(1, 'a')]" + assert run_isolated(script) == "[(1, 'a'), (2, None)]" def test_numpy_long_double_is_refused(self, con): con.execute("CREATE OR REPLACE TABLE t (x DOUBLE)") with pytest.raises(duckdb.NotImplementedException, match="longdouble"), con.appender("t") as appender: appender.append_row(np.longdouble("2.5")) + + +def run_isolated(script): + # -I keeps a user site file that imports numpy out of the child; an editable install that rebuilds on import + # otherwise prints its cmake command into the child's stdout + env = {**os.environ, "SKBUILD_EDITABLE_VERBOSE": "0"} + result = subprocess.run([sys.executable, "-I", "-c", script], capture_output=True, text=True, timeout=120, env=env) + assert result.returncode == 0, result.stderr + return result.stdout.strip() diff --git a/tests/fast/pandas/test_append_df.py b/tests/fast/pandas/test_append_df.py index 4360a8bc8..3a6fbcfd5 100644 --- a/tests/fast/pandas/test_append_df.py +++ b/tests/fast/pandas/test_append_df.py @@ -274,20 +274,28 @@ class TestAppendObjectColumnsToDeclaredTypes: pytest.param( "BOOLEAN", _outside_the_sample(True, np.bool_(False)), True, False, id="numpy_bool_into_boolean" ), + # The engine's TIMESTAMP_NS cast rounds both to the nearest microsecond, as for a datetime64[ns] column pytest.param( "TIMESTAMP", _outside_the_sample(NAIVE, np.datetime64("2024-05-08T01:02:03.123456789", "ns")), NAIVE, - datetime.datetime(2024, 5, 8, 1, 2, 3, 123456), + datetime.datetime(2024, 5, 8, 1, 2, 3, 123457), id="numpy_datetime_into_timestamp", ), pytest.param( "TIMESTAMP", _outside_the_sample(NAIVE, np.array("2024-05-08T01:02:03.123456789", dtype="datetime64[ns]")), NAIVE, - datetime.datetime(2024, 5, 8, 1, 2, 3, 123456), + datetime.datetime(2024, 5, 8, 1, 2, 3, 123457), id="numpy_zero_dimensional_datetime_into_timestamp", ), + pytest.param( + "VARCHAR", + _outside_the_sample("a", np.datetime64("2024-05-08", "D")), + "a", + "2024-05-08", + id="numpy_day_datetime_into_varchar_reads_as_its_date", + ), pytest.param( "STRUCT(x VARCHAR)", _outside_the_sample({"x": "abc"}, None), From 984af330282a38de9d70e5d097502f3f8c9f116c Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 12:42:08 +0000 Subject: [PATCH 20/61] Cache only numpy's own scalar classes, name tuples in the empty paths refusal --- duckdb/_relation.py | 4 ++- .../pyconnection/pyconnection.hpp | 2 +- src/pyconnection.cpp | 2 +- src/typing/pytype.cpp | 19 ++++++++---- tests/fast/api/test_read_csv.py | 2 +- tests/fast/api/test_read_parquet.py | 2 +- tests/fast/api/test_reader_path_lists.py | 4 ++- tests/fast/test_type.py | 30 +++++++++++++++++++ 8 files changed, 53 insertions(+), 12 deletions(-) diff --git a/duckdb/_relation.py b/duckdb/_relation.py index 589983632..683d8b182 100644 --- a/duckdb/_relation.py +++ b/duckdb/_relation.py @@ -3652,7 +3652,9 @@ def one(item: object) -> str: if isinstance(source, (list, tuple)): if not source: - raise _error(_duckdb.InvalidInputException, "Please provide a non-empty list of paths or file-like objects") + raise _error( + _duckdb.InvalidInputException, "Please provide a non-empty list or tuple of paths or file-like objects" + ) paths = [one(item) for item in source] return _option_literal(paths), tuple(handles) return _option_literal(one(source)), tuple(handles) diff --git a/src/include/duckdb_python/pyconnection/pyconnection.hpp b/src/include/duckdb_python/pyconnection/pyconnection.hpp index 0b41db3aa..2a1ae1c83 100644 --- a/src/include/duckdb_python/pyconnection/pyconnection.hpp +++ b/src/include/duckdb_python/pyconnection/pyconnection.hpp @@ -338,7 +338,7 @@ struct DuckDBPyConnection : public std::enable_shared_from_this conn); static PythonImportCache *ImportCache(); static nb::object ConsumedArrowReaders(); - //! The dict of numpy scalar class to the id of the DuckDB type it converts to; call with the GIL held + //! The dict of numpy's own scalar classes to the id of the DuckDB type each converts to; call with the GIL held static nb::object NumpyScalarTypes(); //! Keeps adapt and the nodes module of the duckdb._sources package the package passes in as it imports static void SetArrowSources(const nb::object &sources); diff --git a/src/pyconnection.cpp b/src/pyconnection.cpp index 61bcca98a..151d70f9c 100644 --- a/src/pyconnection.cpp +++ b/src/pyconnection.cpp @@ -50,7 +50,7 @@ struct DuckDBPyModuleState { std::shared_ptr import_cache; //! The single-use Arrow readers that have handed out their stream, by identity and held weakly unique_ptr consumed_arrow_readers; - //! The DuckDB type id of each numpy scalar class converted so far; only Cleanup clears it, as such classes are few + //! The DuckDB type id of each of numpy's own scalar classes converted so far; only Cleanup clears it unique_ptr numpy_scalar_types; //! Held rather than imported on use, since an import fails once the package has left sys.modules unique_ptr arrow_sources_adapt; diff --git a/src/typing/pytype.cpp b/src/typing/pytype.cpp index 0b79f531b..3c73e6b94 100644 --- a/src/typing/pytype.cpp +++ b/src/typing/pytype.cpp @@ -156,7 +156,9 @@ static bool DerivesFromConcreteNumpyScalar(const nb::handle &type, NumpyCacheIte return false; } -static bool ReadNumpyScalarType(const nb::object &type, PythonImportCache &import_cache, LogicalType &result) { +//! is_numpy_own says whether the type is numpy's own scalar class, not a subclass of one +static bool ReadNumpyScalarType(const nb::object &type, PythonImportCache &import_cache, LogicalType &result, + bool &is_numpy_own) { if (!DerivesFromConcreteNumpyScalar(type, import_cache.numpy)) { return false; } @@ -175,6 +177,7 @@ static bool ReadNumpyScalarType(const nb::object &type, PythonImportCache &impor if (!nb::issubclass(type, dtype_type)) { return false; } + is_numpy_own = type.is(dtype_type); // We convert these to string because the underlying physical // types of a numpy type aren't consistent on every platform string type_str = nb::cast(nb::str(dtype)); @@ -219,9 +222,10 @@ static bool FromNumpyType(const nb::object &type, LogicalType &result) { if (!generic || !nb::issubclass(type, generic)) { return false; } - // Reading a class costs more than the rest of converting a value it types, so each class is read once. The - // type is kept as its id, which describes every type a numpy scalar maps to; a kept DuckDBPyType would be - // reported as leaked at exit. + // Reading a class costs more than the rest of converting a value it types, so numpy's own scalar classes are + // read once; a subclass is read each time, since keeping it would keep a class made at run time alive. The type + // is kept as its id, which describes every type a numpy scalar maps to; a kept DuckDBPyType would be reported + // as leaked at exit. auto known = nb::borrow(DuckDBPyConnection::NumpyScalarTypes()); auto cached = PyDict_GetItemWithError(known.ptr(), type.ptr()); if (cached) { @@ -231,10 +235,13 @@ static bool FromNumpyType(const nb::object &type, LogicalType &result) { if (PyErr_Occurred()) { throw nb::python_error(); } - if (!ReadNumpyScalarType(type, import_cache, result)) { + bool is_numpy_own = false; + if (!ReadNumpyScalarType(type, import_cache, result, is_numpy_own)) { return false; } - known[type] = nb::int_(static_cast(result.id())); + if (is_numpy_own) { + known[type] = nb::int_(static_cast(result.id())); + } return true; } diff --git a/tests/fast/api/test_read_csv.py b/tests/fast/api/test_read_csv.py index 4cc81e125..323242b45 100644 --- a/tests/fast/api/test_read_csv.py +++ b/tests/fast/api/test_read_csv.py @@ -558,7 +558,7 @@ def test_read_csv_empty_list(self): con = duckdb.connect() files = [] with pytest.raises( - duckdb.InvalidInputException, match="Please provide a non-empty list of paths or file-like objects" + duckdb.InvalidInputException, match="Please provide a non-empty list or tuple of paths or file-like objects" ): con.read_csv(files) diff --git a/tests/fast/api/test_read_parquet.py b/tests/fast/api/test_read_parquet.py index ebe47095b..257396d42 100644 --- a/tests/fast/api/test_read_parquet.py +++ b/tests/fast/api/test_read_parquet.py @@ -164,7 +164,7 @@ def test_nonexistent_file(self, duckdb_cursor, tmp_path): duckdb_cursor.read_parquet(str(missing)).fetchall() def test_empty_list(self, duckdb_cursor): - with pytest.raises(duckdb.InvalidInputException, match="non-empty list of paths or file-like objects"): + with pytest.raises(duckdb.InvalidInputException, match="non-empty list or tuple of paths or file-like objects"): duckdb_cursor.read_parquet([]) def test_filelike_exception(self, duckdb_cursor): diff --git a/tests/fast/api/test_reader_path_lists.py b/tests/fast/api/test_reader_path_lists.py index 204b19d7c..b271e3be6 100644 --- a/tests/fast/api/test_reader_path_lists.py +++ b/tests/fast/api/test_reader_path_lists.py @@ -62,7 +62,9 @@ def test_every_reader_reads_every_file_of_a_tuple(tmp_path, reader, extension): def test_an_empty_tuple_is_refused_like_an_empty_list(): - with pytest.raises(duckdb.InvalidInputException, match="Please provide a non-empty list of paths"): + with pytest.raises( + duckdb.InvalidInputException, match="Please provide a non-empty list or tuple of paths or file-like objects" + ): duckdb.connect().read_json(()) diff --git a/tests/fast/test_type.py b/tests/fast/test_type.py index 1637cd2aa..685e0d7e7 100644 --- a/tests/fast/test_type.py +++ b/tests/fast/test_type.py @@ -1,6 +1,8 @@ import datetime +import gc import sys import warnings +import weakref import pytest @@ -406,6 +408,34 @@ def test_a_numpy_scalar_type_without_a_duckdb_type_is_refused(self, name, subcla assert [str(warning.message) for warning in caught] == [] +class TestKeptNumpyScalarTypes: + """numpy's own scalar classes are converted once and kept; a subclass of one is converted each time and not kept.""" + + @pytest.mark.parametrize(("name", "expected"), [("int32", INTEGER), ("intc", INTEGER), ("longlong", BIGINT)]) + def test_a_kept_class_converts_the_same_again(self, name, expected): + np = pytest.importorskip("numpy") + scalar = getattr(np, name) + assert [DuckDBPyType(scalar) for _ in range(3)] == [expected] * 3 + assert expected == scalar + assert expected == scalar + + def test_a_converted_subclass_can_be_collected(self): + np = pytest.importorskip("numpy") + enabled = gc.isenabled() + gc.disable() + try: + subclassed = type("Collectable", (np.int16,), {}) + assert DuckDBPyType(subclassed) == SMALLINT + assert SMALLINT == subclassed # noqa: SIM300 + alive = weakref.ref(subclassed) + del subclassed + gc.collect() + assert alive() is None + finally: + if enabled: + gc.enable() + + class TestConvertingATypeOperand: """Converting an operand to a type refuses on an Exception and lets every other BaseException through.""" From b38c021d3834bb669cc391efc3562c14248f36db Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 13:06:36 +0000 Subject: [PATCH 21/61] Pin that con.append keeps the trailing NUL characters of numpy str and bytes scalars --- tests/fast/pandas/test_append_df.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tests/fast/pandas/test_append_df.py b/tests/fast/pandas/test_append_df.py index 3a6fbcfd5..f922a34fe 100644 --- a/tests/fast/pandas/test_append_df.py +++ b/tests/fast/pandas/test_append_df.py @@ -296,6 +296,34 @@ class TestAppendObjectColumnsToDeclaredTypes: "2024-05-08", id="numpy_day_datetime_into_varchar_reads_as_its_date", ), + pytest.param( + "VARCHAR", + _outside_the_sample("a", np.str_("ab\x00")), + "a", + "ab\x00", + id="numpy_str_into_varchar_keeps_a_trailing_nul", + ), + pytest.param( + "VARCHAR", + _outside_the_sample("a", np.str_("\x00\x00")), + "a", + "\x00\x00", + id="numpy_str_of_nuls_into_varchar_keeps_them", + ), + pytest.param( + "BLOB", + _outside_the_sample(b"a", np.bytes_(b"\x01\x00")), + b"a", + b"\x01\x00", + id="numpy_bytes_into_blob_keeps_a_trailing_nul", + ), + pytest.param( + "BLOB", + _outside_the_sample(b"a", np.bytes_(b"\x00\x00")), + b"a", + b"\x00\x00", + id="numpy_bytes_of_nuls_into_blob_keeps_them", + ), pytest.param( "STRUCT(x VARCHAR)", _outside_the_sample({"x": "abc"}, None), From 68ea03abd63491c871054e79f8b27452c85ab204 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 14:15:17 +0000 Subject: [PATCH 22/61] Push only translations that read as polars does: modulus with the divisor's sign, boolean And and Or, exact decimals, byte collation, and refuse types polars widens --- duckdb/polars_io.py | 229 ++++++++- .../arrow/test_polars_pushdown_literals.py | 445 +++++++++++++++++- 2 files changed, 634 insertions(+), 40 deletions(-) diff --git a/duckdb/polars_io.py b/duckdb/polars_io.py index 9746233f9..d93279090 100644 --- a/duckdb/polars_io.py +++ b/duckdb/polars_io.py @@ -6,7 +6,6 @@ import json import operator import typing -from decimal import Decimal import polars as pl from polars.io.plugins import register_io_source @@ -45,11 +44,12 @@ def _tree_to_sql_expression( ) -> duckdb.Expression | None: """Convert an already-parsed Polars expression tree to a DuckDB expression. - ``schema`` is the polars schema of the scanned relation; without it no cast of a column translates. + ``schema`` maps the columns of the scanned relation whose polars dtype stands for their engine type to that dtype; + a comparison on any other column does not translate, and without a schema no cast of a column and no modulus does. Returns None if the tree contains a node we cannot translate to SQL. """ try: - return duckdb.SQLExpression(_pl_tree_to_sql(tree, schema)) + return duckdb.SQLExpression(_predicate_to_sql(tree, schema)) except Exception: # If the conversion fails, we return None return None @@ -140,7 +140,9 @@ def _expression_from_tree(tree: _ExpressionTree) -> pl.Expr: def _pl_operation_to_sql(op: str) -> str: - """Map Polars binary operation strings to SQL equivalents. + """Map Polars comparison operation strings to SQL equivalents. + + And and Or are bitwise on integers, so only ``_predicate_to_sql`` translates them. Example: >>> _pl_operation_to_sql("Eq") @@ -153,9 +155,6 @@ def _pl_operation_to_sql(op: str) -> str: "Gt": ">", "GtEq": ">=", "Eq": "=", - "Modulus": "%", - "And": "AND", - "Or": "OR", }[op] except KeyError: raise NotImplementedError(op) # noqa: B904 @@ -179,14 +178,26 @@ def _escape_sql_identifier(identifier: str) -> str: } -def _widens_exactly(column: pl.DataType | None, target: object) -> bool: - """Whether a cast of a column of dtype ``column`` to the serialized dtype ``target`` keeps every value. +_EXACT_IN_A_DOUBLE = frozenset({"Int8", "Int16", "Int32", "UInt8", "UInt16", "UInt32"}) +# polars 1 casts a column compared with a Python float to the dynamic float type, which it computes as a Float64 +_FLOAT64 = ("Float64", {"Unknown": "Float"}) + + +def _compares_bare(column: pl.DataType | None, target: object) -> bool: + """Whether a column of dtype ``column`` compares as its cast to the serialized dtype ``target`` does. - Only integer to integer and decimal to decimal count: the engine compares those bare columns exactly. An integer + An integer to an integer that holds it and a decimal to a decimal that keeps its integer and fractional digits keep + every value. A cast to Float64 keeps every comparison with a double for an integer of 32 bits or fewer, which is a + double exactly, and for a decimal of 15 digits or fewer, which converts to a double no other such decimal shares; + the engine compares the bare column with a double's shortest text as an exact decimal, or as a double. An integer to a decimal keeps every value too, but the engine raises where the common decimal type of a comparison needs more than 38 digits, and polars casts a Date past 294247 or DATE 'infinity' to a NULL Datetime. """ kind = target.get("Literal") if isinstance(target, dict) else None + if kind in _FLOAT64: + if isinstance(column, pl.Decimal): + return column.precision is not None and column.precision <= 15 + return str(column) in _EXACT_IN_A_DOUBLE if isinstance(kind, str) and kind in _INTEGER_RANGES and str(column) in _INTEGER_RANGES: low, high = _INTEGER_RANGES[str(column)] target_low, target_high = _INTEGER_RANGES[kind] @@ -202,13 +213,149 @@ def _widens_exactly(column: pl.DataType | None, target: object) -> bool: return False +def _integer_literal(tree: _ExpressionTree) -> int | None: + """The value of a typed integer literal, as polars sends it in an optimized predicate, or None.""" + literal = tree.get("Literal") + scalar = literal.get("Scalar") if isinstance(literal, dict) else None + if isinstance(scalar, dict) and len(scalar) == 1: + [(dtype, value)] = scalar.items() + if dtype in _INTEGER_RANGES and isinstance(value, int): + return value + return None + + +def _is_integer(tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | None) -> bool: + """Whether polars types the node as an integer: a column of an integer dtype, or a cast to one.""" + if schema is None: + return False + column = tree.get("Column") + if isinstance(column, str): + return str(schema.get(column)) in _INTEGER_RANGES + cast = tree.get("Cast") + target = cast.get("dtype") if isinstance(cast, dict) else None + kind = target.get("Literal") if isinstance(target, dict) else None + return isinstance(kind, str) and kind in _INTEGER_RANGES + + +def _floored_modulus_to_sql( + dividend: _ExpressionTree, divisor: _ExpressionTree, schema: Mapping[str, pl.DataType] | None +) -> str: + """Translate polars' integer modulus, which takes the divisor's sign where the engine's ``%`` takes the dividend's. + + Only an integer dividend and a nonzero integer literal divisor translate: the engine raises on a zero divisor where + polars gives NULL, and polars floors a float or decimal modulus that the engine truncates. + """ + divisor_value = _integer_literal(divisor) + if not divisor_value or not _is_integer(dividend, schema): + msg = "Only an integer modulus by a nonzero integer literal can be pushed down" + raise NotImplementedError(msg) + remainder = f"({_pl_tree_to_sql(dividend, schema)} % {divisor_value})" + # Adding the divisor moves a remainder of the other sign into the divisor's and stays inside the divisor's range + other_sign = "<" if divisor_value > 0 else ">" + return f"(CASE WHEN {remainder} {other_sign} 0 THEN {remainder} + {divisor_value} ELSE {remainder} END)" + + +def _decimal_to_sql(unscaled: int, scale: int) -> str: + """A decimal literal at its exact value, typed with the digits it needs. + + The engine reads an integer exactly but a decimal text of more than 38 digits, a zero before the point included, as + a DOUBLE, so a fraction is cast; its precision is the digits the value needs, so the literal never widens the + common type of a comparison beyond what the column and the value need. + """ + if scale == 0: + return str(unscaled) + digits = str(abs(unscaled)).rjust(scale + 1, "0") + sign = "-" if unscaled < 0 else "" + precision = max(len(str(abs(unscaled))), scale) + return f"CAST('{sign}{digits[:-scale]}.{digits[-scale:]}' AS DECIMAL({precision}, {scale}))" + + +def _decimal_digits(tree: _ExpressionTree, schema: Mapping[str, pl.DataType]) -> tuple[int, int] | None: + """The integer digits and the scale the engine compares a decimal operand with, or None for any other operand. + + A cast that reaches the engine is a cast pushed as its bare column, so it compares with the column's digits. + """ + cast = tree.get("Cast") + inner = cast.get("expr") if isinstance(cast, dict) else tree + column = inner.get("Column") if isinstance(inner, dict) else None + if isinstance(column, str): + dtype = schema.get(column) + if isinstance(dtype, pl.Decimal) and dtype.precision is not None: + return dtype.precision - dtype.scale, dtype.scale + return None + literal = tree.get("Literal") + scalar = literal.get("Scalar") if isinstance(literal, dict) else None + value = scalar.get("Decimal") if isinstance(scalar, dict) else None + if isinstance(value, list) and isinstance(value[0], int) and isinstance(value[-1], int): + unscaled, scale = value[0], value[-1] + return max(len(str(abs(unscaled))) - scale, 0), scale + return None + + +def _operand_to_sql(tree: _ExpressionTree, schema: Mapping[str, pl.DataType]) -> str: + """An operand of a comparison, a text column compared by its bytes as polars compares it. + + The engine applies the column's collation or the session's default collation to a text comparison, and an ENUM + compares as its text; binary collation keeps the scan filter and its pruning. + """ + sql = _pl_tree_to_sql(tree, schema) + column = tree.get("Column") + dtype = schema.get(column) if isinstance(column, str) else None + if dtype == pl.String: + return f"({sql} COLLATE C)" + if isinstance(dtype, pl.Categorical): + return f"(CAST({sql} AS VARCHAR) COLLATE C)" + return sql + + +def _comparison_to_sql( + lhs: _ExpressionTree, op: str, rhs: _ExpressionTree, schema: Mapping[str, pl.DataType] | None +) -> str: + """A comparison the engine evaluates as polars does. + + A column the schema leaves out has an engine type its polars dtype does not stand for. Two decimals whose common + type needs more than 38 digits stay with polars until the engine compares them: it clamps that type to 38 digits + and raises for a value that does not fit, where polars compares. + """ + sql_op = _pl_operation_to_sql(op) + if schema is None: + return f"({_pl_tree_to_sql(lhs, schema)} {sql_op} {_pl_tree_to_sql(rhs, schema)})" + for side in (lhs, rhs): + column = side.get("Column") + if isinstance(column, str) and column not in schema: + msg = f"The engine does not compare column {column!r} as its polars dtype" + raise NotImplementedError(msg) + left, right = _decimal_digits(lhs, schema), _decimal_digits(rhs, schema) + if left is not None and right is not None and max(left[0], right[0]) + max(left[1], right[1]) > 38: + msg = "The engine raises on a decimal comparison whose common type needs more than 38 digits" + raise NotImplementedError(msg) + return f"({_operand_to_sql(lhs, schema)} {sql_op} {_operand_to_sql(rhs, schema)})" + + +def _predicate_to_sql(tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | None = None) -> str: + """Convert a Boolean polars expression tree, a filter predicate or a conjunct of one, to a SQL string. + + polars applies And and Or bitwise to integers but types them Boolean only between Boolean operands, and a filter + predicate is Boolean, so an And or Or is SQL's AND or OR here and in its operands, and nowhere below. + """ + bin_expr = tree.get("BinaryExpr") + if isinstance(bin_expr, dict) and bin_expr.get("op") in ("And", "Or"): + lhs, op, rhs = bin_expr["left"], bin_expr["op"], bin_expr["right"] + assert isinstance(lhs, dict), f"LHS of a BinaryExpr should be a dict but got {type(lhs)}" + assert isinstance(op, str), f"The op of a BinaryExpr should be a str but got {type(op)}" + assert isinstance(rhs, dict), f"RHS of a BinaryExpr should be a dict but got {type(rhs)}" + return f"({_predicate_to_sql(lhs, schema)} {op.upper()} {_predicate_to_sql(rhs, schema)})" + return _pl_tree_to_sql(tree, schema) + + def _pl_tree_to_sql(tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | None = None) -> str: """Recursively convert a Polars expression tree (as JSON) to a SQL string. Parameters: tree (dict): JSON-deserialized expression tree from Polars - schema (Mapping): the polars schema of the scanned relation, which decides whether a cast of a column widens - exactly; without it no cast of a column translates + schema (Mapping): the polars dtypes of the scanned columns the engine compares as polars does, which decide + whether a cast of a column compares as the bare column, whether a modulus is an integer's and how a + comparison renders; without it no cast of a column and no modulus translates Returns: str: SQL expression string @@ -234,7 +381,9 @@ def _pl_tree_to_sql(tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | N assert isinstance(lhs, dict), f"LHS of a {node_type} should be a dict but got {type(lhs)}" assert isinstance(op, str), f"The op of a {node_type} should be a str but got {type(op)}" assert isinstance(rhs, dict), f"RHS of a {node_type} should be a dict but got {type(rhs)}" - return f"({_pl_tree_to_sql(lhs, schema)} {_pl_operation_to_sql(op)} {_pl_tree_to_sql(rhs, schema)})" + if op == "Modulus": + return _floored_modulus_to_sql(lhs, rhs, schema) + return _comparison_to_sql(lhs, op, rhs, schema) if node_type == "Column": # A reference to a column name # Wrap in quotes to handle special characters @@ -303,9 +452,9 @@ def _pl_tree_to_sql(tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | N if ( schema is not None and isinstance(column, str) - and _widens_exactly(schema.get(column), cast_tree.get("dtype")) + and _compares_bare(schema.get(column), cast_tree.get("dtype")) ): - # No cast option changes a value the target type holds, so the bare column compares the same + # No cast option changes how such a cast compares, so the bare column compares the same return _pl_tree_to_sql(cast_expr, schema) # Any other cast of a column can truncate, turn an overflow into NULL or change the type the comparison runs # in, and the bare column carries none of that @@ -343,7 +492,10 @@ def _pl_tree_to_sql(tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | N assert 2 <= len(decimal_value) <= 3, ( f"A {dtype} should be a two or three member list but got {len(decimal_value)} member list" ) - return str(Decimal(decimal_value[0]) / Decimal(10 ** decimal_value[-1])) + unscaled, scale = decimal_value[0], decimal_value[-1] + assert isinstance(unscaled, int), f"A {dtype} value should be an int but got {type(unscaled)}" + assert isinstance(scale, int), f"A {dtype} scale should be an int but got {type(scale)}" + return _decimal_to_sql(unscaled, scale) # Datetime: [value since epoch, time unit, time zone] if dtype.startswith("{'Datetime'") or dtype == "Datetime": @@ -393,6 +545,10 @@ def _pl_tree_to_sql(tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | N if dtype == "Time": nanoseconds = value["Time"] assert isinstance(nanoseconds, int), f"A {dtype} should be an int but got {type(nanoseconds)}" + if nanoseconds % 1_000: + # A TIME literal cannot hold nanoseconds, let polars apply the filter + msg = "A Time literal finer than a microsecond cannot be pushed down" + raise NotImplementedError(msg) seconds = nanoseconds // 1_000_000_000 microseconds = (nanoseconds % 1_000_000_000) // 1_000 dt_time = (datetime.datetime.min + datetime.timedelta(seconds=seconds, microseconds=microseconds)).time() @@ -429,8 +585,47 @@ def _pl_tree_to_sql(tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | N raise NotImplementedError(msg) +_ENGINE_TYPES = { + "Boolean": ("BOOLEAN",), + "Int8": ("TINYINT",), + "Int16": ("SMALLINT",), + "Int32": ("INTEGER",), + "Int64": ("BIGINT",), + "UInt8": ("UTINYINT",), + "UInt16": ("USMALLINT",), + "UInt32": ("UINTEGER",), + "UInt64": ("UBIGINT",), + "Float32": ("FLOAT",), + "Float64": ("DOUBLE",), + "String": ("VARCHAR",), + "Binary": ("BLOB",), + "Date": ("DATE",), + "Time": ("TIME",), +} +_DATETIME_ENGINE_TYPES = {"ms": ("TIMESTAMP_S", "TIMESTAMP_MS"), "us": ("TIMESTAMP",), "ns": ("TIMESTAMP_NS",)} + + +def _stands_for(dtype: pl.DataType, engine_type: str) -> bool: + """Whether the polars dtype of a column stands for the column's engine type, so both compare it alike. + + UUID and JSON reach polars as a String, BIT as a Binary, TIME_NS and TIME WITH TIME ZONE as a Time, and HUGEINT + and UHUGEINT, which hold 39 digits, as a Decimal(38, 0); the engine compares each by its own type. + """ + if isinstance(dtype, pl.Decimal): + return engine_type == f"DECIMAL({dtype.precision},{dtype.scale})" + if isinstance(dtype, pl.Datetime): + if dtype.time_zone is not None: + return engine_type == "TIMESTAMP WITH TIME ZONE" + return engine_type in _DATETIME_ENGINE_TYPES.get(dtype.time_unit, ()) + if isinstance(dtype, pl.Categorical): + return engine_type.startswith("ENUM(") + return engine_type in _ENGINE_TYPES.get(str(dtype), ()) + + def duckdb_source(relation: duckdb.DuckDBPyRelation, schema: pl.schema.Schema) -> pl.LazyFrame: """A polars IO plugin for DuckDB.""" + engine_types = dict(zip(relation.columns, map(str, relation.types), strict=True)) + comparable = {name: dtype for name, dtype in schema.items() if _stands_for(dtype, engine_types.get(name, ""))} def source_generator( with_columns: list[str] | None, @@ -457,7 +652,7 @@ def source_generator( conjuncts = _conjuncts(real_tree) pushed = [ expression - for expression in (_tree_to_sql_expression(conjunct, schema) for conjunct in conjuncts) + for expression in (_tree_to_sql_expression(conjunct, comparable) for conjunct in conjuncts) if expression is not None ] if pushed: diff --git a/tests/fast/arrow/test_polars_pushdown_literals.py b/tests/fast/arrow/test_polars_pushdown_literals.py index 67fa7806b..717c440b1 100644 --- a/tests/fast/arrow/test_polars_pushdown_literals.py +++ b/tests/fast/arrow/test_polars_pushdown_literals.py @@ -1,6 +1,9 @@ import datetime import decimal +import functools +import itertools import json +import math import operator import subprocess import sys @@ -33,6 +36,7 @@ "INTEGER": (-(2**31), 2**31 - 1), "BIGINT": (-(2**63), 2**63 - 1), "UTINYINT": (0, 2**8 - 1), + "USMALLINT": (0, 2**16 - 1), "UINTEGER": (0, 2**32 - 1), "UBIGINT": (0, 2**64 - 1), } @@ -43,39 +47,64 @@ """ +class Pushdowns(list): + """One entry per conjunct the source translated or refused, and the rows of each batch it handed polars.""" + + def __init__(self) -> None: + super().__init__() + self.rows = [] + + @pytest.fixture def pushdowns(monkeypatch): # The rows alone cannot tell a pushed filter from one polars applied after the source declined it. - seen = [] + seen = Pushdowns() to_sql_expression = polars_io._tree_to_sql_expression + from_arrow = pl.from_arrow def recording(tree, *schema): expression = to_sql_expression(tree, *schema) try: - polars_io._pl_tree_to_sql(tree, *schema) + polars_io._predicate_to_sql(tree, *schema) except Exception as error: seen.append((tree, expression, type(error))) else: seen.append((tree, expression, None)) return expression + def counting(batch, *args, **kwargs): + seen.rows.append(batch.num_rows) + return from_arrow(batch, *args, **kwargs) + monkeypatch.setattr(polars_io, "_tree_to_sql_expression", recording) + monkeypatch.setattr(pl, "from_arrow", counting) return seen def assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, *, pushed, polars_predicate=None): """`pushed` holds for every conjunct of a top level AND, or is "partly" when some reached the engine.""" pushdowns.clear() + pushdowns.rows.clear() actual = lazy_df.filter(predicate).collect() - expected = lazy_df.collect().filter(predicate if polars_predicate is None else polars_predicate) + arrived = sum(pushdowns.rows) + everything = lazy_df.collect() + expected = everything.filter(predicate if polars_predicate is None else polars_predicate) pl_testing.assert_frame_equal(actual, expected) assert pushdowns, predicate states = [expression is not None for _, expression, _ in pushdowns] + # A conjunct that translated proves nothing until the engine filters by it, so count the rows reaching polars if pushed == "partly": assert any(states), (predicate, pushdowns) assert not all(states), (predicate, pushdowns) + translated = [ + polars_io._expression_from_tree(tree) for tree, expression, _ in pushdowns if expression is not None + ] + # The engine kept exactly the rows its conjuncts keep in polars, no more and no fewer + assert arrived == everything.filter(functools.reduce(operator.and_, translated)).height, (predicate, arrived) + assert arrived < everything.height, (predicate, arrived) else: assert all(state == pushed for state in states), (predicate, pushdowns) + assert arrived == (actual.height if pushed else everything.height), (predicate, arrived) for tree, expression, error in pushdowns: if expression is None: assert error is NotImplementedError, (predicate, tree, error) @@ -294,6 +323,25 @@ def test_untyped_non_finite_literal_is_not_pushed_down_without_assertions(self): assert result.returncode == 0, result.stderr +class TestTimeLiteralPushdown: + def test_literal_finer_than_a_microsecond_is_not_pushed(self, duckdb_cursor, pushdowns): + # A TIME holds microseconds, and truncated to them the literal reads as 12:00:00: as the whole predicate == + # keeps that row, which polars drops, and beside a refused conjunct < drops it, which polars keeps + duckdb_cursor.execute("CREATE TABLE t (t TIME, s VARCHAR)") + duckdb_cursor.execute( + "INSERT INTO t VALUES ('12:00:00', 'x'), ('12:00:00.000001', 'x'), ('11:59:59.999999', 'x'), (NULL, 'x')" + ) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + nanosecond = pl.lit(12 * 3600 * 10**9 + 500, dtype=pl.Int64).cast(pl.Time) + for compare in ORDERINGS: + assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("t"), nanosecond), pushed=False) + predicate = compare(pl.col("t"), nanosecond) & pl.col("s").str.contains("x") + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) + microsecond = pl.lit(datetime.time(12, 0, 0, 1)) + for compare in ORDERINGS: + assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("t"), microsecond), pushed=True) + + class TestColumnCastPushdown: # A cast of the column, whether the user wrote it or polars inserted it to reconcile types, can truncate, turn an # overflow into NULL or change the type the comparison runs in, and the bare column carries none of that, so the @@ -330,8 +378,8 @@ def test_column_cast_to_other_units_matches_polars(self, unit, duckdb_cursor, pu ) for compare in ORDERINGS: predicate = compare(pl.col("a").cast(pl.Datetime(unit, "UTC")), literal) - # polars drops a cast to the column's own unit and zone before the source sees the predicate - assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=unit == "us") + # polars 2 drops a cast to the column's own unit and zone before the source sees the predicate + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=unit == "us" and POLARS_2) def test_numeric_column_cast_matches_polars(self, duckdb_cursor, pushdowns): duckdb_cursor.execute("CREATE TABLE t (i INTEGER)") @@ -359,7 +407,7 @@ def test_cast_of_an_expression_matches_polars(self, duckdb_cursor, pushdowns): assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) assert lazy_df.filter(predicate).collect()["i"].to_list() == [200, None] - def test_fallback_filters_every_batch(self, duckdb_cursor, pushdowns, monkeypatch): + def test_fallback_filters_every_batch(self, duckdb_cursor, pushdowns): # One match in the first batch and one past it with empty batches between, so a read that stopped after the # first batch or at an empty one would lose the last match duckdb_cursor.execute( @@ -367,21 +415,13 @@ def test_fallback_filters_every_batch(self, duckdb_cursor, pushdowns, monkeypatc "FROM range(300000)" ) lazy_df = duckdb_cursor.table("t").pl(lazy=True) - batches = [] - from_arrow = pl.from_arrow - - def counting(batch, *args, **kwargs): - batches.append(batch.num_rows) - return from_arrow(batch, *args, **kwargs) - - monkeypatch.setattr(pl, "from_arrow", counting) # Pushed bare, the predicate kept every row; the non strict cast turns 200 into NULL predicate = pl.col("i").cast(pl.Int8, strict=False).is_not_null() assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) - batches.clear() + pushdowns.rows.clear() assert lazy_df.filter(predicate).collect()["id"].to_list() == [100, 250000] - assert len(batches) > 1, batches - assert batches[0] <= 250000, batches + assert len(pushdowns.rows) > 1, pushdowns.rows + assert pushdowns.rows[0] <= 250000, pushdowns.rows def test_float_column_against_a_double_literal_matches_polars(self, duckdb_cursor, pushdowns): # polars widens the FLOAT column with a cast; pushed bare, the engine compared 0.1 as a FLOAT and dropped a row @@ -560,7 +600,13 @@ def test_lossy_cast_is_not_pushed(self, columns, rows, predicate, duckdb_cursor, pytest.param(pl.Date, '{"Datetime": ["Microseconds", null]}', False, id="Date to Datetime(Microseconds)"), pytest.param(pl.Date, '{"Datetime": ["Milliseconds", null]}', False, id="Date to Datetime(Milliseconds)"), pytest.param(pl.Float32, '"Float64"', False, id="Float32 to Float64"), - pytest.param(pl.Int32, '"Float64"', False, id="Int32 to Float64"), + pytest.param(pl.Int32, '"Float64"', True, id="Int32 to Float64"), + pytest.param(pl.UInt32, '"Float64"', True, id="UInt32 to Float64"), + pytest.param(pl.Int64, '"Float64"', False, id="Int64 to Float64"), + pytest.param(pl.Decimal(15, 2), '"Float64"', True, id="Decimal(15,2) to Float64"), + pytest.param(pl.Decimal(16, 2), '"Float64"', False, id="Decimal(16,2) to Float64"), + pytest.param(pl.Int16, '{"Unknown": "Float"}', True, id="Int16 to the dynamic float"), + pytest.param(pl.Int32, '"Float32"', False, id="Int32 to Float32"), ], ) def test_cast_rule_on_hand_built_trees(self, source, target, pushed): @@ -580,12 +626,61 @@ def test_cast_rule_on_hand_built_trees(self, source, target, pushed): with pytest.raises(NotImplementedError): _pl_tree_to_sql(tree, pl.Schema({"b": source})) + @pytest.mark.parametrize( + ("data_type", "value", "unit"), + [ + ("DECIMAL(15,2)", "9999999999999.98", "0.01"), + ("DECIMAL(15,0)", "-999999999999998", "1"), + ("DECIMAL(15,15)", "0.123456789012345", "0.000000000000001"), + ("DECIMAL(9,4)", "-12345.6789", "0.0001"), + ("TINYINT", "-127", "1"), + ("SMALLINT", "32766", "1"), + ("INTEGER", "-2147483647", "1"), + ("UTINYINT", "254", "1"), + ("USMALLINT", "65534", "1"), + ("UINTEGER", "4294967294", "1"), + ], + ) + def test_float_against_a_round_tripping_column_is_pushed(self, data_type, value, unit, duckdb_cursor, pushdowns): + # Such a value converts to a double no other value of its type shares, so the bare column compares with a + # double's shortest text, which the engine reads as an exact decimal, or with a DOUBLE column as polars' Float64 + # cast of it does + value, unit = decimal.Decimal(value), decimal.Decimal(unit) + double = float(value) + doubles = [double, math.nextafter(double, math.inf), math.nextafter(double, -math.inf)] + duckdb_cursor.execute(f"CREATE TABLE t (a {data_type}, x DOUBLE)") + duckdb_cursor.executemany( + "INSERT INTO t VALUES (?, ?)", + [ + (None if a is None else str(a), x) + for a, x in itertools.product( + [value - unit, value, value + unit, None], [*doubles, math.nan, math.inf, -math.inf, None] + ) + ], + ) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + for compare in ORDERINGS: + for literal in doubles: + assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("a"), literal), pushed=True) + assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("a"), pl.col("x")), pushed=True) + + def test_float_against_a_sixteen_digit_decimal_is_not_pushed(self, duckdb_cursor, pushdowns): + # 99999999999999.99 and .98 share a double; pushed bare, the engine compares .99 with the double's shortest + # text, .98, and drops the row polars keeps + duckdb_cursor.execute("CREATE TABLE t (a DECIMAL(16,2))") + duckdb_cursor.execute("INSERT INTO t VALUES (99999999999999.99), (99999999999999.98), (1), (NULL)") + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + for compare in ORDERINGS: + predicate = compare(pl.col("a"), float(decimal.Decimal("99999999999999.99"))) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) + class TestConjunctPushdown: # The source pushes the conjuncts of a top level AND that translate and, when one stays behind, applies the whole # predicate in polars to every batch; a row the predicate keeps has every conjunct TRUE, which the engine keeps. - def test_tpch_q6_shape_pushes_the_translatable_conjuncts(self, duckdb_cursor, pushdowns): - duckdb_cursor.execute("CREATE TABLE t (id INTEGER, ship DATE, disc DECIMAL(15,2), qty DECIMAL(15,2))") + @pytest.mark.parametrize(("disc_type", "pushed"), [("DECIMAL(15,2)", True), ("DECIMAL(16,2)", "partly")]) + def test_tpch_q6_shape_pushes_the_translatable_conjuncts(self, disc_type, pushed, duckdb_cursor, pushdowns): + duckdb_cursor.execute(f"CREATE TABLE t (id INTEGER, ship DATE, disc {disc_type}, qty DECIMAL(15,2))") # Rows the pushed date and quantity bounds keep but a discount bound or a NULL discount removes, so only the # polars pass over the batch can drop them duckdb_cursor.execute( @@ -605,10 +700,13 @@ def test_tpch_q6_shape_pushes_the_translatable_conjuncts(self, duckdb_cursor, pu & (pl.col("disc") <= 0.07) & (pl.col("qty") < 24) ) - assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed="partly") - # polars compares a DECIMAL with a Python float through a Float64 cast of the column, which is refused - assert refused_columns(pushdowns) == ["disc", "disc"] + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=pushed) + # polars compares a DECIMAL with a Python float through a Float64 cast of the column, pushed up to 15 digits + assert refused_columns(pushdowns) == ([] if pushed is True else ["disc", "disc"]) + pushdowns.rows.clear() assert lazy_df.filter(predicate).collect()["id"].to_list() == [1, 5, 6, 12] + # Partly pushed, the seven rows inside the date and quantity bounds reach polars + assert sum(pushdowns.rows) == (4 if pushed is True else 7) def test_refused_conjunct_inside_or_keeps_the_rest_pushed(self, duckdb_cursor, pushdowns): duckdb_cursor.execute("CREATE TABLE t (id INTEGER, a INTEGER, b INTEGER, f FLOAT)") @@ -640,3 +738,304 @@ def test_partly_pushed_predicate_under_head_and_top_k(self, duckdb_cursor, pushd eager.sort("id", descending=True).head(3), ) pl_testing.assert_frame_equal(lazy_df.filter(predicate).select("i").collect(), eager.select("i")) + + +class TestModulusPushdown: + # polars' integer modulus takes the divisor's sign, the engine's % the dividend's + @pytest.mark.parametrize("divisor", [3, -3, -1, 2**40]) + @pytest.mark.parametrize("data_type", list(INTEGER_RANGES)) + def test_modulus_takes_the_divisors_sign(self, data_type, divisor, duckdb_cursor, pushdowns): + low, high = INTEGER_RANGES[data_type] + values = sorted({low, high, *(value for value in (-7, -1, 0, 1, 7) if low <= value <= high)}) + duckdb_cursor.execute(f"CREATE TABLE t (a {data_type})") + duckdb_cursor.executemany("INSERT INTO t VALUES (?)", [(value,) for value in [*values, None]]) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + floored = {value % divisor for value in values} + truncated = {abs(value) % abs(divisor) * (-1 if value < 0 else 1) for value in values} + # polars computes an unsigned 64 bit column against a negative divisor in Int64, through a narrowing cast + pushed = data_type != "UBIGINT" or divisor > 0 + for remainder in sorted(floored | truncated): + assert_pushdown_matches_polars(lazy_df, pushdowns, (pl.col("a") % divisor) == remainder, pushed=pushed) + + def test_modulus_with_a_negative_dividend(self, duckdb_cursor, pushdowns): + duckdb_cursor.execute("CREATE TABLE t (a INTEGER, s VARCHAR)") + duckdb_cursor.execute( + "INSERT INTO t VALUES (-1, 'x'), (2, 'x'), (-4, 'y'), (-7, 'x'), (5, 'x'), (3, 'x'), (NULL, 'x')" + ) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + # The engine's % gives -1 for -1 % 3 and for -1 % 2, which would drop the row + assert_pushdown_matches_polars(lazy_df, pushdowns, (pl.col("a") % 3) == 2, pushed=True) + predicate = ((pl.col("a") % 3) == 2) & pl.col("s").str.contains("x") + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed="partly") + assert lazy_df.filter(predicate).collect()["a"].to_list() == [-1, 2, -7, 5] + predicate = (pl.col("a").cast(pl.Int64) % 2) == 1 + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=True) + assert lazy_df.filter(predicate).collect()["a"].to_list() == [-1, -7, 5, 3] + + @pytest.mark.parametrize( + ("columns", "rows", "predicate"), + [ + pytest.param("a INTEGER", [(5,), (-5,), (None,)], (pl.col("a") % 0).is_null(), id="zero divisor"), + pytest.param( + "a INTEGER, b INTEGER", + [(5, 0), (-5, 3), (7, -3), (None, 1)], + (pl.col("a") % pl.col("b")) == 1, + id="column divisor", + ), + pytest.param("a DOUBLE", [(-1.5,), (1.5,), (None,)], (pl.col("a") % 1.0) == 0.5, id="DOUBLE"), + pytest.param( + "a DECIMAL(10,2)", + [("-1.50",), ("1.50",), (None,)], + (pl.col("a") % 1) == decimal.Decimal("0.5"), + id="DECIMAL", + marks=pytest.mark.skipif(not POLARS_2, reason="polars 1 has no decimal modulus"), + ), + pytest.param( + "a UBIGINT", + [(2**64 - 1,), (5,), (None,)], + (pl.col("a") % -3).is_null(), + id="UBIGINT by a negative divisor", + ), + ], + ) + def test_modulus_that_differs_is_not_pushed(self, columns, rows, predicate, duckdb_cursor, pushdowns): + # Pushed as the engine's %, each raises on a zero divisor or keeps rows polars drops + duckdb_cursor.execute(f"CREATE TABLE t ({columns})") + duckdb_cursor.executemany(f"INSERT INTO t VALUES ({', '.join('?' * len(rows[0]))})", rows) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + [tree] = assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) + assert "Modulus" in json.dumps(tree) + + @pytest.mark.parametrize( + ("dtype", "pushed"), + [(pl.Int32, True), (pl.UInt8, True), (pl.Float64, False), (pl.Decimal(10, 2), False), (pl.Boolean, False)], + ) + def test_modulus_dividend_type_on_hand_built_trees(self, dtype, pushed): + # polars pairs a float or decimal dividend with a divisor of its own type, so only a built tree reaches this + tree = { + "BinaryExpr": {"left": {"Column": "a"}, "op": "Modulus", "right": {"Literal": {"Scalar": {"Int32": 3}}}} + } + if pushed: + assert _pl_tree_to_sql(tree, {"a": dtype}).startswith('(CASE WHEN ("a" % 3) < 0') + else: + with pytest.raises(NotImplementedError): + _pl_tree_to_sql(tree, {"a": dtype}) + + def test_modulus_without_the_schema_is_not_pushed(self): + # Without the source schema an integer column cannot be told from a float or decimal one + assert _predicate_to_expression((pl.col("a") % 3) == 2) is None + + +class TestBooleanOperatorPushdown: + # polars applies & and | bitwise to integers and types them Boolean only between Booleans, where they are AND and + # OR, so they reach the engine only at the level of the predicate + def test_bitwise_and_or_is_not_pushed(self, duckdb_cursor, pushdowns): + duckdb_cursor.execute("CREATE TABLE t (a INTEGER, b INTEGER, s VARCHAR)") + duckdb_cursor.execute("INSERT INTO t VALUES (6, 3, 'x'), (4, 3, 'x'), (5, 2, 'y'), (8, 1, 'x'), (NULL, 1, 'x')") + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + # Pushed as AND and OR, the engine reads the integers as Booleans + for predicate in ( + (pl.col("a") & pl.col("b")) == 0, + ((pl.col("a") & pl.col("b")) == 0) & pl.col("s").str.contains("x"), + (pl.col("a") | pl.col("b")) == 7, + ): + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) + predicate = ((pl.col("a") & pl.col("b")) == 0) & (pl.col("a") > 4) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed="partly") + assert lazy_df.filter(predicate).collect().rows() == [(5, 2, "y"), (8, 1, "x")] + assert _predicate_to_expression((pl.col("a") & pl.col("b")) == 0) is None + + def test_logical_and_or_is_pushed(self, duckdb_cursor, pushdowns): + duckdb_cursor.execute("CREATE TABLE t (p BOOLEAN, q BOOLEAN, i INTEGER, s VARCHAR)") + duckdb_cursor.executemany( + "INSERT INTO t VALUES (?, ?, ?, ?)", + [ + (p, q, i, "x" if i % 2 else "y") + for i, (p, q) in enumerate(itertools.product([True, False, None], repeat=2)) + ], + ) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + # Both sides use three valued logic: TRUE OR NULL keeps a row, FALSE OR NULL drops it + assert_pushdown_matches_polars(lazy_df, pushdowns, pl.col("p") | pl.col("q"), pushed=True) + for predicate in ( + (pl.col("p") | pl.col("q")) & pl.col("s").str.contains("x"), + (pl.col("p") | (pl.col("q") & (pl.col("i") > 2))) & pl.col("s").str.contains("x"), + ): + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed="partly") + + +class TestDecimalLiteralPushdown: + @pytest.mark.parametrize( + ("unscaled", "scale"), + [ + (12345678901234567890123456789, 29), + (11111111111111111111111111111111111111, 38), + (10**37 + 1, 0), + (-1, 30), + (-5, 2), + (150, 2), + (0, 3), + ], + ) + def test_decimal_literal_renders_its_exact_value(self, unscaled, scale): + # Decimal arithmetic under the default context rounds past 28 digits and writes small and large values in + # exponent form, which the engine reads as a DOUBLE + sql = _pl_tree_to_sql({"Scalar": {"Decimal": [unscaled, 38, scale]}}) + value, data_type = duckdb.execute(f"SELECT {sql}, typeof({sql})").fetchone() + assert value == decimal.Decimal(f"{unscaled}E-{scale}") + assert data_type.startswith("DECIMAL" if scale else ("INTEGER", "BIGINT", "HUGEINT")), data_type + + @pytest.mark.parametrize( + ("data_type", "value", "neighbour"), + [ + ("DECIMAL(30,29)", "0.12345678901234567890123456789", "0.12345678901234567890123456788"), + # Untyped, the engine reads this literal, 39 digits with the zero before the point, as a DOUBLE + ("DECIMAL(38,38)", "0." + "1" * 38, "0." + "1" * 37 + "2"), + ("DECIMAL(38,0)", str(10**37 + 1), str(10**37)), + ("DECIMAL(38,30)", "-0." + "0" * 29 + "1", "-0." + "0" * 29 + "2"), + ("DECIMAL(15,2)", "1.5", "1.51"), + ], + ) + def test_decimal_literal_is_exact(self, data_type, value, neighbour, duckdb_cursor, pushdowns): + duckdb_cursor.execute(f"CREATE TABLE t (a {data_type}, s VARCHAR)") + duckdb_cursor.executemany( + "INSERT INTO t VALUES (?, ?)", [(value, "x"), (neighbour, "x"), (value, "y"), (None, "x")] + ) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + literal = decimal.Decimal(value) + for compare in ORDERINGS: + assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("a"), literal), pushed=True) + predicate = (pl.col("a") == literal) & pl.col("s").str.starts_with("x") + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed="partly") + assert lazy_df.filter(predicate).collect()["s"].to_list() == ["x"] + + @pytest.mark.parametrize( + ("columns", "rows", "predicate"), + [ + pytest.param( + "a DECIMAL(38,0)", [(str(10**38 - 1),), ("1",)], pl.col("a") < decimal.Decimal("0.5"), id="38,0 < 0.5" + ), + pytest.param( + "a DECIMAL(38,38)", [("0." + "9" * 38,), ("0.5",)], pl.col("a") < decimal.Decimal("1"), id="38,38 < 1" + ), + pytest.param( + "a DECIMAL(37,0)", [(str(10**37 - 1),), ("1",)], pl.col("a") < decimal.Decimal("0.05"), id="37,0 < 0.05" + ), + pytest.param( + "a DECIMAL(30,10)", + [("9" * 20 + "." + "9" * 10,), ("0",)], + pl.col("a") < decimal.Decimal("1E-19"), + id="30,10 < 1E-19", + ), + pytest.param("a HUGEINT", [(2**127 - 1,), (-5,)], pl.col("a") < decimal.Decimal("0.5"), id="HUGEINT < 0.5"), + pytest.param( + "a DECIMAL(10,2), b DECIMAL(38,0)", + [("1.50", str(10**37)), ("2.00", "1")], + pl.col("a") < pl.col("b"), + id="10,2 < 38,0 column", + ), + pytest.param( + "a DECIMAL(20,0), b DECIMAL(38,20)", + [(str(10**19), "1"), ("0", "1")], + pl.col("a").cast(pl.Decimal(38, 1)) > pl.col("b"), + id="20,0 raised to scale 1 > 38,20 column", + ), + ], + ) + def test_decimal_comparison_past_38_digits_is_not_pushed(self, columns, rows, predicate, duckdb_cursor, pushdowns): + # Refused until the engine compares such decimals: it clamps their common type to 38 digits and raises for a + # value that does not fit, where polars compares + duckdb_cursor.execute(f"CREATE TABLE t ({columns}, s VARCHAR)") + duckdb_cursor.executemany( + f"INSERT INTO t VALUES ({', '.join('?' * (len(rows[0]) + 1))})", + [(*row, "x") for row in [*rows, (None,) * len(rows[0])]], + ) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate & pl.col("s").str.contains("x"), pushed=False) + + def test_decimal_comparison_at_38_digits_is_pushed(self, duckdb_cursor, pushdowns): + duckdb_cursor.execute("CREATE TABLE t (a DECIMAL(37,0), s VARCHAR)") + duckdb_cursor.execute(f"INSERT INTO t VALUES ({10**37 - 1}, 'x'), (0, 'x'), (NULL, 'x')") + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + for compare in ORDERINGS: + assert_pushdown_matches_polars( + lazy_df, pushdowns, compare(pl.col("a"), decimal.Decimal("0.5")), pushed=True + ) + + +class TestColumnTypePushdown: + # UUID and JSON reach polars as a String, BIT as a Binary, TIME_NS and TIME WITH TIME ZONE as a Time, and HUGEINT + # and UHUGEINT, which hold 39 digits, as a Decimal(38, 0); the engine compares each by its own type and raises or + # keeps other rows than polars + @pytest.mark.parametrize( + ("data_type", "values", "predicate"), + [ + pytest.param( + "UUID", + ["a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "10eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"], + pl.col("a") > "B0000000-0000-0000-0000-000000000000", + id="UUID in text order", + ), + pytest.param( + "UUID", + ["a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "10eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"], + pl.col("a") == "abc", + id="UUID against text that is no UUID", + ), + pytest.param("JSON", ['{"a": 1}', "[1]"], pl.col("a") == "abc", id="JSON"), + pytest.param("BIT", ["0101", "1"], pl.col("a") == b"\x01", id="BIT"), + pytest.param("TIMETZ", ["12:00:00+05", "03:00:00+00"], pl.col("a") == datetime.time(12), id="TIMETZ"), + pytest.param("TIME_NS", ["12:00:00.000001", "11:00:00"], pl.col("a") > datetime.time(12), id="TIME_NS"), + pytest.param("UHUGEINT", [2**128 - 1, 5], pl.col("a") < 0, id="UHUGEINT"), + pytest.param("HUGEINT", [2**127 - 1, 5], pl.col("a") == 5, id="HUGEINT"), + ], + ) + def test_comparison_on_a_column_polars_reads_as_another_type_is_not_pushed( + self, data_type, values, predicate, duckdb_cursor, pushdowns + ): + duckdb_cursor.execute("SET TimeZone = 'UTC'") + duckdb_cursor.execute(f"CREATE TABLE t (a {data_type}, s VARCHAR)") + duckdb_cursor.executemany("INSERT INTO t VALUES (?, 'x')", [(value,) for value in [*values, None]]) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate & pl.col("s").str.contains("x"), pushed=False) + # A NULL test reads the same whatever the type + assert_pushdown_matches_polars(lazy_df, pushdowns, pl.col("a").is_null(), pushed=True) + + def test_hugeint_against_a_decimal_column_is_not_pushed(self, duckdb_cursor, pushdowns): + # Compared with a DECIMAL(20,0), the engine casts 2**127 - 1, a 39 digit HUGEINT, to DECIMAL(38,0) and raises + duckdb_cursor.execute("CREATE TABLE t (h HUGEINT, d DECIMAL(20,0), s VARCHAR)") + duckdb_cursor.executemany( + "INSERT INTO t VALUES (?, ?, 'x')", [(2**127 - 1, "1"), (5, "6"), (None, "1"), (1, None)] + ) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + predicate = pl.col("h") > pl.col("d") + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate & pl.col("s").str.contains("x"), pushed=False) + + +class TestCollationPushdown: + # polars compares text by its bytes, the engine by the column's or the session's collation unless told otherwise + @pytest.mark.parametrize( + ("column_type", "default_collation"), + [ + ("VARCHAR COLLATE NOCASE", None), + ("VARCHAR COLLATE NOACCENT", None), + ("VARCHAR", "nocase"), + ("mood", "nocase"), + ], + ) + def test_text_compares_by_its_bytes(self, column_type, default_collation, duckdb_cursor, pushdowns): + duckdb_cursor.execute("CREATE TYPE mood AS ENUM ('x', 'X', 'e', 'é', 'Y')") + if default_collation is not None: + duckdb_cursor.execute(f"SET default_collation = '{default_collation}'") + duckdb_cursor.execute(f"CREATE TABLE t (a {column_type}, s VARCHAR)") + duckdb_cursor.executemany( + "INSERT INTO t VALUES (?, ?)", [("x", "x"), ("X", "x"), ("e", "x"), ("é", "x"), (None, "x"), ("x", "y")] + ) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + for predicate in (pl.col("a") == "x", pl.col("a") == "e", pl.col("a") < "Y", pl.col("a") > "e"): + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=True) + partly = predicate & pl.col("s").str.contains("x") + assert_pushdown_matches_polars(lazy_df, pushdowns, partly, pushed="partly") From 808c19e02a3ea957457434beef8cea2861ad4b8c Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 15:01:47 +0000 Subject: [PATCH 23/61] Type a Float32 literal as FLOAT and compare UUID and JSON columns as their text --- duckdb/polars_io.py | 21 +++--- .../arrow/test_polars_pushdown_literals.py | 68 ++++++++++++++----- 2 files changed, 64 insertions(+), 25 deletions(-) diff --git a/duckdb/polars_io.py b/duckdb/polars_io.py index d93279090..87ce06760 100644 --- a/duckdb/polars_io.py +++ b/duckdb/polars_io.py @@ -293,17 +293,16 @@ def _decimal_digits(tree: _ExpressionTree, schema: Mapping[str, pl.DataType]) -> def _operand_to_sql(tree: _ExpressionTree, schema: Mapping[str, pl.DataType]) -> str: - """An operand of a comparison, a text column compared by its bytes as polars compares it. + """An operand of a comparison, a text column compared as its text and by its bytes, as polars compares it. - The engine applies the column's collation or the session's default collation to a text comparison, and an ENUM - compares as its text; binary collation keeps the scan filter and its pruning. + polars reads a UUID, a JSON and an ENUM column as their text, which the cast gives; the engine applies the column's + collation or the session's default collation to a text comparison. On a VARCHAR the engine drops the cast and the + binary collation, so the scan filter and its pruning stay. """ sql = _pl_tree_to_sql(tree, schema) column = tree.get("Column") dtype = schema.get(column) if isinstance(column, str) else None - if dtype == pl.String: - return f"({sql} COLLATE C)" - if isinstance(dtype, pl.Categorical): + if dtype == pl.String or isinstance(dtype, pl.Categorical): return f"(CAST({sql} AS VARCHAR) COLLATE C)" return sql @@ -539,6 +538,9 @@ def _pl_tree_to_sql(tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | N # JSON has no inf/nan, polars serializes them as null msg = f"Non-finite {dtype} literals cannot be pushed down" raise NotImplementedError(msg) + if dtype == "Float32": + # The engine reads a number with an exponent as a DOUBLE, which would compare a FLOAT column in DOUBLE + return f"CAST('{value[dtype]}' AS FLOAT)" return str(value[dtype]) # Time type @@ -597,7 +599,7 @@ def _pl_tree_to_sql(tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | N "UInt64": ("UBIGINT",), "Float32": ("FLOAT",), "Float64": ("DOUBLE",), - "String": ("VARCHAR",), + "String": ("VARCHAR", "UUID", "JSON"), "Binary": ("BLOB",), "Date": ("DATE",), "Time": ("TIME",), @@ -608,8 +610,9 @@ def _pl_tree_to_sql(tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | N def _stands_for(dtype: pl.DataType, engine_type: str) -> bool: """Whether the polars dtype of a column stands for the column's engine type, so both compare it alike. - UUID and JSON reach polars as a String, BIT as a Binary, TIME_NS and TIME WITH TIME ZONE as a Time, and HUGEINT - and UHUGEINT, which hold 39 digits, as a Decimal(38, 0); the engine compares each by its own type. + A UUID or JSON column reaches polars as its text, a String, which a comparison casts it to. BIT reaches polars as a + Binary, TIME_NS and TIME WITH TIME ZONE as a Time, and HUGEINT and UHUGEINT, which hold 39 digits, as a + Decimal(38, 0); the engine compares each of those by its own type. """ if isinstance(dtype, pl.Decimal): return engine_type == f"DECIMAL({dtype.precision},{dtype.scale})" diff --git a/tests/fast/arrow/test_polars_pushdown_literals.py b/tests/fast/arrow/test_polars_pushdown_literals.py index 717c440b1..65f2abc22 100644 --- a/tests/fast/arrow/test_polars_pushdown_literals.py +++ b/tests/fast/arrow/test_polars_pushdown_literals.py @@ -342,6 +342,24 @@ def test_literal_finer_than_a_microsecond_is_not_pushed(self, duckdb_cursor, pus assert_pushdown_matches_polars(lazy_df, pushdowns, compare(pl.col("t"), microsecond), pushed=True) +class TestFloat32LiteralPushdown: + def test_literal_in_exponent_form_compares_as_a_float(self, duckdb_cursor, pushdowns): + # The engine reads a number with an exponent as a DOUBLE; bare, 1.2345679e-05 compared the FLOAT column in + # DOUBLE, where the FLOAT value is not the literal, and dropped the row polars keeps + duckdb_cursor.execute("CREATE TABLE t (g FLOAT, s VARCHAR)") + duckdb_cursor.executemany( + "INSERT INTO t VALUES (?, ?)", + [(1.2345679e-05, "x"), (1e20, "x"), (0.5, "x"), (-3.5e-08, "x"), (1e20, "y"), (None, "x")], + ) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + for value in (1.2345679e-05, 1e20): + for compare in ORDERINGS: + predicate = compare(pl.col("g"), value) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=True) + partly = predicate & pl.col("s").str.contains("x") + assert_pushdown_matches_polars(lazy_df, pushdowns, partly, pushed="partly") + + class TestColumnCastPushdown: # A cast of the column, whether the user wrote it or polars inserted it to reconcile types, can truncate, turn an # overflow into NULL or change the type the comparison runs in, and the bare column carries none of that, so the @@ -965,25 +983,12 @@ def test_decimal_comparison_at_38_digits_is_pushed(self, duckdb_cursor, pushdown class TestColumnTypePushdown: - # UUID and JSON reach polars as a String, BIT as a Binary, TIME_NS and TIME WITH TIME ZONE as a Time, and HUGEINT - # and UHUGEINT, which hold 39 digits, as a Decimal(38, 0); the engine compares each by its own type and raises or - # keeps other rows than polars + # BIT reaches polars as a Binary, TIME_NS and TIME WITH TIME ZONE as a Time, and HUGEINT and UHUGEINT, which hold + # 39 digits, as a Decimal(38, 0); the engine compares each by its own type and raises or keeps other rows than + # polars @pytest.mark.parametrize( ("data_type", "values", "predicate"), [ - pytest.param( - "UUID", - ["a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "10eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"], - pl.col("a") > "B0000000-0000-0000-0000-000000000000", - id="UUID in text order", - ), - pytest.param( - "UUID", - ["a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "10eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"], - pl.col("a") == "abc", - id="UUID against text that is no UUID", - ), - pytest.param("JSON", ['{"a": 1}', "[1]"], pl.col("a") == "abc", id="JSON"), pytest.param("BIT", ["0101", "1"], pl.col("a") == b"\x01", id="BIT"), pytest.param("TIMETZ", ["12:00:00+05", "03:00:00+00"], pl.col("a") == datetime.time(12), id="TIMETZ"), pytest.param("TIME_NS", ["12:00:00.000001", "11:00:00"], pl.col("a") > datetime.time(12), id="TIME_NS"), @@ -1003,6 +1008,37 @@ def test_comparison_on_a_column_polars_reads_as_another_type_is_not_pushed( # A NULL test reads the same whatever the type assert_pushdown_matches_polars(lazy_df, pushdowns, pl.col("a").is_null(), pushed=True) + def test_uuid_and_json_compare_as_their_text(self, duckdb_cursor, pushdowns): + # polars reads both as their text; compared as a UUID or JSON, the engine raised on text that is neither and + # ordered and matched a UUID apart from its text + duckdb_cursor.execute("CREATE TABLE t (u UUID, j JSON, v VARCHAR, s VARCHAR)") + duckdb_cursor.execute( + """ + INSERT INTO t VALUES + ('a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', '{"a": 1}', 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', 'x'), + ('10eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', '[1]', 'zzz', 'x'), + ('ffffffff-ffff-ffff-ffff-ffffffffffff', '{"b": [1, 2]}', '1', 'y'), + (NULL, NULL, NULL, 'x') + """ + ) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + uuid, upper = "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "B0000000-0000-0000-0000-000000000000" + for predicate in ( + pl.col("u") == uuid, + pl.col("u") == uuid.upper(), + pl.col("u") == "abc", + pl.col("u") < upper, + pl.col("u") > upper, + pl.col("u") == pl.col("v"), + pl.col("u") < pl.col("v"), + pl.col("j") == '{"a": 1}', + pl.col("j") == "abc", + pl.col("j") < "[2", + ): + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=True) + partly = predicate & pl.col("s").str.contains("x") + assert_pushdown_matches_polars(lazy_df, pushdowns, partly, pushed="partly") + def test_hugeint_against_a_decimal_column_is_not_pushed(self, duckdb_cursor, pushdowns): # Compared with a DECIMAL(20,0), the engine casts 2**127 - 1, a 39 digit HUGEINT, to DECIMAL(38,0) and raises duckdb_cursor.execute("CREATE TABLE t (h HUGEINT, d DECIMAL(20,0), s VARCHAR)") From b504c5e38445d125bfe447d34bbc8123885ed5cd Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 15:12:55 +0000 Subject: [PATCH 24/61] Read a map() cell into an inferred type only when its kind fits, keep UNION a guess, confirm a guess by lossless widening, and cast MAP keys as values --- .../duckdb_python/numpy/numpy_scan.hpp | 18 +- .../duckdb_python/pandas/pandas_bind.hpp | 6 + src/map.cpp | 216 ++++-- src/native/python_conversion.cpp | 25 +- src/numpy/numpy_scan.cpp | 443 +++++++++++- tests/fast/pandas/test_append_df.py | 98 +++ tests/fast/test_map.py | 28 +- tests/fast/test_map_types.py | 677 +++++++++++++++++- 8 files changed, 1401 insertions(+), 110 deletions(-) diff --git a/src/include/duckdb_python/numpy/numpy_scan.hpp b/src/include/duckdb_python/numpy/numpy_scan.hpp index 2fdd8410a..940688b99 100644 --- a/src/include/duckdb_python/numpy/numpy_scan.hpp +++ b/src/include/duckdb_python/numpy/numpy_scan.hpp @@ -2,19 +2,33 @@ #include "duckdb_python/nb/casters.hpp" #include "duckdb/common/common.hpp" +#include "duckdb/common/types.hpp" namespace duckdb { struct PandasColumnBindData; +//! A cell of a declared column whose type was implied is not of that type's kind; source is the type the cell +//! converted to, and the caller reports it in the words of its own type check +struct ImpliedTypeRefused : public std::exception { + explicit ImpliedTypeRefused(LogicalType source_p) : source(std::move(source_p)) { + } + const char *what() const noexcept override { + return "a value is not of the kind of its column's implied type"; + } + LogicalType source; +}; + struct NumpyScan { static void Scan(ClientContext &context, PandasColumnBindData &bind_data, idx_t count, idx_t offset, Vector &out); //! masked holds one numpy bool per row of the whole column, read as a byte, or is null when the column has no mask static void ScanObjectColumn(ClientContext &context, PyObject **col, idx_t stride, const uint8_t *masked, idx_t count, idx_t offset, Vector &out); - //! Converts each cell into the declared type of the column as the appender converts a value + //! Converts each cell into the declared type of the column as the appender converts a value; with implied_type, + //! a cell that is not of the type's kind raises ImpliedTypeRefused, and with bit_storage_refused so does one + //! holding bytes where the type holds a BIT static void ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t stride, const uint8_t *masked, - idx_t count, idx_t offset, Vector &out); + idx_t count, idx_t offset, Vector &out, bool implied_type, bool bit_storage_refused); }; } // namespace duckdb diff --git a/src/include/duckdb_python/pandas/pandas_bind.hpp b/src/include/duckdb_python/pandas/pandas_bind.hpp index ee5a6c3cf..b201f044c 100644 --- a/src/include/duckdb_python/pandas/pandas_bind.hpp +++ b/src/include/duckdb_python/pandas/pandas_bind.hpp @@ -40,6 +40,12 @@ struct PandasColumnBindData { PythonObjectContainer object_str_val; //! The caller declared the column's type: each value converts into it as the appender converts a row bool declared = false; + //! Of a declared column: the caller implied the type rather than stating it, so a cell is read only when it is of + //! the type's kind, since a cast could change what it was + bool implied_type = false; + //! Of a declared column map() reads: a cell holding bytes where the type holds a BIT is refused, since df() hands + //! a BIT value to the function as its storage bytes + bool bit_storage_refused = false; }; //! The categories of a CategoricalDtype the caller built from an ENUM's values, in order diff --git a/src/map.cpp b/src/map.cpp index 4c8378d40..b73d286e7 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -13,6 +13,8 @@ #include "duckdb_python/dataframe.hpp" #include "duckdb_python/pyconnection/pyconnection.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" +#include "duckdb/common/type_visitor.hpp" +#include "duckdb_python/python_conversion.hpp" namespace duckdb { @@ -20,15 +22,31 @@ MapFunction::MapFunction() : TableFunction("python_map_function", {LogicalType:: in_out_function = MapFunctionExec; } +//! Where an output column's type came from, which decides how a chunk's column is read into it +enum class TypeSource : uint8_t { + //! The schema stated it, so an object column's values are cast into it whatever they hold + SCHEMA, + //! The empty bind frame typed the column, or the object input column of its name lent its type: an object + //! column's cells are read into it only when they are of its kind, since a function that changed what they hold + //! would otherwise see them cast back + INFERRED, + //! The input column of its name lent its type, but the function got that input typed, or as the member values of + //! a UNION, whose tags cannot travel: an object column is read into it only from cells of its kind, as an + //! inferred one is, and a typed column must have the type, or one that widens into it losslessly + GUESSED, + //! Nothing typed the column: it may hold only missing values + UNTYPED +}; + struct MapFunctionData : public TableFunctionData { explicit MapFunctionData(shared_ptr info_p) : info(std::move(info_p)) { } shared_ptr info; vector in_types, out_types; vector in_names, out_names; - //! Per output column, whether its type is only a guess from the typed input column of its name, which each chunk - //! must confirm, rather than imposed by the schema or an object input - vector guessed; + vector sources; + //! Per output column, the type a returned object column is read into, INVALID where the analyzer types it + vector declared_types; //! Per input column, the CategoricalDtype an ENUM column is handed over in, built once since it lists every value vector enum_dtypes; //! The categories of those dtypes with their ENUM types, by which a returned column of them reads its codes @@ -95,23 +113,44 @@ static optional_idx InputColumnNamed(const vector &input_names, cons } //! An object column of the empty bind frame has no values to type it, so it takes the type of the input column of its -//! name. That type is imposed when the function got the input as an object column too; from a typed input it is only -//! a guess, since the function may have moved the column to another type, and casting back would lose values. +//! name: inferred when the function got that input as an object column too, a guess otherwise (TypeSource). static void OverrideNullType(vector &return_types, const vector &return_names, const vector &input_types, const vector &input_names, - vector &guessed) { - guessed.assign(return_types.size(), false); + vector &sources) { + sources.clear(); for (idx_t col_idx = 0; col_idx < return_types.size(); col_idx++) { if (return_types[col_idx].id() != LogicalTypeId::SQLNULL) { + sources.push_back(TypeSource::INFERRED); continue; } auto input = InputColumnNamed(input_names, return_names[col_idx], col_idx); if (!input.IsValid()) { + sources.push_back(TypeSource::UNTYPED); continue; } auto &input_type = input_types[input.GetIndex()]; return_types[col_idx] = input_type; - guessed[col_idx] = RawArrayWrapper::DuckDBToNumpyDtype(input_type) != "object"; + auto object_input = RawArrayWrapper::DuckDBToNumpyDtype(input_type) == "object"; + auto lends_type = object_input && !TypeVisitor::Contains(input_type, LogicalTypeId::UNION); + sources.push_back(lends_type ? TypeSource::INFERRED : TypeSource::GUESSED); + } +} + +//! Every object column is declared, so the analyzer never reads one and no sample decides how a cell reads; an untyped +//! column is declared NULL, its check that it holds no value comes after the frame's own checks +static void DeclareTypes(MapFunctionData &data) { + data.declared_types.clear(); + for (idx_t col_idx = 0; col_idx < data.out_types.size(); col_idx++) { + switch (data.sources[col_idx]) { + case TypeSource::SCHEMA: + case TypeSource::INFERRED: + case TypeSource::GUESSED: + data.declared_types.push_back(data.out_types[col_idx]); + break; + case TypeSource::UNTYPED: + data.declared_types.push_back(LogicalType::SQLNULL); + break; + } } } @@ -149,7 +188,8 @@ unique_ptr BindExplicitSchema(unique_ptr function function_data->out_names = names; function_data->out_types = types; - function_data->guessed.assign(types.size(), false); + function_data->sources.assign(types.size(), TypeSource::SCHEMA); + DeclareTypes(*function_data); return std::move(function_data); } @@ -185,10 +225,11 @@ static unique_ptr BindMap(ClientContext &context, shared_ptr pandas_bind_data; // unused Pandas::Bind(context, df, pandas_bind_data, return_types, names, {}, data.known_enums); - OverrideNullType(return_types, names, data.in_types, data.in_names, data.guessed); + OverrideNullType(return_types, names, data.in_types, data.in_names, data.sources); data.out_names = names; data.out_types = return_types; + DeclareTypes(data); return std::move(data_uptr); } @@ -218,18 +259,79 @@ static string TypeVectorToString(const vector &types) { return StringUtil::Join(types, types.size(), ", ", [](const LogicalType &argument) { return argument.ToString(); }); } -//! A returned column the analyzer reads as all NULL binds as NULL, which holds for any type, as OverrideNullType -//! assumes at bind -static bool MatchesBoundTypes(const vector &returned, const vector &bound) { - D_ASSERT(returned.size() == bound.size()); - for (idx_t col_idx = 0; col_idx < returned.size(); col_idx++) { - if (returned[col_idx] != bound[col_idx] && returned[col_idx].id() != LogicalTypeId::SQLNULL) { - return false; +static InvalidInputException TypeMismatch(const MapFunctionData &data, const vector &returned) { + return InvalidInputException("UDF column type mismatch, expected [%s], got [%s]", + TypeVectorToString(data.out_types), TypeVectorToString(returned)); +} + +static bool IsTrue(const nb::object &object) { + auto truth = PyObject_IsTrue(object.ptr()); + if (truth < 0) { + throw nb::python_error(); + } + return truth; +} + +//! Whether a column bind could not type holds a value: pandas' missing values, numpy's masked constant and DuckDB's +//! NULL Values are none, as the conversion reads them all as NULL +static bool HoldsValue(const nb::object &column) { + auto present = column.attr("notna")(); + if (!IsTrue(present.attr("any")())) { + return false; + } + auto &import_cache = *DuckDBPyConnection::ImportCache(); + auto cells = nb::list(column.attr("__getitem__")(present).attr("tolist")()); + for (auto cell : cells) { + if (cell.is(import_cache.numpy.ma.masked())) { + continue; + } + if (!duckdb::PyUtil::IsInstance(cell, import_cache.duckdb.Value()) || + !TransformPythonValue(nullptr, cell).IsNull()) { + return true; } } + return false; +} + +static bool IntegerRange(const LogicalType &type, bool &is_signed, idx_t &width) { + switch (type.id()) { + case LogicalTypeId::TINYINT: + case LogicalTypeId::SMALLINT: + case LogicalTypeId::INTEGER: + case LogicalTypeId::BIGINT: + case LogicalTypeId::HUGEINT: + is_signed = true; + break; + case LogicalTypeId::UTINYINT: + case LogicalTypeId::USMALLINT: + case LogicalTypeId::UINTEGER: + case LogicalTypeId::UBIGINT: + case LogicalTypeId::UHUGEINT: + is_signed = false; + break; + default: + return false; + } + width = GetTypeIdSize(type.InternalType()); return true; } +//! Whether every value of one type is a value of the other: an integer into a wider one, a FLOAT into a DOUBLE +static bool WidensLosslessly(const LogicalType &from, const LogicalType &to) { + if (from.id() == LogicalTypeId::FLOAT && to.id() == LogicalTypeId::DOUBLE) { + return true; + } + bool from_signed, to_signed; + idx_t from_width, to_width; + if (!IntegerRange(from, from_signed, from_width) || !IntegerRange(to, to_signed, to_width)) { + return false; + } + if (from_signed) { + return to_signed && to_width >= from_width; + } + return to_signed ? to_width > from_width : to_width >= from_width; +} + static OperatorResultType ExecuteMap(ExecutionContext &context, TableFunctionInput &data_p, DataChunk &input, DataChunk &output) { if (input.size() == 0) { @@ -244,57 +346,38 @@ static OperatorResultType ExecuteMap(ExecutionContext &context, TableFunctionInp auto df = PandasScanFunction::PandasWithBoundNames(FunctionCall(data, conversion)); - auto column_count = nb::len(nb::object(df.attr("columns"))); - if (column_count != output.ColumnCount()) { - throw InvalidInputException("Expected %llu columns from UDF, got %llu", output.ColumnCount(), column_count); - } - // Before anything types the frame, which could fail on a value it cannot read - for (idx_t col_idx = 0; col_idx < output.ColumnCount(); col_idx++) { - if (data.out_types[col_idx].id() != LogicalTypeId::SQLNULL) { - continue; - } - auto column = df.attr("__getitem__")(nb::object(df.attr("columns"))[nb::int_(col_idx)]); - auto has_value = PyObject_IsTrue(nb::object(column.attr("notna")().attr("any")()).ptr()); - if (has_value < 0) { - throw nb::python_error(); - } - if (has_value) { - throw UntypedColumnError(data.out_names[col_idx]); - } - } - // An object column has no type of its own, only values, so it is read into the type the schema or an object input - // imposed, whatever its values. A guessed type and a column bind could not type, which holds only missing values - // here, are left to the analyzer. - vector declared_types; - for (idx_t col_idx = 0; col_idx < output.ColumnCount(); col_idx++) { - auto &type = data.out_types[col_idx]; - auto imposed = type.id() != LogicalTypeId::SQLNULL && !data.guessed[col_idx]; - declared_types.push_back(imposed ? type : LogicalType::INVALID); + auto labels = nb::list(nb::object(df.attr("columns"))); + if (labels.size() != output.ColumnCount()) { + throw InvalidInputException("Expected %llu columns from UDF, got %llu", output.ColumnCount(), labels.size()); } vector pandas_bind_data; vector pandas_return_types; vector pandas_names; auto row_count = Pandas::Bind(context.client, df, pandas_bind_data, pandas_return_types, pandas_names, - declared_types, data.known_enums); + data.declared_types, data.known_enums); + for (idx_t col_idx = 0; col_idx < output.ColumnCount(); col_idx++) { + pandas_bind_data[col_idx].implied_type = + data.sources[col_idx] == TypeSource::INFERRED || data.sources[col_idx] == TypeSource::GUESSED; + pandas_bind_data[col_idx].bit_storage_refused = true; + } - // A guess is only checked: a chunk of only missing values confirms nothing and reads NULL, any other type refutes - // it, and the analyzer's sample decides which, as it did before for every column. - vector missing_values(output.ColumnCount(), false); + // A typed column for a guess must have the guessed type, or one that widens losslessly into it and is cast after + // the read; an object column was declared the guess and reads only cells of its kind + vector widened(output.ColumnCount(), false); + auto checked_types = pandas_return_types; for (idx_t col_idx = 0; col_idx < output.ColumnCount(); col_idx++) { - if (!data.guessed[col_idx] || pandas_return_types[col_idx] == data.out_types[col_idx]) { + auto &returned = pandas_return_types[col_idx]; + auto &bound = data.out_types[col_idx]; + if (data.sources[col_idx] != TypeSource::GUESSED || returned == bound || !WidensLosslessly(returned, bound)) { continue; } - if (pandas_return_types[col_idx].id() != LogicalTypeId::SQLNULL) { - throw UntypedColumnError(data.out_names[col_idx]); - } - pandas_return_types[col_idx] = data.out_types[col_idx]; - missing_values[col_idx] = true; + widened[col_idx] = true; + checked_types[col_idx] = bound; } D_ASSERT(output.GetTypes() == data.out_types); - if (!MatchesBoundTypes(pandas_return_types, output.GetTypes())) { - throw InvalidInputException("UDF column type mismatch, expected [%s], got [%s]", - TypeVectorToString(data.out_types), TypeVectorToString(pandas_return_types)); + if (checked_types != output.GetTypes()) { + throw TypeMismatch(data, pandas_return_types); } if (pandas_names != data.out_names) { throw InvalidInputException("UDF column name mismatch, expected [%s], got [%s]", @@ -304,18 +387,25 @@ static OperatorResultType ExecuteMap(ExecutionContext &context, TableFunctionInp if (row_count > STANDARD_VECTOR_SIZE) { throw InvalidInputException("UDF returned more than %llu rows, which is not allowed.", STANDARD_VECTOR_SIZE); } + for (idx_t col_idx = 0; col_idx < output.ColumnCount(); col_idx++) { + if (data.sources[col_idx] == TypeSource::UNTYPED && HoldsValue(df.attr("__getitem__")(labels[col_idx]))) { + throw UntypedColumnError(data.out_names[col_idx]); + } + } for (idx_t col_idx = 0; col_idx < output.ColumnCount(); col_idx++) { - // A guessed column whose chunk holds only missing values, and a column bind left untyped, the only one still - // typed NULL here; the bound type's scanner would read some missing values as data, such as NaT as 'NaT'. - if (missing_values[col_idx] || pandas_return_types[col_idx].id() == LogicalTypeId::SQLNULL) { + if (pandas_return_types[col_idx].id() == LogicalTypeId::SQLNULL) { ConstantVector::SetNull(output.data[col_idx], count_t(row_count)); continue; } auto &bind_data = pandas_bind_data[col_idx]; - Vector temp(output.data[col_idx].GetType(), row_count); + Vector temp(pandas_return_types[col_idx], row_count); try { PandasScanFunction::PandasBackendScanSwitch(context.client, bind_data, row_count, 0, temp); + } catch (ImpliedTypeRefused &refused) { + auto returned = pandas_return_types; + returned[col_idx] = refused.source; + throw TypeMismatch(data, returned); } catch (std::exception &ex) { ErrorData error(ex); // The cast's own message names no column; a Python error keeps the traceback its message starts with @@ -325,7 +415,11 @@ static OperatorResultType ExecuteMap(ExecutionContext &context, TableFunctionInp } error.Throw(StringUtil::Format("UDF column '%s': ", data.out_names[col_idx].c_str())); } - VectorOperations::Copy(temp, output.data[col_idx], row_count, 0, 0); + if (widened[col_idx]) { + VectorOperations::Cast(context.client, temp, output.data[col_idx], row_count); + } else { + VectorOperations::Copy(temp, output.data[col_idx], row_count, 0, 0); + } } output.SetChildCardinality(row_count); return OperatorResultType::NEED_MORE_INPUT; diff --git a/src/native/python_conversion.cpp b/src/native/python_conversion.cpp index 5a86ae445..cd3be7408 100644 --- a/src/native/python_conversion.cpp +++ b/src/native/python_conversion.cpp @@ -5,6 +5,7 @@ #include "duckdb_python/pyresult.hpp" #include "duckdb_python/pyconnection/pyconnection.hpp" #include "duckdb/common/types.hpp" +#include "duckdb/common/type_visitor.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/list_vector.hpp" #include "duckdb/common/vector/array_vector.hpp" @@ -151,12 +152,15 @@ Value TransformDictionaryToStruct(optional_ptr context, const PyD dict.ToString(), target_type.ToString()); }; bool struct_target = StructType::IsStruct(target_type); - if (struct_target && dict.len != StructType::GetChildCount(target_type)) { + // A target holding UNKNOWN gives only the shape of the values below it: the dict's own keys name the fields, as + // without a target, and each value converts with the shape of the field of its name + bool shape_only = struct_target && TypeVisitor::Contains(target_type, LogicalTypeId::UNKNOWN); + if (struct_target && !shape_only && dict.len != StructType::GetChildCount(target_type)) { throw conversion_error(); } child_list_t struct_values; - if (StructType::IsUnnamed(target_type)) { + if (!shape_only && StructType::IsUnnamed(target_type)) { // A TUPLE has no member names, so its members take the dict's values in dict order. for (idx_t i = 0; i < dict.len; i++) { auto val = TransformPythonValue(context, dict.values.attr("__getitem__")(i), @@ -167,10 +171,16 @@ Value TransformDictionaryToStruct(optional_ptr context, const PyD } auto struct_keys = TransformStructKeys(dict.keys, dict.len); - if (!struct_target) { + if (!struct_target || shape_only) { for (idx_t i = 0; i < dict.len; i++) { - auto val = - TransformPythonValue(context, dict.values.attr("__getitem__")(i), LogicalType::UNKNOWN, nan_as_null); + LogicalType child_type = LogicalType::UNKNOWN; + for (idx_t child = 0; shape_only && child < StructType::GetChildCount(target_type); child++) { + if (StructType::GetChildName(target_type, child) == struct_keys[i]) { + child_type = StructType::GetChildType(target_type, child); + break; + } + } + auto val = TransformPythonValue(context, dict.values.attr("__getitem__")(i), child_type, nan_as_null); struct_values.emplace_back(make_pair(std::move(struct_keys[i]), std::move(val))); } return Value::STRUCT(std::move(struct_values)); @@ -241,10 +251,11 @@ Value TransformStructFormatDictionaryToMap(optional_ptr context, elements.push_back(Value::STRUCT(std::move(struct_values))); } - if (key_type.id() == LogicalTypeId::SQLNULL) { + // A target holding UNKNOWN asks for no type there, and a MAP of such a type is no value the engine can hold + if (key_type.id() == LogicalTypeId::SQLNULL && !TypeVisitor::Contains(key_target, LogicalTypeId::UNKNOWN)) { key_type = key_target; } - if (value_type.id() == LogicalTypeId::SQLNULL) { + if (value_type.id() == LogicalTypeId::SQLNULL && !TypeVisitor::Contains(value_target, LogicalTypeId::UNKNOWN)) { value_type = value_target; } diff --git a/src/numpy/numpy_scan.cpp b/src/numpy/numpy_scan.cpp index d9ff6fe90..9242efadc 100644 --- a/src/numpy/numpy_scan.cpp +++ b/src/numpy/numpy_scan.cpp @@ -4,6 +4,7 @@ #include "duckdb_python/python_conversion.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/swar.hpp" +#include "duckdb/common/type_visitor.hpp" #include "duckdb/common/types/timestamp.hpp" #include "duckdb/common/vector/struct_vector.hpp" #include "duckdb/common/vector/list_vector.hpp" @@ -329,7 +330,11 @@ static nb::object NumpyScalarValue(nb::handle scalar) { return scalar.attr("item")(); } -static Value DeclaredValue(ClientContext &context, const LogicalType &target, nb::handle cell) { +//! With a shape (KeyedShape) the cell converts with it as its target, which a type holding a MAP needs: without it a +//! dict reads as a STRUCT named by its keys' text, and a key whose text does not cast back, such as bytes, is lost. +//! An object without a DuckDB type reads as its text into a stated VARCHAR, and has no kind for an implied one. +static Value DeclaredValue(ClientContext &context, const LogicalType &target, nb::handle cell, + optional_ptr shape, bool implied) { if (cell.ptr() == Py_None) { return Value(); } @@ -337,13 +342,36 @@ static Value DeclaredValue(ClientContext &context, const LogicalType &target, nb auto value = NumpyScalarValue(cell); // A long double's item() is a numpy scalar again; one step, then the conversion refuses what is left if (!IsNumpyScalar(value)) { - return DeclaredValue(context, target, value); + return DeclaredValue(context, target, value, shape, implied); } } - if (target.id() == LogicalTypeId::VARCHAR && GetPythonObjectType(cell) == PythonObjectType::Other) { + if (!implied && target.id() == LogicalTypeId::VARCHAR && GetPythonObjectType(cell) == PythonObjectType::Other) { return Value(TransformPythonString(nb::str(cell))); } - return TransformPythonValue(context, cell, LogicalType::UNKNOWN, true); + return TransformPythonValue(context, cell, shape ? *shape : LogicalType(LogicalTypeId::UNKNOWN), true); +} + +//! The type a cell of a type holding a MAP converts with: its containers and no other type, so a dict builds its MAP +//! from its keys and values in the types they have in Python, and every key and value meets the engine's cast with +//! the connection's settings, as a TIMESTAMPTZ in the session time zone +static LogicalType KeyedShape(const LogicalType &type) { + switch (type.id()) { + case LogicalTypeId::STRUCT: { + child_list_t children; + for (idx_t i = 0; i < StructType::GetChildCount(type); i++) { + children.emplace_back(StructType::GetChildName(type, i), KeyedShape(StructType::GetChildType(type, i))); + } + return LogicalType::STRUCT(std::move(children)); + } + case LogicalTypeId::LIST: + return LogicalType::LIST(KeyedShape(ListType::GetChildType(type))); + case LogicalTypeId::ARRAY: + return LogicalType::ARRAY(KeyedShape(ArrayType::GetChildType(type)), ArrayType::GetSize(type)); + case LogicalTypeId::MAP: + return LogicalType::MAP(KeyedShape(MapType::KeyType(type)), KeyedShape(MapType::ValueType(type))); + default: + return LogicalType::UNKNOWN; + } } //! The values of one vector of a declared column, written once the cells are read: a vector whose values share one @@ -358,6 +386,7 @@ class DeclaredVector { //! A row the scan wrote into the output itself, which Write leaves as it is void MarkWritten(idx_t row) { written[row] = true; + written_count++; } void Set(idx_t row, Value value) { @@ -373,6 +402,9 @@ class DeclaredVector { } void Write(ClientContext &context, Vector &out, idx_t count) { + if (written_count == count) { + return; + } auto &target = out.GetType(); if (uniform && source.id() != LogicalTypeId::SQLNULL && source != target) { idx_t present = 0; @@ -429,10 +461,370 @@ class DeclaredVector { private: vector values; vector written; + idx_t written_count = 0; LogicalType source; bool uniform = true; }; +//! Whether the value a cell of a column whose type was implied, not stated, converted to is of that type's kind: it +//! is the type, or each of its parts is of the kind of the type's part in the same place, by the rules below, so a +//! function that changed what a column holds is refused, not cast back. The check reads the converted value, so it +//! judges exactly what the write would read. +class ImpliedKinds { +public: + explicit ImpliedKinds(ClientContext &context) : context(context) { + } + + bool Fits(const Value &value, const LogicalType &type) { + if (value.IsNull()) { + return true; + } + auto &source = value.type(); + if (source == type) { + return true; + } + for (auto &entry : seen) { + if (entry.source == source) { + return entry.verdict == Verdict::FITS || + (entry.verdict == Verdict::BY_VALUE && FitsByValue(value, type)); + } + } + auto verdict = Judge(source, type); + if (seen.size() < CACHED_SOURCE_TYPES) { + seen.push_back({source, verdict}); + } + return verdict == Verdict::FITS || (verdict == Verdict::BY_VALUE && FitsByValue(value, type)); + } + +private: + //! BY_VALUE: the kinds agree, but whether the type holds the value depends on the value (an integer, a DECIMAL) + enum class Verdict : uint8_t { FITS, REFUSED, BY_VALUE }; + + static Verdict Combine(Verdict a, Verdict b) { + if (a == Verdict::REFUSED || b == Verdict::REFUSED) { + return Verdict::REFUSED; + } + return a == Verdict::BY_VALUE || b == Verdict::BY_VALUE ? Verdict::BY_VALUE : Verdict::FITS; + } + + //! The field of a STRUCT type a key names, or INVALID; the engine's STRUCT cast matches names ignoring case + static optional_idx FieldNamed(const LogicalType &type, const Identifier &name) { + for (idx_t i = 0; i < StructType::GetChildCount(type); i++) { + if (StructType::GetChildName(type, i) == name) { + return i; + } + } + return optional_idx(); + } + + //! The unit of a naive time or timestamp type, finer the higher, or 0 for any other type + static idx_t NaiveUnit(LogicalTypeId id) { + switch (id) { + case LogicalTypeId::TIMESTAMP_SEC: + return 1; + case LogicalTypeId::TIMESTAMP_MS: + return 2; + case LogicalTypeId::TIMESTAMP: + return 3; + case LogicalTypeId::TIMESTAMP_NS: + return 4; + case LogicalTypeId::TIME: + return 13; + case LogicalTypeId::TIME_NS: + return 14; + default: + return 0; + } + } + + static bool IsZoned(LogicalTypeId id) { + return id == LogicalTypeId::TIME_TZ || id == LogicalTypeId::TIMESTAMP_TZ || + id == LogicalTypeId::TIMESTAMP_TZ_NS; + } + + static bool IsNested(const LogicalType &type) { + return type.IsNested() || type.id() == LogicalTypeId::UNION; + } + + Verdict Judge(const LogicalType &source, const LogicalType &type) { + if (source == type || source.id() == LogicalTypeId::SQLNULL) { + return Verdict::FITS; + } + switch (type.id()) { + case LogicalTypeId::STRUCT: { + if (source.id() != LogicalTypeId::STRUCT) { + return Verdict::REFUSED; + } + // A key the STRUCT does not name, or a second key for one field, would be dropped by the cast; a field + // without a key reads NULL + vector claimed(StructType::GetChildCount(type), false); + auto verdict = Verdict::FITS; + for (idx_t i = 0; i < StructType::GetChildCount(source); i++) { + auto field = FieldNamed(type, StructType::GetChildName(source, i)); + if (!field.IsValid() || claimed[field.GetIndex()]) { + return Verdict::REFUSED; + } + claimed[field.GetIndex()] = true; + verdict = Combine(verdict, Judge(StructType::GetChildType(source, i), + StructType::GetChildType(type, field.GetIndex()))); + } + return verdict; + } + // The engine casts any MAP into any MAP implicitly without looking at its key and value types + case LogicalTypeId::MAP: + if (source.id() != LogicalTypeId::MAP) { + return Verdict::REFUSED; + } + return Combine(Judge(MapType::KeyType(source), MapType::KeyType(type)), + Judge(MapType::ValueType(source), MapType::ValueType(type))); + case LogicalTypeId::LIST: + if (source.id() != LogicalTypeId::LIST) { + return Verdict::REFUSED; + } + return Judge(ListType::GetChildType(source), ListType::GetChildType(type)); + case LogicalTypeId::ARRAY: + // A Python list reads as a LIST, which the cast takes into an ARRAY of its length or refuses + if (source.id() == LogicalTypeId::LIST) { + return Judge(ListType::GetChildType(source), ArrayType::GetChildType(type)); + } + if (source.id() != LogicalTypeId::ARRAY) { + return Verdict::REFUSED; + } + return Judge(ArrayType::GetChildType(source), ArrayType::GetChildType(type)); + default: + break; + } + if (IsNested(source) || IsNested(type)) { + return Verdict::REFUSED; + } + // A naive value and one with a time zone are of different kinds: the cast between them reads the wall time in + // the session's time zone + if (IsZoned(source.id()) != IsZoned(type.id())) { + return Verdict::REFUSED; + } + // A time or timestamp of another unit holds only the values the cast keeps unchanged: a coarser unit rounds, + // and a finer one covers fewer years + auto source_unit = NaiveUnit(source.id()); + auto unit = NaiveUnit(type.id()); + if (source_unit && unit && source_unit / 10 == unit / 10) { + return source_unit == unit ? Verdict::FITS : Verdict::BY_VALUE; + } + auto zoned_timestamps = + (source.id() == LogicalTypeId::TIMESTAMP_TZ || source.id() == LogicalTypeId::TIMESTAMP_TZ_NS) && + (type.id() == LogicalTypeId::TIMESTAMP_TZ || type.id() == LogicalTypeId::TIMESTAMP_TZ_NS); + if (zoned_timestamps || (source.id() == LogicalTypeId::VARCHAR && type.id() == LogicalTypeId::VARCHAR) || + (source.id() == LogicalTypeId::DOUBLE && type.id() == LogicalTypeId::FLOAT)) { + return Verdict::FITS; + } + // df() hands a BIT value over as its storage bytes, which the cast from BLOB reads as eight bits per byte + if (source.id() == LogicalTypeId::BLOB && type.id() == LogicalTypeId::BIT) { + return Verdict::REFUSED; + } + // A number fits an integer or a DECIMAL when the cast into it and back gives the number again, whatever kind of + // number it was in Python: 2.0 and Decimal(5) are the integer 2 and 5, 2.5 is none + if (source.IsIntegral() && type.IsIntegral()) { + return CastFunctionSet::ImplicitCastCost(context, source, type) >= 0 ? Verdict::FITS : Verdict::BY_VALUE; + } + if (source.id() == LogicalTypeId::DECIMAL && type.id() == LogicalTypeId::DECIMAL) { + auto source_scale = DecimalType::GetScale(source); + auto scale = DecimalType::GetScale(type); + auto fits = source_scale <= scale && + DecimalType::GetWidth(source) - source_scale <= DecimalType::GetWidth(type) - scale; + return fits ? Verdict::FITS : Verdict::BY_VALUE; + } + auto number = source.IsIntegral() || source.id() == LogicalTypeId::DECIMAL || + source.id() == LogicalTypeId::DOUBLE || source.id() == LogicalTypeId::FLOAT; + if (number && (type.IsIntegral() || type.id() == LogicalTypeId::DECIMAL)) { + return Verdict::BY_VALUE; + } + return CastFunctionSet::ImplicitCastCost(context, source, type) >= 0 ? Verdict::FITS : Verdict::REFUSED; + } + + bool FitsByValue(const Value &value, const LogicalType &type) { + if (value.IsNull()) { + return true; + } + auto &source = value.type(); + switch (Judge(source, type)) { + case Verdict::FITS: + return true; + case Verdict::REFUSED: + return false; + case Verdict::BY_VALUE: + break; + } + switch (type.id()) { + case LogicalTypeId::STRUCT: { + auto &children = StructValue::GetChildren(value); + for (idx_t i = 0; i < children.size(); i++) { + auto field = FieldNamed(type, StructType::GetChildName(source, i)); + if (!FitsByValue(children[i], StructType::GetChildType(type, field.GetIndex()))) { + return false; + } + } + return true; + } + case LogicalTypeId::MAP: + for (auto &entry : MapValue::GetChildren(value)) { + auto &pair = StructValue::GetChildren(entry); + if (!FitsByValue(pair[0], MapType::KeyType(type)) || !FitsByValue(pair[1], MapType::ValueType(type))) { + return false; + } + } + return true; + case LogicalTypeId::LIST: + case LogicalTypeId::ARRAY: { + auto &child = + type.id() == LogicalTypeId::LIST ? ListType::GetChildType(type) : ArrayType::GetChildType(type); + auto &children = + source.id() == LogicalTypeId::LIST ? ListValue::GetChildren(value) : ArrayValue::GetChildren(value); + for (auto &element : children) { + if (!FitsByValue(element, child)) { + return false; + } + } + return true; + } + default: { + if ((source.id() == LogicalTypeId::DOUBLE || source.id() == LogicalTypeId::FLOAT) && + !FloatHoldsItsText(value, type)) { + return false; + } + // The type holds the value when the cast into it and back gives the value again + auto cast = value.DefaultTryCastAs(type); + if (!cast) { + return false; + } + auto back = cast->DefaultTryCastAs(source); + return back && Value::NotDistinctFrom(*back, value); + } + } + } + +public: + //! Whether a value holds bytes where the type holds a BIT, at any depth: df() hands a BIT value over as its + //! storage bytes, which no cast reads back, whether or not the type was stated + static bool HoldsBitStorage(const Value &value, const LogicalType &type) { + if (value.IsNull()) { + return false; + } + auto &source = value.type(); + switch (type.id()) { + case LogicalTypeId::BIT: + return source.id() == LogicalTypeId::BLOB; + case LogicalTypeId::STRUCT: { + if (source.id() != LogicalTypeId::STRUCT) { + return false; + } + auto &children = StructValue::GetChildren(value); + for (idx_t i = 0; i < children.size(); i++) { + auto field = FieldNamed(type, StructType::GetChildName(source, i)); + if (field.IsValid() && HoldsBitStorage(children[i], StructType::GetChildType(type, field.GetIndex()))) { + return true; + } + } + return false; + } + case LogicalTypeId::MAP: + if (source.id() != LogicalTypeId::MAP) { + return false; + } + for (auto &entry : MapValue::GetChildren(value)) { + auto &pair = StructValue::GetChildren(entry); + if (HoldsBitStorage(pair[0], MapType::KeyType(type)) || + HoldsBitStorage(pair[1], MapType::ValueType(type))) { + return true; + } + } + return false; + case LogicalTypeId::LIST: + case LogicalTypeId::ARRAY: { + if (source.id() != LogicalTypeId::LIST && source.id() != LogicalTypeId::ARRAY) { + return false; + } + auto &child = + type.id() == LogicalTypeId::LIST ? ListType::GetChildType(type) : ArrayType::GetChildType(type); + auto &children = + source.id() == LogicalTypeId::LIST ? ListValue::GetChildren(value) : ArrayValue::GetChildren(value); + for (auto &element : children) { + if (HoldsBitStorage(element, child)) { + return true; + } + } + return false; + } + default: + return false; + } + } + +private: + //! The significant digits of a number's shortest text ("2.0" has one, "1e+20" twenty one): from its first digit + //! that is not zero to its last, or to the units when its integer part ends in zeros + static idx_t SignificantDigits(const string &text) { + string digits; + int64_t integer_digits = 0; + bool point = false; + idx_t i = 0; + for (; i < text.size() && text[i] != 'e' && text[i] != 'E'; i++) { + if (text[i] == '.') { + point = true; + } else if (StringUtil::CharacterIsDigit(text[i])) { + digits += text[i]; + integer_digits += point ? 0 : 1; + } + } + int64_t exponent = i < text.size() ? std::stoll(text.substr(i + 1)) : 0; + auto units = integer_digits + exponent; + auto end = static_cast(digits.size()); + while (end > MaxValue(units, 0) && digits[NumericCast(end - 1)] == '0') { + end--; + } + int64_t start = 0; + while (start < end && digits[NumericCast(start)] == '0') { + start++; + } + if (start == end) { + return 0; + } + return NumericCast(MaxValue(end, units) - start); + } + + //! A double holds every decimal of at most 15 significant digits exactly enough to give it back as its shortest + //! text, so a float whose text has more may be a rounding already: df() hands a HUGEINT or a DECIMAL over as a + //! float64. And the engine's cast of a float into a DECIMAL rounds the value times 10**scale in double precision, + //! which for a wide scale is no longer that value (2.0 reads 2.000000000000000039769249677312 in a DECIMAL(38,30), + //! exactly in a DECIMAL(38,20)), so the float fits only when the cast gives the value of its text. + static bool FloatHoldsItsText(const Value &value, const LogicalType &type) { + auto number = value.GetValue(); + if (!Value::DoubleIsFinite(number)) { + return false; + } + auto text = Value::DOUBLE(number).ToString(); + if (SignificantDigits(text) > MAX_EXACT_FLOAT_DIGITS) { + return false; + } + if (type.id() != LogicalTypeId::DECIMAL) { + return true; + } + auto cast = value.DefaultTryCastAs(type); + auto exact = Value(text).DefaultTryCastAs(type); + return cast && exact && Value::NotDistinctFrom(*cast, *exact); + } + + struct Seen { + LogicalType source; + Verdict verdict; + }; + //! DBL_DIG: every decimal of this many significant digits survives a round trip through a double + static constexpr idx_t MAX_EXACT_FLOAT_DIGITS = 15; + //! Bounded like DeclaredCasts, since dicts give a STRUCT type per key set + static constexpr idx_t CACHED_SOURCE_TYPES = 16; + + ClientContext &context; + vector seen; +}; + // A column without a mask takes the instantiation that tests no mask bits, so it reads like the plain array template static void ScanObjectRows(PyObject **col, idx_t stride, const uint8_t *masked, idx_t count, idx_t offset, Vector &out, @@ -471,18 +863,51 @@ static void ScanObjectCells(ClientContext &context, PyObject **col, idx_t stride } void NumpyScan::ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t stride, const uint8_t *masked, - idx_t count, idx_t offset, Vector &out) { + idx_t count, idx_t offset, Vector &out, bool implied_type, + bool bit_storage_refused) { DeclaredVector staged(count); auto &target = out.GetType(); - // A str into plain VARCHAR reads as TransformPythonValue would read it, without building a Value per cell + const auto keyed = TypeVisitor::Contains(target, LogicalTypeId::MAP); + const auto holds_bit = TypeVisitor::Contains(target, LogicalTypeId::BIT); + const auto shape = keyed ? KeyedShape(target) : LogicalType(LogicalTypeId::UNKNOWN); + // A str into VARCHAR without an alias, and bytes or a bytearray into BLOB without one, read as TransformPythonValue + // would read them, without building a Value per cell; a collation governs comparison only, an alias such as JSON + // validates the text in its cast const bool plain_text = target == LogicalType::VARCHAR; + const bool plain_blob = target == LogicalType::BLOB; + ImpliedKinds kinds(context); ScanObjectCells(context, col, stride, masked, count, offset, out, [&](nb::handle cell, idx_t row) { if (plain_text && PyUnicode_CheckExact(cell.ptr())) { - FlatVector::GetDataMutable(out)[row] = StringVector::AddString(out, TransformPythonString(cell)); + Py_ssize_t size; + auto text = PyUnicode_AsUTF8AndSize(cell.ptr(), &size); + if (!text) { + ThrowUnencodableStr(cell); + } + FlatVector::GetDataMutable(out)[row] = + StringVector::AddString(out, text, NumericCast(size)); staged.MarkWritten(row); return; } - staged.Set(row, DeclaredValue(context, target, cell)); + // df() hands a BLOB cell to the function as a bytearray + if (plain_blob && (PyBytes_CheckExact(cell.ptr()) || PyByteArray_CheckExact(cell.ptr()))) { + auto bytes = PyBytes_CheckExact(cell.ptr()); + auto data = bytes ? PyBytes_AS_STRING(cell.ptr()) : PyByteArray_AS_STRING(cell.ptr()); + auto size = bytes ? PyBytes_GET_SIZE(cell.ptr()) : PyByteArray_GET_SIZE(cell.ptr()); + FlatVector::GetDataMutable(out)[row] = + StringVector::AddStringOrBlob(out, data, NumericCast(size)); + staged.MarkWritten(row); + return; + } + auto value = DeclaredValue(context, target, cell, keyed ? &shape : nullptr, implied_type); + // A duckdb.Value states its type, as a schema does, so a cast into the column's type is meant + if (implied_type && !kinds.Fits(value, target) && + !duckdb::PyUtil::IsInstance(cell, DuckDBPyConnection::ImportCache()->duckdb.Value())) { + throw ImpliedTypeRefused(value.type()); + } + if (bit_storage_refused && holds_bit && ImpliedKinds::HoldsBitStorage(value, target)) { + throw ImpliedTypeRefused(value.type()); + } + staged.Set(row, std::move(value)); }); staged.Write(context, out, count); VerifyTypeConstraints(out, count); @@ -761,7 +1186,7 @@ void NumpyScan::Scan(ClientContext &context, PandasColumnBindData &bind_data, id const bool is_object_col = bind_data.numpy_type.type == NumpyNullableType::OBJECT; if (is_object_col && bind_data.declared) { return NumpyScan::ScanDeclaredColumn(context, src_ptr, numpy_col.stride, MaskedRows(bind_data), count, - offset, out); + offset, out, bind_data.implied_type, bind_data.bit_storage_refused); } if (is_object_col && out.GetType().id() != LogicalTypeId::VARCHAR) { //! We have determined the underlying logical type of this object column diff --git a/tests/fast/pandas/test_append_df.py b/tests/fast/pandas/test_append_df.py index 0f3099f86..66007b6b6 100644 --- a/tests/fast/pandas/test_append_df.py +++ b/tests/fast/pandas/test_append_df.py @@ -2,6 +2,7 @@ import enum import math import pathlib +import re import zoneinfo from decimal import Decimal @@ -422,6 +423,97 @@ def test_keys_that_collapse_in_a_nested_map_are_refused(self, duckdb_cursor): with pytest.raises(duckdb.InvalidInputException, match=r"(?i)duplicat|unique"): duckdb_cursor.append("t", frame) + @pytest.mark.parametrize( + ("key_type", "key"), + [ + pytest.param("BLOB", b"\x00ab", id="bytes"), + pytest.param("INTERVAL", datetime.timedelta(days=1), id="timedelta"), + ], + ) + def test_dict_key_whose_text_does_not_cast_back_keeps_its_value_in_a_map(self, duckdb_cursor, key_type, key): + duckdb_cursor.execute(f"CREATE TABLE t (a MAP({key_type}, INTEGER), b STRUCT(m MAP({key_type}, INTEGER)))") + frame = pd.DataFrame( + {"a": pd.Series([{key: 1}, None], dtype=object), "b": pd.Series([{"m": {key: 2}}, None], dtype=object)} + ) + duckdb_cursor.append("t", frame) + assert duckdb_cursor.table("t").fetchall() == [({key: 1}, {"m": {key: 2}}), (None, None)] + + @pytest.mark.parametrize( + ("target", "cell", "expected"), + [ + pytest.param("MAP(VARCHAR, INTEGER)", {"k": None}, {"k": None}, id="scalar_values"), + pytest.param("MAP(VARCHAR, STRUCT(x INTEGER))", {"k": None}, {"k": None}, id="struct_values"), + pytest.param("MAP(VARCHAR, MAP(BLOB, INTEGER))", {"k": {b"z": None}}, {"k": {b"z": None}}, id="nested_map"), + ], + ) + def test_map_of_only_null_values_appends_them(self, duckdb_cursor, target, cell, expected): + duckdb_cursor.execute(f"CREATE TABLE t (a {target})") + duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series([cell], dtype=object)})) + assert duckdb_cursor.table("t").fetchall() == [(expected,)] + + @pytest.mark.parametrize( + "value", [datetime.datetime(2024, 5, 6, 12, 0), "2024-05-06 12:00:00"], ids=["naive_datetime", "text"] + ) + def test_map_value_into_timestamptz_reads_in_the_session_time_zone(self, duckdb_cursor, value): + duckdb_cursor.execute("SET TimeZone = 'Europe/Amsterdam'") + duckdb_cursor.execute("CREATE TABLE t (a MAP(VARCHAR, TIMESTAMPTZ))") + duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series([{"k": value}], dtype=object)})) + assert duckdb_cursor.sql("SELECT a['k']::VARCHAR FROM t").fetchall() == [("2024-05-06 12:00:00+02",)] + + @pytest.mark.parametrize( + ("target", "key", "expected"), + [ + pytest.param("TIMESTAMP_NS", datetime.datetime(2020, 1, 1), "{'2020-01-01 00:00:00'=1}", id="timestamp_ns"), + pytest.param("TIMESTAMP_MS", datetime.datetime(2020, 1, 1), "{'2020-01-01 00:00:00'=1}", id="timestamp_ms"), + pytest.param("TIMESTAMP_S", datetime.datetime(2020, 1, 1), "{'2020-01-01 00:00:00'=1}", id="timestamp_s"), + pytest.param("DATE", datetime.datetime(2020, 1, 1, 5), "{2020-01-01=1}", id="date_from_datetime"), + pytest.param( + "TIMESTAMPTZ", datetime.datetime(2020, 1, 1), "{'2020-01-01 00:00:00-05'=1}", id="timestamptz_naive" + ), + pytest.param("TIMESTAMPTZ", "2020-01-01 00:00:00", "{'2020-01-01 00:00:00-05'=1}", id="timestamptz_text"), + pytest.param("DECIMAL(9,2)", 1.257, "{1.26=1}", id="decimal_from_float"), + ], + ) + def test_map_key_meets_the_cast_in_the_session_settings(self, duckdb_cursor, target, key, expected): + duckdb_cursor.execute("SET TimeZone = 'America/New_York'") + duckdb_cursor.execute(f"CREATE TABLE t (a MAP({target}, INTEGER))") + duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series([{key: 1}], dtype=object)})) + assert duckdb_cursor.sql("SELECT a::VARCHAR FROM t").fetchall() == [(expected,)] + + @pytest.mark.parametrize( + ("target", "key", "expected"), + [ + # The engine's cast reads the instant in the session's time zone; the base dropped the offset + pytest.param( + "TIMESTAMP", + datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc), + "{'2019-12-31 19:00:00'=1}", + id="aware_datetime_into_timestamp", + ), + # The cast from BLOB gives the bytes' text; the base gave the text of the Python bytes object + pytest.param("VARCHAR", b"x", "{x=1}", id="bytes_into_varchar"), + pytest.param("STRUCT(a INTEGER)", (1,), "{{'a': 1}=1}", id="tuple_into_struct"), + ], + ) + def test_map_key_reads_as_the_cast_from_its_python_type_gives_it(self, duckdb_cursor, target, key, expected): + duckdb_cursor.execute("SET TimeZone = 'America/New_York'") + duckdb_cursor.execute(f"CREATE TABLE t (a MAP({target}, INTEGER))") + duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series([{key: 1}], dtype=object)})) + assert duckdb_cursor.sql("SELECT a::VARCHAR FROM t").fetchall() == [(expected,)] + + def test_map_keys_a_str_and_its_bytes_are_one_key_and_refused(self, duckdb_cursor): + duckdb_cursor.execute("CREATE TABLE t (a MAP(VARCHAR, INTEGER))") + frame = pd.DataFrame({"a": pd.Series([{"a": 1, b"a": 2}], dtype=object)}) + with pytest.raises(duckdb.InvalidInputException, match=re.escape("Map keys must be unique")): + duckdb_cursor.append("t", frame) + + def test_map_key_of_none_is_refused_and_the_connection_stays_usable(self, duckdb_cursor): + duckdb_cursor.execute("CREATE TABLE t (a MAP(VARCHAR, INTEGER))") + with pytest.raises(duckdb.Error) as error: + duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series([{None: 1}], dtype=object)})) + assert not isinstance(error.value, duckdb.FatalException), error.value + assert duckdb_cursor.sql("SELECT 42").fetchall() == [(42,)] + def test_text_with_a_lone_surrogate_names_it(self, duckdb_cursor): duckdb_cursor.execute("CREATE TABLE t (a VARCHAR)") frame = pd.DataFrame({"a": _outside_the_sample("a", pathlib.PurePosixPath("/\udcff"))}) @@ -443,6 +535,12 @@ def test_text_column_mixing_str_with_other_cells_appends_each_as_text(self, duck ("\u00e9 \U0001f600",), ] + def test_blob_column_mixing_bytes_with_other_cells_appends_each(self, duckdb_cursor): + duckdb_cursor.execute("CREATE TABLE t (a BLOB)") + cells = [b"a", bytearray(b"b"), None, memoryview(b"c"), b"\x00d", "e"] + duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series(cells, dtype=object)})) + assert duckdb_cursor.table("t").fetchall() == [(b"a",), (b"b",), (None,), (b"c",), (b"\x00d",), (b"e",)] + def test_text_with_a_lone_surrogate_in_a_str_names_it(self, duckdb_cursor): duckdb_cursor.execute("CREATE TABLE t (a VARCHAR)") frame = pd.DataFrame({"a": pd.Series(["a", "b\udcff"], dtype=object)}) diff --git a/tests/fast/test_map.py b/tests/fast/test_map.py index dec9c5409..ea5142ff9 100644 --- a/tests/fast/test_map.py +++ b/tests/fast/test_map.py @@ -393,9 +393,25 @@ def replace(df): ) -@MAP_SCHEMAS -@pytest.mark.xfail( - strict=True, reason="not built: a fractional value outside the chunk's sample is converted with loss into INTEGER" +@pytest.mark.parametrize( + "schema", + [ + pytest.param( + None, + id="inferred", + marks=pytest.mark.xfail( + strict=True, reason="not built: the refusal of a fractional value names neither its row nor the float" + ), + ), + pytest.param( + {"a": duckdb.sqltypes.INTEGER}, + id="explicit_schema", + marks=pytest.mark.xfail( + strict=True, + reason="not built: a fractional value outside the chunk's sample is converted with loss into INTEGER", + ), + ), + ], ) def test_map_fractional_value_outside_the_chunk_sample_raises(duckdb_cursor, schema): duckdb_cursor.execute("set threads = 1") @@ -652,12 +668,14 @@ def missing_on_rows(df): assert mapped.fetchall() == [(None,), (None,), (None,)] -def test_map_returned_object_column_with_a_value_of_another_type_raises_the_casts_error(duckdb_cursor): +def test_map_returned_object_column_with_a_value_of_another_type_still_mismatches(duckdb_cursor): def text_on_rows(df): return df.assign(a=pd.Series(["x"] + [None] * (len(df) - 1), dtype=object)) if len(df) else df mapped = duckdb_cursor.sql("select i as a from range(3) t(i)").map(text_on_rows) - with pytest.raises(duckdb.ConversionException, match=re.escape("Could not convert string 'x' to INT64")): + with pytest.raises( + duckdb.InvalidInputException, match=re.escape("UDF column type mismatch, expected [BIGINT], got [VARCHAR]") + ): mapped.fetchall() diff --git a/tests/fast/test_map_types.py b/tests/fast/test_map_types.py index 8672d4cac..59c45892f 100644 --- a/tests/fast/test_map_types.py +++ b/tests/fast/test_map_types.py @@ -1,6 +1,10 @@ """map() fixes one type per output column at bind and reads each chunk's returned column into it.""" +import datetime +import json import re +from decimal import Decimal +from fractions import Fraction import pytest from conftest import PANDAS_GE_3 @@ -89,7 +93,9 @@ def test_map_enum_column_compares_with_its_text(duckdb_cursor): pytest.param("MAP(INTEGER, INTEGER)", "map([i::INTEGER], [i::INTEGER])", id="MAP_INTEGER_keys"), pytest.param("MAP(VARCHAR, BIGINT)", "map([i::VARCHAR], [i::BIGINT])", id="MAP_BIGINT_values"), pytest.param("INTEGER[2]", "[i, i]::INTEGER[2]", id="ARRAY"), - pytest.param("UNION(a INTEGER, b VARCHAR)", "i::INTEGER::UNION(a INTEGER, b VARCHAR)", id="UNION"), + pytest.param("MAP(BLOB, INTEGER)", "map([i::VARCHAR::BLOB], [i::INTEGER])", id="MAP_BLOB_keys"), + pytest.param("MAP(INTERVAL, INTEGER)", "map([to_days(i::INTEGER)], [i::INTEGER])", id="MAP_INTERVAL_keys"), + pytest.param("MAP(VARCHAR, STRUCT(x INTEGER))", "map(['k'], [NULL::STRUCT(x INTEGER)])", id="MAP_NULL_values"), pytest.param("TIME_NS", "'01:00:00'::TIME_NS", id="TIME_NS"), pytest.param( "STRUCT(a INTEGER[], b MAP(VARCHAR, INTEGER))", @@ -107,6 +113,54 @@ def test_map_identity_returns_an_object_column_in_its_own_type(duckdb_cursor, sq assert mapped.fetchall() == source.fetchall() +UNION_AB = "UNION(a INTEGER, b VARCHAR)" +UNION_OVERLAPPING = "UNION(a INTEGER, b BIGINT)" +# The function gets a UNION's member values only, so the tags cannot reach the result through it. +UNION_ROWS = pytest.mark.parametrize( + ("sql_type", "rows", "returned", "tags_cast"), + [ + pytest.param( + UNION_AB, + f"(union_value(a := 1)::{UNION_AB}), (union_value(b := 'x')::{UNION_AB}), (NULL::{UNION_AB})", + "INTEGER", + [("a", 1), ("b", "x"), (None, None)], + id="both_members", + ), + pytest.param( + UNION_AB, + f"(union_value(a := 1)::{UNION_AB}), (union_value(b := NULL::VARCHAR)::{UNION_AB})", + "INTEGER", + [("a", 1), (None, None)], + id="null_member", + ), + pytest.param( + UNION_OVERLAPPING, + f"(union_value(a := 1)::{UNION_OVERLAPPING}), (union_value(b := 7::BIGINT)::{UNION_OVERLAPPING})", + "INTEGER", + [("a", 1), ("a", 7)], + id="overlapping_members", + ), + ], +) + + +@UNION_ROWS +def test_map_identity_of_a_union_column_is_refused(duckdb_cursor, sql_type, rows, returned, tags_cast): + mapped = duckdb_cursor.sql(f"select * from (values {rows}) t(u)").map(lambda df: df) + expected = f"Invalid Input Error: UDF column type mismatch, expected [{sql_type}], got [{returned}]" + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +@UNION_ROWS +def test_map_union_column_in_the_schema_casts_each_member_value(duckdb_cursor, sql_type, rows, returned, tags_cast): + # The cast picks the member for each value, so a NULL member reads as a NULL UNION and 7 as the INTEGER member. + source = duckdb_cursor.sql(f"select * from (values {rows}) t(u)") + mapped = source.map(lambda df: df, schema={"u": duckdb.sqltype(sql_type)}) + assert mapped.types == source.types + assert mapped.project("union_tag(u), u").fetchall() == tags_cast + + @SCHEMAS def test_map_identity_returns_a_struct_whose_field_is_null_across_a_chunk(duckdb_cursor, explicit_schema): duckdb_cursor.execute("set threads = 1") @@ -217,6 +271,397 @@ def test_map_struct_cell_without_a_field_reads_it_as_null(duckdb_cursor, row): assert mapped.fetchall() == expected +@ODD_ROWS +def test_map_struct_cell_without_a_field_in_a_type_holding_a_map_reads_it_as_null(duckdb_cursor, row): + duckdb_cursor.execute("set threads = 1") + source = duckdb_cursor.sql("select {'x': i::INTEGER, 'm': map(['k'], [i::INTEGER])} as a from range(2048) t(i)") + mapped = source.map(_odd_cell_at(row, {"x": 3})) + expected = [({"x": 3, "m": None} if i == row else {"x": i, "m": {"k": i}},) for i in range(2048)] + assert mapped.types == source.types + assert mapped.fetchall() == expected + + +def _apply_to_a(convert): + return lambda df: df.assign(a=df["a"].apply(convert)) + + +CHANGED_IN_KIND = pytest.mark.parametrize( + ("source", "function", "sql_type", "returned"), + [ + pytest.param( + "{'x': i::BIGINT}", + _apply_to_a(lambda d: {"x": str(d["x"]).zfill(5)}), + "STRUCT(x BIGINT)", + "STRUCT(x VARCHAR)", + id="struct_field_turned_into_text", + ), + pytest.param( + "[i::INTEGER]", + _apply_to_a(lambda values: [str(v).zfill(5) for v in values]), + "INTEGER[]", + "VARCHAR[]", + id="list_elements_turned_into_text", + ), + pytest.param( + """'{"k": ' || i || '}'""", + _apply_to_a(json.loads), + "VARCHAR", + "STRUCT(k INTEGER)", + id="text_parsed_as_json", + ), + pytest.param( + "i", + _apply_to_a(lambda v: Decimal(int(v)) / 3), + "BIGINT", + "DECIMAL(28,28)", + id="integers_divided_as_decimals", + ), + pytest.param( + "map([i::INTEGER], [i::INTEGER])", + _apply_to_a(lambda m: {str(k).zfill(3): v for k, v in m.items()}), + "MAP(INTEGER, INTEGER)", + "MAP(VARCHAR, INTEGER)", + id="map_keys_turned_into_text", + ), + pytest.param( + "{'x': i::TINYINT}", + _apply_to_a(lambda d: {"x": d["x"] + 300}), + "STRUCT(x TINYINT)", + "STRUCT(x INTEGER)", + id="struct_field_outside_its_type", + ), + pytest.param( + "[i::INTEGER]", + _apply_to_a(lambda values: np.asarray(values, dtype=np.float64) / 2), + "INTEGER[]", + "DOUBLE[]", + id="list_given_as_a_float_array", + ), + pytest.param( + "{'x': i::BIGINT}", + _apply_to_a(lambda d: {"x": d["x"], "y": 1}), + "STRUCT(x BIGINT)", + "STRUCT(x INTEGER, y INTEGER)", + id="struct_given_a_key_it_does_not_name", + ), + pytest.param( + "{'t': TIMESTAMP '2020-01-01'}", + _apply_to_a(lambda d: {"t": np.datetime64("2020-01-01T00:00:00", "ns")}), + "STRUCT(t TIMESTAMP)", + "STRUCT(t BIGINT)", + id="nanosecond_datetime64_field", + ), + # A float of more than 15 significant digits, or one the cast into a wide scale rounds in double precision + pytest.param( + "{'x': i::BIGINT}", + _apply_to_a(lambda d: {"x": 9007199254740992.0}), + "STRUCT(x BIGINT)", + "STRUCT(x DOUBLE)", + id="float_of_16_digits", + ), + pytest.param( + "{'x': i::DECIMAL(38,30)}", + _apply_to_a(lambda d: {"x": 0.1}), + "STRUCT(x DECIMAL(38,30))", + "STRUCT(x DOUBLE)", + id="float_the_cast_rounds_at_a_wide_scale", + ), + pytest.param( + "{'x': i::BIGINT}", + _apply_to_a(lambda d: {"x": d["x"], "X": 2}), + "STRUCT(x BIGINT)", + "STRUCT(x INTEGER, X INTEGER)", + id="struct_given_two_keys_for_one_field", + ), + ], +) + + +@CHANGED_IN_KIND +def test_map_column_whose_cells_the_function_changed_in_kind_is_refused( + duckdb_cursor, source, function, sql_type, returned +): + mapped = duckdb_cursor.sql(f"select {source} as a from range(3) t(i)").map(function) + expected = f"Invalid Input Error: UDF column type mismatch, expected [{sql_type}], got [{returned}]" + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +NEW_YORK = "SET TimeZone = 'America/New_York'" +UTC = datetime.timezone.utc + + +@pytest.mark.parametrize( + ("source", "function", "sql_type", "returned"), + [ + # df() hands the elements over as naive UTC datetimes + pytest.param( + "[TIMESTAMPTZ '2020-01-01 12:00:00+00']", + lambda df: df, + "TIMESTAMP WITH TIME ZONE[]", + "TIMESTAMP[]", + id="list_of_timestamptz_identity", + ), + pytest.param( + "{'t': TIMESTAMP '2020-01-01 12:00:00'}", + _apply_to_a(lambda d: {"t": datetime.datetime(2020, 1, 1, 12, tzinfo=UTC)}), + "STRUCT(t TIMESTAMP)", + "STRUCT(t TIMESTAMP WITH TIME ZONE)", + id="aware_datetime_for_timestamp", + ), + pytest.param( + "{'t': TIMESTAMPTZ '2020-01-01 12:00:00+00'}", + _apply_to_a(lambda d: {"t": datetime.datetime(2020, 1, 1, 7)}), + "STRUCT(t TIMESTAMP WITH TIME ZONE)", + "STRUCT(t TIMESTAMP)", + id="naive_datetime_for_timestamptz", + ), + pytest.param( + "{'t': TIME '01:00:00'}", + _apply_to_a(lambda d: {"t": datetime.time(1, tzinfo=UTC)}), + "STRUCT(t TIME)", + "STRUCT(t TIME WITH TIME ZONE)", + id="aware_time_for_time", + ), + pytest.param( + "{'t': TIMETZ '01:00:00+00'}", + _apply_to_a(lambda d: {"t": datetime.time(1)}), + "STRUCT(t TIME WITH TIME ZONE)", + "STRUCT(t TIME)", + id="naive_time_for_timetz", + ), + ], +) +def test_map_value_with_a_time_zone_and_one_without_are_of_different_kinds( + duckdb_cursor, source, function, sql_type, returned +): + duckdb_cursor.execute(NEW_YORK) + mapped = duckdb_cursor.sql(f"select {source} as a from range(1) t(i)").map(function) + expected = f"Invalid Input Error: UDF column type mismatch, expected [{sql_type}], got [{returned}]" + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +@pytest.mark.parametrize( + ("source", "function", "sql_type", "returned"), + [ + pytest.param( + "{'t': '2020-01-01'::TIMESTAMP_S}", + _apply_to_a(lambda d: {"t": datetime.datetime(2020, 1, 1, 0, 0, 0, 500000)}), + "STRUCT(t TIMESTAMP_S)", + "STRUCT(t TIMESTAMP)", + id="milliseconds_for_seconds", + ), + pytest.param( + "{'t': '2020-01-01'::TIMESTAMP_MS}", + _apply_to_a(lambda d: {"t": datetime.datetime(2020, 1, 1, 0, 0, 0, 1)}), + "STRUCT(t TIMESTAMP_MS)", + "STRUCT(t TIMESTAMP)", + id="a_microsecond_for_milliseconds", + ), + pytest.param( + "{'t': TIME '01:00:00'}", + _apply_to_a(lambda d: {"t": duckdb.Value("01:00:00.000000001", duckdb.sqltype("TIME_NS"))}), + "STRUCT(t TIME)", + "STRUCT(t TIME_NS)", + id="a_nanosecond_for_microseconds", + ), + ], +) +def test_map_time_value_finer_than_its_column_keeps_only_values_the_unit_holds( + duckdb_cursor, source, function, sql_type, returned +): + mapped = duckdb_cursor.sql(f"select {source} as a from range(1) t(i)").map(function) + expected = f"Invalid Input Error: UDF column type mismatch, expected [{sql_type}], got [{returned}]" + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +def test_map_time_value_outside_the_range_of_its_columns_unit_is_refused(duckdb_cursor): + # TIMESTAMP_NS covers the years 1677 to 2262 only + mapped = duckdb_cursor.sql("select {'t': '2020-01-01'::TIMESTAMP_NS} as a from range(1) t(i)").map( + _apply_to_a(lambda d: {"t": datetime.datetime(1500, 1, 1)}) + ) + expected = ( + "Invalid Input Error: UDF column type mismatch, expected [STRUCT(t TIMESTAMP_NS)], got [STRUCT(t TIMESTAMP)]" + ) + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +# df() hands a LIST of HUGEINT or DECIMAL over as float64 elements, and a float of more than 15 significant digits +# may already have rounded the value it came from +@pytest.mark.parametrize( + ("values", "sql_type"), + [ + pytest.param("[1152921504606846977::HUGEINT]", "HUGEINT[]", id="hugeint_beyond_2_53"), + pytest.param("[123456789012345678901::HUGEINT]", "HUGEINT[]", id="hugeint_beyond_bigint"), + pytest.param("[1152921504606846977::HUGEINT, NULL]", "HUGEINT[]", id="hugeint_with_a_null"), + pytest.param("[1234567890123456.78::DECIMAL(18,2)]", "DECIMAL(18,2)[]", id="decimal_of_18_digits"), + ], +) +def test_map_identity_of_a_list_whose_floats_may_have_rounded_is_refused(duckdb_cursor, values, sql_type): + mapped = duckdb_cursor.sql(f"select {values} as a").map(lambda df: df) + expected = f"Invalid Input Error: UDF column type mismatch, expected [{sql_type}], got [DOUBLE[]]" + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +@pytest.mark.parametrize( + "values", + [ + pytest.param("[5::HUGEINT, NULL, (-999999999999999)::HUGEINT]", id="hugeint_of_15_digits"), + pytest.param("[1.25::DECIMAL(9,2), NULL, 0.1::DECIMAL(9,2)]", id="decimal"), + ], +) +def test_map_identity_of_a_list_whose_floats_hold_their_values_round_trips(duckdb_cursor, values): + source = duckdb_cursor.sql(f"select {values} as a") + mapped = source.map(lambda df: df) + assert mapped.types == source.types + assert mapped.fetchall() == source.fetchall() + + +def test_map_decimal_column_handed_back_as_objects_of_18_digits_is_refused(duckdb_cursor): + # df() hands a DECIMAL column over as float64, which rounds 1234567890123456.78 + source = duckdb_cursor.sql("select 1234567890123456.78::DECIMAL(18,2) as a") + mapped = source.map(lambda df: df.assign(a=df["a"].astype(object))) + expected = "Invalid Input Error: UDF column type mismatch, expected [DECIMAL(18,2)], got [DOUBLE]" + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +@pytest.mark.parametrize( + ("source", "cell", "expected"), + [ + pytest.param( + "{'t': '2020-01-01'::TIMESTAMP_S}", + datetime.datetime(2020, 1, 1, 0, 0, 3), + datetime.datetime(2020, 1, 1, 0, 0, 3), + id="whole_seconds_into_seconds", + ), + pytest.param( + "{'t': '2020-01-01'::TIMESTAMP_NS}", + datetime.datetime(2020, 1, 1, 0, 0, 0, 7), + datetime.datetime(2020, 1, 1, 0, 0, 0, 7), + id="microseconds_into_nanoseconds", + ), + pytest.param( + "{'t': TIME '01:00:00'}", + duckdb.Value("01:00:00.000001000", duckdb.sqltype("TIME_NS")), + datetime.time(1, 0, 0, 1), + id="whole_microseconds_into_microseconds", + ), + pytest.param( + "{'t': '01:00:00'::TIME_NS}", + datetime.time(2, 0, 0, 5), + datetime.time(2, 0, 0, 5), + id="time_into_nanoseconds", + ), + ], +) +def test_map_time_value_its_column_unit_holds_reads_unchanged(duckdb_cursor, source, cell, expected): + relation = duckdb_cursor.sql(f"select {source} as a from range(1) t(i)") + mapped = relation.map(_apply_to_a(lambda d: {"t": cell})) + assert mapped.types == relation.types + assert mapped.fetchall() == [({"t": expected},)] + + +@pytest.mark.parametrize( + ("source", "function", "expected"), + [ + pytest.param("[1, 2]", _apply_to_a(lambda values: [1, True]), [1, 1], id="int_and_bool_list"), + pytest.param( + "map(['a'], ['x'])", _apply_to_a(lambda m: {"a": 1, "b": "x"}), {"a": "1", "b": "x"}, id="int_and_str_map" + ), + ], +) +def test_map_container_of_mixed_elements_reads_as_the_conversion_types_it(duckdb_cursor, source, function, expected): + # The conversion types a list or a MAP by the common type of its elements; the base refused these + relation = duckdb_cursor.sql(f"select {source} as a from range(1) t(i)") + mapped = relation.map(function) + assert mapped.types == relation.types + assert mapped.fetchall() == [(expected,)] + + +@pytest.mark.parametrize( + "value", + [ + pytest.param("{'t': TIMESTAMPTZ '2020-01-01 12:00:00+00'}", id="struct_field"), + pytest.param("map(['k'], [TIMESTAMPTZ '2020-01-01 12:00:00+00'])", id="map_value"), + pytest.param("{'t': TIMETZ '01:00:00+02'}", id="timetz_field"), + ], +) +def test_map_identity_of_a_zoned_value_keeps_its_instant_in_another_session_time_zone(duckdb_cursor, value): + duckdb_cursor.execute(NEW_YORK) + source = duckdb_cursor.sql(f"select {value} as a") + mapped = source.map(lambda df: df) + assert mapped.types == source.types + assert mapped.project("a::VARCHAR").fetchall() == source.project("a::VARCHAR").fetchall() + + +@SCHEMAS +def test_map_numpy_scalar_inside_a_struct_raises_the_conversions_error(duckdb_cursor, explicit_schema): + source = duckdb_cursor.sql("select {'x': i::INTEGER} as a from range(1) t(i)") + mapped = source.map(_apply_to_a(lambda d: {"x": np.int64(5)}), schema=_schema_of(source, explicit_schema)) + expected = ( + "Not implemented Error: UDF column 'a': Unable to transform python value of type " + "'' to DuckDB LogicalType" + ) + with pytest.raises(duckdb.NotImplementedException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +def test_map_column_whose_cells_changed_in_kind_casts_into_the_schema_type(duckdb_cursor): + mapped = duckdb_cursor.sql("select i as a from range(3) t(i)").map( + _apply_to_a(lambda v: Decimal(int(v)) / 3), schema=BIGINT_A + ) + assert mapped.fetchall() == [(0,), (0,), (1,)] + + +@pytest.mark.parametrize( + ("source", "function", "expected"), + [ + pytest.param("{'x': i::TINYINT}", _apply_to_a(lambda d: {"x": d["x"] + 100}), {"x": 100}, id="int_that_fits"), + pytest.param("[i::DOUBLE]", _apply_to_a(lambda values: [int(v) for v in values]), [0.0], id="int_into_double"), + pytest.param("{'x': i::FLOAT}", _apply_to_a(lambda d: {"x": d["x"] / 2}), {"x": 0.0}, id="float_into_float"), + pytest.param( + "{'x': i::DECIMAL(9,2)}", _apply_to_a(lambda d: {"x": Decimal("1.5")}), {"x": Decimal("1.50")}, id="decimal" + ), + pytest.param( + "{'x': i::BIGINT}", _apply_to_a(lambda d: {"X": d["x"]}), {"x": 0}, id="field_named_in_other_case" + ), + pytest.param( + "map([i::INTEGER], [i::INTEGER])", + _apply_to_a(lambda m: {k + 5: v for k, v in m.items()}), + {5: 0}, + id="map_keys_of_their_kind", + ), + pytest.param( + "[i::INTEGER]", _apply_to_a(lambda values: np.asarray(values, dtype=np.int64) + 3), [3], id="int64_array" + ), + pytest.param( + "[i::DOUBLE]", _apply_to_a(lambda values: np.asarray(values, dtype=np.float32)), [0.0], id="float32_array" + ), + pytest.param("{'x': i::BIGINT}", _apply_to_a(lambda d: {"x": Decimal(5)}), {"x": 5}, id="integral_decimal"), + pytest.param("{'x': i::BIGINT}", _apply_to_a(lambda d: {"x": 2.0}), {"x": 2}, id="integral_float_for_bigint"), + pytest.param( + "{'x': i::DECIMAL(18,2)}", + _apply_to_a(lambda d: {"x": 1234567890123.45}), + {"x": Decimal("1234567890123.45")}, + id="float_of_15_digits", + ), + pytest.param( + "{'x': i::DECIMAL(9,2)}", _apply_to_a(lambda d: {"x": 2.0}), {"x": Decimal("2.00")}, id="integral_float" + ), + ], +) +def test_map_column_whose_cells_keep_their_kind_reads_into_the_input_type(duckdb_cursor, source, function, expected): + relation = duckdb_cursor.sql(f"select {source} as a from range(1) t(i)") + mapped = relation.map(function) + assert mapped.types == relation.types + assert mapped.fetchall() == [(expected,)] + + def test_map_object_column_of_zero_dimensional_arrays_reads_their_values(duckdb_cursor): def arrays(df): cells = np.empty(len(df), dtype=object) @@ -239,17 +684,101 @@ def test_map_declared_column_read_error_names_the_column(duckdb_cursor): @pytest.mark.parametrize( ("cells", "expected"), [ - # Every staged value is an int, so one cast reads them; the str rows between them are written directly. + # A text cell and cells of other kinds in one vector, the NULL among them pytest.param(["a", 5, 6, "b", None, 7, "c"], ["a", "5", "6", "b", None, "7", "c"], id="str_int_and_null"), pytest.param(["a", 5, np.str_("c"), None], ["a", "5", "c", None], id="with_a_str_subclass"), ], ) -def test_map_text_column_mixing_str_with_other_cells_reads_each_as_text(duckdb_cursor, cells, expected): +def test_map_text_column_mixing_str_with_other_cells_reads_each_as_text_in_the_schema_type( + duckdb_cursor, cells, expected +): source = duckdb_cursor.sql(f"select i::VARCHAR as a from range({len(cells)}) t(i)") - mapped = source.map(_text_cells(cells)) + mapped = source.map(_text_cells(cells), schema={"a": duckdb.sqltypes.VARCHAR}) assert mapped.fetchall() == [(value,) for value in expected] +@SCHEMAS +def test_map_text_list_mixing_str_with_an_int_reads_as_text_as_on_the_base(duckdb_cursor, explicit_schema): + # A list converts by the common type of its elements, so the int reads as its text inside a text list + source = duckdb_cursor.sql("select ['x', 'y'] as a from range(1) t(i)") + mapped = source.map( + _apply_to_a(lambda values: np.array(["x", 5], dtype=object)), schema=_schema_of(source, explicit_schema) + ) + assert mapped.types == source.types + assert mapped.fetchall() == [(["x", "5"],)] + + +def test_map_text_column_of_str_subclass_cells_reads_them_without_a_schema(duckdb_cursor): + mapped = duckdb_cursor.sql("select i::VARCHAR as a from range(3) t(i)").map(_text_cells(["a", np.str_("c"), None])) + assert mapped.fetchall() == [("a",), ("c",), (None,)] + + +def test_map_text_column_with_a_cell_of_another_kind_is_refused_without_a_schema(duckdb_cursor): + mapped = duckdb_cursor.sql("select i::VARCHAR as a from range(4) t(i)").map( + _text_cells(["a", np.str_("c"), 5, None]) + ) + expected = "Invalid Input Error: UDF column type mismatch, expected [VARCHAR], got [INTEGER]" + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +@SCHEMAS +def test_map_blob_column_mixing_bytes_with_other_cells_reads_each(duckdb_cursor, explicit_schema): + # Every Python type a BLOB value reads from, in one vector + cells = [b"a", bytearray(b"b"), None, memoryview(b"c"), b"\x00d"] + source = duckdb_cursor.sql(f"select i::VARCHAR::BLOB as a from range({len(cells)}) t(i)") + mapped = source.map( + lambda df: df.assign(a=pd.Series(cells[: len(df)], dtype=object, index=df.index)), + schema=_schema_of(source, explicit_schema), + ) + assert mapped.fetchall() == [(b"a",), (b"b",), (None,), (b"c",), (b"\x00d",)] + + +@pytest.mark.parametrize( + ("cell", "name"), + [pytest.param(Fraction(1, 3), "fractions.Fraction", id="Fraction"), pytest.param({"b"}, "set", id="set")], +) +def test_map_text_column_with_an_object_without_a_duckdb_type_is_refused_without_a_schema(duckdb_cursor, cell, name): + mapped = duckdb_cursor.sql("select i::VARCHAR as a from range(2) t(i)").map(_text_cells(["a", cell])) + expected = ( + f"Not implemented Error: UDF column 'a': Unable to transform python value of type '' to " + "DuckDB LogicalType" + ) + with pytest.raises(duckdb.NotImplementedException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +def test_map_text_column_with_an_object_without_a_duckdb_type_reads_its_text_in_the_schema_type(duckdb_cursor): + source = duckdb_cursor.sql("select i::VARCHAR as a from range(2) t(i)") + mapped = source.map(_text_cells(["a", Fraction(1, 3)]), schema={"a": duckdb.sqltypes.VARCHAR}) + assert mapped.fetchall() == [("a",), ("1/3",)] + + +@SCHEMAS +@pytest.mark.parametrize( + ("value", "function", "sql_type", "returned"), + [ + pytest.param("'101'::BIT", lambda df: df, "BIT", "BLOB", id="column"), + pytest.param("['101'::BIT]", lambda df: df, "BIT[]", "BLOB[]", id="list_element"), + pytest.param( + "'101'::BIT", + lambda df: df.assign(a=pd.Series([memoryview(bytes(v)) for v in df["a"]], dtype=object, index=df.index)), + "BIT", + "BLOB", + id="memoryview", + ), + ], +) +def test_map_bit_value_reaching_the_function_as_its_storage_bytes_is_refused( + duckdb_cursor, explicit_schema, value, function, sql_type, returned +): + source = duckdb_cursor.sql(f"select {value} as a from range(2) t(i)") + mapped = source.map(function, schema=_schema_of(source, explicit_schema)) + expected = f"Invalid Input Error: UDF column type mismatch, expected [{sql_type}], got [{returned}]" + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + def test_map_json_column_still_validates_its_text(duckdb_cursor): schema = {"a": duckdb.sqltype("JSON")} good = duckdb_cursor.sql("select 1 as a").map(_text_cells(['{"k": 1}']), schema=schema) @@ -336,39 +865,142 @@ def array_cell(df): @pytest.mark.parametrize( - ("function", "column"), + ("function", "types"), [ pytest.param( lambda df: df.assign(a=pd.Series(df["a"].astype(str).str.zfill(5).tolist(), dtype=object, index=df.index)), - "a", + ("BIGINT, VARCHAR", "VARCHAR, VARCHAR"), id="typed_input_turned_into_text", ), - pytest.param(lambda df: df.rename(columns={"a": "b", "b": "a"}), "a", id="names_swapped"), + # rename keeps the order, so the BIGINT column comes first under the name b + pytest.param( + lambda df: df.rename(columns={"a": "b", "b": "a"}), + ("BIGINT, BIGINT", "BIGINT, VARCHAR"), + id="names_swapped", + ), ], ) -def test_map_typed_input_column_the_function_moved_to_another_type_is_refused(duckdb_cursor, function, column): +def test_map_typed_input_column_the_function_moved_to_another_type_is_refused(duckdb_cursor, function, types): mapped = duckdb_cursor.sql("select i as a, i::VARCHAR as b from range(3) t(i)").map(function) - with pytest.raises(duckdb.InvalidInputException, match=_no_type(column)): + expected = f"Invalid Input Error: UDF column type mismatch, expected [{types[0]}], got [{types[1]}]" + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): mapped.fetchall() @pytest.mark.parametrize( - ("make_cell", "expected"), + ("sql_type", "offset"), [ - pytest.param(int, [(0,), (1,), (2,)], id="python_ints"), - pytest.param(lambda v: None, [(None,), (None,), (None,)], id="only_none"), + pytest.param("INTEGER", 0, id="INTEGER"), + # Python ints in the INTEGER range for a BIGINT input + pytest.param("BIGINT", 0, id="BIGINT_holding_INTEGER_values"), + pytest.param("BIGINT", 2**40, id="BIGINT_holding_BIGINT_values"), + pytest.param("HUGEINT", 0, id="HUGEINT_holding_INTEGER_values"), ], ) +@pytest.mark.parametrize("only_none", [False, True], ids=["python_ints", "only_none"]) def test_map_typed_input_column_the_function_turned_into_objects_keeps_a_confirmed_type( - duckdb_cursor, make_cell, expected + duckdb_cursor, sql_type, offset, only_none ): def objects(df): - return df.assign(a=pd.Series([make_cell(v) for v in df["a"]], dtype=object, index=df.index)) + return df.assign(a=pd.Series([None if only_none else int(v) for v in df["a"]], dtype=object, index=df.index)) - source = duckdb_cursor.sql("select i::INTEGER as a from range(3) t(i)") + source = duckdb_cursor.sql(f"select (i + {offset})::{sql_type} as a from range(3) t(i)") mapped = source.map(objects) assert mapped.types == source.types - assert mapped.fetchall() == expected + assert mapped.fetchall() == [(None if only_none else i + offset,) for i in range(3)] + + +@ODD_ROWS +def test_map_typed_input_column_turned_into_objects_reads_a_wide_value_at_any_row(duckdb_cursor, row): + duckdb_cursor.execute("set threads = 1") + + def objects(df): + return df.assign(a=pd.Series([2**40 if i == row else int(v) for i, v in enumerate(df["a"])], dtype=object)) + + mapped = duckdb_cursor.sql("select i as a from range(2048) t(i)").map(objects) + assert mapped.types == [duckdb.sqltypes.BIGINT] + assert mapped.fetchall() == [(2**40 if i == row else i,) for i in range(2048)] + + +@pytest.mark.parametrize("sampled", [0, 2**40], ids=["small_sample", "wide_sample"]) +# In a 2048 row chunk the analyzer samples the even rows, so row 6 is inside its sample and row 7 outside it +@pytest.mark.parametrize("row", [6, 7], ids=["sampled_row", "unsampled_row"]) +@pytest.mark.parametrize( + ("cell", "outcome"), [pytest.param(2.0, 2, id="integral_float"), pytest.param(2.5, None, id="fractional_float")] +) +def test_map_typed_input_column_turned_into_objects_reads_a_float_the_same_whatever_the_sample( + duckdb_cursor, sampled, row, cell, outcome +): + duckdb_cursor.execute("set threads = 1") + + def objects(df): + values = [sampled if i == 0 else cell if i == row else int(v) for i, v in enumerate(df["a"])] + return df.assign(a=pd.Series(values, dtype=object, index=df.index)) + + mapped = duckdb_cursor.sql("select i as a from range(2048) t(i)").map(objects) + if outcome is None: + expected = "Invalid Input Error: UDF column type mismatch, expected [BIGINT], got [DOUBLE]" + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + else: + assert mapped.fetchall() == [(sampled if i == 0 else outcome if i == row else i,) for i in range(2048)] + + +@pytest.mark.parametrize( + ("sql_type", "dtype", "values"), + [ + pytest.param("BIGINT", np.int32, [0, 1, 2], id="int32_chunk_for_bigint"), + pytest.param("DOUBLE", np.float32, [0.5, 1.5, 2.5], id="float32_chunk_for_double"), + ], +) +def test_map_typed_chunk_for_a_guess_widens_into_it(duckdb_cursor, sql_type, dtype, values): + # A Series built from no values is object, so the bind frame's column takes the input's type as a guess + def typed_chunk(df): + cells = np.asarray(df["a"], dtype=dtype) if len(df) else [] + return pd.DataFrame({"a": pd.Series(cells, dtype=None if len(df) else object)}) + + source = duckdb_cursor.sql(f"select (i + {values[0]})::{sql_type} as a from range(3) t(i)") + mapped = source.map(typed_chunk) + assert mapped.types == source.types + assert mapped.fetchall() == [(v,) for v in values] + + +def test_map_double_input_column_turned_into_float_values_reads_them_as_double(duckdb_cursor): + def floats(df): + cells = [duckdb.Value(float(v), duckdb.sqltypes.FLOAT) for v in df["a"]] + return df.assign(a=pd.Series(cells, dtype=object, index=df.index)) + + mapped = duckdb_cursor.sql("select (i + 0.5)::DOUBLE as a from range(3) t(i)").map(floats) + assert mapped.types == [duckdb.sqltypes.DOUBLE] + assert mapped.fetchall() == [(0.5,), (1.5,), (2.5,)] + + +@pytest.mark.parametrize(("offset", "fits"), [(0, True), (40000, False)], ids=["values_it_holds", "values_beyond_it"]) +def test_map_typed_input_column_turned_into_objects_of_a_narrow_type_reads_the_values_it_holds( + duckdb_cursor, offset, fits +): + def objects(df): + return df.assign(a=pd.Series([int(v) + offset for v in df["a"]], dtype=object, index=df.index)) + + mapped = duckdb_cursor.sql("select i::SMALLINT as a from range(3) t(i)").map(objects) + if fits: + assert mapped.types == [duckdb.sqltypes.SMALLINT] + assert mapped.fetchall() == [(0,), (1,), (2,)] + else: + expected = "Invalid Input Error: UDF column type mismatch, expected [SMALLINT], got [INTEGER]" + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +def test_map_new_object_column_named_otherwise_after_bind_reports_the_name_mismatch(duckdb_cursor): + def late_name(df): + name = "t" if len(df) else "s" + return df.assign(**{name: pd.Series(["x"] * len(df), dtype=object, index=df.index)}) + + mapped = duckdb_cursor.sql("select i as a from range(3) t(i)").map(late_name) + expected = "Invalid Input Error: UDF column name mismatch, expected [a, s], got [a, t]" + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() def test_map_new_object_column_fails_on_the_first_chunk_with_a_value(duckdb_cursor): @@ -395,6 +1027,9 @@ def late_values(df): pytest.param(pd.NA, id="pd.NA"), pytest.param(pd.NaT, id="pandas_NaT"), pytest.param(np.datetime64("NaT", "us"), id="numpy_NaT"), + # pandas reads neither as missing; the conversion reads both as NULL + pytest.param(duckdb.NullValue(), id="duckdb_NullValue"), + pytest.param(np.ma.masked, id="numpy_masked"), ], ) def test_map_new_object_column_of_only_missing_values_stays_null(duckdb_cursor, missing): @@ -404,13 +1039,3 @@ def note(df): mapped = duckdb_cursor.sql("select i as a from range(3) t(i)").map(note) assert mapped.types == [duckdb.sqltypes.BIGINT, duckdb.sqltypes.SQLNULL] assert mapped.fetchall() == [(0, None), (1, None), (2, None)] - - -def test_map_new_object_column_of_null_values_is_refused_as_untyped(duckdb_cursor): - # pandas does not read a duckdb.NullValue() as missing, so the column holds values bind could not type - def nulls(df): - return df.assign(s=pd.Series([duckdb.NullValue() for _ in range(len(df))], dtype=object, index=df.index)) - - mapped = duckdb_cursor.sql("select i as a from range(3) t(i)").map(nulls) - with pytest.raises(duckdb.InvalidInputException, match=_no_type("s")): - mapped.fetchall() From 24f406a6cb4b775caf989601459eddecd7bc775a Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 16:11:27 +0000 Subject: [PATCH 25/61] Run mypy in a child process in the two stub tests so its recursion limit stays out of the test process --- tests/fast/api/test_reader_path_lists.py | 18 ++++++++++++++++-- .../test_expression_compat_rules.py | 16 ++++++++++++++-- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/tests/fast/api/test_reader_path_lists.py b/tests/fast/api/test_reader_path_lists.py index b271e3be6..e1c3d52d5 100644 --- a/tests/fast/api/test_reader_path_lists.py +++ b/tests/fast/api/test_reader_path_lists.py @@ -1,7 +1,10 @@ """A connection's readers take a list or a tuple of paths, and their annotations say so.""" +import importlib.util import json import re +import subprocess +import sys import pytest @@ -68,14 +71,25 @@ def test_an_empty_tuple_is_refused_like_an_empty_list(): duckdb.connect().read_json(()) +def run_mypy(*arguments): + """Mypy's report and errors, from a process of its own, since mypy raises the recursion limit of its process.""" + if importlib.util.find_spec("mypy") is None: + pytest.skip("mypy is not installed") + checked = subprocess.run( + [sys.executable, "-I", "-m", "mypy", *arguments], capture_output=True, text=True, timeout=300, check=False + ) + return checked.stdout, checked.stderr, checked.returncode + + def test_mypy_accepts_every_path_shape_and_refuses_a_number(tmp_path): - api = pytest.importorskip("mypy.api") text, refused = annotated_calls() snippet = tmp_path / "calls.py" snippet.write_text(text) dash = "-" * 2 flags = [f"{dash}{flag}" for flag in ("strict", "no-incremental", "follow-imports=silent", "no-pretty")] - report, errors, _ = api.run([str(snippet), *flags, f"{dash}cache-dir", str(tmp_path / "cache")]) + limit = sys.getrecursionlimit() + report, errors, _ = run_mypy(str(snippet), *flags, f"{dash}cache-dir", str(tmp_path / "cache")) + assert sys.getrecursionlimit() == limit found = {int(line): message for line, message in re.findall(r"calls\.py:(\d+): error: (.*)", report)} assert sorted(found) == sorted(refused.values()), report + errors for reader, line in refused.items(): diff --git a/tests/fast/relational_api/test_expression_compat_rules.py b/tests/fast/relational_api/test_expression_compat_rules.py index 41185474f..d9afbce03 100644 --- a/tests/fast/relational_api/test_expression_compat_rules.py +++ b/tests/fast/relational_api/test_expression_compat_rules.py @@ -1,8 +1,11 @@ """Expressions built through the old constructor names, used in relation verbs and checked against direct SQL.""" import decimal +import importlib.util import math import re +import subprocess +import sys import pytest @@ -407,7 +410,8 @@ def test_a_value_past_int128_is_refused_as_a_parameter_is(self, con): class TestThePublicAnnotations: def test_mypy_accepts_the_supported_calls(self, tmp_path): - api = pytest.importorskip("mypy.api") + if importlib.util.find_spec("mypy") is None: + pytest.skip("mypy is not installed") snippet = tmp_path / "calls.py" snippet.write_text( "from duckdb import CaseExpression, Expression, when\n\n" @@ -417,7 +421,15 @@ def test_mypy_accepts_the_supported_calls(self, tmp_path): ) dash = "-" * 2 flags = [f"{dash}{flag}" for flag in ("strict", "no-incremental", "follow-imports=silent")] - report, errors, status = api.run([str(snippet), *flags, f"{dash}cache-dir", str(tmp_path)]) + # A process of its own, since mypy raises the recursion limit of the process it runs in. + checked = subprocess.run( + [sys.executable, "-I", "-m", "mypy", str(snippet), *flags, f"{dash}cache-dir", str(tmp_path)], + capture_output=True, + text=True, + timeout=300, + check=False, + ) + report, errors, status = checked.stdout, checked.stderr, checked.returncode assert status == 0, report + errors From 2ed45dd15040d77631b28ec5ebda5a6ec1c2e651 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 18:11:47 +0000 Subject: [PATCH 26/61] Build the stable ABI, lend no type from a NULL input, shape only container cells toward their key and value types, keep nanoseconds and check narrow integers by range --- .../duckdb_python/python_conversion.hpp | 15 + src/map.cpp | 6 +- src/native/python_conversion.cpp | 143 +++++++- src/numpy/numpy_scan.cpp | 237 +++++++++----- tests/fast/pandas/test_append_df.py | 32 +- tests/fast/test_map_types.py | 304 +++++++++++++++++- 6 files changed, 648 insertions(+), 89 deletions(-) diff --git a/src/include/duckdb_python/python_conversion.hpp b/src/include/duckdb_python/python_conversion.hpp index ac4fa11a7..68ffce1f4 100644 --- a/src/include/duckdb_python/python_conversion.hpp +++ b/src/include/duckdb_python/python_conversion.hpp @@ -53,6 +53,21 @@ LogicalType SniffPythonIntegerType(nb::handle ele); //! The type of a duckdb.Value, or InvalidInputException when its 'type' attribute is not a DuckDB type LogicalType PythonValueType(nb::handle value); bool DictionaryHasMapFormat(const PyDictionary &dict); +//! A target the declared scan builds from a column's type (a shape), as opposed to a column's own type: a dict for a +//! shaped STRUCT takes its own keys, as without a target; a shaped MAP casts each key and value whose type has no +//! children with the connection's settings; a shaped naive timestamp reads a cell as TransformTimestamp does +LogicalType AsShape(const LogicalType &type); +bool IsShape(const LogicalType &type); +//! Whether a cell is a naive pandas Timestamp or a numpy datetime64 finer than a microsecond, whose nanoseconds no +//! Python datetime holds; they are then in nanoseconds +bool HoldsNanoseconds(nb::handle cell, timestamp_ns_t &nanoseconds); +//! A numpy scalar's Python value; a datetime64 or timedelta64 at nanoseconds would read as an integer, so those take +//! the microsecond unit first, as a frame's own datetime columns do +nb::object NumpyScalarItem(nb::handle scalar); +//! A value for a naive timestamp type converted without a target, but keeping the nanoseconds of a pandas Timestamp +//! or a fine datetime64 for a TIMESTAMP_NS, and reading a datetime64 at microseconds for a coarser unit +Value TransformTimestamp(optional_ptr context, nb::handle ele, const LogicalType &target_type, + bool nan_as_null); void TransformPythonObject(optional_ptr context, nb::handle ele, Vector &vector, idx_t result_offset, bool nan_as_null = true); Value TransformPythonValue(optional_ptr context, nb::handle ele, diff --git a/src/map.cpp b/src/map.cpp index b73d286e7..b17ed5470 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -45,7 +45,7 @@ struct MapFunctionData : public TableFunctionData { vector in_types, out_types; vector in_names, out_names; vector sources; - //! Per output column, the type a returned object column is read into, INVALID where the analyzer types it + //! Per output column, the type a returned object column is declared: the column's own type, NULL for an untyped one vector declared_types; //! Per input column, the CategoricalDtype an ENUM column is handed over in, built once since it lists every value vector enum_dtypes; @@ -124,7 +124,9 @@ static void OverrideNullType(vector &return_types, const vector context, const PyD dict.ToString(), target_type.ToString()); }; bool struct_target = StructType::IsStruct(target_type); - // A target holding UNKNOWN gives only the shape of the values below it: the dict's own keys name the fields, as - // without a target, and each value converts with the shape of the field of its name - bool shape_only = struct_target && TypeVisitor::Contains(target_type, LogicalTypeId::UNKNOWN); + // A shape gives only the containers of the values below it: the dict's own keys name the fields, as without a + // target, and each value converts with the shape of the field of its name + bool shape_only = struct_target && IsShape(target_type); if (struct_target && !shape_only && dict.len != StructType::GetChildCount(target_type)) { throw conversion_error(); } @@ -213,6 +213,117 @@ Value TransformDictionaryToStruct(optional_ptr context, const PyD return Value::STRUCT(std::move(struct_values)); } +// Short enough to stay in a string's own buffer, since every shaped conversion compares it +static constexpr const char *SHAPE_ALIAS = "duckdb_py_shape"; + +LogicalType AsShape(const LogicalType &type) { + return type.WithAlias(SHAPE_ALIAS); +} + +bool IsShape(const LogicalType &type) { + return type.HasAlias() && type.GetAlias() == SHAPE_ALIAS; +} + +bool HoldsNanoseconds(nb::handle cell, timestamp_ns_t &nanoseconds) { + auto &import_cache = *DuckDBPyConnection::ImportCache(); + auto datetime_type = import_cache.datetime.datetime(); + if (Py_TYPE(cell.ptr()) == reinterpret_cast(datetime_type.ptr())) { + return false; + } + if (duckdb::PyUtil::IsInstance(cell, import_cache.numpy.datetime64())) { + auto code = nb::cast(cell.attr("dtype").attr("str")); + if (!StringUtil::EndsWith(code, "ns]") && !StringUtil::EndsWith(code, "ps]") && + !StringUtil::EndsWith(code, "fs]") && !StringUtil::EndsWith(code, "as]")) { + return false; + } + auto value = cell.attr("astype")("datetime64[ns]").attr("item")(); + if (value.is_none()) { + return false; + } + nanoseconds = timestamp_ns_t(nb::cast(value)); + return true; + } + if (!duckdb::PyUtil::IsInstance(cell, datetime_type) || !PandasIsImported(import_cache) || + cell.is(import_cache.pandas.NaT()) || !nb::hasattr(cell, "nanosecond") || + !nb::getattr(cell, "tzinfo").is_none()) { + return false; + } + nanoseconds = timestamp_ns_t(nb::cast(cell.attr("value"))); + return true; +} + +nb::object NumpyScalarItem(nb::handle scalar) { + auto kind = nb::cast(scalar.attr("dtype").attr("kind")); + if (kind == "M") { + return scalar.attr("astype")("datetime64[us]").attr("item")(); + } + if (kind == "m") { + return scalar.attr("astype")("timedelta64[us]").attr("item")(); + } + return scalar.attr("item")(); +} + +Value TransformTimestamp(optional_ptr context, nb::handle ele, const LogicalType &target_type, + bool nan_as_null) { + switch (target_type.id()) { + case LogicalTypeId::TIMESTAMP_NS: { + timestamp_ns_t nanoseconds; + if (HoldsNanoseconds(ele, nanoseconds)) { + return Value::TIMESTAMPNS(nanoseconds); + } + break; + } + case LogicalTypeId::TIMESTAMP: + case LogicalTypeId::TIMESTAMP_MS: + case LogicalTypeId::TIMESTAMP_SEC: + if (duckdb::PyUtil::IsInstance(ele, DuckDBPyConnection::ImportCache()->numpy.datetime64())) { + return TransformPythonValue(context, NumpyScalarItem(ele), LogicalType::UNKNOWN, nan_as_null); + } + break; + default: + break; + } + return TransformPythonValue(context, ele, LogicalType::UNKNOWN, nan_as_null); +} + +//! Whether an object is what a shape is for: a dict for a MAP or a STRUCT, a list, a tuple or a numpy array for a +//! LIST or an ARRAY; any other object converts without a target and meets the engine's cast or the kind check, so a +//! tuple reads as a LIST at every depth, as the appender reads a value of a row +static bool ShapeTakes(nb::handle ele, const LogicalType &shape) { + switch (shape.id()) { + case LogicalTypeId::MAP: + case LogicalTypeId::STRUCT: + return PyDict_Check(ele.ptr()); + case LogicalTypeId::LIST: + case LogicalTypeId::ARRAY: + return PyList_Check(ele.ptr()) || PyTuple_Check(ele.ptr()) || + duckdb::PyUtil::IsInstance(ele, DuckDBPyConnection::ImportCache()->numpy.ndarray()); + default: + return false; + } +} + +//! A key or value of a MAP whose target is a type without children converts without a target and is then cast with +//! the connection's settings, as a value of a column is, so each keeps its own type until the cast instead of meeting +//! its siblings' common type (2**60 + 1 beside 1.0 would read as a DOUBLE, rounded) +static Value TransformMapEntry(optional_ptr context, nb::handle entry, const LogicalType &target_type, + bool nan_as_null) { + if (IsShape(target_type) || target_type.IsNested() || target_type.id() == LogicalTypeId::UNKNOWN || + target_type.id() == LogicalTypeId::UNION) { + return TransformPythonValue(context, entry, target_type, nan_as_null); + } + auto value = TransformTimestamp(context, entry, target_type, nan_as_null); + if (!context) { + return value.DefaultCastAs(target_type); + } + string error; + auto cast = value.TryCastAs(*context, target_type, &error); + if (!cast) { + throw ConversionException(error); + } + return std::move(*cast); +} + Value TransformStructFormatDictionaryToMap(optional_ptr context, const PyDictionary &dict, const LogicalType &target_type, bool nan_as_null) { if (dict.len == 0) { @@ -232,6 +343,7 @@ Value TransformStructFormatDictionaryToMap(optional_ptr context, auto key_target = MapType::KeyType(target_type); auto value_target = MapType::ValueType(target_type); + auto shape = IsShape(target_type); LogicalType key_type = LogicalType::SQLNULL; LogicalType value_type = LogicalType::SQLNULL; @@ -239,8 +351,12 @@ Value TransformStructFormatDictionaryToMap(optional_ptr context, vector elements; for (idx_t i = 0; i < size; i++) { - Value new_key = TransformPythonValue(context, dict.keys.attr("__getitem__")(i), key_target, nan_as_null); - Value new_value = TransformPythonValue(context, dict.values.attr("__getitem__")(i), value_target, nan_as_null); + auto key = dict.keys.attr("__getitem__")(i); + auto value = dict.values.attr("__getitem__")(i); + Value new_key = shape ? TransformMapEntry(context, key, key_target, nan_as_null) + : TransformPythonValue(context, key, key_target, nan_as_null); + Value new_value = shape ? TransformMapEntry(context, value, value_target, nan_as_null) + : TransformPythonValue(context, value, value_target, nan_as_null); key_type = ProxiedForceMaxLogicalType(context, key_type, new_key.type()); value_type = ProxiedForceMaxLogicalType(context, value_type, new_value.type()); @@ -252,10 +368,12 @@ Value TransformStructFormatDictionaryToMap(optional_ptr context, elements.push_back(Value::STRUCT(std::move(struct_values))); } // A target holding UNKNOWN asks for no type there, and a MAP of such a type is no value the engine can hold - if (key_type.id() == LogicalTypeId::SQLNULL && !TypeVisitor::Contains(key_target, LogicalTypeId::UNKNOWN)) { + if (key_type.id() == LogicalTypeId::SQLNULL && !TypeVisitor::Contains(key_target, LogicalTypeId::UNKNOWN) && + !IsShape(key_target)) { key_type = key_target; } - if (value_type.id() == LogicalTypeId::SQLNULL && !TypeVisitor::Contains(value_target, LogicalTypeId::UNKNOWN)) { + if (value_type.id() == LogicalTypeId::SQLNULL && !TypeVisitor::Contains(value_target, LogicalTypeId::UNKNOWN) && + !IsShape(value_target)) { value_type = value_target; } @@ -1222,6 +1340,17 @@ void TransformPythonObject(optional_ptr context, nb::handle ele, Value TransformPythonValue(optional_ptr context, nb::handle ele, const LogicalType &target_type, bool nan_as_null) { + // A shape of no children marks a timestamp, read as TransformTimestamp reads it; a container shape takes only the + // objects it is for, so a scalar inside a container meets the engine's cast as at the top, never a type holding + // UNKNOWN + if (IsShape(target_type)) { + if (!target_type.IsNested()) { + return TransformTimestamp(context, ele, target_type, nan_as_null); + } + if (!ShapeTakes(ele, target_type)) { + return TransformPythonValue(context, ele, LogicalType::UNKNOWN, nan_as_null); + } + } Value result; TransformPythonObjectInternal(context, ele, result, target_type, nan_as_null); return result; diff --git a/src/numpy/numpy_scan.cpp b/src/numpy/numpy_scan.cpp index 9242efadc..ece998c83 100644 --- a/src/numpy/numpy_scan.cpp +++ b/src/numpy/numpy_scan.cpp @@ -307,9 +307,7 @@ class DeclaredCasts { //! A declared column converts a cell as the appender converts a value of a row: with the type the value has in //! Python, then the engine's cast into the column's type, which reads the connection's settings; NaN reads NULL at //! every depth, and a value without a DuckDB type of its own reads as its text in a text column -//! A numpy scalar, or an array of no dimensions, reads as its Python value; a datetime64 or timedelta64 at -//! nanoseconds would read as an integer, so those take the microsecond unit first, as the frame's own datetime -//! columns do +//! A numpy scalar, or an array of no dimensions, reads as its Python value (NumpyScalarItem) static bool IsNumpyScalar(nb::handle cell) { auto &import_cache = *DuckDBPyConnection::ImportCache(); if (nb::isinstance(cell, import_cache.numpy.generic())) { @@ -319,17 +317,6 @@ static bool IsNumpyScalar(nb::handle cell) { return cell.type().is(import_cache.numpy.ndarray()) && nb::cast(cell.attr("ndim")) == 0; } -static nb::object NumpyScalarValue(nb::handle scalar) { - auto kind = nb::cast(scalar.attr("dtype").attr("kind")); - if (kind == "M") { - return scalar.attr("astype")("datetime64[us]").attr("item")(); - } - if (kind == "m") { - return scalar.attr("astype")("timedelta64[us]").attr("item")(); - } - return scalar.attr("item")(); -} - //! With a shape (KeyedShape) the cell converts with it as its target, which a type holding a MAP needs: without it a //! dict reads as a STRUCT named by its keys' text, and a key whose text does not cast back, such as bytes, is lost. //! An object without a DuckDB type reads as its text into a stated VARCHAR, and has no kind for an implied one. @@ -338,8 +325,19 @@ static Value DeclaredValue(ClientContext &context, const LogicalType &target, nb if (cell.ptr() == Py_None) { return Value(); } + // A TIMESTAMP_NS column keeps a cell's nanoseconds, and an implied naive timestamp type sees them, so its kind + // check refuses what a coarser unit would drop; a stated coarser type reads the cell at microseconds, as a frame's + // own datetime64 column reads + auto naive_timestamp = + target.id() == LogicalTypeId::TIMESTAMP_NS || + (implied && (target.id() == LogicalTypeId::TIMESTAMP || target.id() == LogicalTypeId::TIMESTAMP_MS || + target.id() == LogicalTypeId::TIMESTAMP_SEC)); + timestamp_ns_t nanoseconds; + if (naive_timestamp && HoldsNanoseconds(cell, nanoseconds)) { + return Value::TIMESTAMPNS(nanoseconds); + } if (IsNumpyScalar(cell)) { - auto value = NumpyScalarValue(cell); + auto value = NumpyScalarItem(cell); // A long double's item() is a numpy scalar again; one step, then the conversion refuses what is left if (!IsNumpyScalar(value)) { return DeclaredValue(context, target, value, shape, implied); @@ -351,24 +349,41 @@ static Value DeclaredValue(ClientContext &context, const LogicalType &target, nb return TransformPythonValue(context, cell, shape ? *shape : LogicalType(LogicalTypeId::UNKNOWN), true); } -//! The type a cell of a type holding a MAP converts with: its containers and no other type, so a dict builds its MAP -//! from its keys and values in the types they have in Python, and every key and value meets the engine's cast with -//! the connection's settings, as a TIMESTAMPTZ in the session time zone -static LogicalType KeyedShape(const LogicalType &type) { +//! The type a cell of a nested type converts with: its containers and its naive timestamps and no other type, so a +//! dict builds its MAP from its keys and values in the types they have in Python and every key and value meets the +//! engine's cast with the connection's settings, as a TIMESTAMPTZ in the session time zone, and a timestamp reads in +//! the unit of its place. With typed_entries a MAP keeps a key or value type that +//! has no children, so its entries are each cast into it rather than into their common type first; a type the caller +//! stated takes that, while an implied type keeps the entries' own types for the kind check. +static LogicalType KeyedShape(const LogicalType &type, bool typed_entries) { + auto entry = [&](const LogicalType &entry_type) { + auto plain = !entry_type.IsNested() && entry_type.id() != LogicalTypeId::UNION; + return typed_entries && plain ? entry_type : KeyedShape(entry_type, typed_entries); + }; switch (type.id()) { case LogicalTypeId::STRUCT: { child_list_t children; for (idx_t i = 0; i < StructType::GetChildCount(type); i++) { - children.emplace_back(StructType::GetChildName(type, i), KeyedShape(StructType::GetChildType(type, i))); + children.emplace_back(StructType::GetChildName(type, i), + KeyedShape(StructType::GetChildType(type, i), typed_entries)); } - return LogicalType::STRUCT(std::move(children)); + return AsShape(LogicalType::STRUCT(std::move(children))); } case LogicalTypeId::LIST: - return LogicalType::LIST(KeyedShape(ListType::GetChildType(type))); + return AsShape(LogicalType::LIST(KeyedShape(ListType::GetChildType(type), typed_entries))); case LogicalTypeId::ARRAY: - return LogicalType::ARRAY(KeyedShape(ArrayType::GetChildType(type)), ArrayType::GetSize(type)); + return AsShape( + LogicalType::ARRAY(KeyedShape(ArrayType::GetChildType(type), typed_entries), ArrayType::GetSize(type))); case LogicalTypeId::MAP: - return LogicalType::MAP(KeyedShape(MapType::KeyType(type)), KeyedShape(MapType::ValueType(type))); + return AsShape(LogicalType::MAP(entry(MapType::KeyType(type)), entry(MapType::ValueType(type)))); + case LogicalTypeId::TIMESTAMP_NS: + return AsShape(type); + case LogicalTypeId::TIMESTAMP: + case LogicalTypeId::TIMESTAMP_MS: + case LogicalTypeId::TIMESTAMP_SEC: + // An implied type sees the nanoseconds a coarser unit would drop, so its kind check refuses them; a stated one + // reads them at microseconds, as at the top + return AsShape(typed_entries ? type : LogicalType::TIMESTAMP_NS); default: return LogicalType::UNKNOWN; } @@ -483,16 +498,7 @@ class ImpliedKinds { if (source == type) { return true; } - for (auto &entry : seen) { - if (entry.source == source) { - return entry.verdict == Verdict::FITS || - (entry.verdict == Verdict::BY_VALUE && FitsByValue(value, type)); - } - } - auto verdict = Judge(source, type); - if (seen.size() < CACHED_SOURCE_TYPES) { - seen.push_back({source, verdict}); - } + auto verdict = JudgeOnce(source, type); return verdict == Verdict::FITS || (verdict == Verdict::BY_VALUE && FitsByValue(value, type)); } @@ -565,8 +571,8 @@ class ImpliedKinds { return Verdict::REFUSED; } claimed[field.GetIndex()] = true; - verdict = Combine(verdict, Judge(StructType::GetChildType(source, i), - StructType::GetChildType(type, field.GetIndex()))); + verdict = Combine(verdict, JudgeOnce(StructType::GetChildType(source, i), + StructType::GetChildType(type, field.GetIndex()))); } return verdict; } @@ -575,22 +581,22 @@ class ImpliedKinds { if (source.id() != LogicalTypeId::MAP) { return Verdict::REFUSED; } - return Combine(Judge(MapType::KeyType(source), MapType::KeyType(type)), - Judge(MapType::ValueType(source), MapType::ValueType(type))); + return Combine(JudgeOnce(MapType::KeyType(source), MapType::KeyType(type)), + JudgeOnce(MapType::ValueType(source), MapType::ValueType(type))); case LogicalTypeId::LIST: if (source.id() != LogicalTypeId::LIST) { return Verdict::REFUSED; } - return Judge(ListType::GetChildType(source), ListType::GetChildType(type)); + return JudgeOnce(ListType::GetChildType(source), ListType::GetChildType(type)); case LogicalTypeId::ARRAY: // A Python list reads as a LIST, which the cast takes into an ARRAY of its length or refuses if (source.id() == LogicalTypeId::LIST) { - return Judge(ListType::GetChildType(source), ArrayType::GetChildType(type)); + return JudgeOnce(ListType::GetChildType(source), ArrayType::GetChildType(type)); } if (source.id() != LogicalTypeId::ARRAY) { return Verdict::REFUSED; } - return Judge(ArrayType::GetChildType(source), ArrayType::GetChildType(type)); + return JudgeOnce(ArrayType::GetChildType(source), ArrayType::GetChildType(type)); default: break; } @@ -640,12 +646,64 @@ class ImpliedKinds { return CastFunctionSet::ImplicitCastCost(context, source, type) >= 0 ? Verdict::FITS : Verdict::REFUSED; } + //! Judge, looked up once per pair of types for the scan of a vector: the elements of a list share a type, and so do + //! the cells of a column, so a pair is judged once rather than per cell or element + Verdict JudgeOnce(const LogicalType &source, const LogicalType &type) { + for (auto &entry : judged) { + if (entry.source == source && entry.type == type) { + return entry.verdict; + } + } + auto verdict = Judge(source, type); + if (judged.size() < CACHED_TYPE_PAIRS) { + judged.push_back({source, type, verdict}); + } + return verdict; + } + + static bool HoldsInteger(int64_t value, LogicalTypeId id) { + switch (id) { + case LogicalTypeId::TINYINT: + return value >= NumericLimits::Minimum() && value <= NumericLimits::Maximum(); + case LogicalTypeId::SMALLINT: + return value >= NumericLimits::Minimum() && value <= NumericLimits::Maximum(); + case LogicalTypeId::INTEGER: + return value >= NumericLimits::Minimum() && value <= NumericLimits::Maximum(); + case LogicalTypeId::UTINYINT: + return value >= 0 && value <= NumericLimits::Maximum(); + case LogicalTypeId::USMALLINT: + return value >= 0 && value <= NumericLimits::Maximum(); + case LogicalTypeId::UINTEGER: + return value >= 0 && value <= NumericLimits::Maximum(); + case LogicalTypeId::UBIGINT: + case LogicalTypeId::UHUGEINT: + return value >= 0; + default: + return true; + } + } + + static bool HoldsInt64(LogicalTypeId id) { + switch (id) { + case LogicalTypeId::TINYINT: + case LogicalTypeId::SMALLINT: + case LogicalTypeId::INTEGER: + case LogicalTypeId::BIGINT: + case LogicalTypeId::UTINYINT: + case LogicalTypeId::USMALLINT: + case LogicalTypeId::UINTEGER: + return true; + default: + return false; + } + } + bool FitsByValue(const Value &value, const LogicalType &type) { if (value.IsNull()) { return true; } auto &source = value.type(); - switch (Judge(source, type)) { + switch (JudgeOnce(source, type)) { case Verdict::FITS: return true; case Verdict::REFUSED: @@ -686,6 +744,10 @@ class ImpliedKinds { return true; } default: { + // A Python int converts to INTEGER or BIGINT, whose range says whether a narrower type holds it + if (HoldsInt64(source.id()) && type.IsIntegral()) { + return HoldsInteger(value.GetValue(), type.id()); + } if ((source.id() == LogicalTypeId::DOUBLE || source.id() == LogicalTypeId::FLOAT) && !FloatHoldsItsText(value, type)) { return false; @@ -759,9 +821,8 @@ class ImpliedKinds { } private: - //! The significant digits of a number's shortest text ("2.0" has one, "1e+20" twenty one): from its first digit - //! that is not zero to its last, or to the units when its integer part ends in zeros - static idx_t SignificantDigits(const string &text) { + //! The digits of the integer part of a number's shortest text: none for "0.1", one for "2.0", 21 for "1e+20" + static idx_t IntegerDigits(const string &text) { string digits; int64_t integer_digits = 0; bool point = false; @@ -776,32 +837,28 @@ class ImpliedKinds { } int64_t exponent = i < text.size() ? std::stoll(text.substr(i + 1)) : 0; auto units = integer_digits + exponent; - auto end = static_cast(digits.size()); - while (end > MaxValue(units, 0) && digits[NumericCast(end - 1)] == '0') { - end--; - } - int64_t start = 0; - while (start < end && digits[NumericCast(start)] == '0') { - start++; - } - if (start == end) { - return 0; + int64_t leading_zeros = 0; + while (leading_zeros < units && leading_zeros < static_cast(digits.size()) && + digits[NumericCast(leading_zeros)] == '0') { + leading_zeros++; } - return NumericCast(MaxValue(end, units) - start); + return NumericCast(MaxValue(units - leading_zeros, 0)); } - //! A double holds every decimal of at most 15 significant digits exactly enough to give it back as its shortest - //! text, so a float whose text has more may be a rounding already: df() hands a HUGEINT or a DECIMAL over as a - //! float64. And the engine's cast of a float into a DECIMAL rounds the value times 10**scale in double precision, - //! which for a wide scale is no longer that value (2.0 reads 2.000000000000000039769249677312 in a DECIMAL(38,30), - //! exactly in a DECIMAL(38,20)), so the float fits only when the cast gives the value of its text. + //! A float stands for the value it was made from only when that value had at most 15 significant digits, the + //! decimals a double holds exactly: df() hands a HUGEINT or a DECIMAL over as a float64, already rounded when + //! the value had more. A float with i integer digits stands for a DECIMAL(p, s) value of at most i + s digits, so + //! it fits only when i + s is at most 15 (s is 0 for an integer type). And the engine's cast of a float into a + //! DECIMAL rounds the value times 10**scale in double precision, so it must also give the value of the float's + //! shortest text. static bool FloatHoldsItsText(const Value &value, const LogicalType &type) { auto number = value.GetValue(); if (!Value::DoubleIsFinite(number)) { return false; } auto text = Value::DOUBLE(number).ToString(); - if (SignificantDigits(text) > MAX_EXACT_FLOAT_DIGITS) { + auto scale = type.id() == LogicalTypeId::DECIMAL ? DecimalType::GetScale(type) : 0; + if (IntegerDigits(text) + scale > MAX_EXACT_FLOAT_DIGITS) { return false; } if (type.id() != LogicalTypeId::DECIMAL) { @@ -812,17 +869,18 @@ class ImpliedKinds { return cast && exact && Value::NotDistinctFrom(*cast, *exact); } - struct Seen { + struct Judged { LogicalType source; + LogicalType type; Verdict verdict; }; //! DBL_DIG: every decimal of this many significant digits survives a round trip through a double static constexpr idx_t MAX_EXACT_FLOAT_DIGITS = 15; //! Bounded like DeclaredCasts, since dicts give a STRUCT type per key set - static constexpr idx_t CACHED_SOURCE_TYPES = 16; + static constexpr idx_t CACHED_TYPE_PAIRS = 32; ClientContext &context; - vector seen; + vector judged; }; // A column without a mask takes the instantiation that tests no mask bits, so it reads like the plain array @@ -867,14 +925,22 @@ void NumpyScan::ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t bool bit_storage_refused) { DeclaredVector staged(count); auto &target = out.GetType(); - const auto keyed = TypeVisitor::Contains(target, LogicalTypeId::MAP); + // A type holding a MAP takes a shape for its keys, and one holding a naive timestamp for the unit a nested value + // reads in; a top level timestamp is read by DeclaredValue itself + const auto keyed = target.IsNested() && (TypeVisitor::Contains(target, LogicalTypeId::MAP) || + TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP_NS) || + TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP) || + TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP_MS) || + TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP_SEC)); const auto holds_bit = TypeVisitor::Contains(target, LogicalTypeId::BIT); - const auto shape = keyed ? KeyedShape(target) : LogicalType(LogicalTypeId::UNKNOWN); - // A str into VARCHAR without an alias, and bytes or a bytearray into BLOB without one, read as TransformPythonValue - // would read them, without building a Value per cell; a collation governs comparison only, an alias such as JSON - // validates the text in its cast + const auto shape = keyed ? KeyedShape(target, !implied_type) : LogicalType(LogicalTypeId::UNKNOWN); + // A str into VARCHAR without an alias, bytes or a bytearray into BLOB without one, and a time without a zone into + // TIME read as TransformPythonValue would read them, without building a Value per cell; a collation governs + // comparison only, an alias such as JSON validates the text in its cast const bool plain_text = target == LogicalType::VARCHAR; const bool plain_blob = target == LogicalType::BLOB; + const bool plain_time = target == LogicalType::TIME; + PyObject *time_type = nullptr; ImpliedKinds kinds(context); ScanObjectCells(context, col, stride, masked, count, offset, out, [&](nb::handle cell, idx_t row) { if (plain_text && PyUnicode_CheckExact(cell.ptr())) { @@ -890,14 +956,39 @@ void NumpyScan::ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t } // df() hands a BLOB cell to the function as a bytearray if (plain_blob && (PyBytes_CheckExact(cell.ptr()) || PyByteArray_CheckExact(cell.ptr()))) { - auto bytes = PyBytes_CheckExact(cell.ptr()); - auto data = bytes ? PyBytes_AS_STRING(cell.ptr()) : PyByteArray_AS_STRING(cell.ptr()); - auto size = bytes ? PyBytes_GET_SIZE(cell.ptr()) : PyByteArray_GET_SIZE(cell.ptr()); + char *data; + Py_ssize_t size; + if (PyBytes_CheckExact(cell.ptr())) { + if (PyBytes_AsStringAndSize(cell.ptr(), &data, &size) < 0) { + throw nb::python_error(); + } + } else { + data = PyByteArray_AsString(cell.ptr()); + size = PyByteArray_Size(cell.ptr()); + if (!data || size < 0) { + throw nb::python_error(); + } + } FlatVector::GetDataMutable(out)[row] = StringVector::AddStringOrBlob(out, data, NumericCast(size)); staged.MarkWritten(row); return; } + if (plain_time) { + if (!time_type) { + time_type = DuckDBPyConnection::ImportCache()->datetime.time().ptr(); + } + if (Py_TYPE(cell.ptr()) == reinterpret_cast(time_type)) { + PyTime time(cell); + // A time with a zone converts as a TIMETZ, which an implied TIME refuses and the cast into a stated one + // reads without its offset + if (time.timezone_obj.is_none()) { + FlatVector::GetDataMutable(out)[row] = time.ToDuckTime(); + staged.MarkWritten(row); + return; + } + } + } auto value = DeclaredValue(context, target, cell, keyed ? &shape : nullptr, implied_type); // A duckdb.Value states its type, as a schema does, so a cast into the column's type is meant if (implied_type && !kinds.Fits(value, target) && diff --git a/tests/fast/pandas/test_append_df.py b/tests/fast/pandas/test_append_df.py index 66007b6b6..b5b40fed0 100644 --- a/tests/fast/pandas/test_append_df.py +++ b/tests/fast/pandas/test_append_df.py @@ -483,16 +483,18 @@ def test_map_key_meets_the_cast_in_the_session_settings(self, duckdb_cursor, tar @pytest.mark.parametrize( ("target", "key", "expected"), [ - # The engine's cast reads the instant in the session's time zone; the base dropped the offset + # The engine's cast reads the instant in the session's time zone; 2.0.0 dropped the offset pytest.param( "TIMESTAMP", datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc), "{'2019-12-31 19:00:00'=1}", id="aware_datetime_into_timestamp", ), - # The cast from BLOB gives the bytes' text; the base gave the text of the Python bytes object + # The cast from BLOB gives the bytes' text; 2.0.0 gave the text of the Python bytes object pytest.param("VARCHAR", b"x", "{x=1}", id="bytes_into_varchar"), - pytest.param("STRUCT(a INTEGER)", (1,), "{{'a': 1}=1}", id="tuple_into_struct"), + pytest.param("VARCHAR", True, "{true=1}", id="bool_into_varchar"), + pytest.param("VARCHAR", datetime.timedelta(days=1), "{1 day=1}", id="timedelta_into_varchar"), + pytest.param("VARCHAR", (1, 2), "{'[1, 2]'=1}", id="tuple_into_varchar"), ], ) def test_map_key_reads_as_the_cast_from_its_python_type_gives_it(self, duckdb_cursor, target, key, expected): @@ -501,12 +503,36 @@ def test_map_key_reads_as_the_cast_from_its_python_type_gives_it(self, duckdb_cu duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series([{key: 1}], dtype=object)})) assert duckdb_cursor.sql("SELECT a::VARCHAR FROM t").fetchall() == [(expected,)] + def test_map_key_given_as_a_tuple_for_a_struct_key_type_reads_as_a_list_and_is_refused(self, duckdb_cursor): + # A tuple is a LIST at every depth, as the appender reads a value of a row; 2.0.0 read this key through its text + duckdb_cursor.execute("CREATE TABLE t (a MAP(STRUCT(a INTEGER), INTEGER))") + frame = pd.DataFrame({"a": pd.Series([{(1,): 1}], dtype=object)}) + expected = "Unimplemented type for cast (INTEGER[] -> STRUCT(a INTEGER))" + with pytest.raises(duckdb.ConversionException, match=re.escape(expected)): + duckdb_cursor.append("t", frame) + assert duckdb_cursor.sql("SELECT 42").fetchall() == [(42,)] + def test_map_keys_a_str_and_its_bytes_are_one_key_and_refused(self, duckdb_cursor): duckdb_cursor.execute("CREATE TABLE t (a MAP(VARCHAR, INTEGER))") frame = pd.DataFrame({"a": pd.Series([{"a": 1, b"a": 2}], dtype=object)}) with pytest.raises(duckdb.InvalidInputException, match=re.escape("Map keys must be unique")): duckdb_cursor.append("t", frame) + def test_text_of_a_map_into_a_map_column_reads_as_the_cast_reads_it(self): + con = duckdb.connect() + con.execute("CREATE TABLE t (a MAP(VARCHAR, INTEGER))") + con.append("t", pd.DataFrame({"a": pd.Series(["{a=1}"], dtype=object)})) + assert con.table("t").fetchall() == [({"a": 1},)] + assert con.sql("SELECT 42").fetchall() == [(42,)] + + def test_map_values_of_mixed_numbers_each_keep_their_value(self): + # Converted toward their common type first, 2**60 + 1 beside 1.0 would read as a rounded DOUBLE + con = duckdb.connect() + con.execute("CREATE TABLE t (a MAP(VARCHAR, BIGINT))") + con.append("t", pd.DataFrame({"a": pd.Series([{"a": 2**60 + 1, "b": 1.0}], dtype=object)})) + assert con.table("t").fetchall() == [({"a": 2**60 + 1, "b": 1},)] + assert con.sql("SELECT 42").fetchall() == [(42,)] + def test_map_key_of_none_is_refused_and_the_connection_stays_usable(self, duckdb_cursor): duckdb_cursor.execute("CREATE TABLE t (a MAP(VARCHAR, INTEGER))") with pytest.raises(duckdb.Error) as error: diff --git a/tests/fast/test_map_types.py b/tests/fast/test_map_types.py index 59c45892f..0a54fd85f 100644 --- a/tests/fast/test_map_types.py +++ b/tests/fast/test_map_types.py @@ -346,9 +346,9 @@ def _apply_to_a(convert): ), pytest.param( "{'t': TIMESTAMP '2020-01-01'}", - _apply_to_a(lambda d: {"t": np.datetime64("2020-01-01T00:00:00", "ns")}), + _apply_to_a(lambda d: {"t": np.datetime64("2020-01-01T00:00:00.000000001", "ns")}), "STRUCT(t TIMESTAMP)", - "STRUCT(t BIGINT)", + "STRUCT(t TIMESTAMP_NS)", id="nanosecond_datetime64_field", ), # A float of more than 15 significant digits, or one the cast into a wide scale rounds in double precision @@ -498,6 +498,8 @@ def test_map_time_value_outside_the_range_of_its_columns_unit_is_refused(duckdb_ pytest.param("[123456789012345678901::HUGEINT]", "HUGEINT[]", id="hugeint_beyond_bigint"), pytest.param("[1152921504606846977::HUGEINT, NULL]", "HUGEINT[]", id="hugeint_with_a_null"), pytest.param("[1234567890123456.78::DECIMAL(18,2)]", "DECIMAL(18,2)[]", id="decimal_of_18_digits"), + pytest.param("[1.000000000000000001::DECIMAL(19,18)]", "DECIMAL(19,18)[]", id="decimal_of_scale_18"), + pytest.param("[100000000000000.001::DECIMAL(18,3)]", "DECIMAL(18,3)[]", id="decimal_of_15_integer_digits"), ], ) def test_map_identity_of_a_list_whose_floats_may_have_rounded_is_refused(duckdb_cursor, values, sql_type): @@ -512,6 +514,10 @@ def test_map_identity_of_a_list_whose_floats_may_have_rounded_is_refused(duckdb_ [ pytest.param("[5::HUGEINT, NULL, (-999999999999999)::HUGEINT]", id="hugeint_of_15_digits"), pytest.param("[1.25::DECIMAL(9,2), NULL, 0.1::DECIMAL(9,2)]", id="decimal"), + pytest.param("[1.5::DECIMAL(18,3), NULL]", id="decimal_of_scale_3"), + pytest.param("[(-32768)::SMALLINT, NULL, 32767::SMALLINT]", id="smallint"), + pytest.param("[(-128)::TINYINT, 127::TINYINT]", id="tinyint"), + pytest.param("{'x': 32767::SMALLINT}", id="smallint_field"), ], ) def test_map_identity_of_a_list_whose_floats_hold_their_values_round_trips(duckdb_cursor, values): @@ -521,6 +527,240 @@ def test_map_identity_of_a_list_whose_floats_hold_their_values_round_trips(duckd assert mapped.fetchall() == source.fetchall() +@pytest.mark.parametrize( + ("source", "values", "returned"), + [ + pytest.param("[1::SMALLINT]", [40000], "INTEGER[]", id="smallint_list"), + pytest.param("[1::TINYINT]", [-129], "INTEGER[]", id="tinyint_list"), + ], +) +def test_map_narrow_integer_list_with_an_int_beyond_its_range_is_refused(duckdb_cursor, source, values, returned): + mapped = duckdb_cursor.sql(f"select {source} as a").map(_apply_to_a(lambda v: values)) + sql_type = duckdb_cursor.sql(f"select {source} as a").types[0] + expected = f"Invalid Input Error: UDF column type mismatch, expected [{sql_type}], got [{returned}]" + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +@pytest.mark.parametrize("cell", [0, "x"], ids=["int", "str"]) +def test_map_scalar_returned_for_a_map_column_is_refused_and_the_database_stays_usable(cell): + con = duckdb.connect() + mapped = con.sql("select map(['k'], [1]) as a").map( + lambda df: df.assign(a=pd.Series([cell] * len(df), dtype=object, index=df.index)) + ) + with pytest.raises(duckdb.InvalidInputException, match=re.escape("UDF column type mismatch")): + mapped.fetchall() + assert con.sql("select 42").fetchall() == [(42,)] + + +def test_map_text_of_a_map_for_a_stated_map_column_reads_as_the_cast_reads_it(): + con = duckdb.connect() + mapped = con.sql("select map(['k'], [1]) as a").map( + lambda df: df.assign(a=pd.Series(["{k=2}"] * len(df), dtype=object, index=df.index)), + schema={"a": duckdb.sqltype("MAP(VARCHAR, INTEGER)")}, + ) + assert mapped.fetchall() == [({"k": 2},)] + assert con.sql("select 42").fetchall() == [(42,)] + + +@pytest.mark.parametrize( + ("value", "nanoseconds"), + [ + pytest.param("'2020-01-01 00:00:00.000000001'::TIMESTAMP_NS", 1, id="pandas_timestamp"), + pytest.param("NULL::TIMESTAMP_NS", None, id="null"), + ], +) +def test_map_timestamp_ns_column_handed_back_as_objects_keeps_its_nanoseconds(duckdb_cursor, value, nanoseconds): + source = duckdb_cursor.sql(f"select {value} as a") + mapped = source.map(lambda df: df.assign(a=df["a"].astype(object))) + assert mapped.types == [duckdb.sqltype("TIMESTAMP_NS")] + assert mapped.project("a::VARCHAR").fetchall() == source.project("a::VARCHAR").fetchall() + + +def test_map_timestamp_ns_column_of_numpy_datetime64_cells_keeps_their_nanoseconds(duckdb_cursor): + cell = np.datetime64("2020-01-01T00:00:00.000000002", "ns") + mapped = duckdb_cursor.sql("select '2020-01-01'::TIMESTAMP_NS as a").map( + lambda df: df.assign(a=pd.Series([cell] * len(df), dtype=object, index=df.index)) + ) + assert mapped.project("a::VARCHAR").fetchall() == [("2020-01-01 00:00:00.000000002",)] + + +def test_map_timestamp_column_given_a_timestamp_with_nanoseconds_is_refused(duckdb_cursor): + # The cast into microseconds would drop the nanosecond + stamp = pd.Timestamp("2020-01-01 00:00:00.000000001") + mapped = duckdb_cursor.sql("select TIMESTAMP '2020-01-01' as a").map( + lambda df: df.assign(a=pd.Series([stamp] * len(df), dtype=object, index=df.index)) + ) + expected = "Invalid Input Error: UDF column type mismatch, expected [TIMESTAMP], got [TIMESTAMP_NS]" + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +# A scalar inside a container of a type holding a MAP, which meets the engine's cast or the kind check, never a +# conversion target holding no type +NESTED_SCALARS = pytest.mark.parametrize( + ("sql_type", "cell", "cast_into"), + [ + pytest.param("MAP(VARCHAR, INTEGER)[]", [0], "MAP(VARCHAR, INTEGER)", id="int_in_a_list_of_maps"), + pytest.param("MAP(VARCHAR, INTEGER)[]", ["x"], "MAP(VARCHAR, INTEGER)", id="str_in_a_list_of_maps"), + pytest.param("STRUCT(m MAP(VARCHAR, INTEGER))", {"m": 5}, "MAP(VARCHAR, INTEGER)", id="int_for_a_map_field"), + pytest.param("MAP(VARCHAR, INTEGER)[]", np.array([0, 1]), "MAP(VARCHAR, INTEGER)", id="int_array_for_a_list"), + pytest.param("MAP(VARCHAR, INTEGER)[]", (0,), "MAP(VARCHAR, INTEGER)", id="tuple_for_a_list"), + pytest.param("MAP(VARCHAR, STRUCT(x INTEGER))", {"k": "abc"}, "STRUCT(x INTEGER)", id="str_for_a_struct_value"), + ], +) + + +def _returning(cell): + def replace(df): + return df.assign(a=pd.Series([cell] * len(df), dtype=object, index=df.index)) + + return replace + + +@NESTED_SCALARS +@pytest.mark.parametrize("mode", ["inferred", "explicit_schema", "append"]) +def test_map_scalar_inside_a_container_of_a_type_holding_a_map_is_refused_and_the_database_stays_usable( + sql_type, cell, cast_into, mode +): + con = duckdb.connect() + con.execute(f"create table t (a {sql_type})") + con.execute("insert into t values (NULL)") + if mode == "append": + run = lambda: con.append("t", pd.DataFrame({"a": pd.Series([cell], dtype=object)})) # noqa: E731 + else: + schema = {"a": duckdb.sqltype(sql_type)} if mode == "explicit_schema" else None + run = con.table("t").map(_returning(cell), schema=schema).fetchall + with pytest.raises(duckdb.Error) as error: + run() + message = str(error.value) + assert not isinstance(error.value, duckdb.FatalException), message + if mode == "inferred": + assert message.startswith(f"Invalid Input Error: UDF column type mismatch, expected [{sql_type}], got ["), ( + message + ) + else: + # The message names the column's own types, never a conversion target + assert cast_into in message, message + assert "shape" not in message, message + assert con.sql("select 42").fetchall() == [(42,)] + + +def test_map_cast_error_for_a_nested_scalar_names_the_columns_type(): + con = duckdb.connect() + con.execute("create table t (a MAP(VARCHAR, INTEGER)[])") + expected = "Conversion Error: Unimplemented type for cast (INTEGER -> MAP(VARCHAR, INTEGER))" + with pytest.raises(duckdb.ConversionException, match=re.escape(expected)): + con.append("t", pd.DataFrame({"a": pd.Series([[0]], dtype=object)})) + assert con.sql("select 42").fetchall() == [(42,)] + + +NANOSECOND = pd.Timestamp("2020-01-01 00:00:00.000000001") + + +@pytest.mark.parametrize( + ("value", "cell"), + [ + pytest.param("{'t': '2020-01-01'::TIMESTAMP_NS}", {"t": NANOSECOND}, id="struct_field"), + pytest.param("['2020-01-01'::TIMESTAMP_NS]", [NANOSECOND], id="list_element"), + ], +) +def test_map_nested_timestamp_ns_value_keeps_its_nanoseconds(duckdb_cursor, value, cell): + source = duckdb_cursor.sql(f"select {value} as a") + mapped = source.map(_returning(cell)) + assert mapped.types == source.types + assert "00:00:00.000000001" in mapped.project("a::VARCHAR").fetchall()[0][0] + + +def test_map_nested_timestamp_with_nanoseconds_for_an_implied_timestamp_is_refused(duckdb_cursor): + mapped = duckdb_cursor.sql("select {'t': TIMESTAMP '2020-01-01'} as a").map(_returning({"t": NANOSECOND})) + expected = ( + "Invalid Input Error: UDF column type mismatch, expected [STRUCT(t TIMESTAMP)], got [STRUCT(t TIMESTAMP_NS)]" + ) + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +FIVE_MICROSECONDS = np.datetime64("2020-01-01T00:00:00.000005123", "ns") + + +@pytest.mark.parametrize( + ("sql_type", "cell", "expected"), + [ + pytest.param( + "STRUCT(t TIMESTAMP)", + {"t": FIVE_MICROSECONDS}, + "{'t': '2020-01-01 00:00:00.000005'}", + id="datetime64_in_a_struct", + ), + pytest.param( + "STRUCT(t TIMESTAMP)", + {"t": pd.Timestamp(FIVE_MICROSECONDS)}, + "{'t': '2020-01-01 00:00:00.000005'}", + id="pandas_timestamp_in_a_struct", + ), + pytest.param("TIMESTAMP[]", [FIVE_MICROSECONDS], "['2020-01-01 00:00:00.000005']", id="datetime64_in_a_list"), + pytest.param( + "MAP(VARCHAR, TIMESTAMP)", + {"k": FIVE_MICROSECONDS}, + "{k='2020-01-01 00:00:00.000005'}", + id="datetime64_as_a_map_value", + ), + pytest.param( + "TIMESTAMP_MS[]", + [np.datetime64("2020-01-01T00:00:00.005123", "ns")], + "['2020-01-01 00:00:00.005']", + id="datetime64_in_a_list_of_milliseconds", + ), + ], +) +@pytest.mark.parametrize("mode", ["explicit_schema", "append"]) +def test_map_nested_timestamp_with_nanoseconds_for_a_stated_coarser_unit_reads_at_microseconds_as_at_the_top( + sql_type, cell, expected, mode +): + con = duckdb.connect() + con.execute(f"create table t (a {sql_type})") + if mode == "append": + con.append("t", pd.DataFrame({"a": pd.Series([cell], dtype=object)})) + rows = con.sql("select a::VARCHAR from t").fetchall() + else: + con.execute("insert into t values (NULL)") + schema = {"a": duckdb.sqltype(sql_type)} + rows = con.table("t").map(_returning(cell), schema=schema).project("a::VARCHAR").fetchall() + assert rows == [(expected,)] + + +@pytest.mark.parametrize( + "sql_type", + ["STRUCT(a INTEGER, b INTEGER)", "STRUCT(a INTEGER, t TIMESTAMP)", "STRUCT(a INTEGER, m MAP(VARCHAR, INTEGER))"], + ids=["plain_fields", "timestamp_field", "map_field"], +) +@pytest.mark.parametrize("depth", ["top", "struct_field", "list_element"]) +@pytest.mark.parametrize("mode", ["inferred", "explicit_schema", "append"]) +def test_map_tuple_reads_as_a_list_at_every_depth_so_a_struct_refuses_it(sql_type, depth, mode): + column_type, cell = { + "top": (sql_type, (3, 4)), + "struct_field": (f"STRUCT(s {sql_type})", {"s": (3, 4)}), + "list_element": (f"{sql_type}[]", [(3, 4)]), + }[depth] + con = duckdb.connect() + con.execute(f"create table t (a {column_type})") + con.execute("insert into t values (NULL)") + if mode == "append": + run = lambda: con.append("t", pd.DataFrame({"a": pd.Series([cell], dtype=object)})) # noqa: E731 + else: + schema = {"a": duckdb.sqltype(column_type)} if mode == "explicit_schema" else None + run = con.table("t").map(_returning(cell), schema=schema).fetchall + if mode == "inferred": + expected = f"UDF column type mismatch, expected [{column_type}], got [" + with pytest.raises(duckdb.InvalidInputException, match=re.escape(expected)): + run() + else: + with pytest.raises(duckdb.ConversionException, match=re.escape(f"(INTEGER[] -> {sql_type})")): + run() + assert con.sql("select 42").fetchall() == [(42,)] + + def test_map_decimal_column_handed_back_as_objects_of_18_digits_is_refused(duckdb_cursor): # df() hands a DECIMAL column over as float64, which rounds 1234567890123456.78 source = duckdb_cursor.sql("select 1234567890123456.78::DECIMAL(18,2) as a") @@ -576,7 +816,7 @@ def test_map_time_value_its_column_unit_holds_reads_unchanged(duckdb_cursor, sou ], ) def test_map_container_of_mixed_elements_reads_as_the_conversion_types_it(duckdb_cursor, source, function, expected): - # The conversion types a list or a MAP by the common type of its elements; the base refused these + # The conversion types a list or a MAP by the common type of its elements; 2.0.0 refused these relation = duckdb_cursor.sql(f"select {source} as a from range(1) t(i)") mapped = relation.map(function) assert mapped.types == relation.types @@ -644,6 +884,12 @@ def test_map_column_whose_cells_changed_in_kind_casts_into_the_schema_type(duckd ), pytest.param("{'x': i::BIGINT}", _apply_to_a(lambda d: {"x": Decimal(5)}), {"x": 5}, id="integral_decimal"), pytest.param("{'x': i::BIGINT}", _apply_to_a(lambda d: {"x": 2.0}), {"x": 2}, id="integral_float_for_bigint"), + pytest.param( + "{'t': TIMESTAMP '2020-01-01'}", + _apply_to_a(lambda d: {"t": np.datetime64("2020-01-02T00:00:00", "ns")}), + {"t": datetime.datetime(2020, 1, 2)}, + id="nanosecond_datetime64_of_whole_microseconds", + ), pytest.param( "{'x': i::DECIMAL(18,2)}", _apply_to_a(lambda d: {"x": 1234567890123.45}), @@ -698,7 +944,7 @@ def test_map_text_column_mixing_str_with_other_cells_reads_each_as_text_in_the_s @SCHEMAS -def test_map_text_list_mixing_str_with_an_int_reads_as_text_as_on_the_base(duckdb_cursor, explicit_schema): +def test_map_text_list_mixing_str_with_an_int_reads_as_text_as_2_0_0_reads_it(duckdb_cursor, explicit_schema): # A list converts by the common type of its elements, so the int reads as its text inside a text list source = duckdb_cursor.sql("select ['x', 'y'] as a from range(1) t(i)") mapped = source.map( @@ -779,6 +1025,29 @@ def test_map_bit_value_reaching_the_function_as_its_storage_bytes_is_refused( mapped.fetchall() +@SCHEMAS +def test_map_time_column_of_times_with_and_without_a_zone(duckdb_cursor, explicit_schema): + source = duckdb_cursor.sql( + "select (case when i = 1 then NULL else TIME '01:02:03.000004' end) as a from range(3) t(i)" + ) + schema = _schema_of(source, explicit_schema) + mapped = source.map(lambda df: df, schema=schema) + assert mapped.types == source.types + assert mapped.fetchall() == source.fetchall() + zone = datetime.timezone(datetime.timedelta(hours=2)) + zoned = source.map( + lambda df: df.assign(a=pd.Series([datetime.time(1, tzinfo=zone)] * len(df), dtype=object, index=df.index)), + schema=schema, + ) + if explicit_schema: + # The cast of a TIMETZ into TIME keeps the wall time and drops the offset + assert zoned.fetchall() == [(datetime.time(1),)] * 3 + else: + expected = "Invalid Input Error: UDF column type mismatch, expected [TIME], got [TIME WITH TIME ZONE]" + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + zoned.fetchall() + + def test_map_json_column_still_validates_its_text(duckdb_cursor): schema = {"a": duckdb.sqltype("JSON")} good = duckdb_cursor.sql("select 1 as a").map(_text_cells(['{"k": 1}']), schema=schema) @@ -1003,6 +1272,33 @@ def late_name(df): mapped.fetchall() +def test_map_column_filled_from_a_null_typed_input_names_the_column_and_schema(duckdb_cursor): + def fill(df): + return df.assign(c=pd.Series(["x"] * len(df), dtype=object, index=df.index)) + + mapped = duckdb_cursor.sql("select i as a, NULL as c from range(3) t(i)").map(fill) + with pytest.raises(duckdb.InvalidInputException, match=_no_type("c")): + mapped.fetchall() + + +def test_map_column_a_first_map_added_as_none_and_a_second_fills_names_the_column_and_schema(duckdb_cursor): + def add_none(df): + return df.assign(c=pd.Series([None] * len(df), dtype=object, index=df.index)) + + def fill(df): + return df.assign(c=pd.Series([1] * len(df), dtype=object, index=df.index)) + + mapped = duckdb_cursor.sql("select i as a from range(3) t(i)").map(add_none).map(fill) + with pytest.raises(duckdb.InvalidInputException, match=_no_type("c")): + mapped.fetchall() + + +def test_map_identity_of_a_null_typed_input_column_reads_null(duckdb_cursor): + mapped = duckdb_cursor.sql("select i as a, NULL as c from range(3) t(i)").map(lambda df: df) + assert mapped.types == [duckdb.sqltypes.BIGINT, duckdb.sqltypes.SQLNULL] + assert mapped.fetchall() == [(0, None), (1, None), (2, None)] + + def test_map_new_object_column_fails_on_the_first_chunk_with_a_value(duckdb_cursor): duckdb_cursor.execute("set threads = 1") rows_per_call = [] From 6746e39887f93cbe8b75151cc040b20e8708cb6f Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 22:23:05 +0000 Subject: [PATCH 27/61] Give the key and value list form of a MAP the entry rules, count a Timestamp as nanoseconds only when it has them, pick the declared cell reader once per vector --- .../duckdb_python/python_conversion.hpp | 6 +- src/native/python_conversion.cpp | 179 ++++++++++++------ src/numpy/numpy_scan.cpp | 133 +++++++++---- tests/fast/pandas/test_append_df.py | 28 +++ tests/fast/test_map_types.py | 134 +++++++++++++ 5 files changed, 382 insertions(+), 98 deletions(-) diff --git a/src/include/duckdb_python/python_conversion.hpp b/src/include/duckdb_python/python_conversion.hpp index 68ffce1f4..1337fa921 100644 --- a/src/include/duckdb_python/python_conversion.hpp +++ b/src/include/duckdb_python/python_conversion.hpp @@ -58,8 +58,10 @@ bool DictionaryHasMapFormat(const PyDictionary &dict); //! children with the connection's settings; a shaped naive timestamp reads a cell as TransformTimestamp does LogicalType AsShape(const LogicalType &type); bool IsShape(const LogicalType &type); -//! Whether a cell is a naive pandas Timestamp or a numpy datetime64 finer than a microsecond, whose nanoseconds no -//! Python datetime holds; they are then in nanoseconds +//! The nanosecond a datetime subclass such as a pandas Timestamp gives as an int, or -1 when it gives none +int64_t NanosecondOf(nb::handle cell); +//! Whether a cell is a naive pandas Timestamp with nanoseconds or a numpy datetime64 finer than a microsecond, whose +//! nanoseconds no Python datetime holds; they are then in nanoseconds bool HoldsNanoseconds(nb::handle cell, timestamp_ns_t &nanoseconds); //! A numpy scalar's Python value; a datetime64 or timedelta64 at nanoseconds would read as an integer, so those take //! the microsecond unit first, as a frame's own datetime columns do diff --git a/src/native/python_conversion.cpp b/src/native/python_conversion.cpp index a03d3839f..74baab011 100644 --- a/src/native/python_conversion.cpp +++ b/src/native/python_conversion.cpp @@ -111,6 +111,17 @@ static bool IsValidMapComponent(const nb::handle &component) { return true; } +//! The length of a MAP's key or value component, or -1 for one that has none although it claims one, as a numpy +//! array of no dimensions does +static int64_t ComponentLength(nb::handle component) { + auto length = PyObject_Length(component.ptr()); + if (length < 0) { + PyErr_Clear(); + return -1; + } + return length; +} + bool DictionaryHasMapFormat(const PyDictionary &dict) { if (dict.len != 2) { return false; @@ -137,12 +148,11 @@ bool DictionaryHasMapFormat(const PyDictionary &dict) { return true; } - // Verify that both the keys and values are of the same length - auto size = nb::len(keys); - if (size != nb::len(values)) { - return false; - } - return true; + // Verify that both the keys and values are of the same length; a component without one is refused by the + // conversion + auto key_size = ComponentLength(keys); + auto value_size = ComponentLength(values); + return key_size < 0 || value_size < 0 || key_size == value_size; } Value TransformDictionaryToStruct(optional_ptr context, const PyDictionary &dict, @@ -224,12 +234,37 @@ bool IsShape(const LogicalType &type) { return type.HasAlias() && type.GetAlias() == SHAPE_ALIAS; } +int64_t NanosecondOf(nb::handle cell) { + // Interned once, since every cell of a timestamp column asks + static PyObject *const name = PyUnicode_InternFromString("nanosecond"); + if (!name) { + PyErr_Clear(); + return -1; + } + auto nanosecond = nb::steal(PyObject_GetAttr(cell.ptr(), name)); + if (!nanosecond.is_valid()) { + PyErr_Clear(); + return -1; + } + // NaT's nanosecond is NaN + return PyLong_Check(nanosecond.ptr()) ? PyLong_AsLongLong(nanosecond.ptr()) : -1; +} + bool HoldsNanoseconds(nb::handle cell, timestamp_ns_t &nanoseconds) { auto &import_cache = *DuckDBPyConnection::ImportCache(); auto datetime_type = import_cache.datetime.datetime(); if (Py_TYPE(cell.ptr()) == reinterpret_cast(datetime_type.ptr())) { return false; } + if (duckdb::PyUtil::IsInstance(cell, datetime_type)) { + // A Timestamp without nanoseconds reads as the datetime it is: its value in nanoseconds overflows outside the + // years 1677 to 2262, and building it costs more than the datetime's own conversion + if (NanosecondOf(cell) <= 0 || !nb::getattr(cell, "tzinfo").is_none()) { + return false; + } + nanoseconds = timestamp_ns_t(nb::cast(cell.attr("value"))); + return true; + } if (duckdb::PyUtil::IsInstance(cell, import_cache.numpy.datetime64())) { auto code = nb::cast(cell.attr("dtype").attr("str")); if (!StringUtil::EndsWith(code, "ns]") && !StringUtil::EndsWith(code, "ps]") && @@ -243,13 +278,7 @@ bool HoldsNanoseconds(nb::handle cell, timestamp_ns_t &nanoseconds) { nanoseconds = timestamp_ns_t(nb::cast(value)); return true; } - if (!duckdb::PyUtil::IsInstance(cell, datetime_type) || !PandasIsImported(import_cache) || - cell.is(import_cache.pandas.NaT()) || !nb::hasattr(cell, "nanosecond") || - !nb::getattr(cell, "tzinfo").is_none()) { - return false; - } - nanoseconds = timestamp_ns_t(nb::cast(cell.attr("value"))); - return true; + return false; } nb::object NumpyScalarItem(nb::handle scalar) { @@ -286,9 +315,19 @@ Value TransformTimestamp(optional_ptr context, nb::handle ele, co return TransformPythonValue(context, ele, LogicalType::UNKNOWN, nan_as_null); } -//! Whether an object is what a shape is for: a dict for a MAP or a STRUCT, a list, a tuple or a numpy array for a -//! LIST or an ARRAY; any other object converts without a target and meets the engine's cast or the kind check, so a -//! tuple reads as a LIST at every depth, as the appender reads a value of a row +//! Whether an object is a list a shape takes: a list, a tuple or a numpy array of at least one dimension, since an +//! array of none holds a single value +static bool ShapeTakesAsList(nb::handle ele) { + if (PyList_Check(ele.ptr()) || PyTuple_Check(ele.ptr())) { + return true; + } + return duckdb::PyUtil::IsInstance(ele, DuckDBPyConnection::ImportCache()->numpy.ndarray()) && + nb::cast(ele.attr("ndim")) > 0; +} + +//! Whether an object is what a shape is for: a dict for a MAP or a STRUCT, a list for a LIST or an ARRAY; any other +//! object converts without a target and meets the engine's cast or the kind check, so a tuple reads as a LIST at +//! every depth, as the appender reads a value of a row static bool ShapeTakes(nb::handle ele, const LogicalType &shape) { switch (shape.id()) { case LogicalTypeId::MAP: @@ -296,8 +335,7 @@ static bool ShapeTakes(nb::handle ele, const LogicalType &shape) { return PyDict_Check(ele.ptr()); case LogicalTypeId::LIST: case LogicalTypeId::ARRAY: - return PyList_Check(ele.ptr()) || PyTuple_Check(ele.ptr()) || - duckdb::PyUtil::IsInstance(ele, DuckDBPyConnection::ImportCache()->numpy.ndarray()); + return ShapeTakesAsList(ele); default: return false; } @@ -324,23 +362,10 @@ static Value TransformMapEntry(optional_ptr context, nb::handle e return std::move(*cast); } -Value TransformStructFormatDictionaryToMap(optional_ptr context, const PyDictionary &dict, - const LogicalType &target_type, bool nan_as_null) { - if (dict.len == 0) { - return EmptyMapValue(); - } - - if (target_type.id() != LogicalTypeId::MAP) { - throw InvalidInputException("Please provide a valid target type for transform from Python to Value"); - } - - if (nb::none().is(dict.keys) || nb::none().is(dict.values)) { - return Value(LogicalType::MAP(LogicalTypeId::SQLNULL, LogicalTypeId::SQLNULL)); - } - - auto size = nb::len(dict.keys); - D_ASSERT(size == nb::len(dict.values)); - +//! A MAP of the entries of a sequence of keys and one of values, both of the given size; under a shape each key and +//! value converts as TransformMapEntry reads it +static Value MapFromEntries(optional_ptr context, nb::handle keys, nb::handle values, idx_t size, + const LogicalType &target_type, bool nan_as_null) { auto key_target = MapType::KeyType(target_type); auto value_target = MapType::ValueType(target_type); auto shape = IsShape(target_type); @@ -351,8 +376,8 @@ Value TransformStructFormatDictionaryToMap(optional_ptr context, vector elements; for (idx_t i = 0; i < size; i++) { - auto key = dict.keys.attr("__getitem__")(i); - auto value = dict.values.attr("__getitem__")(i); + auto key = keys.attr("__getitem__")(i); + auto value = values.attr("__getitem__")(i); Value new_key = shape ? TransformMapEntry(context, key, key_target, nan_as_null) : TransformPythonValue(context, key, key_target, nan_as_null); Value new_value = shape ? TransformMapEntry(context, value, value_target, nan_as_null) @@ -382,6 +407,25 @@ Value TransformStructFormatDictionaryToMap(optional_ptr context, return Value::MAP(ListType::GetChildType(map_type), std::move(elements)); } +Value TransformStructFormatDictionaryToMap(optional_ptr context, const PyDictionary &dict, + const LogicalType &target_type, bool nan_as_null) { + if (dict.len == 0) { + return EmptyMapValue(); + } + + if (target_type.id() != LogicalTypeId::MAP) { + throw InvalidInputException("Please provide a valid target type for transform from Python to Value"); + } + + if (nb::none().is(dict.keys) || nb::none().is(dict.values)) { + return Value(LogicalType::MAP(LogicalTypeId::SQLNULL, LogicalTypeId::SQLNULL)); + } + + auto size = nb::len(dict.keys); + D_ASSERT(size == nb::len(dict.values)); + return MapFromEntries(context, dict.keys, dict.values, size, target_type, nan_as_null); +} + Value TransformDictionaryToMap(optional_ptr context, const PyDictionary &dict, const LogicalType &target_type, bool nan_as_null) { if (target_type.id() != LogicalTypeId::UNKNOWN && !DictionaryHasMapFormat(dict)) { @@ -397,9 +441,9 @@ Value TransformDictionaryToMap(optional_ptr context, const PyDict return Value(LogicalType::MAP(LogicalTypeId::SQLNULL, LogicalTypeId::SQLNULL)); } - auto key_size = nb::len(keys); - D_ASSERT(key_size == nb::len(values)); - if (key_size == 0) { + auto key_size = ComponentLength(keys); + auto sized = key_size >= 0 && ComponentLength(values) >= 0; + if (sized && key_size == 0) { // dict == { 'key': [], 'value': [] } return EmptyMapValue(); } @@ -408,19 +452,35 @@ Value TransformDictionaryToMap(optional_ptr context, const PyDict LogicalType key_target = LogicalTypeId::UNKNOWN; LogicalType value_target = LogicalTypeId::UNKNOWN; - if (target_type.id() != LogicalTypeId::UNKNOWN) { + if (IsShape(target_type)) { + // A shape reads the two lists entry by entry, as it reads a dict's own entries; a component that is no list + // converts without a target and is refused below + if (sized && ShapeTakesAsList(keys) && ShapeTakesAsList(values)) { + auto items = [](nb::handle list) { + return PyList_Check(list.ptr()) || PyTuple_Check(list.ptr()) ? nb::borrow(list) + : list.attr("tolist")(); + }; + return MapFromEntries(context, items(keys), items(values), key_size, target_type, nan_as_null); + } + } else if (target_type.id() != LogicalTypeId::UNKNOWN) { key_target = LogicalType::LIST(MapType::KeyType(target_type)); value_target = LogicalType::LIST(MapType::ValueType(target_type)); } auto key_list = TransformPythonValue(context, keys, key_target, nan_as_null); auto value_list = TransformPythonValue(context, values, value_target, nan_as_null); + if (key_list.type().id() != LogicalTypeId::LIST || value_list.type().id() != LogicalTypeId::LIST || + ListValue::GetChildren(key_list).size() != ListValue::GetChildren(value_list).size()) { + throw InvalidInputException("A dict of 'key' and 'value' for a MAP takes a list of keys and a list of values, " + "not %s and %s", + key_list.type().ToString(), value_list.type().ToString()); + } LogicalType key_type = LogicalType::SQLNULL; LogicalType value_type = LogicalType::SQLNULL; vector elements; - for (idx_t i = 0; i < key_size; i++) { + for (idx_t i = 0; i < ListValue::GetChildren(key_list).size(); i++) { Value new_key = ListValue::GetChildren(key_list)[i]; Value new_value = ListValue::GetChildren(value_list)[i]; @@ -1338,21 +1398,32 @@ void TransformPythonObject(optional_ptr context, nb::handle ele, TransformPythonObjectInternal(context, ele, vector, result_offset, nan_as_null); } +//! A shape of no children marks a timestamp, read as TransformTimestamp reads it; a container shape takes only the +//! objects it is for, so a scalar inside a container meets the engine's cast as at the top, never a type holding +//! UNKNOWN +static Value TransformShapedValue(optional_ptr context, nb::handle ele, const LogicalType &shape, + bool nan_as_null) { + if (!shape.IsNested()) { + return TransformTimestamp(context, ele, shape, nan_as_null); + } + if (!ShapeTakes(ele, shape)) { + return TransformPythonValue(context, ele, LogicalType::UNKNOWN, nan_as_null); + } + Value result; + TransformPythonObjectInternal(context, ele, result, shape, nan_as_null); + return result; +} + Value TransformPythonValue(optional_ptr context, nb::handle ele, const LogicalType &target_type, bool nan_as_null) { - // A shape of no children marks a timestamp, read as TransformTimestamp reads it; a container shape takes only the - // objects it is for, so a scalar inside a container meets the engine's cast as at the top, never a type holding - // UNKNOWN - if (IsShape(target_type)) { - if (!target_type.IsNested()) { - return TransformTimestamp(context, ele, target_type, nan_as_null); - } - if (!ShapeTakes(ele, target_type)) { - return TransformPythonValue(context, ele, LogicalType::UNKNOWN, nan_as_null); - } - } + // One named result on every path, so it is built in place rather than moved out for every value converted; a + // conversion without a target, the most common, asks for no alias Value result; - TransformPythonObjectInternal(context, ele, result, target_type, nan_as_null); + if (target_type.id() != LogicalTypeId::UNKNOWN && IsShape(target_type)) { + result = TransformShapedValue(context, ele, target_type, nan_as_null); + } else { + TransformPythonObjectInternal(context, ele, result, target_type, nan_as_null); + } return result; } diff --git a/src/numpy/numpy_scan.cpp b/src/numpy/numpy_scan.cpp index ece998c83..2d82fde93 100644 --- a/src/numpy/numpy_scan.cpp +++ b/src/numpy/numpy_scan.cpp @@ -317,11 +317,13 @@ static bool IsNumpyScalar(nb::handle cell) { return cell.type().is(import_cache.numpy.ndarray()) && nb::cast(cell.attr("ndim")) == 0; } -//! With a shape (KeyedShape) the cell converts with it as its target, which a type holding a MAP needs: without it a -//! dict reads as a STRUCT named by its keys' text, and a key whose text does not cast back, such as bytes, is lost. +//! The cell converts with the column type's shape (KeyedShape) as its target, or with UNKNOWN for a type that takes +//! none; a type holding a MAP needs one: without it a dict reads as a STRUCT named by its keys' text, and a key whose +//! text does not cast back, such as bytes, is lost. Both are built once per vector, since building a type looks up +//! its type information each time. //! An object without a DuckDB type reads as its text into a stated VARCHAR, and has no kind for an implied one. -static Value DeclaredValue(ClientContext &context, const LogicalType &target, nb::handle cell, - optional_ptr shape, bool implied) { +static Value DeclaredValue(ClientContext &context, const LogicalType &target, nb::handle cell, const LogicalType &shape, + bool implied) { if (cell.ptr() == Py_None) { return Value(); } @@ -346,7 +348,7 @@ static Value DeclaredValue(ClientContext &context, const LogicalType &target, nb if (!implied && target.id() == LogicalTypeId::VARCHAR && GetPythonObjectType(cell) == PythonObjectType::Other) { return Value(TransformPythonString(nb::str(cell))); } - return TransformPythonValue(context, cell, shape ? *shape : LogicalType(LogicalTypeId::UNKNOWN), true); + return TransformPythonValue(context, cell, shape, true); } //! The type a cell of a nested type converts with: its containers and its naive timestamps and no other type, so a @@ -404,7 +406,7 @@ class DeclaredVector { written_count++; } - void Set(idx_t row, Value value) { + void Set(idx_t row, Value &&value) { if (value.IsNull()) { return; } @@ -420,6 +422,17 @@ class DeclaredVector { if (written_count == count) { return; } + // A vector the scan wrote no row of skips the test for one, which would cost every row of the plain path + if (written_count == 0) { + WriteStaged(context, out, count); + } else { + WriteStaged(context, out, count); + } + } + +private: + template + void WriteStaged(ClientContext &context, Vector &out, idx_t count) { auto &target = out.GetType(); if (uniform && source.id() != LogicalTypeId::SQLNULL && source != target) { idx_t present = 0; @@ -441,7 +454,7 @@ class DeclaredVector { VectorOperations::TryCast(context, staged, casted, present, nullptr); idx_t copied = 0; for (idx_t row = 0; row < count;) { - if (written[row]) { + if (SKIP_WRITTEN && written[row]) { row++; continue; } @@ -462,18 +475,21 @@ class DeclaredVector { } DeclaredCasts casts(context, target); for (idx_t row = 0; row < count; row++) { - if (written[row]) { + if (SKIP_WRITTEN && written[row]) { continue; } - if (values[row].IsNull()) { + auto &value = values[row]; + if (value.IsNull()) { FlatVector::SetNull(out, row, true); + } else if (value.type() == target) { + // Written as it is, without the copy of the Value that a cast of it would return + out.SetValue(row, value); } else { - out.SetValue(row, casts.Cast(values[row])); + out.SetValue(row, casts.Cast(value)); } } } -private: vector values; vector written; idx_t written_count = 0; @@ -932,18 +948,34 @@ void NumpyScan::ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP) || TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP_MS) || TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP_SEC)); - const auto holds_bit = TypeVisitor::Contains(target, LogicalTypeId::BIT); + const auto bits_refused = bit_storage_refused && TypeVisitor::Contains(target, LogicalTypeId::BIT); const auto shape = keyed ? KeyedShape(target, !implied_type) : LogicalType(LogicalTypeId::UNKNOWN); - // A str into VARCHAR without an alias, bytes or a bytearray into BLOB without one, and a time without a zone into - // TIME read as TransformPythonValue would read them, without building a Value per cell; a collation governs - // comparison only, an alias such as JSON validates the text in its cast - const bool plain_text = target == LogicalType::VARCHAR; - const bool plain_blob = target == LogicalType::BLOB; - const bool plain_time = target == LogicalType::TIME; - PyObject *time_type = nullptr; ImpliedKinds kinds(context); - ScanObjectCells(context, col, stride, masked, count, offset, out, [&](nb::handle cell, idx_t row) { - if (plain_text && PyUnicode_CheckExact(cell.ptr())) { + auto read = [&](nb::handle cell, idx_t row) { + // The row already holds the NULL a None reads as + if (cell.ptr() == Py_None) { + return; + } + auto value = DeclaredValue(context, target, cell, shape, implied_type); + // A duckdb.Value states its type, as a schema does, so a cast into the column's type is meant + if (implied_type && !kinds.Fits(value, target) && + !duckdb::PyUtil::IsInstance(cell, DuckDBPyConnection::ImportCache()->duckdb.Value())) { + throw ImpliedTypeRefused(value.type()); + } + if (bits_refused && ImpliedKinds::HoldsBitStorage(value, target)) { + throw ImpliedTypeRefused(value.type()); + } + staged.Set(row, std::move(value)); + }; + // A str into VARCHAR without an alias, bytes or a bytearray into BLOB without one, and a time or a datetime without + // a zone into TIME or TIMESTAMP read as TransformPythonValue would read them, without building a Value per cell; a + // collation governs comparison only, an alias such as JSON validates the text in its cast. The reader is chosen + // once per vector, since a test per cell for every fast path costs the plain path more than the tests themselves. + if (target == LogicalType::VARCHAR) { + ScanObjectCells(context, col, stride, masked, count, offset, out, [&](nb::handle cell, idx_t row) { + if (!PyUnicode_CheckExact(cell.ptr())) { + return read(cell, row); + } Py_ssize_t size; auto text = PyUnicode_AsUTF8AndSize(cell.ptr(), &size); if (!text) { @@ -952,33 +984,36 @@ void NumpyScan::ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t FlatVector::GetDataMutable(out)[row] = StringVector::AddString(out, text, NumericCast(size)); staged.MarkWritten(row); - return; - } + }); + } else if (target == LogicalType::BLOB) { // df() hands a BLOB cell to the function as a bytearray - if (plain_blob && (PyBytes_CheckExact(cell.ptr()) || PyByteArray_CheckExact(cell.ptr()))) { + ScanObjectCells(context, col, stride, masked, count, offset, out, [&](nb::handle cell, idx_t row) { char *data; Py_ssize_t size; if (PyBytes_CheckExact(cell.ptr())) { if (PyBytes_AsStringAndSize(cell.ptr(), &data, &size) < 0) { throw nb::python_error(); } - } else { + } else if (PyByteArray_CheckExact(cell.ptr())) { data = PyByteArray_AsString(cell.ptr()); size = PyByteArray_Size(cell.ptr()); if (!data || size < 0) { throw nb::python_error(); } + } else { + return read(cell, row); } FlatVector::GetDataMutable(out)[row] = StringVector::AddStringOrBlob(out, data, NumericCast(size)); staged.MarkWritten(row); - return; - } - if (plain_time) { + }); + } else if (target == LogicalType::TIME) { + PyTypeObject *time_type = nullptr; + ScanObjectCells(context, col, stride, masked, count, offset, out, [&](nb::handle cell, idx_t row) { if (!time_type) { - time_type = DuckDBPyConnection::ImportCache()->datetime.time().ptr(); + time_type = reinterpret_cast(DuckDBPyConnection::ImportCache()->datetime.time().ptr()); } - if (Py_TYPE(cell.ptr()) == reinterpret_cast(time_type)) { + if (Py_TYPE(cell.ptr()) == time_type) { PyTime time(cell); // A time with a zone converts as a TIMETZ, which an implied TIME refuses and the cast into a stated one // reads without its offset @@ -988,18 +1023,32 @@ void NumpyScan::ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t return; } } - } - auto value = DeclaredValue(context, target, cell, keyed ? &shape : nullptr, implied_type); - // A duckdb.Value states its type, as a schema does, so a cast into the column's type is meant - if (implied_type && !kinds.Fits(value, target) && - !duckdb::PyUtil::IsInstance(cell, DuckDBPyConnection::ImportCache()->duckdb.Value())) { - throw ImpliedTypeRefused(value.type()); - } - if (bit_storage_refused && holds_bit && ImpliedKinds::HoldsBitStorage(value, target)) { - throw ImpliedTypeRefused(value.type()); - } - staged.Set(row, std::move(value)); - }); + read(cell, row); + }); + } else if (target == LogicalType::TIMESTAMP) { + PyTypeObject *datetime_type = nullptr; + ScanObjectCells(context, col, stride, masked, count, offset, out, [&](nb::handle cell, idx_t row) { + if (!datetime_type) { + datetime_type = + reinterpret_cast(DuckDBPyConnection::ImportCache()->datetime.datetime().ptr()); + } + // A datetime, or a pandas Timestamp without nanoseconds, holds what the conversion reads + auto type = Py_TYPE(cell.ptr()); + if (type == datetime_type || (PyType_IsSubtype(type, datetime_type) && NanosecondOf(cell) == 0)) { + PyDateTime datetime(cell); + // A datetime with a zone converts as a TIMESTAMPTZ, which an implied TIMESTAMP refuses and the cast + // into a stated one reads in the session's time zone + if (datetime.tzone_obj.is_none()) { + FlatVector::GetDataMutable(out)[row] = datetime.ToTimestamp(); + staged.MarkWritten(row); + return; + } + } + read(cell, row); + }); + } else { + ScanObjectCells(context, col, stride, masked, count, offset, out, read); + } staged.Write(context, out, count); VerifyTypeConstraints(out, count); } diff --git a/tests/fast/pandas/test_append_df.py b/tests/fast/pandas/test_append_df.py index b5b40fed0..93f81ca7f 100644 --- a/tests/fast/pandas/test_append_df.py +++ b/tests/fast/pandas/test_append_df.py @@ -512,6 +512,34 @@ def test_map_key_given_as_a_tuple_for_a_struct_key_type_reads_as_a_list_and_is_r duckdb_cursor.append("t", frame) assert duckdb_cursor.sql("SELECT 42").fetchall() == [(42,)] + @pytest.mark.parametrize( + ("target", "value", "expected"), + [ + pytest.param( + "TIMESTAMPTZ", + datetime.datetime(2024, 5, 6), + "{k='2024-05-06 00:00:00-04'}", + id="naive_datetime_into_timestamptz", + ), + pytest.param("VARCHAR", b"x", "{k=x}", id="bytes_into_varchar"), + pytest.param("DECIMAL(9,2)", 1.5, "{k=1.50}", id="float_into_decimal"), + pytest.param( + "TIMESTAMP_NS", + datetime.datetime(2024, 5, 6), + "{k='2024-05-06 00:00:00'}", + id="datetime_into_timestamp_ns", + ), + ], + ) + def test_map_of_key_and_value_lists_reads_each_entry_as_the_same_dict_does( + self, duckdb_cursor, target, value, expected + ): + duckdb_cursor.execute("SET TimeZone = 'America/New_York'") + duckdb_cursor.execute(f"CREATE TABLE t (a MAP(VARCHAR, {target}))") + frame = pd.DataFrame({"a": pd.Series([{"key": ["k"], "value": [value]}, {"k": value}], dtype=object)}) + duckdb_cursor.append("t", frame) + assert duckdb_cursor.sql("SELECT a::VARCHAR FROM t").fetchall() == [(expected,), (expected,)] + def test_map_keys_a_str_and_its_bytes_are_one_key_and_refused(self, duckdb_cursor): duckdb_cursor.execute("CREATE TABLE t (a MAP(VARCHAR, INTEGER))") frame = pd.DataFrame({"a": pd.Series([{"a": 1, b"a": 2}], dtype=object)}) diff --git a/tests/fast/test_map_types.py b/tests/fast/test_map_types.py index 0a54fd85f..d541635ce 100644 --- a/tests/fast/test_map_types.py +++ b/tests/fast/test_map_types.py @@ -596,6 +596,71 @@ def test_map_timestamp_column_given_a_timestamp_with_nanoseconds_is_refused(duck mapped.fetchall() +def _far_from_1970(value): + return pytest.param(value, id=value[:4]) + + +FAR_YEARS = pytest.mark.parametrize( + "value", [_far_from_1970("1500-01-01"), _far_from_1970("2500-01-01"), _far_from_1970("9999-12-31")] +) + + +@FAR_YEARS +@pytest.mark.parametrize("sql_type", ["TIMESTAMP", "TIMESTAMP_S"]) +def test_map_timestamp_column_handed_back_as_timestamps_outside_the_nanosecond_range_round_trips( + duckdb_cursor, sql_type, value +): + source = duckdb_cursor.sql(f"select '{value}'::{sql_type} as a") + mapped = source.map(lambda df: df.assign(a=df["a"].astype(object))) + assert mapped.types == source.types + assert mapped.fetchall() == source.fetchall() + + +@FAR_YEARS +def test_map_struct_field_given_a_timestamp_outside_the_nanosecond_range_reads_it(duckdb_cursor, value): + source = duckdb_cursor.sql(f"select {{'t': '{value}'::TIMESTAMP}} as a") + mapped = source.map(_returning({"t": pd.Timestamp(value)})) + assert mapped.types == source.types + assert mapped.fetchall() == source.fetchall() + + +def test_map_timestamp_column_of_2020_and_9999_handed_back_as_timestamps_round_trips(duckdb_cursor): + source = duckdb_cursor.sql( + "select (case when i = 0 then '2020-01-01' else '9999-12-31' end)::TIMESTAMP as a from range(2) t(i)" + ) + mapped = source.map(lambda df: df.assign(a=df["a"].astype(object))) + assert mapped.types == source.types + assert mapped.fetchall() == source.fetchall() + + +@SCHEMAS +def test_map_timestamp_ns_column_given_a_timestamp_beyond_its_range_is_refused(duckdb_cursor, explicit_schema): + source = duckdb_cursor.sql("select TIMESTAMP_NS '2020-01-01' as a") + mapped = source.map(_returning(pd.Timestamp("9999-12-31")), schema=_schema_of(source, explicit_schema)) + if explicit_schema: + expected = "UDF column 'a': Could not convert Timestamp to higher precision" + with pytest.raises(duckdb.ConversionException, match=re.escape(expected)): + mapped.fetchall() + else: + expected = "Invalid Input Error: UDF column type mismatch, expected [TIMESTAMP_NS], got [TIMESTAMP]" + with pytest.raises(duckdb.InvalidInputException, match=f"^{re.escape(expected)}$"): + mapped.fetchall() + + +@pytest.mark.parametrize( + "value", + ["infinity", "-infinity", "2262-04-11 23:47:16.854775806"], + ids=["infinity", "minus_infinity", "largest_finite_nanosecond_but_one"], +) +@SCHEMAS +def test_map_timestamp_ns_identity_handed_back_as_timestamps_keeps_infinity(duckdb_cursor, value, explicit_schema): + # df() hands an infinity over as pandas' Timestamp.max or Timestamp.min, which read back as that infinity + source = duckdb_cursor.sql(f"select '{value}'::TIMESTAMP_NS as a") + mapped = source.map(lambda df: df.assign(a=df["a"].astype(object)), schema=_schema_of(source, explicit_schema)) + assert mapped.types == source.types + assert mapped.project("a::VARCHAR").fetchall() == [(value,)] + + # A scalar inside a container of a type holding a MAP, which meets the engine's cast or the kind check, never a # conversion target holding no type NESTED_SCALARS = pytest.mark.parametrize( @@ -607,6 +672,12 @@ def test_map_timestamp_column_given_a_timestamp_with_nanoseconds_is_refused(duck pytest.param("MAP(VARCHAR, INTEGER)[]", np.array([0, 1]), "MAP(VARCHAR, INTEGER)", id="int_array_for_a_list"), pytest.param("MAP(VARCHAR, INTEGER)[]", (0,), "MAP(VARCHAR, INTEGER)", id="tuple_for_a_list"), pytest.param("MAP(VARCHAR, STRUCT(x INTEGER))", {"k": "abc"}, "STRUCT(x INTEGER)", id="str_for_a_struct_value"), + pytest.param( + "MAP(VARCHAR, INTEGER)[][]", + [np.array(5)], + "MAP(VARCHAR, INTEGER)[]", + id="zero_dimensional_array_for_a_list", + ), ], ) @@ -646,6 +717,69 @@ def test_map_scalar_inside_a_container_of_a_type_holding_a_map_is_refused_and_th assert con.sql("select 42").fetchall() == [(42,)] +@pytest.mark.parametrize( + ("sql_type", "cell", "converted"), + [ + pytest.param("MAP(VARCHAR, VARCHAR)", {"key": "ab", "value": "cd"}, "VARCHAR and VARCHAR", id="map"), + pytest.param( + "STRUCT(m MAP(VARCHAR, VARCHAR))", + {"m": {"key": "ab", "value": "cd"}}, + "VARCHAR and VARCHAR", + id="map_field", + ), + pytest.param( + "MAP(VARCHAR, INTEGER)", + {"key": np.array("a"), "value": np.array(1)}, + "VARCHAR and INTEGER", + id="zero_dimensional_arrays", + ), + ], +) +@pytest.mark.parametrize("mode", ["inferred", "explicit_schema", "append", "appender", "parameter"]) +def test_map_of_a_key_and_a_value_that_are_no_lists_is_refused_and_the_database_stays_usable( + sql_type, cell, converted, mode +): + con = duckdb.connect() + con.execute(f"create table t (a {sql_type})") + if mode == "append": + run = lambda: con.append("t", pd.DataFrame({"a": pd.Series([cell], dtype=object)})) # noqa: E731 + elif mode == "appender": + + def run(): + with con.appender("t") as appender: + appender.append_row(cell) + + elif mode == "parameter": + run = lambda: con.execute("insert into t values (?)", [cell]) # noqa: E731 + else: + con.execute("insert into t values (NULL)") + schema = {"a": duckdb.sqltype(sql_type)} if mode == "explicit_schema" else None + run = con.table("t").map(_returning(cell), schema=schema).fetchall + expected = f"A dict of 'key' and 'value' for a MAP takes a list of keys and a list of values, not {converted}" + with pytest.raises(duckdb.InvalidInputException, match=re.escape(expected)): + run() + assert con.sql("select 42").fetchall() == [(42,)] + + +@pytest.mark.parametrize( + ("cell", "expected"), + [ + pytest.param({"key": ["k"], "value": [5]}, "{k=5}", id="list_of_an_int"), + pytest.param({"key": ("k",), "value": (5,)}, "{k=5}", id="tuple_of_an_int"), + pytest.param({"key": np.array(["k"]), "value": np.array([5])}, "{k=5}", id="numpy_arrays"), + pytest.param({"key": ["a", "b"], "value": [2**60 + 1, 1]}, "{a=1152921504606846977, b=1}", id="wide_ints"), + ], +) +@SCHEMAS +def test_map_of_key_and_value_lists_reads_each_entry_as_a_dicts_entry_reads( + duckdb_cursor, cell, expected, explicit_schema +): + source = duckdb_cursor.sql("select MAP {'k': 1::BIGINT} as a") + mapped = source.map(_returning(cell), schema=_schema_of(source, explicit_schema)) + assert mapped.types == source.types + assert mapped.project("a::VARCHAR").fetchall() == [(expected,)] + + def test_map_cast_error_for_a_nested_scalar_names_the_columns_type(): con = duckdb.connect() con.execute("create table t (a MAP(VARCHAR, INTEGER)[])") From 66a35e7ea22f0b628a9faae077264f42191327ea Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 6 Nov 2026 23:48:36 +0000 Subject: [PATCH 28/61] Read an aware datetime once in the TIMESTAMP fast path and detect the key and value form of a MAP by its components --- src/native/python_conversion.cpp | 35 ++++++------- src/numpy/numpy_scan.cpp | 19 ++++--- tests/fast/pandas/test_append_df.py | 6 +++ tests/fast/test_map_types.py | 77 +++++++++++++++++++++++++++-- 4 files changed, 104 insertions(+), 33 deletions(-) diff --git a/src/native/python_conversion.cpp b/src/native/python_conversion.cpp index 74baab011..1e5f4ad69 100644 --- a/src/native/python_conversion.cpp +++ b/src/native/python_conversion.cpp @@ -97,18 +97,11 @@ static vector TransformStructKeys(nb::handle keys, idx_t size) { return res; } -static bool IsValidMapComponent(const nb::handle &component) { - // The component is either NULL - if (nb::none().is(component)) { - return true; - } - if (!nb::hasattr(component, "__getitem__")) { - return false; - } - if (!nb::hasattr(component, "__len__")) { - return false; - } - return true; +//! Whether a MAP's key or value component is a column of keys or values: a list, a tuple or a numpy array, which the +//! conversion reads as a LIST (an array of no dimensions it refuses) +static bool IsMapComponentList(nb::handle component) { + return PyList_Check(component.ptr()) || PyTuple_Check(component.ptr()) || + duckdb::PyUtil::IsInstance(component, DuckDBPyConnection::ImportCache()->numpy.ndarray()); } //! The length of a MAP's key or value component, or -1 for one that has none although it claims one, as a numpy @@ -136,15 +129,17 @@ bool DictionaryHasMapFormat(const PyDictionary &dict) { return false; } - if (!IsValidMapComponent(keys)) { - return false; - } - if (!IsValidMapComponent(values)) { + // A list on either side, or None on both, makes the dict a MAP of the two lists: None a NULL MAP, and the + // conversion refuses the other side when it is no list. Without a list it is a plain dict, a MAP of the entries + // 'key' and 'value', so a NULL entry beside a plain value stays an entry + auto key_none = nb::none().is(keys); + auto value_none = nb::none().is(values); + auto key_list = IsMapComponentList(keys); + auto value_list = IsMapComponentList(values); + if (!key_list && !value_list && !(key_none && value_none)) { return false; } - - // If either of the components is NULL, return early - if (nb::none().is(keys) || nb::none().is(values)) { + if (key_none || value_none || !key_list || !value_list) { return true; } @@ -258,7 +253,7 @@ bool HoldsNanoseconds(nb::handle cell, timestamp_ns_t &nanoseconds) { } if (duckdb::PyUtil::IsInstance(cell, datetime_type)) { // A Timestamp without nanoseconds reads as the datetime it is: its value in nanoseconds overflows outside the - // years 1677 to 2262, and building it costs more than the datetime's own conversion + // years 1677 to 2262, and a coarser column would judge that value by a cast where the datetime fits outright if (NanosecondOf(cell) <= 0 || !nb::getattr(cell, "tzinfo").is_none()) { return false; } diff --git a/src/numpy/numpy_scan.cpp b/src/numpy/numpy_scan.cpp index 2d82fde93..4e724b138 100644 --- a/src/numpy/numpy_scan.cpp +++ b/src/numpy/numpy_scan.cpp @@ -951,12 +951,7 @@ void NumpyScan::ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t const auto bits_refused = bit_storage_refused && TypeVisitor::Contains(target, LogicalTypeId::BIT); const auto shape = keyed ? KeyedShape(target, !implied_type) : LogicalType(LogicalTypeId::UNKNOWN); ImpliedKinds kinds(context); - auto read = [&](nb::handle cell, idx_t row) { - // The row already holds the NULL a None reads as - if (cell.ptr() == Py_None) { - return; - } - auto value = DeclaredValue(context, target, cell, shape, implied_type); + auto accept = [&](nb::handle cell, idx_t row, Value &&value) { // A duckdb.Value states its type, as a schema does, so a cast into the column's type is meant if (implied_type && !kinds.Fits(value, target) && !duckdb::PyUtil::IsInstance(cell, DuckDBPyConnection::ImportCache()->duckdb.Value())) { @@ -967,6 +962,13 @@ void NumpyScan::ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t } staged.Set(row, std::move(value)); }; + auto read = [&](nb::handle cell, idx_t row) { + // The row already holds the NULL a None reads as + if (cell.ptr() == Py_None) { + return; + } + accept(cell, row, DeclaredValue(context, target, cell, shape, implied_type)); + }; // A str into VARCHAR without an alias, bytes or a bytearray into BLOB without one, and a time or a datetime without // a zone into TIME or TIMESTAMP read as TransformPythonValue would read them, without building a Value per cell; a // collation governs comparison only, an alias such as JSON validates the text in its cast. The reader is chosen @@ -1036,13 +1038,14 @@ void NumpyScan::ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t auto type = Py_TYPE(cell.ptr()); if (type == datetime_type || (PyType_IsSubtype(type, datetime_type) && NanosecondOf(cell) == 0)) { PyDateTime datetime(cell); - // A datetime with a zone converts as a TIMESTAMPTZ, which an implied TIMESTAMP refuses and the cast - // into a stated one reads in the session's time zone if (datetime.tzone_obj.is_none()) { FlatVector::GetDataMutable(out)[row] = datetime.ToTimestamp(); staged.MarkWritten(row); return; } + // A datetime with a zone converts as a TIMESTAMPTZ, as the conversion reads the one built here, which + // an implied TIMESTAMP refuses and the cast into a stated one reads in the session's time zone + return accept(cell, row, datetime.ToDuckValue(LogicalType::UNKNOWN)); } read(cell, row); }); diff --git a/tests/fast/pandas/test_append_df.py b/tests/fast/pandas/test_append_df.py index 93f81ca7f..1083016fe 100644 --- a/tests/fast/pandas/test_append_df.py +++ b/tests/fast/pandas/test_append_df.py @@ -540,6 +540,12 @@ def test_map_of_key_and_value_lists_reads_each_entry_as_the_same_dict_does( duckdb_cursor.append("t", frame) assert duckdb_cursor.sql("SELECT a::VARCHAR FROM t").fetchall() == [(expected,), (expected,)] + def test_map_of_two_plain_values_named_key_and_value_appends_its_entries(self, duckdb_cursor): + duckdb_cursor.execute("CREATE TABLE t (a MAP(VARCHAR, VARCHAR))") + frame = pd.DataFrame({"a": pd.Series([{"key": "ab", "value": "cd"}], dtype=object)}) + duckdb_cursor.append("t", frame) + assert duckdb_cursor.table("t").fetchall() == [({"key": "ab", "value": "cd"},)] + def test_map_keys_a_str_and_its_bytes_are_one_key_and_refused(self, duckdb_cursor): duckdb_cursor.execute("CREATE TABLE t (a MAP(VARCHAR, INTEGER))") frame = pd.DataFrame({"a": pd.Series([{"a": 1, b"a": 2}], dtype=object)}) diff --git a/tests/fast/test_map_types.py b/tests/fast/test_map_types.py index d541635ce..1b4f9b34c 100644 --- a/tests/fast/test_map_types.py +++ b/tests/fast/test_map_types.py @@ -606,7 +606,7 @@ def _far_from_1970(value): @FAR_YEARS -@pytest.mark.parametrize("sql_type", ["TIMESTAMP", "TIMESTAMP_S"]) +@pytest.mark.parametrize("sql_type", ["TIMESTAMP", "TIMESTAMP_MS", "TIMESTAMP_S"]) def test_map_timestamp_column_handed_back_as_timestamps_outside_the_nanosecond_range_round_trips( duckdb_cursor, sql_type, value ): @@ -720,11 +720,11 @@ def test_map_scalar_inside_a_container_of_a_type_holding_a_map_is_refused_and_th @pytest.mark.parametrize( ("sql_type", "cell", "converted"), [ - pytest.param("MAP(VARCHAR, VARCHAR)", {"key": "ab", "value": "cd"}, "VARCHAR and VARCHAR", id="map"), + pytest.param("MAP(VARCHAR, VARCHAR)", {"key": ["a"], "value": "b"}, "VARCHAR[] and VARCHAR", id="map"), pytest.param( "STRUCT(m MAP(VARCHAR, VARCHAR))", - {"m": {"key": "ab", "value": "cd"}}, - "VARCHAR and VARCHAR", + {"m": {"key": ["a"], "value": "b"}}, + "VARCHAR[] and VARCHAR", id="map_field", ), pytest.param( @@ -736,7 +736,7 @@ def test_map_scalar_inside_a_container_of_a_type_holding_a_map_is_refused_and_th ], ) @pytest.mark.parametrize("mode", ["inferred", "explicit_schema", "append", "appender", "parameter"]) -def test_map_of_a_key_and_a_value_that_are_no_lists_is_refused_and_the_database_stays_usable( +def test_map_of_a_key_list_and_a_value_that_is_no_list_is_refused_and_the_database_stays_usable( sql_type, cell, converted, mode ): con = duckdb.connect() @@ -761,6 +761,73 @@ def run(): assert con.sql("select 42").fetchall() == [(42,)] +@pytest.mark.parametrize( + "value", + [ + "MAP {'key': 'ab', 'value': 'cd'}", + "MAP {'key': 'ab', 'value': 'cde'}", + "MAP {'key': 1, 'value': 2}", + "MAP {'key': 'x', 'value': NULL}", + "MAP {'key': NULL, 'value': 'y'}", + ], + ids=["text_of_one_length", "text_of_two_lengths", "ints", "null_value", "null_key_entry"], +) +@SCHEMAS +def test_map_identity_of_a_map_keyed_by_key_and_value_reads_its_entries(duckdb_cursor, value, explicit_schema): + # df() hands such a MAP over as the dict of its two entries, which no list makes a dict of key and value lists + source = duckdb_cursor.sql(f"select {value} as a") + mapped = source.map(lambda df: df, schema=_schema_of(source, explicit_schema)) + assert mapped.types == source.types + assert mapped.fetchall() == source.fetchall() + + +@pytest.mark.parametrize( + "value", ["MAP {'key': NULL, 'value': NULL}", "MAP {'key': [1], 'value': NULL}"], ids=["both_null", "list_and_null"] +) +@SCHEMAS +def test_map_identity_of_a_map_keyed_by_key_and_value_of_a_null_beside_a_list_or_a_null_reads_null( + duckdb_cursor, value, explicit_schema +): + # df() hands it over as {"key": None, "value": None} or {"key": [1], "value": None}, the forms of a NULL MAP + source = duckdb_cursor.sql(f"select {value} as a") + mapped = source.map(lambda df: df, schema=_schema_of(source, explicit_schema)) + assert mapped.types == source.types + assert mapped.fetchall() == [(None,)] + + +@pytest.mark.parametrize("mode", ["append", "appender", "parameter"]) +def test_map_of_a_null_key_entry_beside_a_plain_value_reads_its_two_entries(mode): + cell = {"key": None, "value": 5} + con = duckdb.connect() + con.execute("create table t (a MAP(VARCHAR, INTEGER))") + if mode == "append": + con.append("t", pd.DataFrame({"a": pd.Series([cell], dtype=object)})) + elif mode == "appender": + with con.appender("t") as appender: + appender.append_row(cell) + else: + con.execute("insert into t values (?)", [cell]) + assert con.table("t").fetchall() == [({"key": None, "value": 5},)] + + +@pytest.mark.parametrize( + "cell", + [{"key": None, "value": None}, {"key": ["a"], "value": None}, {"key": None, "value": ["a"]}], + ids=["both_none", "values_none", "keys_none"], +) +@pytest.mark.parametrize("mode", ["inferred", "explicit_schema", "append"]) +def test_map_of_key_and_value_with_a_none_reads_a_null_map(cell, mode): + con = duckdb.connect() + con.execute("create table t (a MAP(VARCHAR, VARCHAR))") + if mode == "append": + con.append("t", pd.DataFrame({"a": pd.Series([cell], dtype=object)})) + assert con.table("t").fetchall() == [(None,)] + else: + con.execute("insert into t values (MAP {'k': 'v'})") + schema = {"a": duckdb.sqltype("MAP(VARCHAR, VARCHAR)")} if mode == "explicit_schema" else None + assert con.table("t").map(_returning(cell), schema=schema).fetchall() == [(None,)] + + @pytest.mark.parametrize( ("cell", "expected"), [ From 0da3cbfc8bc660c20e2507d83cce4b48cfc2c044 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Sat, 7 Nov 2026 00:43:50 +0000 Subject: [PATCH 29/61] Take a dict as MAP keys and values only for two lists, read a declared STRUCT by its field names --- src/native/python_conversion.cpp | 92 ++++++++--------- src/numpy/numpy_scan.cpp | 6 +- tests/fast/pandas/test_append_df.py | 10 ++ tests/fast/test_map_types.py | 151 ++++++++++++++++++++++------ 4 files changed, 174 insertions(+), 85 deletions(-) diff --git a/src/native/python_conversion.cpp b/src/native/python_conversion.cpp index 1e5f4ad69..77f613b63 100644 --- a/src/native/python_conversion.cpp +++ b/src/native/python_conversion.cpp @@ -97,22 +97,28 @@ static vector TransformStructKeys(nb::handle keys, idx_t size) { return res; } -//! Whether a MAP's key or value component is a column of keys or values: a list, a tuple or a numpy array, which the -//! conversion reads as a LIST (an array of no dimensions it refuses) -static bool IsMapComponentList(nb::handle component) { - return PyList_Check(component.ptr()) || PyTuple_Check(component.ptr()) || - duckdb::PyUtil::IsInstance(component, DuckDBPyConnection::ImportCache()->numpy.ndarray()); +//! Whether an object is a list the conversion reads as a LIST: a list, a tuple or a numpy array of at least one +//! dimension, since an array of none holds a single value +static bool IsListLike(nb::handle ele) { + if (PyList_Check(ele.ptr()) || PyTuple_Check(ele.ptr())) { + return true; + } + return duckdb::PyUtil::IsInstance(ele, DuckDBPyConnection::ImportCache()->numpy.ndarray()) && + nb::cast(ele.attr("ndim")) > 0; } -//! The length of a MAP's key or value component, or -1 for one that has none although it claims one, as a numpy -//! array of no dimensions does -static int64_t ComponentLength(nb::handle component) { - auto length = PyObject_Length(component.ptr()); - if (length < 0) { - PyErr_Clear(); - return -1; +//! A dict of exactly 'key' and 'value' with a list on one side and a plain value on the other: a STRUCT of those +//! fields without a target, and refused as a MAP's key and value lists for a MAP target +static bool MixesAListAndAValue(const PyDictionary &dict) { + if (dict.len != 2) { + return false; } - return length; + auto keys = dict[nb::str("key")]; + auto values = dict[nb::str("value")]; + if (!keys || !values || nb::none().is(keys) || nb::none().is(values)) { + return false; + } + return IsListLike(keys) != IsListLike(values); } bool DictionaryHasMapFormat(const PyDictionary &dict) { @@ -129,25 +135,14 @@ bool DictionaryHasMapFormat(const PyDictionary &dict) { return false; } - // A list on either side, or None on both, makes the dict a MAP of the two lists: None a NULL MAP, and the - // conversion refuses the other side when it is no list. Without a list it is a plain dict, a MAP of the entries - // 'key' and 'value', so a NULL entry beside a plain value stays an entry + // Two lists of one length are a MAP's keys and values, and None on both sides, or beside a list, a NULL MAP; any + // other dict is a plain one, so a NULL entry or a list beside a plain value stays an entry or a field auto key_none = nb::none().is(keys); auto value_none = nb::none().is(values); - auto key_list = IsMapComponentList(keys); - auto value_list = IsMapComponentList(values); - if (!key_list && !value_list && !(key_none && value_none)) { - return false; + if (key_none || value_none) { + return (key_none || IsListLike(keys)) && (value_none || IsListLike(values)); } - if (key_none || value_none || !key_list || !value_list) { - return true; - } - - // Verify that both the keys and values are of the same length; a component without one is refused by the - // conversion - auto key_size = ComponentLength(keys); - auto value_size = ComponentLength(values); - return key_size < 0 || value_size < 0 || key_size == value_size; + return IsListLike(keys) && IsListLike(values) && nb::len(keys) == nb::len(values); } Value TransformDictionaryToStruct(optional_ptr context, const PyDictionary &dict, @@ -310,16 +305,6 @@ Value TransformTimestamp(optional_ptr context, nb::handle ele, co return TransformPythonValue(context, ele, LogicalType::UNKNOWN, nan_as_null); } -//! Whether an object is a list a shape takes: a list, a tuple or a numpy array of at least one dimension, since an -//! array of none holds a single value -static bool ShapeTakesAsList(nb::handle ele) { - if (PyList_Check(ele.ptr()) || PyTuple_Check(ele.ptr())) { - return true; - } - return duckdb::PyUtil::IsInstance(ele, DuckDBPyConnection::ImportCache()->numpy.ndarray()) && - nb::cast(ele.attr("ndim")) > 0; -} - //! Whether an object is what a shape is for: a dict for a MAP or a STRUCT, a list for a LIST or an ARRAY; any other //! object converts without a target and meets the engine's cast or the kind check, so a tuple reads as a LIST at //! every depth, as the appender reads a value of a row @@ -330,7 +315,7 @@ static bool ShapeTakes(nb::handle ele, const LogicalType &shape) { return PyDict_Check(ele.ptr()); case LogicalTypeId::LIST: case LogicalTypeId::ARRAY: - return ShapeTakesAsList(ele); + return IsListLike(ele); default: return false; } @@ -424,6 +409,13 @@ Value TransformStructFormatDictionaryToMap(optional_ptr context, Value TransformDictionaryToMap(optional_ptr context, const PyDictionary &dict, const LogicalType &target_type, bool nan_as_null) { if (target_type.id() != LogicalTypeId::UNKNOWN && !DictionaryHasMapFormat(dict)) { + if (MixesAListAndAValue(dict)) { + auto keys = TransformPythonValue(context, dict[nb::str("key")], LogicalType::UNKNOWN, nan_as_null); + auto values = TransformPythonValue(context, dict[nb::str("value")], LogicalType::UNKNOWN, nan_as_null); + throw InvalidInputException("A dict of 'key' and 'value' for a MAP takes a list of keys and a list of " + "values, not %s and %s", + keys.type().ToString(), values.type().ToString()); + } // dict == { 'k1': v1, 'k2': v2, ..., 'kn': vn } return TransformStructFormatDictionaryToMap(context, dict, target_type, nan_as_null); } @@ -436,9 +428,8 @@ Value TransformDictionaryToMap(optional_ptr context, const PyDict return Value(LogicalType::MAP(LogicalTypeId::SQLNULL, LogicalTypeId::SQLNULL)); } - auto key_size = ComponentLength(keys); - auto sized = key_size >= 0 && ComponentLength(values) >= 0; - if (sized && key_size == 0) { + auto key_size = nb::len(keys); + if (key_size == 0) { // dict == { 'key': [], 'value': [] } return EmptyMapValue(); } @@ -448,15 +439,12 @@ Value TransformDictionaryToMap(optional_ptr context, const PyDict LogicalType value_target = LogicalTypeId::UNKNOWN; if (IsShape(target_type)) { - // A shape reads the two lists entry by entry, as it reads a dict's own entries; a component that is no list - // converts without a target and is refused below - if (sized && ShapeTakesAsList(keys) && ShapeTakesAsList(values)) { - auto items = [](nb::handle list) { - return PyList_Check(list.ptr()) || PyTuple_Check(list.ptr()) ? nb::borrow(list) - : list.attr("tolist")(); - }; - return MapFromEntries(context, items(keys), items(values), key_size, target_type, nan_as_null); - } + // A shape reads the two lists entry by entry, as it reads a dict's own entries + auto items = [](nb::handle list) { + return PyList_Check(list.ptr()) || PyTuple_Check(list.ptr()) ? nb::borrow(list) + : list.attr("tolist")(); + }; + return MapFromEntries(context, items(keys), items(values), key_size, target_type, nan_as_null); } else if (target_type.id() != LogicalTypeId::UNKNOWN) { key_target = LogicalType::LIST(MapType::KeyType(target_type)); value_target = LogicalType::LIST(MapType::ValueType(target_type)); diff --git a/src/numpy/numpy_scan.cpp b/src/numpy/numpy_scan.cpp index 4e724b138..e0a282033 100644 --- a/src/numpy/numpy_scan.cpp +++ b/src/numpy/numpy_scan.cpp @@ -941,9 +941,11 @@ void NumpyScan::ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t bool bit_storage_refused) { DeclaredVector staged(count); auto &target = out.GetType(); - // A type holding a MAP takes a shape for its keys, and one holding a naive timestamp for the unit a nested value - // reads in; a top level timestamp is read by DeclaredValue itself + // A type holding a MAP takes a shape for its keys, one holding a STRUCT for a dict to name its fields, not to be + // guessed a MAP's key and value lists, and one holding a naive timestamp for the unit a nested value reads in; a + // top level timestamp is read by DeclaredValue itself const auto keyed = target.IsNested() && (TypeVisitor::Contains(target, LogicalTypeId::MAP) || + TypeVisitor::Contains(target, LogicalTypeId::STRUCT) || TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP_NS) || TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP) || TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP_MS) || diff --git a/tests/fast/pandas/test_append_df.py b/tests/fast/pandas/test_append_df.py index 1083016fe..b0c0819fe 100644 --- a/tests/fast/pandas/test_append_df.py +++ b/tests/fast/pandas/test_append_df.py @@ -540,6 +540,16 @@ def test_map_of_key_and_value_lists_reads_each_entry_as_the_same_dict_does( duckdb_cursor.append("t", frame) assert duckdb_cursor.sql("SELECT a::VARCHAR FROM t").fetchall() == [(expected,), (expected,)] + def test_aware_timestamp_without_nanoseconds_reads_in_the_session_time_zone(self, duckdb_cursor): + duckdb_cursor.execute("SET TimeZone = 'America/New_York'") + duckdb_cursor.execute("CREATE TABLE t (a TIMESTAMP)") + stamp = pd.Timestamp("2020-01-01 00:00", tz="UTC") + duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series([stamp, stamp.to_pydatetime()], dtype=object)})) + assert duckdb_cursor.sql("SELECT a::VARCHAR FROM t").fetchall() == [ + ("2019-12-31 19:00:00",), + ("2019-12-31 19:00:00",), + ] + def test_map_of_two_plain_values_named_key_and_value_appends_its_entries(self, duckdb_cursor): duckdb_cursor.execute("CREATE TABLE t (a MAP(VARCHAR, VARCHAR))") frame = pd.DataFrame({"a": pd.Series([{"key": "ab", "value": "cd"}], dtype=object)}) diff --git a/tests/fast/test_map_types.py b/tests/fast/test_map_types.py index 1b4f9b34c..2bfcc378d 100644 --- a/tests/fast/test_map_types.py +++ b/tests/fast/test_map_types.py @@ -717,48 +717,137 @@ def test_map_scalar_inside_a_container_of_a_type_holding_a_map_is_refused_and_th assert con.sql("select 42").fetchall() == [(42,)] +def _through(mode, con, sql_type, cell): + con.execute(f"create or replace table t (a {sql_type})") + if mode == "append": + con.append("t", pd.DataFrame({"a": pd.Series([cell], dtype=object)})) + elif mode == "appender": + with con.appender("t") as appender: + appender.append_row(cell) + elif mode == "parameter": + con.execute("insert into t values (?)", [cell]) + else: + con.execute("insert into t values (NULL)") + schema = {"a": duckdb.sqltype(sql_type)} if mode == "explicit_schema" else None + return con.table("t").map(_returning(cell), schema=schema).fetchall() + return con.table("t").fetchall() + + @pytest.mark.parametrize( - ("sql_type", "cell", "converted"), + ("sql_type", "cell"), [ - pytest.param("MAP(VARCHAR, VARCHAR)", {"key": ["a"], "value": "b"}, "VARCHAR[] and VARCHAR", id="map"), - pytest.param( - "STRUCT(m MAP(VARCHAR, VARCHAR))", - {"m": {"key": ["a"], "value": "b"}}, - "VARCHAR[] and VARCHAR", - id="map_field", - ), - pytest.param( - "MAP(VARCHAR, INTEGER)", - {"key": np.array("a"), "value": np.array(1)}, - "VARCHAR and INTEGER", - id="zero_dimensional_arrays", - ), + pytest.param("MAP(VARCHAR, VARCHAR)", {"key": ["a"], "value": "b"}, id="map"), + pytest.param("STRUCT(m MAP(VARCHAR, VARCHAR))", {"m": {"key": ["a"], "value": "b"}}, id="map_field"), ], ) -@pytest.mark.parametrize("mode", ["inferred", "explicit_schema", "append", "appender", "parameter"]) -def test_map_of_a_key_list_and_a_value_that_is_no_list_is_refused_and_the_database_stays_usable( - sql_type, cell, converted, mode +@pytest.mark.parametrize("mode", ["inferred", "explicit_schema", "append"]) +def test_map_of_a_key_list_beside_a_plain_value_for_a_map_type_is_refused_and_the_database_stays_usable( + sql_type, cell, mode ): con = duckdb.connect() - con.execute(f"create table t (a {sql_type})") + expected = ( + "A dict of 'key' and 'value' for a MAP takes a list of keys and a list of values, not VARCHAR[] and VARCHAR" + ) + with pytest.raises(duckdb.InvalidInputException, match=re.escape(expected)): + _through(mode, con, sql_type, cell) + assert con.sql("select 42").fetchall() == [(42,)] + + +@pytest.mark.parametrize("mode", ["appender", "parameter"]) +def test_map_of_a_key_list_beside_a_plain_value_without_a_target_converts_as_a_struct(mode): + # The conversion has no MAP to read for, so the dict is the STRUCT of its fields, which the engine casts into the + # MAP of the two entries, the list as its text + con = duckdb.connect() + assert _through(mode, con, "MAP(VARCHAR, VARCHAR)", {"key": ["a"], "value": "b"}) == [ + ({"key": "[a]", "value": "b"},) + ] + + +@pytest.mark.parametrize( + ("cell", "struct_type"), + [ + pytest.param({"key": [], "value": "ab"}, 'STRUCT("key" "NULL"[], "value" VARCHAR)', id="empty_list_and_text"), + pytest.param({"key": [1], "value": 5}, 'STRUCT("key" INTEGER[], "value" INTEGER)', id="list_and_int"), + pytest.param({"key": "x", "value": None}, 'STRUCT("key" VARCHAR, "value" "NULL")', id="text_and_null"), + ], +) +@pytest.mark.parametrize("mode", ["parameter", "dataframe_scan"]) +def test_dict_of_key_and_value_without_two_lists_is_inferred_as_a_struct(cell, struct_type, mode): + con = duckdb.connect() + if mode == "parameter": + rows = con.execute("select ?, typeof(?)", [cell, cell]).fetchall() + else: + frame = pd.DataFrame({"a": pd.Series([cell], dtype=object)}) # noqa: F841 + rows = con.sql("select a, typeof(a) from frame").fetchall() + assert rows == [(cell, struct_type)] + + +KEY_AND_VALUE_STRUCTS = pytest.mark.parametrize( + "value", + [ + "{'key': 'color', 'value': ['red', 'blue']}::STRUCT(key VARCHAR, value VARCHAR[])", + "map_entries(MAP {'color': ['red', 'blue']})", + "{'key': [1], 'value': 5}::STRUCT(key INTEGER[], value INTEGER)", + "{'key': 1, 'value': [5]}::STRUCT(key INTEGER, value INTEGER[])", + ], + ids=["text_and_list", "map_entries", "list_and_int", "int_and_list"], +) + + +@KEY_AND_VALUE_STRUCTS +@pytest.mark.parametrize("mode", ["inferred", "explicit_schema", "append", "appender", "parameter", "dataframe_scan"]) +def test_struct_with_fields_key_and_value_one_a_list_converts_as_its_struct(value, mode): + con = duckdb.connect() + source = con.sql(f"select {value} as a") + expected = source.fetchall() + frame = source.df() + if mode == "dataframe_scan": + assert duckdb.connect().sql("select a from frame").fetchall() == expected + return + if mode in ("inferred", "explicit_schema"): + schema = _schema_of(source, mode == "explicit_schema") + assert source.map(lambda df: df, schema=schema).fetchall() == expected + return + con.execute(f"create table t (a {source.types[0]})") if mode == "append": - run = lambda: con.append("t", pd.DataFrame({"a": pd.Series([cell], dtype=object)})) # noqa: E731 + con.append("t", frame) elif mode == "appender": + with con.appender("t") as appender: + appender.append_row(frame["a"][0]) + else: + con.execute("insert into t values (?)", [frame["a"][0]]) + assert con.table("t").fetchall() == expected - def run(): - with con.appender("t") as appender: - appender.append_row(cell) - elif mode == "parameter": - run = lambda: con.execute("insert into t values (?)", [cell]) # noqa: E731 +@pytest.mark.parametrize( + "value", + [ + "{'key': NULL, 'value': NULL}::STRUCT(key VARCHAR, value VARCHAR)", + "{'key': [1], 'value': NULL}::STRUCT(key INTEGER[], value INTEGER)", + ], + ids=["both_null", "list_and_null"], +) +@pytest.mark.parametrize("mode", ["inferred", "explicit_schema", "append"]) +def test_declared_struct_with_fields_key_and_value_reads_a_null_field_as_its_struct(value, mode): + # A declared STRUCT names its fields, so such a dict is no NULL MAP of key and value lists + con = duckdb.connect() + source = con.sql(f"select {value} as a") + expected = source.fetchall() + if mode == "append": + con.execute(f"create table t (a {source.types[0]})") + con.append("t", source.df()) + assert con.table("t").fetchall() == expected else: - con.execute("insert into t values (NULL)") - schema = {"a": duckdb.sqltype(sql_type)} if mode == "explicit_schema" else None - run = con.table("t").map(_returning(cell), schema=schema).fetchall - expected = f"A dict of 'key' and 'value' for a MAP takes a list of keys and a list of values, not {converted}" - with pytest.raises(duckdb.InvalidInputException, match=re.escape(expected)): - run() - assert con.sql("select 42").fetchall() == [(42,)] + mapped = source.map(lambda df: df, schema=_schema_of(source, mode == "explicit_schema")) + assert mapped.fetchall() == expected + + +@pytest.mark.parametrize("mode", ["inferred", "explicit_schema", "append", "appender", "parameter"]) +def test_map_of_key_and_value_arrays_of_no_dimensions_reads_their_two_entries(mode): + # An array of no dimensions holds a single value, so the dict is a plain one + con = duckdb.connect() + cell = {"key": np.array("a"), "value": np.array("b")} + assert _through(mode, con, "MAP(VARCHAR, VARCHAR)", cell) == [({"key": "a", "value": "b"},)] @pytest.mark.parametrize( From fee081e93f072c7de815ca651d0f93c341c9d7aa Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Sat, 7 Nov 2026 04:52:45 +0000 Subject: [PATCH 30/61] Stage a MAP column's keys and values once per vector and index a STRUCT shape's fields once per scan --- .../duckdb_python/python_conversion.hpp | 11 +++ src/native/python_conversion.cpp | 98 ++++++++++++++----- src/numpy/numpy_scan.cpp | 83 +++++++++++++--- tests/fast/pandas/test_append_df.py | 19 ++++ tests/fast/test_map_types.py | 46 +++++++++ 5 files changed, 217 insertions(+), 40 deletions(-) diff --git a/src/include/duckdb_python/python_conversion.hpp b/src/include/duckdb_python/python_conversion.hpp index 3d96301cb..dec847c87 100644 --- a/src/include/duckdb_python/python_conversion.hpp +++ b/src/include/duckdb_python/python_conversion.hpp @@ -53,6 +53,17 @@ LogicalType SniffPythonIntegerType(nb::handle ele); //! The type of a duckdb.Value, or InvalidInputException when its 'type' attribute is not a DuckDB type LogicalType PythonValueType(nb::handle value); bool DictionaryHasMapFormat(const PyDictionary &dict); +//! A dict of exactly 'key' and 'value' with a list on one side and a plain value on the other: a STRUCT of those +//! fields without a target, and refused as a MAP's key and value lists for a MAP target +bool MixesAListAndAValue(const PyDictionary &dict); +//! Drops the field indexes the conversion of shaped STRUCT dicts kept on this thread; the declared scan calls it when +//! the scan of a vector ends, so no index outlives the shape it was built for +void ClearStructFieldIndexes(); +//! A key or value of a MAP whose target is a type without children converts without a target and is then cast with +//! the connection's settings, as a value of a column is, so each keeps its own type until the cast instead of meeting +//! its siblings' common type (2**60 + 1 beside 1.0 would read as a DOUBLE, rounded) +Value TransformMapEntry(optional_ptr context, nb::handle entry, const LogicalType &target_type, + bool nan_as_null); //! A target the declared scan builds from a column's type (a shape), as opposed to a column's own type: a dict for a //! shaped STRUCT takes its own keys, as without a target; a shaped MAP casts each key and value whose type has no //! children with the connection's settings; a shaped naive timestamp reads a cell as TransformTimestamp does diff --git a/src/native/python_conversion.cpp b/src/native/python_conversion.cpp index 76d63e9ec..8d884a207 100644 --- a/src/native/python_conversion.cpp +++ b/src/native/python_conversion.cpp @@ -191,9 +191,7 @@ static bool IsListLike(nb::handle ele) { nb::cast(ele.attr("ndim")) > 0; } -//! A dict of exactly 'key' and 'value' with a list on one side and a plain value on the other: a STRUCT of those -//! fields without a target, and refused as a MAP's key and value lists for a MAP target -static bool MixesAListAndAValue(const PyDictionary &dict) { +bool MixesAListAndAValue(const PyDictionary &dict) { if (dict.len != 2) { return false; } @@ -229,6 +227,40 @@ bool DictionaryHasMapFormat(const PyDictionary &dict) { return IsListLike(keys) && IsListLike(values) && nb::len(keys) == nb::len(values); } +namespace { +//! The field index of each shaped STRUCT a declared scan meets, kept per thread until the scan of the vector ends, +//! since each takes a pass over the fields to build and every dict of the vector asks the same one; an entry holds +//! its type, so the type information it is found by cannot be freed and given to another type while it is kept, and +//! an index stays where it is while others are added +struct FieldIndex { + LogicalType type; + identifier_map_t fields; +}; + +unordered_map &FieldIndexes() { + thread_local unordered_map indexes; + return indexes; +} + +const identifier_map_t &FieldIndexOf(const LogicalType &struct_type) { + auto &indexes = FieldIndexes(); + auto entry = indexes.find(&struct_type.GetTypeInfo()); + if (entry != indexes.end()) { + return entry->second.fields; + } + auto &index = indexes[&struct_type.GetTypeInfo()]; + index.type = struct_type; + for (idx_t child = 0; child < StructType::GetChildCount(struct_type); child++) { + index.fields.emplace(StructType::GetChildName(struct_type, child), child); + } + return index.fields; +} +} // namespace + +void ClearStructFieldIndexes() { + FieldIndexes().clear(); +} + Value TransformDictionaryToStruct(optional_ptr context, const PyDictionary &dict, const LogicalType &target_type, bool nan_as_null) { auto conversion_error = [&]() { @@ -256,15 +288,30 @@ Value TransformDictionaryToStruct(optional_ptr context, const PyD auto struct_keys = TransformStructKeys(dict.keys, dict.len); if (!struct_target || shape_only) { + const LogicalType unknown(LogicalTypeId::UNKNOWN); + auto field_count = shape_only ? StructType::GetChildCount(target_type) : 0; + // The field at a key's own position is tried first, as df() hands a STRUCT over in field order; a key found + // elsewhere is looked up in an index of the field names, so a wide STRUCT costs no search for every key + optional_ptr> fields; for (idx_t i = 0; i < dict.len; i++) { - LogicalType child_type = LogicalType::UNKNOWN; - for (idx_t child = 0; shape_only && child < StructType::GetChildCount(target_type); child++) { - if (StructType::GetChildName(target_type, child) == struct_keys[i]) { - child_type = StructType::GetChildType(target_type, child); - break; + optional_idx field; + if (i < field_count && StructType::GetChildName(target_type, i) == struct_keys[i]) { + field = i; + } else if (field_count > 0) { + if (!fields) { + fields = &FieldIndexOf(target_type); + } + auto entry = fields->find(struct_keys[i]); + if (entry != fields->end()) { + field = entry->second; } } - auto val = TransformPythonValue(context, dict.values.attr("__getitem__")(i), child_type, nan_as_null); + auto &child_type = field.IsValid() ? StructType::GetChildType(target_type, field.GetIndex()) : unknown; + auto value = nb::steal(PySequence_GetItem(dict.values.ptr(), NumericCast(i))); + if (!value.is_valid()) { + throw nb::python_error(); + } + auto val = TransformPythonValue(context, value, child_type, nan_as_null); struct_values.emplace_back(make_pair(std::move(struct_keys[i]), std::move(val))); } return Value::STRUCT(std::move(struct_values)); @@ -368,11 +415,8 @@ static bool ShapeTakes(nb::handle ele, const LogicalType &shape) { } } -//! A key or value of a MAP whose target is a type without children converts without a target and is then cast with -//! the connection's settings, as a value of a column is, so each keeps its own type until the cast instead of meeting -//! its siblings' common type (2**60 + 1 beside 1.0 would read as a DOUBLE, rounded) -static Value TransformMapEntry(optional_ptr context, nb::handle entry, const LogicalType &target_type, - bool nan_as_null) { +Value TransformMapEntry(optional_ptr context, nb::handle entry, const LogicalType &target_type, + bool nan_as_null) { if (IsShape(target_type) || target_type.IsNested() || target_type.id() == LogicalTypeId::UNKNOWN || target_type.id() == LogicalTypeId::UNION) { return TransformPythonValue(context, entry, target_type, nan_as_null); @@ -400,11 +444,16 @@ static Value MapFromEntries(optional_ptr context, nb::handle keys LogicalType key_type = LogicalType::SQLNULL; LogicalType value_type = LogicalType::SQLNULL; - vector elements; + vector map_keys; + vector map_values; + map_keys.reserve(size); + map_values.reserve(size); for (idx_t i = 0; i < size; i++) { - - auto key = keys.attr("__getitem__")(i); - auto value = values.attr("__getitem__")(i); + auto key = nb::steal(PySequence_GetItem(keys.ptr(), NumericCast(i))); + auto value = nb::steal(PySequence_GetItem(values.ptr(), NumericCast(i))); + if (!key.is_valid() || !value.is_valid()) { + throw nb::python_error(); + } Value new_key = shape ? TransformMapEntry(context, key, key_target, nan_as_null) : TransformPythonValue(context, key, key_target, nan_as_null); Value new_value = shape ? TransformMapEntry(context, value, value_target, nan_as_null) @@ -412,12 +461,8 @@ static Value MapFromEntries(optional_ptr context, nb::handle keys key_type = ProxiedForceMaxLogicalType(context, key_type, new_key.type()); value_type = ProxiedForceMaxLogicalType(context, value_type, new_value.type()); - - child_list_t struct_values; - struct_values.emplace_back(make_pair("key", std::move(new_key))); - struct_values.emplace_back(make_pair("value", std::move(new_value))); - - elements.push_back(Value::STRUCT(std::move(struct_values))); + map_keys.push_back(std::move(new_key)); + map_values.push_back(std::move(new_value)); } // A target holding UNKNOWN asks for no type there, and a MAP of such a type is no value the engine can hold if (key_type.id() == LogicalTypeId::SQLNULL && !TypeVisitor::Contains(key_target, LogicalTypeId::UNKNOWN) && @@ -429,9 +474,8 @@ static Value MapFromEntries(optional_ptr context, nb::handle keys value_type = value_target; } - LogicalType map_type = LogicalType::MAP(key_type, value_type); - - return Value::MAP(ListType::GetChildType(map_type), std::move(elements)); + // Built from the keys and values themselves, as the STRUCT of each entry would only be taken apart again + return Value::MAP(key_type, value_type, std::move(map_keys), std::move(map_values)); } Value TransformStructFormatDictionaryToMap(optional_ptr context, const PyDictionary &dict, diff --git a/src/numpy/numpy_scan.cpp b/src/numpy/numpy_scan.cpp index 9938f88a3..d30026bd6 100644 --- a/src/numpy/numpy_scan.cpp +++ b/src/numpy/numpy_scan.cpp @@ -207,18 +207,10 @@ void ScanNumpyObject(optional_ptr context, PyObject *object, idx_ TransformPythonObject(context, object, out, offset); } +//! Raises what the engine raises building a MAP Value of such keys, so a MAP written straight into its vector and one +//! built as a Value are refused alike static void VerifyMapConstraints(Vector &vec, idx_t count) { - auto invalid_reason = MapVector::CheckMapValidity(vec, count); - switch (invalid_reason) { - case MapInvalidReason::VALID: - return; - case MapInvalidReason::DUPLICATE_KEY: - throw InvalidInputException("Dict->Map conversion failed because 'key' list contains duplicates"); - case MapInvalidReason::NULL_KEY: - throw InvalidInputException("Dict->Map conversion failed because 'key' list contains None"); - default: - throw InvalidInputException("Option not implemented for MapInvalidReason"); - } + MapVector::EvalMapInvalidReason(MapVector::CheckMapValidity(vec, count)); } //! A MAP's keys must be unique at every depth; a cast of a STRUCT into a MAP, as of a dict whose keys collapse into @@ -343,6 +335,11 @@ static Value DeclaredValue(ClientContext &context, const LogicalType &target, nb return TransformPythonValue(context, value, shape, true); } +//! A key or value type a stated MAP casts its entries into one by one +static bool IsPlainEntryType(const LogicalType &type) { + return !type.IsNested() && type.id() != LogicalTypeId::UNION; +} + //! The type a cell of a nested type converts with: its containers and its naive timestamps and no other type, so a //! dict builds its MAP from its keys and values in the types they have in Python and every key and value meets the //! engine's cast with the connection's settings, as a TIMESTAMPTZ in the session time zone, and a timestamp reads in @@ -351,8 +348,7 @@ static Value DeclaredValue(ClientContext &context, const LogicalType &target, nb //! stated takes that, while an implied type keeps the entries' own types for the kind check. static LogicalType KeyedShape(const LogicalType &type, bool typed_entries) { auto entry = [&](const LogicalType &entry_type) { - auto plain = !entry_type.IsNested() && entry_type.id() != LogicalTypeId::UNION; - return typed_entries && plain ? entry_type : KeyedShape(entry_type, typed_entries); + return typed_entries && IsPlainEntryType(entry_type) ? entry_type : KeyedShape(entry_type, typed_entries); }; switch (type.id()) { case LogicalTypeId::STRUCT: { @@ -928,10 +924,30 @@ static void ScanObjectCells(ClientContext &context, PyObject **col, idx_t stride } } +//! Writes the converted keys or values of a MAP vector's entries from first on, cast into the child's type as a +//! declared column's values are +static void WriteEntries(ClientContext &context, vector &entries, Vector &child, idx_t first) { + if (entries.empty()) { + return; + } + DeclaredVector staged(entries.size()); + for (idx_t i = 0; i < entries.size(); i++) { + staged.Set(i, std::move(entries[i])); + } + Vector written(child.GetType(), entries.size()); + staged.Write(context, written, entries.size()); + VectorOperations::Copy(written, child, entries.size(), 0, first); +} + void NumpyScan::ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t stride, const uint8_t *masked, idx_t count, idx_t offset, Vector &out, bool implied_type, bool bit_storage_refused) { DeclaredVector staged(count); + struct FieldIndexesOfTheScan { + ~FieldIndexesOfTheScan() { + ClearStructFieldIndexes(); + } + } field_indexes; auto &target = out.GetType(); // A type holding a MAP takes a shape for its keys, one holding a STRUCT for a dict to name its fields, not to be // guessed a MAP's key and value lists, and one holding a naive timestamp for the unit a nested value reads in; a @@ -1043,6 +1059,47 @@ void NumpyScan::ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t } read(cell, row); }); + } else if (target.id() == LogicalTypeId::MAP && !implied_type && !bits_refused && + IsPlainEntryType(MapType::KeyType(target)) && IsPlainEntryType(MapType::ValueType(target))) { + // A dict of its entries goes straight into the MAP's keys and values, each converted as a MAP entry is and all + // of them cast together once the vector is read, since a MAP Value per cell builds and takes apart a STRUCT + // Value per entry; the key and value lists and every other cell take the general reader + auto &key_type = MapType::KeyType(target); + auto &value_type = MapType::ValueType(target); + auto first_entry = ListVector::GetListSize(out); + vector keys; + vector values; + ScanObjectCells(context, col, stride, masked, count, offset, out, [&](nb::handle cell, idx_t row) { + if (!PyDict_Check(cell.ptr())) { + return read(cell, row); + } + auto size = NumericCast(PyDict_Size(cell.ptr())); + if (size == 2) { + PyDictionary dict(nb::borrow(cell)); + if (DictionaryHasMapFormat(dict) || MixesAListAndAValue(dict)) { + return read(cell, row); + } + } + auto start = ListVector::GetListSize(out); + Py_ssize_t position = 0; + PyObject *key; + PyObject *value; + while (PyDict_Next(cell.ptr(), &position, &key, &value)) { + // Converting runs Python, which could drop the dict's references to them + auto key_object = nb::borrow(key); + auto value_object = nb::borrow(value); + keys.push_back(TransformTimestamp(context, key_object, key_type, true)); + values.push_back(TransformTimestamp(context, value_object, value_type, true)); + } + auto &list_entry = FlatVector::GetDataMutable(out)[row]; + list_entry.offset = start; + list_entry.length = first_entry + keys.size() - start; + ListVector::Reserve(out, first_entry + keys.size()); + ListVector::SetListSize(out, first_entry + keys.size()); + staged.MarkWritten(row); + }); + WriteEntries(context, keys, MapVector::GetKeys(out), first_entry); + WriteEntries(context, values, MapVector::GetValues(out), first_entry); } else { ScanObjectCells(context, col, stride, masked, count, offset, out, read); } diff --git a/tests/fast/pandas/test_append_df.py b/tests/fast/pandas/test_append_df.py index c35e9182a..61b318020 100644 --- a/tests/fast/pandas/test_append_df.py +++ b/tests/fast/pandas/test_append_df.py @@ -586,6 +586,25 @@ def test_aware_timestamp_without_nanoseconds_reads_in_the_session_time_zone(self ("2019-12-31 19:00:00",), ] + def test_struct_dicts_with_keys_out_of_field_order_read_each_field_by_name(self, duckdb_cursor): + # Twelve STRUCT types, more than the per thread field indexes keep, each dict's keys in reverse field order + inner = [f"s{i} STRUCT(a{i} INTEGER, b{i} INTEGER, c{i} INTEGER)" for i in range(12)] + duckdb_cursor.execute(f"CREATE TABLE t (i INTEGER, a STRUCT({', '.join(inner)}))") + cells = [ + {f"s{i}": {f"c{i}": row + 3, f"b{i}": row + 2, f"a{i}": row + 1} for i in reversed(range(12))} + for row in range(3000) + ] + duckdb_cursor.append("t", pd.DataFrame({"i": range(3000), "a": pd.Series(cells, dtype=object)})) + assert [row[0] for row in duckdb_cursor.sql("SELECT a FROM t ORDER BY i").fetchall()] == cells + + def test_map_column_mixing_dicts_with_other_cells_keeps_every_row_in_place(self, duckdb_cursor): + # Dicts are written into the MAP's entries directly and the other cells after them; 3000 rows span two vectors + cells = [{"a": 1}, "{b=2}", {"key": ["c"], "value": [3]}, None, {"d": 4, "e": 5}, {}] * 500 + expected = [{"a": 1}, {"b": 2}, {"c": 3}, None, {"d": 4, "e": 5}, {}] * 500 + duckdb_cursor.execute("CREATE TABLE t (i INTEGER, a MAP(VARCHAR, INTEGER))") + duckdb_cursor.append("t", pd.DataFrame({"i": range(len(cells)), "a": pd.Series(cells, dtype=object)})) + assert [row[0] for row in duckdb_cursor.sql("SELECT a FROM t ORDER BY i").fetchall()] == expected + def test_map_of_two_plain_values_named_key_and_value_appends_its_entries(self, duckdb_cursor): duckdb_cursor.execute("CREATE TABLE t (a MAP(VARCHAR, VARCHAR))") frame = pd.DataFrame({"a": pd.Series([{"key": "ab", "value": "cd"}], dtype=object)}) diff --git a/tests/fast/test_map_types.py b/tests/fast/test_map_types.py index 2bfcc378d..683ee0a06 100644 --- a/tests/fast/test_map_types.py +++ b/tests/fast/test_map_types.py @@ -842,6 +842,15 @@ def test_declared_struct_with_fields_key_and_value_reads_a_null_field_as_its_str assert mapped.fetchall() == expected +@pytest.mark.parametrize("mode", ["inferred", "explicit_schema", "append"]) +def test_struct_given_an_empty_dict_is_refused(mode): + # A missing field reads NULL, but a dict of no keys is no STRUCT of the column's fields + con = duckdb.connect() + with pytest.raises(duckdb.TypeMismatchException, match="Cannot cast STRUCTs of different size"): + _through(mode, con, "STRUCT(a INTEGER, b INTEGER)", {}) + assert con.sql("select 42").fetchall() == [(42,)] + + @pytest.mark.parametrize("mode", ["inferred", "explicit_schema", "append", "appender", "parameter"]) def test_map_of_key_and_value_arrays_of_no_dimensions_reads_their_two_entries(mode): # An array of no dimensions holds a single value, so the dict is a plain one @@ -1020,6 +1029,43 @@ def test_map_nested_timestamp_with_nanoseconds_for_a_stated_coarser_unit_reads_a assert rows == [(expected,)] +@pytest.mark.parametrize( + ("value", "text"), + [ + pytest.param( + np.datetime64("2020-01-01T00:00:00.000005789", "ns"), + "2020-01-01 00:00:00.000006", + id="datetime64_rounds_up", + ), + pytest.param(np.datetime64(-1, "ns"), "1970-01-01 00:00:00", id="datetime64_before_the_epoch"), + pytest.param( + pd.Timestamp("2020-01-01 00:00:00.000005789"), "2020-01-01 00:00:00.000005", id="timestamp_as_its_datetime" + ), + pytest.param(pd.Timestamp(-1, unit="ns"), "1969-12-31 23:59:59.999999", id="timestamp_before_the_epoch"), + ], +) +@pytest.mark.parametrize("place", ["top", "list_element", "struct_field", "map_value"]) +@pytest.mark.parametrize("mode", ["explicit_schema", "append"]) +def test_map_timestamp_finer_than_a_stated_coarser_unit_reads_at_every_depth_as_at_the_top(value, text, place, mode): + # A datetime64 is a TIMESTAMP_NS the engine's cast rounds into microseconds; a Timestamp is the datetime it is + sql_type, cell, expected = { + "top": ("TIMESTAMP", value, text), + "list_element": ("TIMESTAMP[]", [value], f"['{text}']"), + "struct_field": ("STRUCT(t TIMESTAMP)", {"t": value}, f"{{'t': '{text}'}}"), + "map_value": ("MAP(VARCHAR, TIMESTAMP)", {"k": value}, f"{{k='{text}'}}"), + }[place] + con = duckdb.connect() + con.execute(f"create table t (a {sql_type})") + if mode == "append": + con.append("t", pd.DataFrame({"a": pd.Series([cell], dtype=object)})) + rows = con.sql("select a::VARCHAR from t").fetchall() + else: + con.execute("insert into t values (NULL)") + schema = {"a": duckdb.sqltype(sql_type)} + rows = con.table("t").map(_returning(cell), schema=schema).project("a::VARCHAR").fetchall() + assert rows == [(expected,)] + + @pytest.mark.parametrize( "sql_type", ["STRUCT(a INTEGER, b INTEGER)", "STRUCT(a INTEGER, t TIMESTAMP)", "STRUCT(a INTEGER, m MAP(VARCHAR, INTEGER))"], From 5ee6ecc552016f4ad62226dd6e9895567cc8b96a Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Sat, 7 Nov 2026 07:10:20 +0000 Subject: [PATCH 31/61] Clear the STRUCT field index from the outermost scan only, take exact dicts in the MAP reader, keep a zoned Timestamp's nanoseconds for TIMESTAMPTZ_NS --- .../duckdb_python/python_conversion.hpp | 24 ++-- src/native/python_conversion.cpp | 24 +++- src/numpy/numpy_scan.cpp | 52 ++++++--- tests/fast/pandas/test_append_df.py | 109 ++++++++++++++++-- tests/fast/test_map_types.py | 78 +++++++++++++ 5 files changed, 244 insertions(+), 43 deletions(-) diff --git a/src/include/duckdb_python/python_conversion.hpp b/src/include/duckdb_python/python_conversion.hpp index dec847c87..33133d421 100644 --- a/src/include/duckdb_python/python_conversion.hpp +++ b/src/include/duckdb_python/python_conversion.hpp @@ -56,9 +56,15 @@ bool DictionaryHasMapFormat(const PyDictionary &dict); //! A dict of exactly 'key' and 'value' with a list on one side and a plain value on the other: a STRUCT of those //! fields without a target, and refused as a MAP's key and value lists for a MAP target bool MixesAListAndAValue(const PyDictionary &dict); -//! Drops the field indexes the conversion of shaped STRUCT dicts kept on this thread; the declared scan calls it when -//! the scan of a vector ends, so no index outlives the shape it was built for -void ClearStructFieldIndexes(); +//! Keeps the field indexes the conversion of shaped STRUCT dicts builds on this thread while a declared scan runs; the +//! outermost scope drops them when it ends, so no index outlives the shapes it was built for +class StructFieldIndexScope { +public: + StructFieldIndexScope(); + ~StructFieldIndexScope(); + StructFieldIndexScope(const StructFieldIndexScope &) = delete; + StructFieldIndexScope &operator=(const StructFieldIndexScope &) = delete; +}; //! A key or value of a MAP whose target is a type without children converts without a target and is then cast with //! the connection's settings, as a value of a column is, so each keeps its own type until the cast instead of meeting //! its siblings' common type (2**60 + 1 beside 1.0 would read as a DOUBLE, rounded) @@ -71,12 +77,12 @@ LogicalType AsShape(const LogicalType &type); bool IsShape(const LogicalType &type); //! The nanosecond a datetime subclass such as a pandas Timestamp gives as an int, or -1 when it gives none int64_t NanosecondOf(nb::handle cell); -//! Whether a cell is a naive pandas Timestamp with nanoseconds, which no Python datetime holds; they are then in -//! nanoseconds -bool HoldsNanoseconds(nb::handle cell, timestamp_ns_t &nanoseconds); -//! A value for a naive timestamp type converted without a target, but keeping the nanoseconds of a pandas Timestamp -//! for a TIMESTAMP_NS, and reading a numpy scalar as PythonValueOfNumpyScalar does, so a datetime64 finer than a -//! microsecond is a TIMESTAMP_NS that a coarser unit takes through the engine's cast +//! Whether a cell is a pandas Timestamp with nanoseconds, which no Python datetime holds, naive or, when zoned, zone +//! aware; they are then the nanoseconds since the epoch, in UTC for a zone aware one +bool HoldsNanoseconds(nb::handle cell, timestamp_ns_t &nanoseconds, bool zoned); +//! A value for a timestamp type converted without a target, but keeping the nanoseconds of a pandas Timestamp for a +//! TIMESTAMP_NS or a TIMESTAMPTZ_NS, and reading a numpy scalar as PythonValueOfNumpyScalar does, so a datetime64 finer +//! than a microsecond is a TIMESTAMP_NS that a coarser unit takes through the engine's cast Value TransformTimestamp(optional_ptr context, nb::handle ele, const LogicalType &target_type, bool nan_as_null); void TransformPythonObject(optional_ptr context, nb::handle ele, Vector &vector, idx_t result_offset, diff --git a/src/native/python_conversion.cpp b/src/native/python_conversion.cpp index 8d884a207..dab25344b 100644 --- a/src/native/python_conversion.cpp +++ b/src/native/python_conversion.cpp @@ -257,8 +257,18 @@ const identifier_map_t &FieldIndexOf(const LogicalType &struct_type) { } } // namespace -void ClearStructFieldIndexes() { - FieldIndexes().clear(); +// Python a conversion runs, as a tzinfo's utcoffset, can start another declared scan on this thread while an outer +// conversion holds an index, so only the outermost scope drops them +static thread_local idx_t struct_field_index_scopes = 0; + +StructFieldIndexScope::StructFieldIndexScope() { + struct_field_index_scopes++; +} + +StructFieldIndexScope::~StructFieldIndexScope() { + if (--struct_field_index_scopes == 0) { + FieldIndexes().clear(); + } } Value TransformDictionaryToStruct(optional_ptr context, const PyDictionary &dict, @@ -371,7 +381,7 @@ int64_t NanosecondOf(nb::handle cell) { return PyLong_Check(nanosecond.ptr()) ? PyLong_AsLongLong(nanosecond.ptr()) : -1; } -bool HoldsNanoseconds(nb::handle cell, timestamp_ns_t &nanoseconds) { +bool HoldsNanoseconds(nb::handle cell, timestamp_ns_t &nanoseconds, bool zoned) { auto datetime_type = DuckDBPyConnection::ImportCache()->datetime.datetime(); if (Py_TYPE(cell.ptr()) == reinterpret_cast(datetime_type.ptr()) || !duckdb::PyUtil::IsInstance(cell, datetime_type)) { @@ -379,9 +389,10 @@ bool HoldsNanoseconds(nb::handle cell, timestamp_ns_t &nanoseconds) { } // A Timestamp without nanoseconds reads as the datetime it is: its value in nanoseconds overflows outside the // years 1677 to 2262, and a coarser column would judge that value by a cast where the datetime fits outright - if (NanosecondOf(cell) <= 0 || !nb::getattr(cell, "tzinfo").is_none()) { + if (NanosecondOf(cell) <= 0 || nb::getattr(cell, "tzinfo").is_none() == zoned) { return false; } + // A zone aware Timestamp's value counts the nanoseconds since the epoch in UTC, as a TIMESTAMPTZ_NS does nanoseconds = timestamp_ns_t(nb::cast(cell.attr("value"))); return true; } @@ -389,9 +400,12 @@ bool HoldsNanoseconds(nb::handle cell, timestamp_ns_t &nanoseconds) { Value TransformTimestamp(optional_ptr context, nb::handle ele, const LogicalType &target_type, bool nan_as_null) { timestamp_ns_t nanoseconds; - if (target_type.id() == LogicalTypeId::TIMESTAMP_NS && HoldsNanoseconds(ele, nanoseconds)) { + if (target_type.id() == LogicalTypeId::TIMESTAMP_NS && HoldsNanoseconds(ele, nanoseconds, false)) { return Value::TIMESTAMPNS(nanoseconds); } + if (target_type.id() == LogicalTypeId::TIMESTAMP_TZ_NS && HoldsNanoseconds(ele, nanoseconds, true)) { + return Value::TIMESTAMPTZNS(timestamp_tz_ns_t(nanoseconds.value)); + } auto plain = PythonValueOfNumpyScalar(ele, nanoseconds); if (!plain.is_valid()) { return Value::TIMESTAMPNS(nanoseconds); diff --git a/src/numpy/numpy_scan.cpp b/src/numpy/numpy_scan.cpp index d30026bd6..671269dce 100644 --- a/src/numpy/numpy_scan.cpp +++ b/src/numpy/numpy_scan.cpp @@ -309,17 +309,22 @@ static Value DeclaredValue(ClientContext &context, const LogicalType &target, nb if (cell.ptr() == Py_None) { return Value(); } - // A TIMESTAMP_NS column keeps a pandas Timestamp's nanoseconds, and an implied naive timestamp type sees them, so - // its kind check refuses what a coarser unit would drop; a stated coarser type reads the Timestamp as the datetime - // it also is + // A TIMESTAMP_NS or TIMESTAMPTZ_NS column keeps a pandas Timestamp's nanoseconds, and an implied timestamp type of + // a coarser unit sees them, so its kind check refuses what the unit would drop; a stated coarser type reads the + // Timestamp as the datetime it also is auto naive_timestamp = target.id() == LogicalTypeId::TIMESTAMP_NS || (implied && (target.id() == LogicalTypeId::TIMESTAMP || target.id() == LogicalTypeId::TIMESTAMP_MS || target.id() == LogicalTypeId::TIMESTAMP_SEC)); + auto zoned_timestamp = + target.id() == LogicalTypeId::TIMESTAMP_TZ_NS || (implied && target.id() == LogicalTypeId::TIMESTAMP_TZ); timestamp_ns_t nanoseconds; - if (naive_timestamp && HoldsNanoseconds(cell, nanoseconds)) { + if (naive_timestamp && HoldsNanoseconds(cell, nanoseconds, false)) { return Value::TIMESTAMPNS(nanoseconds); } + if (zoned_timestamp && HoldsNanoseconds(cell, nanoseconds, true)) { + return Value::TIMESTAMPTZNS(timestamp_tz_ns_t(nanoseconds.value)); + } auto plain = PythonValueOfNumpyScalar(cell, nanoseconds); if (!plain.is_valid()) { return Value::TIMESTAMPNS(nanoseconds); @@ -367,6 +372,7 @@ static LogicalType KeyedShape(const LogicalType &type, bool typed_entries) { case LogicalTypeId::MAP: return AsShape(LogicalType::MAP(entry(MapType::KeyType(type)), entry(MapType::ValueType(type)))); case LogicalTypeId::TIMESTAMP_NS: + case LogicalTypeId::TIMESTAMP_TZ_NS: return AsShape(type); case LogicalTypeId::TIMESTAMP: case LogicalTypeId::TIMESTAMP_MS: @@ -374,6 +380,9 @@ static LogicalType KeyedShape(const LogicalType &type, bool typed_entries) { // An implied type sees the nanoseconds a coarser unit would drop, so its kind check refuses them; a stated one // takes them through the engine's cast into its unit, as at the top return AsShape(typed_entries ? type : LogicalType::TIMESTAMP_NS); + case LogicalTypeId::TIMESTAMP_TZ: + // A stated one reads a zone aware Timestamp as the datetime it also is, as at the top + return typed_entries ? LogicalType(LogicalTypeId::UNKNOWN) : AsShape(LogicalType::TIMESTAMP_TZ_NS); default: return LogicalType::UNKNOWN; } @@ -622,7 +631,11 @@ class ImpliedKinds { auto zoned_timestamps = (source.id() == LogicalTypeId::TIMESTAMP_TZ || source.id() == LogicalTypeId::TIMESTAMP_TZ_NS) && (type.id() == LogicalTypeId::TIMESTAMP_TZ || type.id() == LogicalTypeId::TIMESTAMP_TZ_NS); - if (zoned_timestamps || (source.id() == LogicalTypeId::VARCHAR && type.id() == LogicalTypeId::VARCHAR) || + // Another unit of a zoned timestamp, as of a naive one, holds only the values the cast keeps unchanged + if (zoned_timestamps) { + return source.id() == type.id() ? Verdict::FITS : Verdict::BY_VALUE; + } + if ((source.id() == LogicalTypeId::VARCHAR && type.id() == LogicalTypeId::VARCHAR) || (source.id() == LogicalTypeId::DOUBLE && type.id() == LogicalTypeId::FLOAT)) { return Verdict::FITS; } @@ -943,21 +956,20 @@ void NumpyScan::ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t idx_t count, idx_t offset, Vector &out, bool implied_type, bool bit_storage_refused) { DeclaredVector staged(count); - struct FieldIndexesOfTheScan { - ~FieldIndexesOfTheScan() { - ClearStructFieldIndexes(); - } - } field_indexes; + StructFieldIndexScope field_indexes; auto &target = out.GetType(); // A type holding a MAP takes a shape for its keys, one holding a STRUCT for a dict to name its fields, not to be - // guessed a MAP's key and value lists, and one holding a naive timestamp for the unit a nested value reads in; a - // top level timestamp is read by DeclaredValue itself - const auto keyed = target.IsNested() && (TypeVisitor::Contains(target, LogicalTypeId::MAP) || - TypeVisitor::Contains(target, LogicalTypeId::STRUCT) || - TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP_NS) || - TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP) || - TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP_MS) || - TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP_SEC)); + // guessed a MAP's key and value lists, and one holding a timestamp for the unit a nested value reads in; a + // top level timestamp is read by DeclaredValue itself, and a stated TIMESTAMPTZ takes no mark in the shape + const auto keyed = + target.IsNested() && + (TypeVisitor::Contains(target, LogicalTypeId::MAP) || TypeVisitor::Contains(target, LogicalTypeId::STRUCT) || + TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP_NS) || + TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP_TZ_NS) || + (implied_type && TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP_TZ)) || + TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP) || + TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP_MS) || + TypeVisitor::Contains(target, LogicalTypeId::TIMESTAMP_SEC)); const auto bits_refused = bit_storage_refused && TypeVisitor::Contains(target, LogicalTypeId::BIT); const auto shape = keyed ? KeyedShape(target, !implied_type) : LogicalType(LogicalTypeId::UNKNOWN); ImpliedKinds kinds(context); @@ -1070,7 +1082,9 @@ void NumpyScan::ScanDeclaredColumn(ClientContext &context, PyObject **col, idx_t vector keys; vector values; ScanObjectCells(context, col, stride, masked, count, offset, out, [&](nb::handle cell, idx_t row) { - if (!PyDict_Check(cell.ptr())) { + // A dict subclass, as an OrderedDict, may iterate in another order than its storage, which is what + // PyDict_Next walks + if (!PyDict_CheckExact(cell.ptr())) { return read(cell, row); } auto size = NumericCast(PyDict_Size(cell.ptr())); diff --git a/tests/fast/pandas/test_append_df.py b/tests/fast/pandas/test_append_df.py index 61b318020..86a4e6015 100644 --- a/tests/fast/pandas/test_append_df.py +++ b/tests/fast/pandas/test_append_df.py @@ -1,3 +1,4 @@ +import collections import datetime import enum import math @@ -587,15 +588,104 @@ def test_aware_timestamp_without_nanoseconds_reads_in_the_session_time_zone(self ] def test_struct_dicts_with_keys_out_of_field_order_read_each_field_by_name(self, duckdb_cursor): - # Twelve STRUCT types, more than the per thread field indexes keep, each dict's keys in reverse field order - inner = [f"s{i} STRUCT(a{i} INTEGER, b{i} INTEGER, c{i} INTEGER)" for i in range(12)] - duckdb_cursor.execute(f"CREATE TABLE t (i INTEGER, a STRUCT({', '.join(inner)}))") - cells = [ - {f"s{i}": {f"c{i}": row + 3, f"b{i}": row + 2, f"a{i}": row + 1} for i in reversed(range(12))} - for row in range(3000) - ] + # Each dict's keys in reverse field order, for twelve STRUCT types and one inside a LIST; the TIMESTAMP_NS and + # BLOB keyed MAP fields read their nanoseconds and bytes only when the key finds its field + nanosecond = pd.Timestamp("2020-01-01 00:00:00.000000001") + + def fields(i): + return f"a{i} INTEGER, t{i} TIMESTAMP_NS, m{i} MAP(BLOB, INTEGER)" + + def cell(i, row): + return {f"m{i}": {b"\x00k": row}, f"t{i}": nanosecond, f"a{i}": row} + + inner = [f"s{i} STRUCT({fields(i)})" for i in range(12)] + duckdb_cursor.execute(f"CREATE TABLE t (i INTEGER, a STRUCT({', '.join(inner)}, l STRUCT({fields(12)})[]))") + cells = [{"l": [cell(12, row)], **{f"s{i}": cell(i, row) for i in reversed(range(12))}} for row in range(3000)] duckdb_cursor.append("t", pd.DataFrame({"i": range(3000), "a": pd.Series(cells, dtype=object)})) - assert [row[0] for row in duckdb_cursor.sql("SELECT a FROM t ORDER BY i").fetchall()] == cells + places = [(f"a.s{i}", i) for i in range(12)] + [("a.l[1]", 12)] + columns = ", ".join(f"{place}.a{i}, {place}.t{i}::VARCHAR, {place}.m{i}" for place, i in places) + expected = [(row, "2020-01-01 00:00:00.000000001", {b"\x00k": row}) * len(places) for row in range(3000)] + assert duckdb_cursor.sql(f"SELECT {columns} FROM t ORDER BY i").fetchall() == expected + + def test_struct_append_inside_a_conversion_keeps_the_outer_scans_field_index(self, duckdb_cursor): + # A tzinfo's utcoffset that appends on another connection runs a declared scan inside this one's, between + # this dict's out of order keys + other = duckdb.connect() + other.execute("CREATE TABLE y (c BIGINT)") + + class Appending(datetime.tzinfo): + def utcoffset(self, dt): + other.append("y", pd.DataFrame({"c": pd.Series([1, 2, 3], dtype=object)})) + return datetime.timedelta(0) + + def dst(self, dt): + return datetime.timedelta(0) + + def tzname(self, dt): + return "UTC" + + fields = [f"f{j}" for j in range(30)] + duckdb_cursor.execute(f"CREATE TABLE t (a STRUCT(t TIMESTAMPTZ, {', '.join(f'{f} INTEGER' for f in fields)}))") + moment = datetime.datetime(2020, 1, 1, tzinfo=Appending()) + cells = [{"f29": row, "t": moment, **dict.fromkeys(reversed(fields[:-1]), row)} for row in range(20)] + duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series(cells, dtype=object)})) + assert duckdb_cursor.sql("SELECT count(*), sum(a.f0), sum(a.f29) FROM t").fetchall() == [(20, 190, 190)] + assert other.sql("SELECT count(*) > 0 FROM y").fetchall() == [(True,)] + + @pytest.mark.parametrize( + ("target", "cell", "expected"), + [ + pytest.param("TIMESTAMPTZ_NS", "stamp", "2020-01-01 00:00:00.000000001+00", id="top"), + pytest.param( + "STRUCT(t TIMESTAMPTZ_NS)", {"t": "stamp"}, "{'t': '2020-01-01 00:00:00.000000001+00'}", id="field" + ), + pytest.param("TIMESTAMPTZ_NS[]", ["stamp"], "['2020-01-01 00:00:00.000000001+00']", id="list_element"), + pytest.param( + "MAP(VARCHAR, TIMESTAMPTZ_NS)", {"k": "stamp"}, "{k='2020-01-01 00:00:00.000000001+00'}", id="map_value" + ), + ], + ) + def test_zoned_timestamp_with_nanoseconds_keeps_them_in_a_timestamptz_ns( + self, duckdb_cursor, target, cell, expected + ): + stamp = pd.Timestamp("2020-01-01 00:00:00.000000001", tz="UTC") + + def with_stamp(value): + if isinstance(value, dict): + return {key: with_stamp(item) for key, item in value.items()} + if isinstance(value, list): + return [with_stamp(item) for item in value] + return stamp if value == "stamp" else value + + duckdb_cursor.execute("SET TimeZone = 'UTC'") + duckdb_cursor.execute(f"CREATE TABLE t (a {target})") + duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series([with_stamp(cell)], dtype=object)})) + assert duckdb_cursor.sql("SELECT a::VARCHAR FROM t").fetchall() == [(expected,)] + + @pytest.mark.parametrize( + ("stamp", "text"), + [ + pytest.param(pd.Timestamp.max.tz_localize("UTC"), "infinity", id="max"), + pytest.param(pd.Timestamp.min.tz_localize("UTC"), "-infinity", id="min"), + ], + ) + @pytest.mark.parametrize("place", ["top", "field", "list_element"]) + def test_zoned_timestamp_max_and_min_store_infinity_in_a_timestamptz_ns(self, duckdb_cursor, stamp, text, place): + target, cell, expected = { + "top": ("TIMESTAMPTZ_NS", stamp, text), + "field": ("STRUCT(t TIMESTAMPTZ_NS)", {"t": stamp}, f"{{'t': {text}}}"), + "list_element": ("TIMESTAMPTZ_NS[]", [stamp], f"[{text}]"), + }[place] + duckdb_cursor.execute(f"CREATE TABLE t (a {target})") + duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series([cell], dtype=object)})) + assert duckdb_cursor.sql("SELECT a::VARCHAR FROM t").fetchall() == [(expected,)] + + def test_map_of_an_ordered_dict_keeps_its_iteration_order(self, duckdb_cursor): + ordered = collections.OrderedDict([("a", 1), ("b", 2), ("c", 3)]) + ordered.move_to_end("a") + duckdb_cursor.execute("CREATE TABLE t (a MAP(VARCHAR, INTEGER))") + duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series([ordered], dtype=object)})) + assert duckdb_cursor.sql("SELECT map_keys(a) FROM t").fetchall() == [(["b", "c", "a"],)] def test_map_column_mixing_dicts_with_other_cells_keeps_every_row_in_place(self, duckdb_cursor): # Dicts are written into the MAP's entries directly and the other cells after them; 3000 rows span two vectors @@ -634,9 +724,8 @@ def test_map_values_of_mixed_numbers_each_keep_their_value(self): def test_map_key_of_none_is_refused_and_the_connection_stays_usable(self, duckdb_cursor): duckdb_cursor.execute("CREATE TABLE t (a MAP(VARCHAR, INTEGER))") - with pytest.raises(duckdb.Error) as error: + with pytest.raises(duckdb.InvalidInputException, match=re.escape("Map keys can not be NULL.")): duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series([{None: 1}], dtype=object)})) - assert not isinstance(error.value, duckdb.FatalException), error.value assert duckdb_cursor.sql("SELECT 42").fetchall() == [(42,)] def test_text_with_a_lone_surrogate_names_it(self, duckdb_cursor): diff --git a/tests/fast/test_map_types.py b/tests/fast/test_map_types.py index 683ee0a06..043ff41f5 100644 --- a/tests/fast/test_map_types.py +++ b/tests/fast/test_map_types.py @@ -1,5 +1,6 @@ """map() fixes one type per output column at bind and reads each chunk's returned column into it.""" +import collections import datetime import json import re @@ -842,6 +843,14 @@ def test_declared_struct_with_fields_key_and_value_reads_a_null_field_as_its_str assert mapped.fetchall() == expected +def test_map_of_an_ordered_dict_for_a_stated_map_keeps_its_iteration_order(duckdb_cursor): + ordered = collections.OrderedDict([("a", 1), ("b", 2), ("c", 3)]) + ordered.move_to_end("a") + source = duckdb_cursor.sql("select MAP {'k': 1} as a") + mapped = source.map(_returning(ordered), schema={"a": duckdb.sqltype("MAP(VARCHAR, INTEGER)")}) + assert mapped.project("map_keys(a)").fetchall() == [(["b", "c", "a"],)] + + @pytest.mark.parametrize("mode", ["inferred", "explicit_schema", "append"]) def test_struct_given_an_empty_dict_is_refused(mode): # A missing field reads NULL, but a dict of no keys is no STRUCT of the column's fields @@ -971,6 +980,75 @@ def test_map_nested_timestamp_ns_value_keeps_its_nanoseconds(duckdb_cursor, valu assert "00:00:00.000000001" in mapped.project("a::VARCHAR").fetchall()[0][0] +AWARE_NANOSECOND = pd.Timestamp("2020-01-01 00:00:00.000000001", tz="UTC") + + +@pytest.mark.parametrize( + ("value", "cell"), + [ + pytest.param("'2020-01-01 00:00:00.000000001+00'::TIMESTAMPTZ_NS", AWARE_NANOSECOND, id="top"), + pytest.param("{'t': '2020-01-01 00:00:00.000000001+00'::TIMESTAMPTZ_NS}", {"t": AWARE_NANOSECOND}, id="field"), + pytest.param("['2020-01-01 00:00:00.000000001+00'::TIMESTAMPTZ_NS]", [AWARE_NANOSECOND], id="list_element"), + ], +) +@SCHEMAS +def test_map_zoned_timestamp_ns_value_keeps_its_nanoseconds(duckdb_cursor, value, cell, explicit_schema): + duckdb_cursor.execute("SET TimeZone = 'UTC'") + source = duckdb_cursor.sql(f"select {value} as a") + mapped = source.map(_returning(cell), schema=_schema_of(source, explicit_schema)) + assert mapped.types == source.types + assert mapped.project("a::VARCHAR").fetchall() == source.project("a::VARCHAR").fetchall() + + +@pytest.mark.parametrize( + ("value", "cell", "returned"), + [ + pytest.param("'2020-01-01 00:00:00+00'::TIMESTAMPTZ", AWARE_NANOSECOND, "TIMESTAMPTZ_NS", id="top"), + pytest.param( + "{'t': '2020-01-01 00:00:00+00'::TIMESTAMPTZ}", + {"t": AWARE_NANOSECOND}, + "STRUCT(t TIMESTAMPTZ_NS)", + id="field", + ), + pytest.param( + "['2020-01-01 00:00:00+00'::TIMESTAMPTZ]", [AWARE_NANOSECOND], "TIMESTAMPTZ_NS[]", id="list_element" + ), + ], +) +def test_map_zoned_timestamp_with_nanoseconds_for_an_implied_timestamptz_is_refused( + duckdb_cursor, value, cell, returned +): + duckdb_cursor.execute("SET TimeZone = 'UTC'") + source = duckdb_cursor.sql(f"select {value} as a") + expected = f"UDF column type mismatch, expected [{source.types[0]}], got [{returned}]" + with pytest.raises(duckdb.InvalidInputException, match=re.escape(expected)): + source.map(_returning(cell)).fetchall() + + +@pytest.mark.parametrize("place", ["top", "field", "list_element", "map_value"]) +@pytest.mark.parametrize("mode", ["explicit_schema", "append"]) +def test_map_zoned_timestamp_with_nanoseconds_for_a_stated_timestamptz_reads_as_its_datetime(place, mode): + stamp = pd.Timestamp("2020-01-01 00:00:00.000005789", tz="UTC") + text = "2020-01-01 00:00:00.000005+00" + sql_type, cell, expected = { + "top": ("TIMESTAMPTZ", stamp, text), + "field": ("STRUCT(t TIMESTAMPTZ)", {"t": stamp}, f"{{'t': '{text}'}}"), + "list_element": ("TIMESTAMPTZ[]", [stamp], f"['{text}']"), + "map_value": ("MAP(VARCHAR, TIMESTAMPTZ)", {"k": stamp}, f"{{k='{text}'}}"), + }[place] + con = duckdb.connect() + con.execute("SET TimeZone = 'UTC'") + con.execute(f"create table t (a {sql_type})") + if mode == "append": + con.append("t", pd.DataFrame({"a": pd.Series([cell], dtype=object)})) + rows = con.sql("select a::VARCHAR from t").fetchall() + else: + con.execute("insert into t values (NULL)") + schema = {"a": duckdb.sqltype(sql_type)} + rows = con.table("t").map(_returning(cell), schema=schema).project("a::VARCHAR").fetchall() + assert rows == [(expected,)] + + def test_map_nested_timestamp_with_nanoseconds_for_an_implied_timestamp_is_refused(duckdb_cursor): mapped = duckdb_cursor.sql("select {'t': TIMESTAMP '2020-01-01'} as a").map(_returning({"t": NANOSECOND})) expected = ( From e4bb2a7bb4737eb0aba43b3f60934b481ad4d4d9 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Sat, 7 Nov 2026 08:06:56 +0000 Subject: [PATCH 32/61] Nest the reentrancy test's scans on one thread and pin the zoned nanoseconds under a New York zone --- tests/fast/pandas/test_append_df.py | 26 +++++++++++++++++++------- tests/fast/test_map_types.py | 16 +++++++++++----- 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/tests/fast/pandas/test_append_df.py b/tests/fast/pandas/test_append_df.py index 86a4e6015..0ebe0b2b3 100644 --- a/tests/fast/pandas/test_append_df.py +++ b/tests/fast/pandas/test_append_df.py @@ -609,8 +609,8 @@ def cell(i, row): def test_struct_append_inside_a_conversion_keeps_the_outer_scans_field_index(self, duckdb_cursor): # A tzinfo's utcoffset that appends on another connection runs a declared scan inside this one's, between - # this dict's out of order keys - other = duckdb.connect() + # this dict's out of order keys; with one thread that scan runs on this thread, which holds the index + other = duckdb.connect(config={"threads": 1}) other.execute("CREATE TABLE y (c BIGINT)") class Appending(datetime.tzinfo): @@ -625,12 +625,22 @@ def tzname(self, dt): return "UTC" fields = [f"f{j}" for j in range(30)] - duckdb_cursor.execute(f"CREATE TABLE t (a STRUCT(t TIMESTAMPTZ, {', '.join(f'{f} INTEGER' for f in fields)}))") + integers = ", ".join(f"{f} INTEGER" for f in fields) + duckdb_cursor.execute( + f"CREATE TABLE t (a STRUCT(t TIMESTAMPTZ, {integers}, n TIMESTAMP_NS, m MAP(BLOB, INTEGER)))" + ) moment = datetime.datetime(2020, 1, 1, tzinfo=Appending()) - cells = [{"f29": row, "t": moment, **dict.fromkeys(reversed(fields[:-1]), row)} for row in range(20)] + stamp = pd.Timestamp("2020-01-01 00:00:00.000000001") + # The fields after the callback read right only through the index: n keeps its nanosecond, m its bytes keys + cells = [ + {"f29": row, "t": moment, "n": stamp, "m": {b"\x00k": row}, **dict.fromkeys(reversed(fields[:-1]), row)} + for row in range(20) + ] duckdb_cursor.append("t", pd.DataFrame({"a": pd.Series(cells, dtype=object)})) - assert duckdb_cursor.sql("SELECT count(*), sum(a.f0), sum(a.f29) FROM t").fetchall() == [(20, 190, 190)] + rows = duckdb_cursor.sql("SELECT a.f0, a.f29, a.n::VARCHAR, a.m FROM t ORDER BY a.f0").fetchall() + assert rows == [(row, row, "2020-01-01 00:00:00.000000001", {b"\x00k": row}) for row in range(20)] assert other.sql("SELECT count(*) > 0 FROM y").fetchall() == [(True,)] + other.close() @pytest.mark.parametrize( ("target", "cell", "expected"), @@ -645,10 +655,12 @@ def tzname(self, dt): ), ], ) + @pytest.mark.parametrize("zone", ["UTC", "America/New_York"], ids=["UTC", "America_New_York"]) def test_zoned_timestamp_with_nanoseconds_keeps_them_in_a_timestamptz_ns( - self, duckdb_cursor, target, cell, expected + self, duckdb_cursor, target, cell, expected, zone ): - stamp = pd.Timestamp("2020-01-01 00:00:00.000000001", tz="UTC") + # The same instant in either zone, so a reading of the wall time instead would differ + stamp = pd.Timestamp("2020-01-01 00:00:00.000000001", tz="UTC").tz_convert(zoneinfo.ZoneInfo(zone)) def with_stamp(value): if isinstance(value, dict): diff --git a/tests/fast/test_map_types.py b/tests/fast/test_map_types.py index 043ff41f5..9b71b9bcf 100644 --- a/tests/fast/test_map_types.py +++ b/tests/fast/test_map_types.py @@ -4,6 +4,7 @@ import datetime import json import re +import zoneinfo from decimal import Decimal from fractions import Fraction @@ -986,16 +987,21 @@ def test_map_nested_timestamp_ns_value_keeps_its_nanoseconds(duckdb_cursor, valu @pytest.mark.parametrize( ("value", "cell"), [ - pytest.param("'2020-01-01 00:00:00.000000001+00'::TIMESTAMPTZ_NS", AWARE_NANOSECOND, id="top"), - pytest.param("{'t': '2020-01-01 00:00:00.000000001+00'::TIMESTAMPTZ_NS}", {"t": AWARE_NANOSECOND}, id="field"), - pytest.param("['2020-01-01 00:00:00.000000001+00'::TIMESTAMPTZ_NS]", [AWARE_NANOSECOND], id="list_element"), + pytest.param("'2020-01-01 00:00:00.000000001+00'::TIMESTAMPTZ_NS", lambda stamp: stamp, id="top"), + pytest.param( + "{'t': '2020-01-01 00:00:00.000000001+00'::TIMESTAMPTZ_NS}", lambda stamp: {"t": stamp}, id="field" + ), + pytest.param("['2020-01-01 00:00:00.000000001+00'::TIMESTAMPTZ_NS]", lambda stamp: [stamp], id="list_element"), ], ) +@pytest.mark.parametrize("zone", ["UTC", "America/New_York"], ids=["UTC", "America_New_York"]) @SCHEMAS -def test_map_zoned_timestamp_ns_value_keeps_its_nanoseconds(duckdb_cursor, value, cell, explicit_schema): +def test_map_zoned_timestamp_ns_value_keeps_its_nanoseconds(duckdb_cursor, value, cell, zone, explicit_schema): + # The same instant in either zone, so a reading of the wall time instead would differ + stamp = AWARE_NANOSECOND.tz_convert(zoneinfo.ZoneInfo(zone)) duckdb_cursor.execute("SET TimeZone = 'UTC'") source = duckdb_cursor.sql(f"select {value} as a") - mapped = source.map(_returning(cell), schema=_schema_of(source, explicit_schema)) + mapped = source.map(_returning(cell(stamp)), schema=_schema_of(source, explicit_schema)) assert mapped.types == source.types assert mapped.project("a::VARCHAR").fetchall() == source.project("a::VARCHAR").fetchall() From 50f050d26d9b091ec1798c3f64c7a05f7116fc43 Mon Sep 17 00:00:00 2001 From: DuckDB Labs GitHub Bot Date: Mon, 9 Nov 2026 02:34:48 +0000 Subject: [PATCH 33/61] Bump submodule --- external/duckdb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/external/duckdb b/external/duckdb index 910c73dab..29b26cb10 160000 --- a/external/duckdb +++ b/external/duckdb @@ -1 +1 @@ -Subproject commit 910c73dabeafc0290907a0c37e09f6abed8e9446 +Subproject commit 29b26cb10605e45d7dac7237bce34423ebba4512 From 84f96346a07e702e8177928d39f1d44bc1dfcdf0 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Mon, 9 Nov 2026 10:23:08 +0000 Subject: [PATCH 34/61] Regenerate the benchmark baseline for v2.0-cyanoptera at engine 29b26cb106 --- benchmarks/baseline.json | 618 +++++++++++++++++++++++++++++++-------- 1 file changed, 493 insertions(+), 125 deletions(-) diff --git a/benchmarks/baseline.json b/benchmarks/baseline.json index f35dbda75..92592bab0 100644 --- a/benchmarks/baseline.json +++ b/benchmarks/baseline.json @@ -1,10 +1,10 @@ { "meta": { "schema_version": 1, - "generated_at_utc": "2026-07-02T10:39:31+00:00", - "git_commit": "ddd71963ded733c0d70841cf0a27ce3efbdb8c6f", - "duckdb_submodule_sha": "1da5b6c8cf6ce50ff8089aa59eb028bae8044f08", - "requirements_bench_sha256": "2bdfd6a766947a61559afb2799c54f0ea173b9325f55082ad809bf7b97b2c659", + "generated_at_utc": "2026-11-09T09:47:27+00:00", + "git_commit": "c2556eddc0609205380fb608be67525853cc0ef8", + "duckdb_submodule_sha": "29b26cb10605e45d7dac7237bce34423ebba4512", + "requirements_bench_sha256": "f54318c37c877b516dc1d57e99d0c5e518d7a2fbaa88e7a75cfd723537bcbe2c", "measurement": { "tool": "valgrind callgrind", "event": "Ir", @@ -20,7 +20,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 13234377, + "instructions": 8882992, "binding_fraction": null, "threshold_pct": null }, @@ -28,7 +28,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 12899099, + "instructions": 7889469, "binding_fraction": null, "threshold_pct": null }, @@ -36,7 +36,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 16808671, + "instructions": 12057962, "binding_fraction": null, "threshold_pct": null }, @@ -44,7 +44,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 6654121, + "instructions": 2610186, "binding_fraction": null, "threshold_pct": null }, @@ -52,7 +52,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 7788904, + "instructions": 3578674, "binding_fraction": null, "threshold_pct": null }, @@ -60,7 +60,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 16318265, + "instructions": 11871014, "binding_fraction": null, "threshold_pct": null }, @@ -68,7 +68,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 35184533, + "instructions": 15046613, "binding_fraction": null, "threshold_pct": null }, @@ -76,7 +76,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 34891957, + "instructions": 15070695, "binding_fraction": null, "threshold_pct": null }, @@ -84,7 +84,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 32861083, + "instructions": 27755247, "binding_fraction": null, "threshold_pct": null }, @@ -92,7 +92,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 35112605, + "instructions": 15430188, "binding_fraction": null, "threshold_pct": null }, @@ -100,7 +100,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 34730605, + "instructions": 29909202, "binding_fraction": null, "threshold_pct": null }, @@ -108,7 +108,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 51734481, + "instructions": 22431764, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -116,7 +116,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 33850667, + "instructions": 6157657, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -124,7 +124,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 32217517, + "instructions": 4606504, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -132,7 +132,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 71513957, + "instructions": 40521097, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -140,7 +140,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 66950208, + "instructions": 36756628, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -148,7 +148,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 34404751, + "instructions": 6180722, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -156,7 +156,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 31383134, + "instructions": 3270932, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -164,7 +164,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 103824509, + "instructions": 71457595, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -172,7 +172,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 43074317, + "instructions": 13258290, "binding_fraction": null, "threshold_pct": null }, @@ -180,7 +180,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 32401442, + "instructions": 4608949, "binding_fraction": null, "threshold_pct": null }, @@ -188,7 +188,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 31416581, + "instructions": 3797663, "binding_fraction": null, "threshold_pct": null }, @@ -196,7 +196,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 55048499, + "instructions": 22922768, "binding_fraction": null, "threshold_pct": null }, @@ -204,7 +204,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 3633775, + "instructions": 1536470, "binding_fraction": null, "threshold_pct": null }, @@ -212,7 +212,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 3632023, + "instructions": 1531822, "binding_fraction": null, "threshold_pct": null }, @@ -220,7 +220,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 3211889, + "instructions": 1191042, "binding_fraction": null, "threshold_pct": null }, @@ -228,7 +228,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 37557571, + "instructions": 14219172, "binding_fraction": null, "threshold_pct": null }, @@ -236,7 +236,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 36895059, + "instructions": 34904579, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -244,7 +244,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 6055741, + "instructions": 4437264, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -252,7 +252,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 54059510, + "instructions": 47565528, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -260,7 +260,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 271638006, + "instructions": 190344567, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -268,7 +268,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 33349249, + "instructions": 26377678, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -276,7 +276,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 22345385, + "instructions": 22410515, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -284,7 +284,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 3724222, + "instructions": 2834823, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -292,7 +292,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 340003609, + "instructions": 266283703, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -300,7 +300,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 702796711, + "instructions": 578055278, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -308,7 +308,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 21094700, + "instructions": 19114762, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -316,7 +316,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 21409422, + "instructions": 21424509, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -324,7 +324,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 41836625, + "instructions": 40156986, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -332,7 +332,15 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 390785984, + "instructions": 179045645, + "binding_fraction": null, + "threshold_pct": 5.0 + }, + "benchmarks/test_fetch_perf.py::test_fetchall_timetz": { + "marker": "gate", + "source_marker": "gate", + "auto_moved": false, + "instructions": 187566472, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -340,7 +348,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 52492693, + "instructions": 44235323, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -348,7 +356,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 64211821, + "instructions": 55017231, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -356,7 +364,31 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 22773135475, + "instructions": 27525141021, + "binding_fraction": null, + "threshold_pct": 5.0 + }, + "benchmarks/test_ingest_native_perf.py::test_ingest_values_binary[bytearray]": { + "marker": "gate", + "source_marker": "gate", + "auto_moved": false, + "instructions": 157265151, + "binding_fraction": null, + "threshold_pct": 5.0 + }, + "benchmarks/test_ingest_native_perf.py::test_ingest_values_binary[bytes]": { + "marker": "gate", + "source_marker": "gate", + "auto_moved": false, + "instructions": 92927379, + "binding_fraction": null, + "threshold_pct": 5.0 + }, + "benchmarks/test_ingest_native_perf.py::test_ingest_values_binary[memoryview]": { + "marker": "gate", + "source_marker": "gate", + "auto_moved": false, + "instructions": 115802086, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -364,7 +396,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 7011565008, + "instructions": 6705370672, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -372,7 +404,47 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 4830766039, + "instructions": 4875300833, + "binding_fraction": null, + "threshold_pct": 5.0 + }, + "benchmarks/test_ingest_native_perf.py::test_ingest_values_temporal[date]": { + "marker": "gate", + "source_marker": "gate", + "auto_moved": false, + "instructions": 93873204, + "binding_fraction": null, + "threshold_pct": 5.0 + }, + "benchmarks/test_ingest_native_perf.py::test_ingest_values_temporal[datetime]": { + "marker": "gate", + "source_marker": "gate", + "auto_moved": false, + "instructions": 111960361, + "binding_fraction": null, + "threshold_pct": 5.0 + }, + "benchmarks/test_ingest_native_perf.py::test_ingest_values_temporal[datetime_tz]": { + "marker": "gate", + "source_marker": "gate", + "auto_moved": false, + "instructions": 198914238, + "binding_fraction": null, + "threshold_pct": 5.0 + }, + "benchmarks/test_ingest_native_perf.py::test_ingest_values_temporal[time]": { + "marker": "gate", + "source_marker": "gate", + "auto_moved": false, + "instructions": 95639098, + "binding_fraction": null, + "threshold_pct": 5.0 + }, + "benchmarks/test_ingest_native_perf.py::test_ingest_values_temporal[timedelta]": { + "marker": "gate", + "source_marker": "gate", + "auto_moved": false, + "instructions": 167744853, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -380,7 +452,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 5805088896, + "instructions": 5766575644, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -388,7 +460,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 22592113, + "instructions": 3031357, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -396,7 +468,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 6448389, + "instructions": 2802115, "binding_fraction": null, "threshold_pct": null }, @@ -404,7 +476,23 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 4939556, + "instructions": 2414981, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_ingest_numpy_perf.py::test_read_numpy_ma_int": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 2440378, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_ingest_numpy_perf.py::test_read_numpy_ma_object_string": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 12192352, "binding_fraction": null, "threshold_pct": null }, @@ -412,7 +500,15 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 4834310, + "instructions": 2537490, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_ingest_numpy_perf.py::test_read_numpy_object_mixed_types": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 21645298, "binding_fraction": null, "threshold_pct": null }, @@ -420,7 +516,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 80120985, + "instructions": 13072158, "binding_fraction": null, "threshold_pct": null }, @@ -428,7 +524,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 6644414, + "instructions": 2533218, "binding_fraction": null, "threshold_pct": null }, @@ -436,7 +532,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 16303697, + "instructions": 11868101, "binding_fraction": null, "threshold_pct": null }, @@ -444,7 +540,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 7031838, + "instructions": 3096587, "binding_fraction": null, "threshold_pct": null }, @@ -452,7 +548,231 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 32692229, + "instructions": 14949635, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_object_datetime[aware]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 333245060, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_object_datetime[naive]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 196615619, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[1-no_nulls-bind]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 18209594, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[1-no_nulls-sum_i]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 18802324, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[1-no_nulls-sum_length]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 27434024, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[1-nulls-bind]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 151049119, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[1-nulls-sum_i]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 151658184, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[1-nulls-sum_length]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 159573893, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[10-no_nulls-bind]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 18024200, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[10-no_nulls-sum_i]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 18609758, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[10-no_nulls-sum_length]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 27238048, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[10-nulls-bind]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 36726237, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[10-nulls-sum_i]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 37326239, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[10-nulls-sum_length]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 45245981, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[100-no_nulls-bind]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 2770480, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[100-no_nulls-sum_i]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 3352616, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[100-no_nulls-sum_length]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 7182243, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[100-nulls-bind]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 2768708, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[100-nulls-sum_i]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 3348804, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[100-nulls-sum_length]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 7098966, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[1000-no_nulls-bind]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 1398195, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[1000-no_nulls-sum_i]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 1986949, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[1000-no_nulls-sum_length]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 5671963, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[1000-nulls-bind]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 1409254, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[1000-nulls-sum_i]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 1987878, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_str_chunked[1000-nulls-sum_length]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 5515684, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_string_dtype[python]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 13464420, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_pandas_perf.py::test_read_pandas_string_dtype[str]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 10650270, "binding_fraction": null, "threshold_pct": null }, @@ -460,7 +780,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 35531575, + "instructions": 15830074, "binding_fraction": null, "threshold_pct": null }, @@ -468,7 +788,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 33395666, + "instructions": 28527344, "binding_fraction": null, "threshold_pct": null }, @@ -476,7 +796,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 35262927, + "instructions": 16291194, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -484,7 +804,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 45978557, + "instructions": 27621588, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -492,7 +812,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 76064352, + "instructions": 75237949, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -500,7 +820,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 25492525, + "instructions": 27374782, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -508,7 +828,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 14746792, + "instructions": 7705108, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -516,7 +836,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 7995031, + "instructions": 6759375, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -524,7 +844,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 35256355, + "instructions": 16281343, "binding_fraction": null, "threshold_pct": null }, @@ -532,7 +852,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 45939193, + "instructions": 27553719, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -540,7 +860,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 75962963, + "instructions": 75054138, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -548,7 +868,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 25473843, + "instructions": 27352419, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -556,7 +876,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 220298436, + "instructions": 216479567, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -564,7 +884,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 49712218, + "instructions": 29210755, "binding_fraction": null, "threshold_pct": null }, @@ -572,7 +892,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 33944853, + "instructions": 14969013, "binding_fraction": null, "threshold_pct": null }, @@ -580,7 +900,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 40658168, + "instructions": 22316786, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -588,7 +908,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 69063552, + "instructions": 186545252, "binding_fraction": null, "threshold_pct": null }, @@ -596,7 +916,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 3940908, + "instructions": 2874182, "binding_fraction": null, "threshold_pct": null }, @@ -604,7 +924,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 5917219, + "instructions": 4631614, "binding_fraction": null, "threshold_pct": null }, @@ -612,7 +932,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 13682653, + "instructions": 6427004, "binding_fraction": null, "threshold_pct": null }, @@ -620,7 +940,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 6989466, + "instructions": 5607398, "binding_fraction": null, "threshold_pct": null }, @@ -628,7 +948,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 14807454, + "instructions": 6783679, "binding_fraction": null, "threshold_pct": null }, @@ -636,7 +956,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 7044278, + "instructions": 5545357, "binding_fraction": null, "threshold_pct": null }, @@ -644,7 +964,15 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 2720419, + "instructions": 2085120, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_types_roundtrip_perf.py::test_out_arrow_table[interval]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 4451807, "binding_fraction": null, "threshold_pct": null }, @@ -652,7 +980,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 12925581, + "instructions": 7979132, "binding_fraction": null, "threshold_pct": null }, @@ -660,7 +988,15 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 5744664, + "instructions": 3763278, + "binding_fraction": null, + "threshold_pct": null + }, + "benchmarks/test_types_roundtrip_perf.py::test_out_arrow_table[time]": { + "marker": "informational", + "source_marker": "informational", + "auto_moved": false, + "instructions": 6051843, "binding_fraction": null, "threshold_pct": null }, @@ -668,7 +1004,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 12021064, + "instructions": 12200160, "binding_fraction": null, "threshold_pct": null }, @@ -676,7 +1012,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 13392814, + "instructions": 11443890, "binding_fraction": null, "threshold_pct": null }, @@ -684,7 +1020,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 28029946, + "instructions": 22795863, "binding_fraction": null, "threshold_pct": null }, @@ -692,7 +1028,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 14498290, + "instructions": 12302829, "binding_fraction": null, "threshold_pct": null }, @@ -700,7 +1036,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 3965864, + "instructions": 2880675, "binding_fraction": null, "threshold_pct": null }, @@ -708,15 +1044,15 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 7406654, - "binding_fraction": 0.5094, + "instructions": 6069480, + "binding_fraction": 0.7469, "threshold_pct": 5.0 }, "benchmarks/test_types_roundtrip_perf.py::test_out_col_df[decimal128]": { "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 14746031, + "instructions": 7719560, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -724,7 +1060,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 7331242, + "instructions": 6097920, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -732,15 +1068,15 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 15690529, - "binding_fraction": 0.7684, + "instructions": 7254960, + "binding_fraction": 0.7882, "threshold_pct": 5.0 }, "benchmarks/test_types_roundtrip_perf.py::test_out_col_df[hugeint]": { "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 7998654, + "instructions": 6763531, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -748,15 +1084,23 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 2957718, + "instructions": 2432693, "binding_fraction": null, "threshold_pct": null }, + "benchmarks/test_types_roundtrip_perf.py::test_out_col_df[interval]": { + "marker": "gate", + "source_marker": "gate", + "auto_moved": false, + "instructions": 6513218, + "binding_fraction": null, + "threshold_pct": 5.0 + }, "benchmarks/test_types_roundtrip_perf.py::test_out_col_df[list]": { "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 99033627, + "instructions": 87400780, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -764,7 +1108,15 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 125117218, + "instructions": 96427811, + "binding_fraction": null, + "threshold_pct": 5.0 + }, + "benchmarks/test_types_roundtrip_perf.py::test_out_col_df[time]": { + "marker": "gate", + "source_marker": "gate", + "auto_moved": false, + "instructions": 30072887, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -772,7 +1124,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 12351561, + "instructions": 12644671, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -780,7 +1132,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 220313633, + "instructions": 216526832, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -788,7 +1140,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 47128590, + "instructions": 43655354, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -796,7 +1148,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 31366014, + "instructions": 29961175, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -804,7 +1156,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 21042553, + "instructions": 21258689, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -812,7 +1164,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 27286189, + "instructions": 39689696, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -820,7 +1172,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 271217448, + "instructions": 190560482, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -828,7 +1180,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 25532489, + "instructions": 25297760, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -836,7 +1188,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 33290221, + "instructions": 26566754, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -844,7 +1196,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 184865901, + "instructions": 148018857, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -852,7 +1204,15 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 22382107, + "instructions": 22663918, + "binding_fraction": null, + "threshold_pct": 5.0 + }, + "benchmarks/test_types_roundtrip_perf.py::test_out_row_fetchall[interval]": { + "marker": "gate", + "source_marker": "gate", + "auto_moved": false, + "instructions": 150502022, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -860,7 +1220,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 172332344, + "instructions": 130036280, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -868,7 +1228,15 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 134136017, + "instructions": 107107955, + "binding_fraction": null, + "threshold_pct": 5.0 + }, + "benchmarks/test_types_roundtrip_perf.py::test_out_row_fetchall[time]": { + "marker": "gate", + "source_marker": "gate", + "auto_moved": false, + "instructions": 40229255, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -876,7 +1244,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 35722888, + "instructions": 50553445, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -884,7 +1252,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 234289800, + "instructions": 232141899, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -892,7 +1260,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 59326464, + "instructions": 52909321, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -900,7 +1268,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 39627192, + "instructions": 38154559, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -908,7 +1276,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 113267549, + "instructions": 35548987, "binding_fraction": null, "threshold_pct": null }, @@ -916,7 +1284,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 55495884, + "instructions": 15870441, "binding_fraction": null, "threshold_pct": null }, @@ -924,7 +1292,7 @@ "marker": "informational", "source_marker": "informational", "auto_moved": false, - "instructions": 73488819, + "instructions": 27069988, "binding_fraction": null, "threshold_pct": null }, @@ -932,7 +1300,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 47311728, + "instructions": 36134192, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -940,7 +1308,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 40500454, + "instructions": 35888895, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -948,7 +1316,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 56305063, + "instructions": 49555567, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -956,7 +1324,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 30843428, + "instructions": 24552459, "binding_fraction": null, "threshold_pct": 5.0 }, @@ -964,7 +1332,7 @@ "marker": "gate", "source_marker": "gate", "auto_moved": false, - "instructions": 105343681, + "instructions": 64377805, "binding_fraction": null, "threshold_pct": 5.0 } From 7fa2cfe73c8b904cfcf8da0e3a16fdfeb53fb254 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Tue, 10 Nov 2026 17:50:30 +0000 Subject: [PATCH 35/61] Hold one connection claim from submission to settling in execute, executemany and the DB-API Arrow fetch --- src/engine/connection.cpp | 29 +-- src/engine/result.cpp | 26 ++- .../duckdb_python/engine/connection.hpp | 18 +- src/include/duckdb_python/engine/result.hpp | 22 ++- .../pyconnection/pyconnection.hpp | 92 ++++++--- src/include/duckdb_python/pyresult.hpp | 15 +- src/pyconnection.cpp | 178 ++++++++++-------- src/pyresult.cpp | 74 +++++--- tests/fast/api/test_appender.py | 77 ++++++++ tests/fast/api/test_execute_contract.py | 158 +++++++++++++++- 10 files changed, 516 insertions(+), 173 deletions(-) diff --git a/src/engine/connection.cpp b/src/engine/connection.cpp index d9733108f..1f98f194f 100644 --- a/src/engine/connection.cpp +++ b/src/engine/connection.cpp @@ -65,12 +65,16 @@ bool CallbackScope::Inside(const ClientContext &context) { return false; } +void ThrowBusy() { + throw ResourceInUseException(BUSY_ERROR); +} + ConnectionClaim::ConnectionClaim(ConnectionState &state_p, const ClientContext &context) : state(state_p) { if (CallbackScope::Inside(context)) { throw ResourceInUseException(CALLBACK_ERROR); } if (state.busy.exchange(true)) { - throw ResourceInUseException(BUSY_ERROR); + ThrowBusy(); } if (Exiting()) { state.admitted_during_exit = OnExitThread(); @@ -89,7 +93,7 @@ void ConnectionState::ThrowIfBusy(const ClientContext &context) const { throw ResourceInUseException(CALLBACK_ERROR); } if (busy) { - throw ResourceInUseException(BUSY_ERROR); + ThrowBusy(); } } @@ -340,12 +344,6 @@ ConnectionClaim Session::Claim() { return ConnectionClaim(*state, *context); } -shared_ptr Session::Submit(unique_ptr statement, identifier_map_t &values, - const Format &format) { - auto claim = Claim(); - return SubmitClaimed(std::move(statement), values, format); -} - shared_ptr Session::SubmitClaimed(unique_ptr statement, identifier_map_t &values, const Format &format) { auto written_type = statement->type; @@ -357,9 +355,8 @@ shared_ptr Session::SubmitClaimed(unique_ptr statement, return result; } -shared_ptr Session::Submit(Prepared &prepared, identifier_map_t &values, - const Format &format) { - ConnectionClaim claim(*state, *context); +shared_ptr Session::SubmitClaimed(Prepared &prepared, identifier_map_t &values, + const Format &format) { registry->CountStatement(prepared.statement->GetStatementType()); unique_ptr handle; { @@ -372,8 +369,8 @@ shared_ptr Session::Submit(Prepared &prepared, identifier_map_t Session::Submit(unique_ptr collection, const vector &names, - const Format &format) { +shared_ptr Session::SubmitClaimed(unique_ptr collection, const vector &names, + const Format &format) { // The binder rejects duplicate column names; the caller keeps the originals auto deduplicated_names = names; QueryResult::DeduplicateColumns(deduplicated_names); @@ -386,7 +383,7 @@ shared_ptr Session::Submit(unique_ptr collection, auto select = make_uniq(); select->node = std::move(select_node); identifier_map_t no_values; - return Submit(std::move(select), no_values, format); + return SubmitClaimed(std::move(select), no_values, format); } StatementSignature Session::Bind(unique_ptr statement, ResolvedTables &tables) { @@ -557,6 +554,10 @@ shared_ptr StatementGroup::Choose(shared_ptr last) { void StatementGroup::RefuseParameters() { auto claim = session.Claim(); + RefuseParametersClaimed(); +} + +void StatementGroup::RefuseParametersClaimed() { Fail(ErrorData(InvalidInputException("Parameters were given, but the last statement of the query takes none"))); } diff --git a/src/engine/result.cpp b/src/engine/result.cpp index d23502845..aae5de4a0 100644 --- a/src/engine/result.cpp +++ b/src/engine/result.cpp @@ -218,12 +218,6 @@ shared_ptr Result::TryGetContext() const { return context; } -void Result::Retain(const InterruptCheck &check) { - DUCKDB_PY_ASSERT_GIL_RELEASED(); - auto claim = ClaimWhileRunning(); - RetainClaimed(check); -} - void Result::CloseAfterFailure(std::exception_ptr error) noexcept { DUCKDB_PY_ASSERT_GIL_RELEASED(); { @@ -281,12 +275,6 @@ void Result::RetainClaimed(const InterruptCheck &check) { state = State::RETAINED; } -void Result::Settle(const InterruptCheck &check) { - DUCKDB_PY_ASSERT_GIL_RELEASED(); - auto claim = ClaimWhileRunning(); - SettleClaimed(check); -} - void Result::SettleClaimed(const InterruptCheck &check) { DUCKDB_PY_ASSERT_GIL_RELEASED(); if (state != State::PENDING) { @@ -375,10 +363,16 @@ unique_ptr Result::FetchArray(const InterruptCheck &check) { unique_ptr Result::TakeChunks(const InterruptCheck &check) { DUCKDB_PY_ASSERT_GIL_RELEASED(); - D_ASSERT(!format.IsArrow()); ThrowIfFailed(); // Claimed only while the query can still run engine work: rows already in the client need no connection auto claim = ClaimWhileRunning(); + return TakeChunksClaimed(check); +} + +unique_ptr Result::TakeChunksClaimed(const InterruptCheck &check) { + DUCKDB_PY_ASSERT_GIL_RELEASED(); + D_ASSERT(!format.IsArrow()); + ThrowIfFailed(); if (state == State::PENDING) { RetainClaimed(check); } @@ -448,9 +442,13 @@ void Result::CopyArrowSchema(ArrowSchema &out) const { } void Result::BuildArrowSchema(const vector &schema_names, ArrowSchema &out) const { + ConnectionClaim claim(*connection_state, *TryGetContext()); + BuildArrowSchemaClaimed(schema_names, out); +} + +void Result::BuildArrowSchemaClaimed(const vector &schema_names, ArrowSchema &out) const { auto context = TryGetContext(); auto properties = client_properties; - ConnectionClaim claim(*connection_state, *context); context->RunFunctionInTransaction( [&]() { ArrowConverter::ToArrowSchema(&out, Types(), schema_names, properties); }); } diff --git a/src/include/duckdb_python/engine/connection.hpp b/src/include/duckdb_python/engine/connection.hpp index f1f35be04..be4c96875 100644 --- a/src/include/duckdb_python/engine/connection.hpp +++ b/src/include/duckdb_python/engine/connection.hpp @@ -168,6 +168,9 @@ class SourceRegistry : public ObjectCacheEntry { std::deque released_order; }; +//! The refusal of a call that finds the connection taken by another call +[[noreturn]] void ThrowBusy(); + //! Holds the connection for one stretch of engine work. A second claim, and any claim from a callback of the //! connection's queries, is refused instead of waiting: the work it would wait for may be waiting for it. class ConnectionClaim { @@ -205,15 +208,16 @@ class Session { return *context; } Prepared Prepare(unique_ptr statement); - shared_ptr Submit(unique_ptr statement, identifier_map_t &values, - const Format &format); - //! Submit for a caller that already holds the connection's claim + //! Submits a statement whose result the caller reads later, for a caller that holds the connection's claim; + //! the caller keeps its claim until the result is settled or retained, so no other call finds the statement + //! pending. Run and RunClaimed below submit and complete a statement in one go. shared_ptr SubmitClaimed(unique_ptr statement, identifier_map_t &values, const Format &format); - shared_ptr Submit(Prepared &prepared, identifier_map_t &values, const Format &format); + shared_ptr SubmitClaimed(Prepared &prepared, identifier_map_t &values, + const Format &format); //! Scans a collection, for example to read rows a result already holds in another format - shared_ptr Submit(unique_ptr collection, const vector &names, - const Format &format); + shared_ptr SubmitClaimed(unique_ptr collection, const vector &names, + const Format &format); //! Binds a statement without running it, keeping the tables its replacement scans resolved in tables StatementSignature Bind(unique_ptr statement, ResolvedTables &tables); //! Binds a statement with values for its parameters, as the engine rebinds a prepared statement for the values it @@ -267,6 +271,8 @@ class StatementGroup { shared_ptr Choose(shared_ptr last); //! Throws for parameters given to a group whose text after the statements that ran held no statement [[noreturn]] void RefuseParameters(); + //! RefuseParameters for a caller that already holds the connection's claim + [[noreturn]] void RefuseParametersClaimed(); private: bool HasMore(); diff --git a/src/include/duckdb_python/engine/result.hpp b/src/include/duckdb_python/engine/result.hpp index feb5cadd2..ca20b063e 100644 --- a/src/include/duckdb_python/engine/result.hpp +++ b/src/include/duckdb_python/engine/result.hpp @@ -52,9 +52,10 @@ class Format { class ConnectionState; class ConnectionClaim; -//! A submitted statement. Retention is settled by the first consumer: a fetch opens a stream, Retain and the -//! Take calls keep every row. Every call that drives the query claims the connection, takes the client context -//! lock and may wait for running tasks, so callers must not hold a lock those tasks need. +//! A submitted statement. Retention is settled by the first consumer: a fetch opens a stream, RetainClaimed and +//! the Take calls keep every row. Every call that drives the query runs under the connection's claim, its own or +//! the caller's, takes the client context lock and may wait for running tasks, so callers must not hold a lock +//! those tasks need. class Result : public enable_shared_from_this { public: //! written_type is the submitted statement's own type, since the handle of a prepared execution reports EXECUTE @@ -105,14 +106,11 @@ class Result : public enable_shared_from_this { shared_ptr TryGetContext() const; //! The database whose buffers hold the rows, null once it is gone. Weak for the same reason as the context. shared_ptr TryGetDatabase() const; - //! Keeps every row: drives the query to its end unless it already ended. A failure ends the query. - void Retain(const InterruptCheck &check); - //! Retain for a caller that already holds the connection's claim. A failure ends the query. + //! Keeps every row: drives the query to its end unless it already ended, for a caller that holds the + //! connection's claim. A failure ends the query. void RetainClaimed(const InterruptCheck &check); - //! Runs the statement until its first unit is ready or it ends, without deciding how its rows are read, - //! and throws the error it ended with. A failure ends the query. - void Settle(const InterruptCheck &check); - //! Settle for a caller that already holds the connection's claim. A failure ends the query. + //! Runs the statement until its first unit is ready or it ends, without deciding how its rows are read, and + //! throws the error it ended with, for a caller that holds the connection's claim. A failure ends the query. void SettleClaimed(const InterruptCheck &check); //! Rows of a retained result. Materializes it first. idx_t RowCount(const InterruptCheck &check); @@ -122,12 +120,16 @@ class Result : public enable_shared_from_this { unique_ptr FetchArray(const InterruptCheck &check); //! Every remaining row, the result is empty afterwards unique_ptr TakeChunks(const InterruptCheck &check); + //! TakeChunks for a caller that already holds the connection's claim + unique_ptr TakeChunksClaimed(const InterruptCheck &check); //! Every remaining array, the result is empty afterwards vector> TakeArrays(const InterruptCheck &check); //! A copy of the result's Arrow schema, owned by the caller. Arrow results only. void CopyArrowSchema(ArrowSchema &out) const; //! An Arrow schema for the result's types under the given names, built in a transaction on its connection void BuildArrowSchema(const vector &names, ArrowSchema &out) const; + //! BuildArrowSchema for a caller that already holds the connection's claim + void BuildArrowSchemaClaimed(const vector &names, ArrowSchema &out) const; //! Renders the rows of a retained result string ToBox(BoxRendererContext &context, const BoxRendererConfig &config); diff --git a/src/include/duckdb_python/pyconnection/pyconnection.hpp b/src/include/duckdb_python/pyconnection/pyconnection.hpp index 779537020..03a85cf41 100644 --- a/src/include/duckdb_python/pyconnection/pyconnection.hpp +++ b/src/include/duckdb_python/pyconnection/pyconnection.hpp @@ -88,8 +88,9 @@ class DbapiResult { void Supersede(); //! Every row the result still holds, under names, which leaves it read out as a consuming fetch does; null //! when the rows were used up already. The rows are gone even when the take fails, since it ran the - //! statement to its end or ended it. - unique_ptr TakeRows(vector &names); + //! statement to its end or ended it. The caller holds the connection's claim, so nothing can refuse the take + //! once it has begun. + unique_ptr TakeRowsClaimed(vector &names); shared_ptr EngineResult() const { return result ? result->EngineResult() : nullptr; } @@ -266,38 +267,90 @@ struct DuckDBPyConnection : public std::enable_shared_from_this lock_; + bool marks_submitting_call = false; }; ConnectionGuard con; Cursors cursors; - // Recursive so that the outer lock taken at the top of execute/fetch - // methods (while still holding the GIL) does not deadlock against the - // inner lock taken by PrepareQuery / ExecuteInternal / - // PrepareAndSubmitInternal (after releasing the GIL). Serialises every - // path that touches `con.result` so concurrent calls on a single - // DuckDBPyConnection cannot dereference an already-freed result — see - // duckdb-python#435. + //! Serialises every path that touches con.result, so concurrent calls on one connection cannot dereference a + //! freed result (duckdb-python#435). Recursive, so the lock taken at the top of execute and the fetches does not + //! deadlock against the one PrepareQuery and ExecuteInternal take after releasing the GIL std::recursive_mutex py_connection_lock; + //! Whether the thread holding py_connection_lock is inside a call that submits a statement (IfHeld::REFUSE) + std::atomic mutex_held_by_submitting_call {false}; + //! How many times a submitting call has taken py_connection_lock + std::atomic submitting_entries {0}; //! The database's store of file-like objects for reading, kept once this connection has found it shared_ptr object_store; case_insensitive_map_t> registered_functions; @@ -372,9 +425,6 @@ struct DuckDBPyConnection : public std::enable_shared_from_this statement); shared_ptr ExecuteInternal(engine::Prepared &prep, nb::object params, engine::StatementGroup &statements); - //! Binds the parameters and submits the statement. The result is returned undriven. - shared_ptr PrepareAndSubmitInternal(unique_ptr statement, - nb::object params = nb::list()); engine::Session EngineSession(); std::shared_ptr Execute(const nb::object &query, nb::object params = nb::list()); diff --git a/src/include/duckdb_python/pyresult.hpp b/src/include/duckdb_python/pyresult.hpp index abad6e35f..28188411e 100644 --- a/src/include/duckdb_python/pyresult.hpp +++ b/src/include/duckdb_python/pyresult.hpp @@ -76,6 +76,12 @@ struct DuckDBPyResult { duckdb::pyarrow::Table FetchArrowTable(idx_t rows_per_batch, bool to_polars); duckdb::pyarrow::RecordBatchReader FetchRecordBatchReader(idx_t rows_per_batch = DEFAULT_ARROW_BATCH_SIZE); + //! The two fetches above over a schema built with BuildArrowSchemaClaimed, which they take over + duckdb::pyarrow::Table FetchArrowTable(ArrowSchema &schema); + duckdb::pyarrow::RecordBatchReader FetchRecordBatchReader(ArrowSchema &schema, idx_t rows_per_batch); + //! The result's Arrow schema under the names the Python layer reports, for a caller that holds the connection's + //! claim; out is the caller's to release until a fetch takes it over + void BuildArrowSchemaClaimed(ArrowSchema &out); nb::object FetchArrowCapsule(idx_t rows_per_batch = DEFAULT_ARROW_BATCH_SIZE); static void CheckBatchSize(idx_t rows_per_batch); @@ -89,8 +95,8 @@ struct DuckDBPyResult { unique_ptr FetchChunk(); //! Every row the result still holds, the rows buffered from a partial fetch first; the result is empty - //! afterwards. Call with the GIL held. - unique_ptr TakeRows(const engine::InterruptCheck &check); + //! afterwards. Call with the GIL held and the connection's claim. + unique_ptr TakeRowsClaimed(const engine::InterruptCheck &check); //! The names the Python layer reports, which are names_override when that is set. const vector &ResultNames() const; //! The rows a completed DML statement changed, -1 otherwise @@ -123,8 +129,11 @@ struct DuckDBPyResult { template T RunWithArrowSchema(const std::function &fun, bool dedup_col_names); + duckdb::pyarrow::Table ConvertToArrowTable(const ArrowSchema &schema); + duckdb::pyarrow::RecordBatchReader ImportRecordBatchReader(ArrowSchema *prebuilt, idx_t rows_per_batch); //! The stream's private data owns the result, and its callbacks run without the GIL. - ArrowArrayStream FetchArrowArrayStream(idx_t rows_per_batch); + //! prebuilt, when given, becomes the stream's schema; otherwise the result's own is copied or built + ArrowArrayStream FetchArrowArrayStream(idx_t rows_per_batch, ArrowSchema *prebuilt); private: shared_ptr result; diff --git a/src/pyconnection.cpp b/src/pyconnection.cpp index c82b65d17..12b1ce65c 100644 --- a/src/pyconnection.cpp +++ b/src/pyconnection.cpp @@ -181,7 +181,7 @@ void DbapiResult::Supersede() { } } -unique_ptr DbapiResult::TakeRows(vector &names) { +unique_ptr DbapiResult::TakeRowsClaimed(vector &names) { if (!result) { return nullptr; } @@ -189,7 +189,7 @@ unique_ptr DbapiResult::TakeRows(vector &names // failure must leave the result read out rather than reporting its error at every later fetch auto taken = std::move(result); names = taken->ResultNames(); - return taken->TakeRows(DuckDBPyConnection::CheckSignals); + return taken->TakeRowsClaimed(DuckDBPyConnection::CheckSignals); } void DbapiResult::Abort() { @@ -627,7 +627,7 @@ void DuckDBPyConnection::SupersedeResult(bool cancel) { std::shared_ptr DuckDBPyConnection::ExecuteMany(const nb::object &query, nb::object params_p) { nb::gil_scoped_acquire gil; - ConnectionLockGuard conn_lock(*this); + ConnectionLockGuard conn_lock(*this, IfHeld::REFUSE); if (params_p.is_none()) { params_p = nb::list(); } @@ -768,6 +768,31 @@ identifier_map_t TransformPreparedParameters(ClientContext & return named_values; } +//! Submits through submit under the claim the caller holds, then runs the result to its first unit or, when +//! retain is set, to its end; a statement that expanded to nothing refuses the parameters it was given. A failure +//! ends the query here, with the GIL released, since ending a pending query waits for its tasks +template +static shared_ptr SubmitAndDrive(engine::StatementGroup &statements, bool parameters_given, bool retain, + SUBMIT &&submit) { + DUCKDB_PY_ASSERT_GIL_RELEASED(); + shared_ptr res = submit(); + try { + if (parameters_given && ExpandedToNothing(*res)) { + statements.RefuseParametersClaimed(); + } + statements.ReleaseIfReplaced(*res); + if (retain) { + res->RetainClaimed(DuckDBPyConnection::CheckSignals); + } else { + res->SettleClaimed(DuckDBPyConnection::CheckSignals); + } + } catch (...) { + res->Close(); + throw; + } + return res; +} + engine::Prepared DuckDBPyConnection::PrepareQuery(unique_ptr statement) { auto session = EngineSession(); engine::Prepared prep; @@ -801,38 +826,10 @@ shared_ptr DuckDBPyConnection::ExecuteInternal(engine::Prepared DUCKDB_PY_ASSERT_GIL_HELD(); nb::gil_scoped_release release; unique_lock lock(py_connection_lock); - - res = session.Submit(prep, named_values, engine::Format::Chunks()); - if (parameters_given && ExpandedToNothing(*res)) { - try { - statements.RefuseParameters(); - } catch (...) { - // Ended here, with the GIL released, since ending the pending query waits for its tasks - res->Close(); - throw; - } - } - statements.ReleaseIfReplaced(*res); - res->Retain(CheckSignals); - } - return res; -} - -shared_ptr DuckDBPyConnection::PrepareAndSubmitInternal(unique_ptr statement, - nb::object params) { - if (params.is_none()) { - params = nb::list(); - } - auto session = EngineSession(); - - auto named_values = TransformPreparedParameters(session.Context(), params); - - shared_ptr res; - { - DUCKDB_PY_ASSERT_GIL_HELD(); - nb::gil_scoped_release release; - unique_lock lock(py_connection_lock); - res = session.Submit(std::move(statement), named_values, engine::Format::Chunks()); + // One claim from submission to the end of the run, so no other call finds the statement pending + auto claim = session.Claim(); + res = SubmitAndDrive(statements, parameters_given, true, + [&]() { return session.SubmitClaimed(prep, named_values, engine::Format::Chunks()); }); } return res; } @@ -875,7 +872,7 @@ std::shared_ptr DuckDBPyConnection::ExecuteFromString(const std::shared_ptr DuckDBPyConnection::Execute(const nb::object &query, nb::object params) { nb::gil_scoped_acquire gil; - ConnectionLockGuard conn_lock(*this); + ConnectionLockGuard conn_lock(*this, IfHeld::REFUSE); auto statements = GetStatements(query); auto parameters_given = HasParameters(params); @@ -886,27 +883,25 @@ std::shared_ptr DuckDBPyConnection::Execute(const nb::object } shared_ptr res; if (last_statement) { - res = PrepareAndSubmitInternal(std::move(last_statement), std::move(params)); - if (parameters_given && ExpandedToNothing(*res)) { - try { - RefuseParameters(statements); - } catch (...) { - // Ending the pending query waits for its tasks, so the GIL is released for it - duckdb::PyUtil::GilReleaseIfHeld release; - res->Close(); - throw; - } + if (params.is_none()) { + params = nb::list(); } - } - { + auto session = EngineSession(); + auto named_values = TransformPreparedParameters(session.Context(), params); DUCKDB_PY_ASSERT_GIL_HELD(); nb::gil_scoped_release release; unique_lock lock(py_connection_lock); - if (res) { - statements.ReleaseIfReplaced(*res); - res->Settle(CheckSignals); - } + // One claim from submission to settling, so no other call finds the statement pending + auto claim = session.Claim(); + res = SubmitAndDrive(statements, parameters_given, false, [&]() { + return session.SubmitClaimed(std::move(last_statement), named_values, engine::Format::Chunks()); + }); res = statements.Choose(std::move(res)); + } else { + DUCKDB_PY_ASSERT_GIL_HELD(); + nb::gil_scoped_release release; + unique_lock lock(py_connection_lock); + res = statements.Choose(nullptr); } if (!res) { // TODO: should we throw? @@ -1513,8 +1508,19 @@ nb::dict DuckDBPyConnection::FetchTF() { return result.FetchTF(); } +//! Releases an Arrow schema that was never handed over, after a throw before the import into pyarrow, which takes the +//! schema over even when it fails +struct ArrowSchemaHolder { + ArrowSchema schema {}; + ~ArrowSchemaHolder() { + if (schema.release) { + schema.release(&schema); + } + } +}; + nb::object DuckDBPyConnection::ResultAsArrow(idx_t batch_size, bool reader) { - ConnectionLockGuard conn_lock(*this); + ConnectionLockGuard conn_lock(*this, IfHeld::REFUSE); // Asked before the result, so a closed connection reports itself and not the slot its close emptied auto session = EngineSession(); if (!con.HasResult()) { @@ -1534,41 +1540,53 @@ nb::object DuckDBPyConnection::ResultAsArrow(idx_t batch_size, bool reader) { // Imported before the engine checks, so no Python code runs between what they find and the take nb::module_::import_("pyarrow"); auto held = con.GetResult().EngineResult(); + unique_ptr converted; + ArrowSchemaHolder schema; { - DUCKDB_PY_ASSERT_GIL_HELD(); - nb::gil_scoped_release release; + // One claim from the checks through the take of the rows, the statement over them, its settle or retain and + // the schema build, so a refusal comes before the rows are taken and never loses them. The claim is a flag + // that never waits, so holding it while the GIL is held is safe auto claim = session.Claim(); - // The engine refuses an aborted transaction here under its own lock, and a running result keeps its - // transaction active, so the empty function neither begins nor commits anything the result depends on - session.Context().RunFunctionInTransaction([] {}); - // Another open result, a relation's reader for one, would refuse the statement over the rows after the take; - // a running DB-API result is itself the one open result and the take drains it - if (held && !held->Running()) { - engine::VerifyNoOpenResult(session.Context()); + { + DUCKDB_PY_ASSERT_GIL_HELD(); + nb::gil_scoped_release release; + // The engine refuses an aborted transaction here under its own lock, and a running result keeps its + // transaction active, so the empty function neither begins nor commits anything the result depends on + session.Context().RunFunctionInTransaction([] {}); + // Another open result, a relation's reader for one, would refuse the statement over the rows after the + // take; a running DB-API result is itself the one open result and the take drains it + if (held && !held->Running()) { + engine::VerifyNoOpenResult(session.Context()); + } } - } - vector names; - auto rows = con.GetResult().TakeRows(names); - if (!rows) { - return nb::none(); - } - shared_ptr arrow; - { - DUCKDB_PY_ASSERT_GIL_HELD(); - nb::gil_scoped_release release; - arrow = session.Submit(std::move(rows), names, format); - if (reader) { - arrow->Settle(DuckDBPyConnection::CheckSignals); - } else { - arrow->Retain(DuckDBPyConnection::CheckSignals); + vector names; + auto rows = con.GetResult().TakeRowsClaimed(names); + if (!rows) { + return nb::none(); + } + shared_ptr arrow; + { + DUCKDB_PY_ASSERT_GIL_HELD(); + nb::gil_scoped_release release; + arrow = session.SubmitClaimed(std::move(rows), names, format); + if (reader) { + arrow->SettleClaimed(DuckDBPyConnection::CheckSignals); + } else { + arrow->RetainClaimed(DuckDBPyConnection::CheckSignals); + } } + converted = make_uniq(std::move(arrow), std::move(names)); + // The converter reads the connection's settings and its catalog's types, so the schema is built here + converted->BuildArrowSchemaClaimed(schema.schema); } - DuckDBPyResult converted(std::move(arrow), std::move(names)); + // The rows are retained, or the stream is settled, so the conversion into pyarrow holds the connection no longer + // and refuses no other call + conn_lock.DropSubmittingMark(); if (reader) { - return nb::cast(converted.FetchRecordBatchReader(batch_size)); + return nb::cast(converted->FetchRecordBatchReader(schema.schema, batch_size)); } - return nb::cast(converted.FetchArrowTable(batch_size, false)); + return nb::cast(converted->FetchArrowTable(schema.schema)); } identifier_map_t TransformPyConfigDict(const nb::dict &py_config_dict) { diff --git a/src/pyresult.cpp b/src/pyresult.cpp index b796af6bf..74b8c5abc 100644 --- a/src/pyresult.cpp +++ b/src/pyresult.cpp @@ -114,16 +114,16 @@ unique_ptr DuckDBPyResult::TakeBufferedRows() { return remainder; } -unique_ptr DuckDBPyResult::TakeRows(const engine::InterruptCheck &check) { +unique_ptr DuckDBPyResult::TakeRowsClaimed(const engine::InterruptCheck &check) { if (Empty()) { - throw InternalException("TakeRows called without a result object"); + throw InternalException("TakeRowsClaimed called without a result object"); } auto buffered = TakeBufferedRows(); unique_ptr rows; { DUCKDB_PY_ASSERT_GIL_HELD(); nb::gil_scoped_release release; - auto taken = result->TakeChunks(check); + auto taken = result->TakeChunksClaimed(check); if (!buffered) { return taken; } @@ -495,29 +495,43 @@ T DuckDBPyResult::RunWithArrowSchema(const std::function return fun(arrow_schema); } +void DuckDBPyResult::BuildArrowSchemaClaimed(ArrowSchema &out) { + D_ASSERT(!Empty()); + result->BuildArrowSchemaClaimed(IdentifiersToStrings(ResultNames()), out); +} + duckdb::pyarrow::Table DuckDBPyResult::FetchArrowTable(const idx_t rows_per_batch, const bool to_polars) { if (Empty()) { throw InvalidInputException("There is no query result"); } RequireArrowFormat(*result); return RunWithArrowSchema( - [&](const ArrowSchema &schema) -> duckdb::pyarrow::Table { - auto pyarrow_schema = pyarrow::ToPyArrowSchema(schema); - vector> arrays; - { - DUCKDB_PY_ASSERT_GIL_HELD(); - nb::gil_scoped_release release; - arrays = result->TakeArrays(DuckDBPyConnection::CheckSignals); - } - nb::list batches; - for (auto &array : arrays) { - ArrowArray data; - array->MoveTo(data); - TransformDuckToArrowChunk(pyarrow_schema, data, batches); - } - return pyarrow::ToArrowTable(std::move(batches), pyarrow_schema); - }, - to_polars); + [&](const ArrowSchema &schema) -> duckdb::pyarrow::Table { return ConvertToArrowTable(schema); }, to_polars); +} + +duckdb::pyarrow::Table DuckDBPyResult::FetchArrowTable(ArrowSchema &schema) { + if (Empty()) { + throw InvalidInputException("There is no query result"); + } + RequireArrowFormat(*result); + return ConvertToArrowTable(schema); +} + +duckdb::pyarrow::Table DuckDBPyResult::ConvertToArrowTable(const ArrowSchema &schema) { + auto pyarrow_schema = pyarrow::ToPyArrowSchema(schema); + vector> arrays; + { + DUCKDB_PY_ASSERT_GIL_HELD(); + nb::gil_scoped_release release; + arrays = result->TakeArrays(DuckDBPyConnection::CheckSignals); + } + nb::list batches; + for (auto &array : arrays) { + ArrowArray data; + array->MoveTo(data); + TransformDuckToArrowChunk(pyarrow_schema, data, batches); + } + return pyarrow::ToArrowTable(std::move(batches), pyarrow_schema); } void DuckDBPyResult::CheckBatchSize(idx_t rows_per_batch) { @@ -652,10 +666,13 @@ struct ArrowArrayStreamGuard { } // namespace -ArrowArrayStream DuckDBPyResult::FetchArrowArrayStream(idx_t rows_per_batch) { +ArrowArrayStream DuckDBPyResult::FetchArrowArrayStream(idx_t rows_per_batch, ArrowSchema *prebuilt) { RequireArrowFormat(*result); auto state = make_uniq(); - if (names_override.empty()) { + if (prebuilt) { + state->cached_schema = *prebuilt; + prebuilt->release = nullptr; + } else if (names_override.empty()) { result->CopyArrowSchema(state->cached_schema); } else { result->BuildArrowSchema(IdentifiersToStrings(names_override), state->cached_schema); @@ -674,13 +691,22 @@ ArrowArrayStream DuckDBPyResult::FetchArrowArrayStream(idx_t rows_per_batch) { } duckdb::pyarrow::RecordBatchReader DuckDBPyResult::FetchRecordBatchReader(idx_t rows_per_batch) { + return ImportRecordBatchReader(nullptr, rows_per_batch); +} + +duckdb::pyarrow::RecordBatchReader DuckDBPyResult::FetchRecordBatchReader(ArrowSchema &schema, idx_t rows_per_batch) { + return ImportRecordBatchReader(&schema, rows_per_batch); +} + +duckdb::pyarrow::RecordBatchReader DuckDBPyResult::ImportRecordBatchReader(ArrowSchema *prebuilt, + idx_t rows_per_batch) { if (Empty()) { throw InvalidInputException("There is no query result"); } CheckBatchSize(rows_per_batch); auto pyarrow_lib_module = nb::module_::import_("pyarrow").attr("lib"); auto record_batch_reader_func = pyarrow_lib_module.attr("RecordBatchReader").attr("_import_from_c"); - ArrowArrayStreamGuard guard {FetchArrowArrayStream(rows_per_batch)}; + ArrowArrayStreamGuard guard {FetchArrowArrayStream(rows_per_batch, prebuilt)}; nb::object record_batch_reader = record_batch_reader_func((uint64_t)&guard.stream); // NOLINT return nb::cast(record_batch_reader); } @@ -701,7 +727,7 @@ nb::object DuckDBPyResult::FetchArrowCapsule(const idx_t rows_per_batch) { throw InvalidInputException("There is no query result"); } CheckBatchSize(rows_per_batch); - auto inner_stream = FetchArrowArrayStream(rows_per_batch); + auto inner_stream = FetchArrowArrayStream(rows_per_batch, nullptr); auto arrow_stream = new ArrowArrayStream(); *arrow_stream = inner_stream; return nb::capsule(arrow_stream, "arrow_array_stream", ArrowArrayStreamPyCapsuleDestructor); diff --git a/tests/fast/api/test_appender.py b/tests/fast/api/test_appender.py index cf2dfcb7b..72c6473d3 100644 --- a/tests/fast/api/test_appender.py +++ b/tests/fast/api/test_appender.py @@ -1757,6 +1757,83 @@ def test_another_thread_is_refused_during_a_flush_without_waiting(self, con, hel app.flush() assert table_rows(con) == [(1, "a")] + @pytest.mark.timeout(120) + def test_a_flush_that_collides_with_a_submitted_statement_is_refused_as_busy(self): + # The engine starts a statement as soon as another thread submits it, so a flush that lands right after the + # submission collides with a running statement: it is refused as busy, like one that lands later, instead + # of getting the engine's refusal or hanging the statement + code, output = run_isolated( + f""" + import collections + import threading + import time + import duckdb + from duckdb.sqltypes import BIGINT + con = duckdb.connect() + con.execute("CREATE TABLE t (k INTEGER, v VARCHAR)") + con.execute("CREATE TABLE log (k BIGINT)") + # Workers are what runs the statement from its submission on, so a one-CPU host must still get some + con.execute("SET threads = 4") + gates = [] + def hold(x): + gates[-1].wait(3) + return x + con.create_function("hold", hold, [BIGINT], BIGINT) + app = con.appender("t") + flushed = 0 + refusals = collections.Counter() + submitted = 0 + print("started", flush=True) + overall = time.monotonic() + 40 + while submitted < 20 and time.monotonic() < overall: + go, stop, release = threading.Event(), threading.Event(), threading.Event() + gates.append(release) + def flush_until_stopped(): + global flushed + # Started as the first thread enters its execute, so that call is the one under way; the + # statement is held through the first attempts and released while the attempts go on + go.wait(10) + attempts = 0 + try: + while not stop.is_set(): + app.append_row(flushed, "a") + try: + app.flush() + flushed += 1 + except duckdb.ResourceInUseException as error: + refusals["busy" if {BUSY!r} in str(error) else str(error)] += 1 + app.clear() + attempts += 1 + if attempts == 200: + release.set() + finally: + release.set() + thread = threading.Thread(target=flush_until_stopped) + thread.start() + go.set() + deadline = time.monotonic() + 1 + while time.monotonic() < deadline: + try: + con.execute("INSERT INTO log SELECT hold(i) FROM range(1) t(i)") + submitted += 1 + break + except duckdb.ResourceInUseException as error: + if {BUSY!r} not in str(error): + refusals["execute: " + str(error)] += 1 + stop.set() + thread.join(10) + print("submitted:", submitted) + print("refusals:", sorted(refusals)) + kept = con.execute("SELECT count(*) = ? FROM t", [flushed]).fetchall() + print("rows:", kept + con.execute("SELECT count(*) FROM log").fetchall()) + """, + timeout=90, + ) + assert code == 0, output + assert "submitted: 20" in output, output + assert "refusals: ['busy']" in output, output + assert "rows: [(True,), (20,)]" in output, output + @pytest.mark.parametrize("call", ["app.append_row(9, 'z')", "app.flush()", "app.clear()"]) def test_a_callback_during_its_flush_is_refused(self, call): code, output = run_isolated( diff --git a/tests/fast/api/test_execute_contract.py b/tests/fast/api/test_execute_contract.py index df91e510e..11b66f060 100644 --- a/tests/fast/api/test_execute_contract.py +++ b/tests/fast/api/test_execute_contract.py @@ -1,3 +1,4 @@ +import contextlib import gc import importlib.util import re @@ -6,6 +7,7 @@ import textwrap import threading import time +from collections.abc import Iterator import pytest @@ -577,7 +579,10 @@ def inner(x): assert INSIDE_A_QUERY in output assert "usable after: [(42,)]" in output - def test_another_thread_is_refused_while_a_statement_runs(self, con): + def test_another_thread_is_refused_while_a_statement_runs(self): + # At the default thread count the engine runs the statement from its submission on, so the other thread + # may land right after the submission as well as during the settling + con = duckdb.connect() running, release = threading.Event(), threading.Event() def hold(x): @@ -602,9 +607,160 @@ def contend(): thread.start() assert con.execute("SELECT hold(i) FROM range(1) t(i)").fetchall() == [(0,)] thread.join(10) + con.close() assert len(outcome) == 1 assert BUSY in outcome[0] + @pytest.mark.timeout(120) + def test_a_second_execute_is_refused_instead_of_waiting(self): + # A collision refuses at once. An execute that passes the busy check while the other thread's statement is + # already submitted would wait for that statement instead, and a second execute never waits for one + code, output = run_isolated( + f""" + import collections + import threading + import time + import duckdb + from duckdb.sqltypes import BIGINT + con = duckdb.connect() + # Workers are what runs the statement from its submission on, so a one-CPU host must still get some + con.execute("SET threads = 4") + gates = [] + def hold(x): + gates[-1].wait(3) + return x + con.create_function("hold", hold, [BIGINT], BIGINT) + outcomes = collections.Counter() + submitted = 0 + print("started", flush=True) + overall = time.monotonic() + 40 + while submitted < 20 and time.monotonic() < overall: + go, release = threading.Event(), threading.Event() + gates.append(release) + def execute_two_hundred_times(): + # Started as the first thread enters its execute, so that call is the one under way; the + # statement is held until the attempts are over, so a call of this thread can replace the + # first thread's result only by waiting for it + go.wait(10) + try: + for attempt in range(200): + began = time.monotonic() + try: + con.execute("SELECT 7") + except duckdb.ResourceInUseException as error: + if {BUSY!r} not in str(error): + outcomes[str(error)] += 1 + if time.monotonic() - began > 1: + outcomes["waited"] += 1 + finally: + release.set() + thread = threading.Thread(target=execute_two_hundred_times) + thread.start() + go.set() + deadline = time.monotonic() + 1 + got_through = False + while time.monotonic() < deadline: + try: + con.execute("SELECT hold(i) + 10 FROM range(1) t(i)") + submitted += 1 + got_through = True + break + except duckdb.ResourceInUseException as error: + if {BUSY!r} not in str(error): + outcomes["execute: " + str(error)] += 1 + thread.join(10) + if got_through: + rows = con.fetchall() + if rows != [(10,)]: + outcomes[f"first thread read {{rows}}"] += 1 + print("submitted:", submitted) + print("outcomes:", sorted(outcomes)) + """, + timeout=90, + ) + assert code == 0, output + assert "submitted: 20" in output, output + assert "outcomes: []" in output, output + + def test_a_second_execute_during_parameter_conversion_is_refused_at_once(self): + # The first thread holds the connection mutex and no claim while its parameters are read, so a second + # execute reaches the mutex; it is refused there, and does not wait for the first call and replace its result + con = duckdb.connect() + inside, done = threading.Event(), threading.Event() + timed_out = [] + + class Params: + def __len__(self) -> int: + return 1 + + def __iter__(self) -> Iterator[int]: + inside.set() + # The second thread ends the wait once its call returned; a call that waits for this one never does + timed_out.append(not done.wait(5)) + return iter([1]) + + outcome = [] + + def second(): + assert inside.wait(10) + try: + con.execute("SELECT 2") + outcome.append("ran") + except duckdb.ResourceInUseException as error: + outcome.append(str(error)) + finally: + done.set() + + thread = threading.Thread(target=second) + thread.start() + try: + con.execute("SELECT ?::INTEGER", Params()) + rows = con.fetchall() + finally: + thread.join(10) + con.close() + assert timed_out == [False], outcome + assert len(outcome) == 1, outcome + assert BUSY in outcome[0], outcome + assert rows == [(1,)] + + def test_a_thread_reading_the_description_does_not_make_execute_fail(self): + # A reader holds the connection mutex while it waits for the GIL back; an execute on another thread waits for + # such a holder as every call did, and is refused only behind another call that submits a statement + con = duckdb.connect() + con.execute("SELECT 1") + stop = threading.Event() + + def read_until_stopped(): + while not stop.is_set(): + with contextlib.suppress(duckdb.ResourceInUseException): + con.description # noqa: B018 + time.sleep(0.0005) + + def execute_once(): + try: + con.execute("SELECT 1") + except duckdb.ResourceInUseException: + return False + return True + + thread = threading.Thread(target=read_until_stopped) + thread.start() + ran, refused = 0, 0 + deadline = time.monotonic() + 1 + try: + while time.monotonic() < deadline: + if execute_once(): + ran += 1 + else: + refused += 1 + finally: + stop.set() + thread.join(10) + con.close() + assert refused == 0, (ran, refused) + assert ran > 0 + @pytest.mark.timeout(60) def test_progress_and_interrupt_reach_a_running_statement(self, con): seen = [] From 8e73d3f1aaafd38cdac51f9a08975031a2db95be Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Tue, 10 Nov 2026 23:08:13 +0000 Subject: [PATCH 36/61] Refuse a submitting call on arrival while another thread's submitting call is in flight, and pin each closed gap with a test --- src/engine/connection.cpp | 3 + src/engine/result.cpp | 2 + .../duckdb_python/engine/connection.hpp | 4 + .../pyconnection/pyconnection.hpp | 61 +++---- src/include/duckdb_python/pyresult.hpp | 5 +- src/pyconnection.cpp | 33 ++-- src/pyresult.cpp | 5 - tests/fast/api/test_appender.py | 78 +++++++++ tests/fast/api/test_execute_contract.py | 165 +++++++++++++++++- 9 files changed, 286 insertions(+), 70 deletions(-) diff --git a/src/engine/connection.cpp b/src/engine/connection.cpp index 1f98f194f..d9f8cf963 100644 --- a/src/engine/connection.cpp +++ b/src/engine/connection.cpp @@ -346,6 +346,7 @@ ConnectionClaim Session::Claim() { shared_ptr Session::SubmitClaimed(unique_ptr statement, identifier_map_t &values, const Format &format) { + D_ASSERT(state->Claimed()); auto written_type = statement->type; registry->CountStatement(written_type); auto handle = context->Submit(std::move(statement), values, QueryParameters(format.EngineFormat())); @@ -357,6 +358,7 @@ shared_ptr Session::SubmitClaimed(unique_ptr statement, shared_ptr Session::SubmitClaimed(Prepared &prepared, identifier_map_t &values, const Format &format) { + D_ASSERT(state->Claimed()); registry->CountStatement(prepared.statement->GetStatementType()); unique_ptr handle; { @@ -371,6 +373,7 @@ shared_ptr Session::SubmitClaimed(Prepared &prepared, identifier_map_t Session::SubmitClaimed(unique_ptr collection, const vector &names, const Format &format) { + D_ASSERT(state->Claimed()); // The binder rejects duplicate column names; the caller keeps the originals auto deduplicated_names = names; QueryResult::DeduplicateColumns(deduplicated_names); diff --git a/src/engine/result.cpp b/src/engine/result.cpp index aae5de4a0..5137ae2c8 100644 --- a/src/engine/result.cpp +++ b/src/engine/result.cpp @@ -265,6 +265,7 @@ void Result::RetainClaimed(const InterruptCheck &check) { if (state != State::PENDING) { return; } + D_ASSERT(connection_state->Claimed()); try { Complete(*handle, check); CaptureMetadata(); @@ -280,6 +281,7 @@ void Result::SettleClaimed(const InterruptCheck &check) { if (state != State::PENDING) { return; } + D_ASSERT(connection_state->Claimed()); if (CompletesBeforeReturning()) { RetainClaimed(check); return; diff --git a/src/include/duckdb_python/engine/connection.hpp b/src/include/duckdb_python/engine/connection.hpp index be4c96875..a9a282262 100644 --- a/src/include/duckdb_python/engine/connection.hpp +++ b/src/include/duckdb_python/engine/connection.hpp @@ -86,6 +86,10 @@ class ConnectionState : public ClientContextState { bool AdmittedDuringExit() const { return admitted_during_exit; } + //! Whether a call holds the connection's claim right now + bool Claimed() const { + return busy; + } private: friend class ConnectionClaim; diff --git a/src/include/duckdb_python/pyconnection/pyconnection.hpp b/src/include/duckdb_python/pyconnection/pyconnection.hpp index 03a85cf41..06ecb3243 100644 --- a/src/include/duckdb_python/pyconnection/pyconnection.hpp +++ b/src/include/duckdb_python/pyconnection/pyconnection.hpp @@ -7,6 +7,8 @@ //===----------------------------------------------------------------------===// #pragma once + +#include #include "duckdb.hpp" #include "duckdb_python/nb/casters.hpp" #include "duckdb_python/import_cache/python_import_cache.hpp" @@ -267,13 +269,15 @@ struct DuckDBPyConnection : public std::enable_shared_from_this mutex_held_by_submitting_call {false}; - //! How many times a submitting call has taken py_connection_lock - std::atomic submitting_entries {0}; + //! The thread whose call that submits a statement (IfHeld::REFUSE) is in flight, or no thread + std::atomic submitting_thread {std::thread::id()}; //! The database's store of file-like objects for reading, kept once this connection has found it shared_ptr object_store; case_insensitive_map_t> registered_functions; diff --git a/src/include/duckdb_python/pyresult.hpp b/src/include/duckdb_python/pyresult.hpp index 28188411e..bb1e1da60 100644 --- a/src/include/duckdb_python/pyresult.hpp +++ b/src/include/duckdb_python/pyresult.hpp @@ -76,12 +76,9 @@ struct DuckDBPyResult { duckdb::pyarrow::Table FetchArrowTable(idx_t rows_per_batch, bool to_polars); duckdb::pyarrow::RecordBatchReader FetchRecordBatchReader(idx_t rows_per_batch = DEFAULT_ARROW_BATCH_SIZE); - //! The two fetches above over a schema built with BuildArrowSchemaClaimed, which they take over + //! The two fetches above over a schema the caller built for the result's names, which they take over duckdb::pyarrow::Table FetchArrowTable(ArrowSchema &schema); duckdb::pyarrow::RecordBatchReader FetchRecordBatchReader(ArrowSchema &schema, idx_t rows_per_batch); - //! The result's Arrow schema under the names the Python layer reports, for a caller that holds the connection's - //! claim; out is the caller's to release until a fetch takes it over - void BuildArrowSchemaClaimed(ArrowSchema &out); nb::object FetchArrowCapsule(idx_t rows_per_batch = DEFAULT_ARROW_BATCH_SIZE); static void CheckBatchSize(idx_t rows_per_batch); diff --git a/src/pyconnection.cpp b/src/pyconnection.cpp index 12b1ce65c..427dc034b 100644 --- a/src/pyconnection.cpp +++ b/src/pyconnection.cpp @@ -1508,17 +1508,6 @@ nb::dict DuckDBPyConnection::FetchTF() { return result.FetchTF(); } -//! Releases an Arrow schema that was never handed over, after a throw before the import into pyarrow, which takes the -//! schema over even when it fails -struct ArrowSchemaHolder { - ArrowSchema schema {}; - ~ArrowSchemaHolder() { - if (schema.release) { - schema.release(&schema); - } - } -}; - nb::object DuckDBPyConnection::ResultAsArrow(idx_t batch_size, bool reader) { ConnectionLockGuard conn_lock(*this, IfHeld::REFUSE); // Asked before the result, so a closed connection reports itself and not the slot its close emptied @@ -1540,8 +1529,10 @@ nb::object DuckDBPyConnection::ResultAsArrow(idx_t batch_size, bool reader) { // Imported before the engine checks, so no Python code runs between what they find and the take nb::module_::import_("pyarrow"); auto held = con.GetResult().EngineResult(); - unique_ptr converted; - ArrowSchemaHolder schema; + shared_ptr arrow; + vector names; + // Released by the wrapper when a throw before the import into pyarrow leaves it unused; the import takes it over + ArrowSchemaWrapper schema; { // One claim from the checks through the take of the rows, the statement over them, its settle or retain and // the schema build, so a refusal comes before the rows are taken and never loses them. The claim is a flag @@ -1560,12 +1551,14 @@ nb::object DuckDBPyConnection::ResultAsArrow(idx_t batch_size, bool reader) { } } - vector names; auto rows = con.GetResult().TakeRowsClaimed(names); if (!rows) { return nb::none(); } - shared_ptr arrow; + vector schema_names; + for (auto &name : names) { + schema_names.push_back(name.GetIdentifierName()); + } { DUCKDB_PY_ASSERT_GIL_HELD(); nb::gil_scoped_release release; @@ -1575,18 +1568,18 @@ nb::object DuckDBPyConnection::ResultAsArrow(idx_t batch_size, bool reader) { } else { arrow->RetainClaimed(DuckDBPyConnection::CheckSignals); } + // The converter reads the connection's settings and its catalog's types, so the schema is built here + arrow->BuildArrowSchemaClaimed(schema_names, schema.arrow_schema); } - converted = make_uniq(std::move(arrow), std::move(names)); - // The converter reads the connection's settings and its catalog's types, so the schema is built here - converted->BuildArrowSchemaClaimed(schema.schema); } // The rows are retained, or the stream is settled, so the conversion into pyarrow holds the connection no longer // and refuses no other call conn_lock.DropSubmittingMark(); + DuckDBPyResult converted(std::move(arrow), std::move(names)); if (reader) { - return nb::cast(converted->FetchRecordBatchReader(schema.schema, batch_size)); + return nb::cast(converted.FetchRecordBatchReader(schema.arrow_schema, batch_size)); } - return nb::cast(converted->FetchArrowTable(schema.schema)); + return nb::cast(converted.FetchArrowTable(schema.arrow_schema)); } identifier_map_t TransformPyConfigDict(const nb::dict &py_config_dict) { diff --git a/src/pyresult.cpp b/src/pyresult.cpp index 74b8c5abc..666d065eb 100644 --- a/src/pyresult.cpp +++ b/src/pyresult.cpp @@ -495,11 +495,6 @@ T DuckDBPyResult::RunWithArrowSchema(const std::function return fun(arrow_schema); } -void DuckDBPyResult::BuildArrowSchemaClaimed(ArrowSchema &out) { - D_ASSERT(!Empty()); - result->BuildArrowSchemaClaimed(IdentifiersToStrings(ResultNames()), out); -} - duckdb::pyarrow::Table DuckDBPyResult::FetchArrowTable(const idx_t rows_per_batch, const bool to_polars) { if (Empty()) { throw InvalidInputException("There is no query result"); diff --git a/tests/fast/api/test_appender.py b/tests/fast/api/test_appender.py index 72c6473d3..e4e57b8e6 100644 --- a/tests/fast/api/test_appender.py +++ b/tests/fast/api/test_appender.py @@ -1834,6 +1834,84 @@ def flush_until_stopped(): assert "refusals: ['busy']" in output, output assert "rows: [(True,), (20,)]" in output, output + @pytest.mark.timeout(120) + def test_a_flush_that_collides_with_a_submitted_executemany_is_refused_as_busy(self): + # As above, with the statement submitted by executemany, which runs it once per parameter set + code, output = run_isolated( + f""" + import collections + import threading + import time + import duckdb + from duckdb.sqltypes import BIGINT + con = duckdb.connect() + con.execute("CREATE TABLE t (k INTEGER, v VARCHAR)") + con.execute("CREATE TABLE log (k BIGINT)") + # Workers are what runs the statement from its submission on, so a one-CPU host must still get some + con.execute("SET threads = 4") + gates = [] + def hold(x): + gates[-1].wait(3) + return x + con.create_function("hold", hold, [BIGINT], BIGINT) + app = con.appender("t") + flushed = 0 + refusals = collections.Counter() + submitted = 0 + print("started", flush=True) + overall = time.monotonic() + 40 + while submitted < 20 and time.monotonic() < overall: + go, stop, release = threading.Event(), threading.Event(), threading.Event() + gates.append(release) + def flush_until_stopped(): + global flushed + # Started as the first thread enters its execute, so that call is the one under way; the + # statement is held through the first attempts and released while the attempts go on + go.wait(10) + attempts = 0 + try: + while not stop.is_set(): + app.append_row(flushed, "a") + try: + app.flush() + flushed += 1 + except duckdb.ResourceInUseException as error: + refusals["busy" if {BUSY!r} in str(error) else str(error)] += 1 + app.clear() + attempts += 1 + if attempts == 200: + release.set() + finally: + release.set() + thread = threading.Thread(target=flush_until_stopped) + thread.start() + go.set() + deadline = time.monotonic() + 1 + while time.monotonic() < deadline: + try: + con.executemany("INSERT INTO log SELECT hold(i + ?::BIGINT) FROM range(1) t(i)", [[1], [2]]) + submitted += 1 + break + except duckdb.ResourceInUseException as error: + if {BUSY!r} not in str(error): + refusals["execute: " + str(error)] += 1 + stop.set() + thread.join(10) + print("submitted:", submitted) + print("refusals:", sorted(refusals)) + kept = con.execute("SELECT count(*) = ? FROM t", [flushed]).fetchall() + # An executemany refused between its two parameter sets, which is allowed, has inserted its first row + # already and is retried in full, so the log holds at least two rows per submission + logged = con.execute("SELECT count(*) >= 40 FROM log").fetchall() + print("rows:", kept + logged) + """, + timeout=90, + ) + assert code == 0, output + assert "submitted: 20" in output, output + assert "refusals: ['busy']" in output, output + assert "rows: [(True,), (True,)]" in output, output + @pytest.mark.parametrize("call", ["app.append_row(9, 'z')", "app.flush()", "app.clear()"]) def test_a_callback_during_its_flush_is_refused(self, call): code, output = run_isolated( diff --git a/tests/fast/api/test_execute_contract.py b/tests/fast/api/test_execute_contract.py index 11b66f060..b3ecb2534 100644 --- a/tests/fast/api/test_execute_contract.py +++ b/tests/fast/api/test_execute_contract.py @@ -441,7 +441,7 @@ def test_a_lazy_polars_frame_scanned_on_its_own_connection_errors(self): ) assert code == 0, output assert "refused:" in output - assert re.search(REFUSED, output) + assert BUSY in output, output assert "usable after: [(42,)]" in output def test_a_udf_that_reenters_its_connection_errors(self): @@ -580,9 +580,11 @@ def inner(x): assert "usable after: [(42,)]" in output def test_another_thread_is_refused_while_a_statement_runs(self): - # At the default thread count the engine runs the statement from its submission on, so the other thread - # may land right after the submission as well as during the settling + # With worker threads the engine runs the statement from its submission on, so the other thread may land + # right after the submission as well as during the settling. It contends through a relation, which takes + # the connection's claim and not the mutex, so it sees the claim and nothing else con = duckdb.connect() + con.execute("SET threads = 4") running, release = threading.Event(), threading.Event() def hold(x): @@ -596,7 +598,7 @@ def hold(x): def contend(): running.wait(10) try: - con.execute("SELECT 1") + con.sql("SELECT 1") outcome.append("ran") except duckdb.ResourceInUseException as error: outcome.append(str(error)) @@ -682,10 +684,65 @@ def execute_two_hundred_times(): assert "submitted: 20" in output, output assert "outcomes: []" in output, output + @pytest.mark.timeout(120) + def test_a_refused_arrow_fetch_keeps_its_rows(self): + # The DB-API Arrow fetch takes the rows out of the result and runs a statement over them; a second thread + # that takes the connection's claim between the two would make the fetch fail after the take, and a retry + # would then find no rows. The fetch holds one claim across both, so a refusal always comes before the take + code, output = run_isolated( + f""" + import collections + import sys + import threading + import time + import duckdb + con = duckdb.connect() + con.execute("SET threads = 4") + # A short switch interval hands the GIL to the other thread often, as a busy program does + sys.setswitchinterval(0.0001) + stop = threading.Event() + def bind_until_stopped(): + while not stop.is_set(): + try: + con.sql("SELECT 1") + except duckdb.ResourceInUseException: + pass + thread = threading.Thread(target=bind_until_stopped) + thread.start() + counts = collections.Counter() + print("started", flush=True) + deadline = time.monotonic() + 8 + while time.monotonic() < deadline and counts["retried"] < 50: + try: + con.execute("SELECT * FROM range(5) t(i)") + except duckdb.ResourceInUseException: + continue + for attempt in range(1000): + try: + table = con.to_arrow_table() + break + except duckdb.ResourceInUseException as error: + if {BUSY!r} not in str(error): + counts["refused: " + str(error)] += 1 + rows = None if table is None else table.num_rows + if attempt: + counts["retried"] += 1 + if rows != 5: + counts[f"rows {{rows}}" + (" after a refusal" if attempt else "")] += 1 + stop.set() + thread.join(10) + print("counts:", sorted(counts)) + """, + timeout=90, + ) + assert code == 0, output + assert "counts: ['retried']" in output or "counts: []" in output, output + def test_a_second_execute_during_parameter_conversion_is_refused_at_once(self): # The first thread holds the connection mutex and no claim while its parameters are read, so a second # execute reaches the mutex; it is refused there, and does not wait for the first call and replace its result con = duckdb.connect() + con.execute("SET threads = 4") inside, done = threading.Event(), threading.Event() timed_out = [] @@ -728,6 +785,7 @@ def test_a_thread_reading_the_description_does_not_make_execute_fail(self): # A reader holds the connection mutex while it waits for the GIL back; an execute on another thread waits for # such a holder as every call did, and is refused only behind another call that submits a statement con = duckdb.connect() + con.execute("SET threads = 4") con.execute("SELECT 1") stop = threading.Event() @@ -761,6 +819,105 @@ def execute_once(): assert refused == 0, (ran, refused) assert ran > 0 + def test_a_submitting_call_beside_a_reader_is_refused_at_once(self): + # A reader holding the mutex puts two submitting calls in line for it; the refusal of the second is decided + # when it arrives, so it never waits for the first one's statement and is then refused + con = duckdb.connect() + con.execute("SET threads = 4") + # The held statement lasts well over any scheduling stall, so only a wait for it crosses the bound below + con.create_function("hold", lambda x: time.sleep(0.3) or x, [BIGINT], BIGINT) + stop = threading.Event() + waited = [] + + def read_until_stopped(): + while not stop.is_set(): + with contextlib.suppress(duckdb.ResourceInUseException): + con.description # noqa: B018 + + def run_held_statements(): + while not stop.is_set(): + with contextlib.suppress(duckdb.ResourceInUseException): + con.execute("SELECT hold(i) FROM range(1) t(i)") + + def execute_once(): + began = time.monotonic() + with contextlib.suppress(duckdb.ResourceInUseException): + con.execute("SELECT 7") + return time.monotonic() - began + + threads = [threading.Thread(target=read_until_stopped), threading.Thread(target=run_held_statements)] + for thread in threads: + thread.start() + deadline = time.monotonic() + 4 + try: + while time.monotonic() < deadline: + took = execute_once() + if took > 0.15: + waited.append(took) + finally: + stop.set() + for thread in threads: + thread.join(10) + con.close() + assert waited == [] + + def test_other_calls_run_while_a_result_is_converted_to_arrow(self): + # The Arrow fetch holds the connection only until the rows are taken and the schema is built; the conversion + # into pyarrow that follows holds the mutex and no claim, so a relation runs during it and an execute waits + # for it instead of being refused. Small batches make the conversion the long part of the fetch + con = duckdb.connect() + con.execute("SET threads = 4") + con.execute("CREATE TABLE t (k INTEGER)") + converting = threading.Event() + marks = {} + attempts = [] + outcome = {} + + def attempt(call): + try: + call() + except duckdb.ResourceInUseException as error: + return str(error) + return "ran" + + def second(): + assert converting.wait(10) + deadline = time.monotonic() + 20 + while time.monotonic() < deadline and "done" not in marks: + began = time.monotonic() + kind = attempt(lambda: con.table("t")) + attempts.append((began, kind)) + # A relation admitted after the take was refused ran during the conversion; an execute then too + if kind == "ran" and any(k != "ran" for _, k in attempts): + outcome["execute during the conversion"] = attempt(lambda: con.execute("SELECT 1")) + break + + def fetch_or_none(): + try: + return con.to_arrow_table(200) + except duckdb.ResourceInUseException: + return None + + thread = threading.Thread(target=second) + thread.start() + try: + con.execute("SELECT i, i::VARCHAR AS s FROM range(1000000) t(i)") + converting.set() + table = None + while table is None: + table = fetch_or_none() + marks["done"] = time.monotonic() + finally: + marks.setdefault("done", time.monotonic()) + thread.join(30) + con.close() + assert table.num_rows == 1000000 + refused = [t for t, k in attempts if k != "ran"] + assert refused, attempts[:5] + ran_after_take = [t for t, k in attempts if k == "ran" and t > max(refused) and t < marks["done"]] + assert ran_after_take, (len(attempts), max(refused), marks["done"]) + assert outcome == {"execute during the conversion": "ran"}, outcome + @pytest.mark.timeout(60) def test_progress_and_interrupt_reach_a_running_statement(self, con): seen = [] From 27e7efbf930f91c62880f05f37e66a0928bf51e2 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Wed, 11 Nov 2026 00:13:45 +0000 Subject: [PATCH 37/61] Let the executemany collision test retry past the refusal between parameter sets --- tests/fast/api/test_appender.py | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/tests/fast/api/test_appender.py b/tests/fast/api/test_appender.py index e4e57b8e6..b94000fe8 100644 --- a/tests/fast/api/test_appender.py +++ b/tests/fast/api/test_appender.py @@ -1836,7 +1836,9 @@ def flush_until_stopped(): @pytest.mark.timeout(120) def test_a_flush_that_collides_with_a_submitted_executemany_is_refused_as_busy(self): - # As above, with the statement submitted by executemany, which runs it once per parameter set + # As above, with the statement submitted by executemany, which runs it once per parameter set. Between two + # sets the connection is free, so a flush landing there runs and the executemany is refused at its next set; + # that is allowed, and the main thread retries it, so the second thread stops after its attempts code, output = run_isolated( f""" import collections @@ -1859,18 +1861,17 @@ def hold(x): refusals = collections.Counter() submitted = 0 print("started", flush=True) - overall = time.monotonic() + 40 + overall = time.monotonic() + 60 while submitted < 20 and time.monotonic() < overall: - go, stop, release = threading.Event(), threading.Event(), threading.Event() + go, release = threading.Event(), threading.Event() gates.append(release) - def flush_until_stopped(): + def flush_two_hundred_times(): global flushed - # Started as the first thread enters its execute, so that call is the one under way; the + # Started as the first thread enters its executemany, so that call is the one under way; the # statement is held through the first attempts and released while the attempts go on go.wait(10) - attempts = 0 try: - while not stop.is_set(): + for attempt in range(200): app.append_row(flushed, "a") try: app.flush() @@ -1878,31 +1879,28 @@ def flush_until_stopped(): except duckdb.ResourceInUseException as error: refusals["busy" if {BUSY!r} in str(error) else str(error)] += 1 app.clear() - attempts += 1 - if attempts == 200: + if attempt == 100: release.set() finally: release.set() - thread = threading.Thread(target=flush_until_stopped) + thread = threading.Thread(target=flush_two_hundred_times) thread.start() go.set() - deadline = time.monotonic() + 1 - while time.monotonic() < deadline: + while time.monotonic() < overall: try: con.executemany("INSERT INTO log SELECT hold(i + ?::BIGINT) FROM range(1) t(i)", [[1], [2]]) submitted += 1 break except duckdb.ResourceInUseException as error: if {BUSY!r} not in str(error): - refusals["execute: " + str(error)] += 1 - stop.set() + refusals["executemany: " + str(error)] += 1 thread.join(10) print("submitted:", submitted) print("refusals:", sorted(refusals)) kept = con.execute("SELECT count(*) = ? FROM t", [flushed]).fetchall() - # An executemany refused between its two parameter sets, which is allowed, has inserted its first row - # already and is retried in full, so the log holds at least two rows per submission - logged = con.execute("SELECT count(*) >= 40 FROM log").fetchall() + # An executemany refused between its two parameter sets has written its first row already and is retried + # in full, so the log holds at least two rows per submission + logged = con.execute("SELECT count(*) >= 2 * ? FROM log", [submitted]).fetchall() print("rows:", kept + logged) """, timeout=90, From ad67684bcd47393d981c4e841ed7f99d5d427f44 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Wed, 11 Nov 2026 01:13:08 +0000 Subject: [PATCH 38/61] Register the DB-API result inside execute's claim, mark the Arrow tests as needing pyarrow, bound the retry loops --- .../pyconnection/pyconnection.hpp | 6 +- src/pyconnection.cpp | 27 ++- src/pyresult.cpp | 8 +- tests/fast/api/test_appender.py | 6 + tests/fast/api/test_execute_contract.py | 193 ++++++++++++++---- 5 files changed, 184 insertions(+), 56 deletions(-) diff --git a/src/include/duckdb_python/pyconnection/pyconnection.hpp b/src/include/duckdb_python/pyconnection/pyconnection.hpp index 06ecb3243..014449990 100644 --- a/src/include/duckdb_python/pyconnection/pyconnection.hpp +++ b/src/include/duckdb_python/pyconnection/pyconnection.hpp @@ -282,7 +282,9 @@ struct DuckDBPyConnection : public std::enable_shared_from_this Execute(const nb::object &query, nb::object params = nb::list()); + //! Makes the result the connection's DB-API result, under the caller's claim; false when there is none + bool RegisterResult(shared_ptr res); std::shared_ptr ExecuteFromString(const string &query); std::shared_ptr Append(const string &name, const PandasDataFrame &value, bool by_name); diff --git a/src/pyconnection.cpp b/src/pyconnection.cpp index 427dc034b..40623c939 100644 --- a/src/pyconnection.cpp +++ b/src/pyconnection.cpp @@ -882,6 +882,7 @@ std::shared_ptr DuckDBPyConnection::Execute(const nb::object RefuseParameters(statements); } shared_ptr res; + bool registered = false; if (last_statement) { if (params.is_none()) { params = nb::list(); @@ -891,27 +892,38 @@ std::shared_ptr DuckDBPyConnection::Execute(const nb::object DUCKDB_PY_ASSERT_GIL_HELD(); nb::gil_scoped_release release; unique_lock lock(py_connection_lock); - // One claim from submission to settling, so no other call finds the statement pending + // One claim from submission to settling and on to the registration of the result, so no other call finds + // the statement pending, and one that takes the claim next meets the registered result and gets the + // client's refusal auto claim = session.Claim(); res = SubmitAndDrive(statements, parameters_given, false, [&]() { return session.SubmitClaimed(std::move(last_statement), named_values, engine::Format::Chunks()); }); - res = statements.Choose(std::move(res)); + registered = RegisterResult(statements.Choose(std::move(res))); } else { DUCKDB_PY_ASSERT_GIL_HELD(); nb::gil_scoped_release release; unique_lock lock(py_connection_lock); - res = statements.Choose(nullptr); + registered = RegisterResult(statements.Choose(nullptr)); } - if (!res) { + if (!registered) { // TODO: should we throw? return nullptr; } - auto py_result = std::make_shared(std::move(res)); - con.SetResult(std::make_unique(std::move(py_result))); return shared_from_this(); } +bool DuckDBPyConnection::RegisterResult(shared_ptr res) { + DUCKDB_PY_ASSERT_GIL_RELEASED(); + if (!res) { + return false; + } + // The result the call superseded is gone already, so nothing that needs the GIL is destroyed here + D_ASSERT(!con.HasResult()); + con.SetResult(make_uniq(std::make_shared(std::move(res)))); + return true; +} + std::unique_ptr DuckDBPyConnection::CreateAppender(const string &table, const std::optional &columns, const string &action, @@ -1573,7 +1585,8 @@ nb::object DuckDBPyConnection::ResultAsArrow(idx_t batch_size, bool reader) { } } // The rows are retained, or the stream is settled, so the conversion into pyarrow holds the connection no longer - // and refuses no other call + // and refuses no submitting call; a settled stream stays the connection's open result until it is read out, as a + // relation's reader does conn_lock.DropSubmittingMark(); DuckDBPyResult converted(std::move(arrow), std::move(names)); if (reader) { diff --git a/src/pyresult.cpp b/src/pyresult.cpp index 666d065eb..3ff6f9d66 100644 --- a/src/pyresult.cpp +++ b/src/pyresult.cpp @@ -667,10 +667,12 @@ ArrowArrayStream DuckDBPyResult::FetchArrowArrayStream(idx_t rows_per_batch, Arr if (prebuilt) { state->cached_schema = *prebuilt; prebuilt->release = nullptr; - } else if (names_override.empty()) { - result->CopyArrowSchema(state->cached_schema); } else { - result->BuildArrowSchema(IdentifiersToStrings(names_override), state->cached_schema); + // A result with its own names comes with a prebuilt schema, see ResultAsArrow + if (!names_override.empty()) { + throw InternalException("Arrow stream over a result with its own names and no schema built for them"); + } + result->CopyArrowSchema(state->cached_schema); } state->result = std::move(result); current_chunk.reset(); diff --git a/tests/fast/api/test_appender.py b/tests/fast/api/test_appender.py index b94000fe8..3005f6338 100644 --- a/tests/fast/api/test_appender.py +++ b/tests/fast/api/test_appender.py @@ -1803,6 +1803,9 @@ def flush_until_stopped(): except duckdb.ResourceInUseException as error: refusals["busy" if {BUSY!r} in str(error) else str(error)] += 1 app.clear() + except Exception as error: + refusals["second thread: " + type(error).__name__] += 1 + return attempts += 1 if attempts == 200: release.set() @@ -1879,6 +1882,9 @@ def flush_two_hundred_times(): except duckdb.ResourceInUseException as error: refusals["busy" if {BUSY!r} in str(error) else str(error)] += 1 app.clear() + except Exception as error: + refusals["second thread: " + type(error).__name__] += 1 + return if attempt == 100: release.set() finally: diff --git a/tests/fast/api/test_execute_contract.py b/tests/fast/api/test_execute_contract.py index b3ecb2534..f0fe1e074 100644 --- a/tests/fast/api/test_execute_contract.py +++ b/tests/fast/api/test_execute_contract.py @@ -596,11 +596,11 @@ def hold(x): outcome = [] def contend(): - running.wait(10) try: + assert running.wait(10), "the statement never reached its UDF" con.sql("SELECT 1") outcome.append("ran") - except duckdb.ResourceInUseException as error: + except Exception as error: outcome.append(str(error)) finally: release.set() @@ -652,6 +652,8 @@ def execute_two_hundred_times(): except duckdb.ResourceInUseException as error: if {BUSY!r} not in str(error): outcomes[str(error)] += 1 + except Exception as error: + outcomes["second thread: " + type(error).__name__] += 1 if time.monotonic() - began > 1: outcomes["waited"] += 1 finally: @@ -684,6 +686,7 @@ def execute_two_hundred_times(): assert "submitted: 20" in output, output assert "outcomes: []" in output, output + @needs_pyarrow @pytest.mark.timeout(120) def test_a_refused_arrow_fetch_keeps_its_rows(self): # The DB-API Arrow fetch takes the rows out of the result and runs a statement over them; a second thread @@ -696,47 +699,62 @@ def test_a_refused_arrow_fetch_keeps_its_rows(self): import threading import time import duckdb + import pyarrow # noqa: F401 con = duckdb.connect() con.execute("SET threads = 4") # A short switch interval hands the GIL to the other thread often, as a busy program does sys.setswitchinterval(0.0001) stop = threading.Event() + counts = collections.Counter() def bind_until_stopped(): while not stop.is_set(): try: con.sql("SELECT 1") except duckdb.ResourceInUseException: pass - thread = threading.Thread(target=bind_until_stopped) + except Exception as error: + counts["binder: " + type(error).__name__] += 1 + return + thread = threading.Thread(target=bind_until_stopped, daemon=True) thread.start() - counts = collections.Counter() + fetches = retried = 0 print("started", flush=True) - deadline = time.monotonic() + 8 - while time.monotonic() < deadline and counts["retried"] < 50: - try: - con.execute("SELECT * FROM range(5) t(i)") - except duckdb.ResourceInUseException: - continue - for attempt in range(1000): + try: + deadline = time.monotonic() + 8 + while time.monotonic() < deadline and retried < 50: try: - table = con.to_arrow_table() - break - except duckdb.ResourceInUseException as error: - if {BUSY!r} not in str(error): - counts["refused: " + str(error)] += 1 - rows = None if table is None else table.num_rows - if attempt: - counts["retried"] += 1 - if rows != 5: - counts[f"rows {{rows}}" + (" after a refusal" if attempt else "")] += 1 - stop.set() - thread.join(10) + con.execute("SELECT * FROM range(5) t(i)") + except duckdb.ResourceInUseException: + continue + table = None + for attempt in range(1000): + try: + table = con.to_arrow_table() + break + except duckdb.ResourceInUseException as error: + if {BUSY!r} not in str(error): + counts["refused: " + str(error)] += 1 + fetches += 1 + if attempt: + retried += 1 + if table is None: + counts["no table" + (" after a refusal" if attempt else "")] += 1 + elif table.num_rows != 5: + counts[f"rows {{table.num_rows}}" + (" after a refusal" if attempt else "")] += 1 + finally: + stop.set() + thread.join(10) + print("fetches:", fetches, "retried:", retried) print("counts:", sorted(counts)) """, timeout=90, ) assert code == 0, output - assert "counts: ['retried']" in output or "counts: []" in output, output + assert "counts: []" in output, output + fetches, retried = (int(n) for n in re.search(r"fetches: (\d+) retried: (\d+)", output).groups()) + assert fetches > 0, output + if retried == 0: + pytest.skip("inconclusive: no fetch was refused by the binding thread") def test_a_second_execute_during_parameter_conversion_is_refused_at_once(self): # The first thread holds the connection mutex and no claim while its parameters are read, so a second @@ -781,6 +799,70 @@ def second(): assert BUSY in outcome[0], outcome assert rows == [(1,)] + def test_a_nested_execute_from_the_submitting_thread_still_enters(self): + # The thread whose submitting call is in flight may submit again from inside it, as the recursive mutex + # admits it: a parameter object that runs a statement reads its row, and the outer call returns its own + con = duckdb.connect() + con.execute("SET threads = 4") + inner = [] + + class Params: + def __len__(self) -> int: + return 1 + + def __iter__(self) -> Iterator[int]: + inner.append(con.execute("SELECT 99").fetchall()) + return iter([1]) + + try: + rows = con.execute("SELECT ?::INTEGER", Params()).fetchall() + finally: + con.close() + assert inner == [[(99,)]] + assert rows == [(1,)] + + def test_a_reader_is_refused_while_a_statement_runs(self): + # A call that waits for the mutex when a reader holds it is still refused outright while a statement holds + # the connection: the busy check comes before the wait + con = duckdb.connect() + con.execute("SET threads = 4") + running, release = threading.Event(), threading.Event() + + def hold(x): + running.set() + release.wait(10) + return x + + con.create_function("hold", hold, [BIGINT], BIGINT) + outcome = {} + + def attempt(name, call): + try: + call() + outcome[name] = "ran" + except duckdb.ResourceInUseException as error: + outcome[name] = "busy" if BUSY in str(error) else str(error) + + def contend(): + try: + assert running.wait(10), "the statement never reached its UDF" + attempt("description", lambda: con.description) + attempt("fetchall", con.fetchall) + except Exception as error: + outcome["contender failed"] = repr(error) + finally: + release.set() + + thread = threading.Thread(target=contend) + thread.start() + try: + rows = con.execute("SELECT hold(i) FROM range(1) t(i)").fetchall() + finally: + thread.join(10) + con.close() + assert rows == [(0,)] + assert outcome == {"description": "busy", "fetchall": "busy"}, outcome + def test_a_thread_reading_the_description_does_not_make_execute_fail(self): # A reader holds the connection mutex while it waits for the GIL back; an execute on another thread waits for # such a holder as every call did, and is refused only behind another call that submits a statement @@ -789,11 +871,16 @@ def test_a_thread_reading_the_description_does_not_make_execute_fail(self): con.execute("SELECT 1") stop = threading.Event() + failures = [] + def read_until_stopped(): - while not stop.is_set(): - with contextlib.suppress(duckdb.ResourceInUseException): - con.description # noqa: B018 - time.sleep(0.0005) + try: + while not stop.is_set(): + with contextlib.suppress(duckdb.ResourceInUseException): + con.description # noqa: B018 + time.sleep(0.0005) + except Exception as error: + failures.append(repr(error)) def execute_once(): try: @@ -816,6 +903,7 @@ def execute_once(): stop.set() thread.join(10) con.close() + assert failures == [] assert refused == 0, (ran, refused) assert ran > 0 @@ -828,16 +916,21 @@ def test_a_submitting_call_beside_a_reader_is_refused_at_once(self): con.create_function("hold", lambda x: time.sleep(0.3) or x, [BIGINT], BIGINT) stop = threading.Event() waited = [] + failures = [] + + def until_stopped(call): + try: + while not stop.is_set(): + with contextlib.suppress(duckdb.ResourceInUseException): + call() + except Exception as error: + failures.append(repr(error)) def read_until_stopped(): - while not stop.is_set(): - with contextlib.suppress(duckdb.ResourceInUseException): - con.description # noqa: B018 + until_stopped(lambda: con.description) def run_held_statements(): - while not stop.is_set(): - with contextlib.suppress(duckdb.ResourceInUseException): - con.execute("SELECT hold(i) FROM range(1) t(i)") + until_stopped(lambda: con.execute("SELECT hold(i) FROM range(1) t(i)")) def execute_once(): began = time.monotonic() @@ -859,8 +952,10 @@ def execute_once(): for thread in threads: thread.join(10) con.close() + assert failures == [] assert waited == [] + @needs_pyarrow def test_other_calls_run_while_a_result_is_converted_to_arrow(self): # The Arrow fetch holds the connection only until the rows are taken and the schema is built; the conversion # into pyarrow that follows holds the mutex and no claim, so a relation runs during it and an execute waits @@ -881,16 +976,19 @@ def attempt(call): return "ran" def second(): - assert converting.wait(10) - deadline = time.monotonic() + 20 - while time.monotonic() < deadline and "done" not in marks: - began = time.monotonic() - kind = attempt(lambda: con.table("t")) - attempts.append((began, kind)) - # A relation admitted after the take was refused ran during the conversion; an execute then too - if kind == "ran" and any(k != "ran" for _, k in attempts): - outcome["execute during the conversion"] = attempt(lambda: con.execute("SELECT 1")) - break + try: + assert converting.wait(10) + deadline = time.monotonic() + 20 + while time.monotonic() < deadline and "done" not in marks: + began = time.monotonic() + kind = attempt(lambda: con.table("t")) + attempts.append((began, kind)) + # A relation admitted after the take was refused ran during the conversion; an execute then too + if kind == "ran" and any(k != "ran" for _, k in attempts): + outcome["execute during the conversion"] = attempt(lambda: con.execute("SELECT 1")) + break + except Exception as error: + outcome["second thread failed"] = repr(error) def fetch_or_none(): try: @@ -904,13 +1002,18 @@ def fetch_or_none(): con.execute("SELECT i, i::VARCHAR AS s FROM range(1000000) t(i)") converting.set() table = None - while table is None: + # Bounded: a fetch that lost its rows to a refusal returns None forever + give_up = time.monotonic() + 20 + for _ in range(1000): table = fetch_or_none() + if table is not None or time.monotonic() > give_up: + break marks["done"] = time.monotonic() finally: marks.setdefault("done", time.monotonic()) thread.join(30) con.close() + assert table is not None, (len(attempts), outcome) assert table.num_rows == 1000000 refused = [t for t, k in attempts if k != "ran"] assert refused, attempts[:5] From efe893aa163e425c83ef8a27af5233654f104fbe Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Wed, 11 Nov 2026 01:45:11 +0000 Subject: [PATCH 39/61] Supersede a result the parameter code registered before execute's claim, so the registration assertion states the rule --- src/pyconnection.cpp | 6 +++++- tests/fast/api/test_execute_contract.py | 12 +++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/pyconnection.cpp b/src/pyconnection.cpp index 40623c939..d4e20dd41 100644 --- a/src/pyconnection.cpp +++ b/src/pyconnection.cpp @@ -889,6 +889,9 @@ std::shared_ptr DuckDBPyConnection::Execute(const nb::object } auto session = EngineSession(); auto named_values = TransformPreparedParameters(session.Context(), params); + // Converting the parameters runs their Python code, which may have run its own statement on this connection + // from this thread; that result gives way to this call's, as any earlier result does + SupersedeResult(false); DUCKDB_PY_ASSERT_GIL_HELD(); nb::gil_scoped_release release; unique_lock lock(py_connection_lock); @@ -918,7 +921,8 @@ bool DuckDBPyConnection::RegisterResult(shared_ptr res) { if (!res) { return false; } - // The result the call superseded is gone already, so nothing that needs the GIL is destroyed here + // The call superseded the earlier result, and the one its parameter code may have registered, before the claim, + // so nothing that needs the GIL is destroyed here D_ASSERT(!con.HasResult()); con.SetResult(make_uniq(std::make_shared(std::move(res)))); return true; diff --git a/tests/fast/api/test_execute_contract.py b/tests/fast/api/test_execute_contract.py index f0fe1e074..5fcdb80a6 100644 --- a/tests/fast/api/test_execute_contract.py +++ b/tests/fast/api/test_execute_contract.py @@ -801,7 +801,8 @@ def second(): def test_a_nested_execute_from_the_submitting_thread_still_enters(self): # The thread whose submitting call is in flight may submit again from inside it, as the recursive mutex - # admits it: a parameter object that runs a statement reads its row, and the outer call returns its own + # admits it: a parameter object that runs a statement reads its row, and the outer call's result then + # supersedes the nested one, so the outer call returns its own row and the connection holds only that result con = duckdb.connect() con.execute("SET threads = 4") inner = [] @@ -811,15 +812,20 @@ def __len__(self) -> int: return 1 def __iter__(self) -> Iterator[int]: - inner.append(con.execute("SELECT 99").fetchall()) + inner.append(con.execute("SELECT 99 AS nested").fetchall()) return iter([1]) try: - rows = con.execute("SELECT ?::INTEGER", Params()).fetchall() + con.execute("SELECT ?::INTEGER AS outer", Params()) + description = [column[0] for column in con.description] + rows = con.fetchall() + left = con.fetchall() finally: con.close() assert inner == [[(99,)]] + assert description == ["outer"] assert rows == [(1,)] + assert left == [] def test_a_reader_is_refused_while_a_statement_runs(self): # A call that waits for the mutex when a reader holds it is still refused outright while a statement holds From b54a0f1f22e612da6c40917bcb11498cacc14237 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Wed, 11 Nov 2026 02:48:22 +0000 Subject: [PATCH 40/61] Pin the unread nested result case and retry the Arrow fetch test by time --- .../pyconnection/pyconnection.hpp | 2 +- src/include/duckdb_python/pyresult.hpp | 2 +- src/pyconnection.cpp | 7 ++--- tests/fast/api/test_appender.py | 4 +-- tests/fast/api/test_execute_contract.py | 29 ++++++++++++++++--- 5 files changed, 32 insertions(+), 12 deletions(-) diff --git a/src/include/duckdb_python/pyconnection/pyconnection.hpp b/src/include/duckdb_python/pyconnection/pyconnection.hpp index 014449990..829ce3c0f 100644 --- a/src/include/duckdb_python/pyconnection/pyconnection.hpp +++ b/src/include/duckdb_python/pyconnection/pyconnection.hpp @@ -417,7 +417,7 @@ struct DuckDBPyConnection : public std::enable_shared_from_this Execute(const nb::object &query, nb::object params = nb::list()); - //! Makes the result the connection's DB-API result, under the caller's claim; false when there is none + //! Makes the result the connection's DB-API result, with the GIL released; false when there is none bool RegisterResult(shared_ptr res); std::shared_ptr ExecuteFromString(const string &query); diff --git a/src/include/duckdb_python/pyresult.hpp b/src/include/duckdb_python/pyresult.hpp index bb1e1da60..8ae1114e2 100644 --- a/src/include/duckdb_python/pyresult.hpp +++ b/src/include/duckdb_python/pyresult.hpp @@ -129,7 +129,7 @@ struct DuckDBPyResult { duckdb::pyarrow::Table ConvertToArrowTable(const ArrowSchema &schema); duckdb::pyarrow::RecordBatchReader ImportRecordBatchReader(ArrowSchema *prebuilt, idx_t rows_per_batch); //! The stream's private data owns the result, and its callbacks run without the GIL. - //! prebuilt, when given, becomes the stream's schema; otherwise the result's own is copied or built + //! prebuilt, when given, becomes the stream's schema; otherwise the result's own is copied ArrowArrayStream FetchArrowArrayStream(idx_t rows_per_batch, ArrowSchema *prebuilt); private: diff --git a/src/pyconnection.cpp b/src/pyconnection.cpp index d4e20dd41..9ccd6562a 100644 --- a/src/pyconnection.cpp +++ b/src/pyconnection.cpp @@ -1,5 +1,7 @@ #include "duckdb_python/pyconnection/pyconnection.hpp" +#include "duckdb/common/identifier.hpp" + #include "duckdb/catalog/catalog.hpp" #include "duckdb/common/arrow/arrow.hpp" #include "duckdb/common/types.hpp" @@ -1571,10 +1573,7 @@ nb::object DuckDBPyConnection::ResultAsArrow(idx_t batch_size, bool reader) { if (!rows) { return nb::none(); } - vector schema_names; - for (auto &name : names) { - schema_names.push_back(name.GetIdentifierName()); - } + auto schema_names = IdentifiersToStrings(names); { DUCKDB_PY_ASSERT_GIL_HELD(); nb::gil_scoped_release release; diff --git a/tests/fast/api/test_appender.py b/tests/fast/api/test_appender.py index 3005f6338..8e2d2ac61 100644 --- a/tests/fast/api/test_appender.py +++ b/tests/fast/api/test_appender.py @@ -1796,8 +1796,8 @@ def flush_until_stopped(): attempts = 0 try: while not stop.is_set(): - app.append_row(flushed, "a") try: + app.append_row(flushed, "a") app.flush() flushed += 1 except duckdb.ResourceInUseException as error: @@ -1875,8 +1875,8 @@ def flush_two_hundred_times(): go.wait(10) try: for attempt in range(200): - app.append_row(flushed, "a") try: + app.append_row(flushed, "a") app.flush() flushed += 1 except duckdb.ResourceInUseException as error: diff --git a/tests/fast/api/test_execute_contract.py b/tests/fast/api/test_execute_contract.py index 5fcdb80a6..1ca5929c5 100644 --- a/tests/fast/api/test_execute_contract.py +++ b/tests/fast/api/test_execute_contract.py @@ -726,18 +726,24 @@ def bind_until_stopped(): con.execute("SELECT * FROM range(5) t(i)") except duckdb.ResourceInUseException: continue - table = None - for attempt in range(1000): + # Retried by time: the binding thread can refuse the fetch many times in a row under load + table, admitted, attempt = None, False, 0 + give_up = time.monotonic() + 5 + while time.monotonic() < give_up: try: table = con.to_arrow_table() + admitted = True break except duckdb.ResourceInUseException as error: + attempt += 1 if {BUSY!r} not in str(error): counts["refused: " + str(error)] += 1 fetches += 1 if attempt: retried += 1 - if table is None: + if not admitted: + counts["fetch never admitted in 5 s"] += 1 + elif table is None: counts["no table" + (" after a refusal" if attempt else "")] += 1 elif table.num_rows != 5: counts[f"rows {{table.num_rows}}" + (" after a refusal" if attempt else "")] += 1 @@ -802,7 +808,8 @@ def second(): def test_a_nested_execute_from_the_submitting_thread_still_enters(self): # The thread whose submitting call is in flight may submit again from inside it, as the recursive mutex # admits it: a parameter object that runs a statement reads its row, and the outer call's result then - # supersedes the nested one, so the outer call returns its own row and the connection holds only that result + # supersedes the nested one, read out or left open, so the outer call returns its own row and the connection + # holds only that result con = duckdb.connect() con.execute("SET threads = 4") inner = [] @@ -815,17 +822,31 @@ def __iter__(self) -> Iterator[int]: inner.append(con.execute("SELECT 99 AS nested").fetchall()) return iter([1]) + class UnreadParams: + def __len__(self) -> int: + return 1 + + def __iter__(self) -> Iterator[int]: + # Left open on purpose: the outer call supersedes it, where it used to be refused for it + con.execute("SELECT 99 AS nested") + return iter([2]) + try: con.execute("SELECT ?::INTEGER AS outer", Params()) description = [column[0] for column in con.description] rows = con.fetchall() left = con.fetchall() + con.execute("SELECT ?::INTEGER AS outer", UnreadParams()) + unread_description = [column[0] for column in con.description] + unread_rows = con.fetchall() finally: con.close() assert inner == [[(99,)]] assert description == ["outer"] assert rows == [(1,)] assert left == [] + assert unread_description == ["outer"] + assert unread_rows == [(2,)] def test_a_reader_is_refused_while_a_statement_runs(self): # A call that waits for the mutex when a reader holds it is still refused outright while a statement holds From efdbaa5e4b3692329827235209323dfef519ad9f Mon Sep 17 00:00:00 2001 From: DuckDB Labs GitHub Bot Date: Wed, 11 Nov 2026 03:40:22 +0000 Subject: [PATCH 41/61] Bump submodule --- external/duckdb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/external/duckdb b/external/duckdb index 29b26cb10..a7e6fc10d 160000 --- a/external/duckdb +++ b/external/duckdb @@ -1 +1 @@ -Subproject commit 29b26cb10605e45d7dac7237bce34423ebba4512 +Subproject commit a7e6fc10d2f12ba0784f0843ee9ec517dcba561b From be4f0b0bcb42586fe3251b0cdff7f3ea61592e57 Mon Sep 17 00:00:00 2001 From: DuckDB Labs GitHub Bot Date: Wed, 11 Nov 2026 13:37:50 +0000 Subject: [PATCH 42/61] Bump submodule --- external/duckdb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/external/duckdb b/external/duckdb index a7e6fc10d..925bcdf35 160000 --- a/external/duckdb +++ b/external/duckdb @@ -1 +1 @@ -Subproject commit a7e6fc10d2f12ba0784f0843ee9ec517dcba561b +Subproject commit 925bcdf35756dca26ada5228a0c76dc227c5aca5 From fd7028fa4d7f1d209fe9165d7a5ac8e27271ffca Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Thu, 12 Nov 2026 09:55:33 +0000 Subject: [PATCH 43/61] Follow the engine's text for a folded range with an exclusive bound in the predicate tests --- tests/fast/arrow/scan/test_predicate_translation.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/fast/arrow/scan/test_predicate_translation.py b/tests/fast/arrow/scan/test_predicate_translation.py index 4ad56c69d..9eda08788 100644 --- a/tests/fast/arrow/scan/test_predicate_translation.py +++ b/tests/fast/arrow/scan/test_predicate_translation.py @@ -100,10 +100,10 @@ def p(predicate, *entries, id): p("n > 1 + 1", ("(n > 2)", '("n" > 2)'), id="folded-constant"), p("b = true", ("(b = true)", '("b" = TRUE)'), id="boolean"), p("s LIKE 'abc'", ("(s = 'abc')", "(\"s\" = 'abc')"), id="like-without-wildcards"), - # BETWEEN, read through the bound inclusivity flags + # BETWEEN, read through the bound inclusivity flags; an exclusive bound prints as two comparisons p("n BETWEEN 3 AND 6", ("(n BETWEEN 3 AND 6)", '(("n" >= 3) AND ("n" <= 6))'), id="between"), - p("n > 1 AND n < 8", ("(n BETWEEN 1 AND 8)", '(("n" > 1) AND ("n" < 8))'), id="exclusive-range-folded"), - p("n >= 1 AND n < 8", ("(n BETWEEN 1 AND 8)", '(("n" >= 1) AND ("n" < 8))'), id="half-open-range-folded"), + p("n > 1 AND n < 8", ("((n > 1) AND (n < 8))", '(("n" > 1) AND ("n" < 8))'), id="exclusive-range-folded"), + p("n >= 1 AND n < 8", ("((n >= 1) AND (n < 8))", '(("n" >= 1) AND ("n" < 8))'), id="half-open-range-folded"), p("n BETWEEN 1 AND 1", ("(n = 1)", '("n" = 1)'), id="between-one-value"), p("n NOT BETWEEN 3 AND 6", ("((n < 3) OR (n > 6))", '(("n" < 3) OR ("n" > 6))'), id="not-between"), p( @@ -115,7 +115,7 @@ def p(predicate, *entries, id): p( "CAST(ts AS DATE) = DATE '2024-01-01'", ( - "(ts BETWEEN '2024-01-01 00:00:00'::TIMESTAMP AND '2024-01-02 00:00:00'::TIMESTAMP)", + "((ts >= '2024-01-01 00:00:00'::TIMESTAMP) AND (ts < '2024-01-02 00:00:00'::TIMESTAMP))", "((\"ts\" >= TIMESTAMP '2024-01-01 00:00:00') AND (\"ts\" < TIMESTAMP '2024-01-02 00:00:00'))", ), id="date-cast-equality-rewritten", @@ -123,7 +123,7 @@ def p(predicate, *entries, id): p( "date_trunc('day', ts) = TIMESTAMP '2024-01-01'", ( - "(ts BETWEEN '2024-01-01 00:00:00'::TIMESTAMP AND '2024-01-02 00:00:00'::TIMESTAMP)", + "((ts >= '2024-01-01 00:00:00'::TIMESTAMP) AND (ts < '2024-01-02 00:00:00'::TIMESTAMP))", "((\"ts\" >= TIMESTAMP '2024-01-01 00:00:00') AND (\"ts\" < TIMESTAMP '2024-01-02 00:00:00'))", ), id="date-trunc-equality-rewritten", From dfca0f44d539e55e9b3206b999a72bfc22360dda Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Thu, 12 Nov 2026 10:30:15 +0000 Subject: [PATCH 44/61] Move the engine pin to 76e6bf79426, which prints an exclusive bound of a folded range as two comparisons --- external/duckdb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/external/duckdb b/external/duckdb index 925bcdf35..76e6bf794 160000 --- a/external/duckdb +++ b/external/duckdb @@ -1 +1 @@ -Subproject commit 925bcdf35756dca26ada5228a0c76dc227c5aca5 +Subproject commit 76e6bf79426c414cc5f0634adbe824dba941c98d From 93e70201966099c295ba7fcca2a85a79a79be5b6 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Fri, 13 Nov 2026 12:25:24 +0000 Subject: [PATCH 45/61] Move the engine pin to cb5673685153 and follow its statement text, which keeps the comments in front of a statement --- external/duckdb | 2 +- tests/fast/api/test_duckdb_connection.py | 9 +++++++-- tests/fast/api/test_seam.py | 6 +++--- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/external/duckdb b/external/duckdb index 76e6bf794..cb5673685 160000 --- a/external/duckdb +++ b/external/duckdb @@ -1 +1 @@ -Subproject commit 76e6bf79426c414cc5f0634adbe824dba941c98d +Subproject commit cb5673685153159d22bf1042ab444273c9ad268a diff --git a/tests/fast/api/test_duckdb_connection.py b/tests/fast/api/test_duckdb_connection.py index fbd8e6c0a..dae89cd07 100644 --- a/tests/fast/api/test_duckdb_connection.py +++ b/tests/fast/api/test_duckdb_connection.py @@ -129,15 +129,20 @@ def test_pystatement(self): statements = duckdb.extract_statements("select $1; select 21") assert len(statements) == 2 - assert statements[0].query.startswith("select $1") + # A statement's text runs from the end of the one before it through its own semicolon, so what stands + # between two statements belongs to the second + assert statements[0].query == "select $1;" assert statements[0].type == duckdb.StatementType.SELECT assert statements[0].named_parameters == set("1") assert statements[0].expected_result_type == [duckdb.ExpectedResultType.QUERY_RESULT] - assert statements[1].query.startswith("select 21") + assert statements[1].query == " select 21" assert statements[1].type == duckdb.StatementType.SELECT assert statements[1].named_parameters == set() + commented = duckdb.extract_statements("select 1; /* between */ select 2 -- after") + assert [s.query for s in commented] == ["select 1;", " /* between */ select 2 -- after"] + with pytest.raises( duckdb.InvalidInputException, match="Please provide either a DuckDBPyStatement or a string representing the query", diff --git a/tests/fast/api/test_seam.py b/tests/fast/api/test_seam.py index febb9391d..a1ce016e7 100644 --- a/tests/fast/api/test_seam.py +++ b/tests/fast/api/test_seam.py @@ -1028,13 +1028,13 @@ class TestPrepareScript: def test_runs_all_but_the_last(self, con): kept, text, kind = con._prepare_script("SELECT 42; CREATE TABLE u AS SELECT 1 AS x;\n FROM u", None) assert kept.fetchall() == [(42,)] - assert (text, kind) == ("FROM u", "select") + assert (text, kind) == ("\n FROM u", "select") assert con.execute("SELECT * FROM u").fetchall() == [(1,)] def test_last_statement_is_not_run(self, con): kept, text, kind = con._prepare_script("CREATE TABLE u (i INTEGER); INSERT INTO u VALUES (1);", None) assert kept is None - assert (text, kind) == ("INSERT INTO u VALUES (1)", "insert") + assert (text, kind) == (" INSERT INTO u VALUES (1)", "insert") assert con.execute("SELECT count(*) FROM u").fetchall() == [(0,)] @pytest.mark.parametrize( @@ -1051,7 +1051,7 @@ def test_single_statement(self, con, sql, expected): assert con._prepare_script(sql, None) == expected def test_parameters_only_on_the_last(self, con): - assert con._prepare_script("SELECT 1; SELECT ?", [1])[1:] == ("SELECT ?", "select") + assert con._prepare_script("SELECT 1; SELECT ?", [1])[1:] == (" SELECT ?", "select") with pytest.raises(duckdb.NotImplementedException, match="only supported for the last statement"): con._prepare_script("SELECT ?; SELECT 1", [1]) with pytest.raises(duckdb.InvalidInputException, match="Parameters were given"): From f8551ea4967fd4074c606ca5984cdee8faaa29c3 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Tue, 17 Nov 2026 15:07:55 +0000 Subject: [PATCH 46/61] Move the engine pin to 0c429a4d and follow its MERGE multi match revert --- external/duckdb | 2 +- tests/fast/api/test_appender.py | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/external/duckdb b/external/duckdb index cb5673685..0c429a4d3 160000 --- a/external/duckdb +++ b/external/duckdb @@ -1 +1 @@ -Subproject commit cb5673685153159d22bf1042ab444273c9ad268a +Subproject commit 0c429a4d3c3980595c465e2470974e0006c11fdd diff --git a/tests/fast/api/test_appender.py b/tests/fast/api/test_appender.py index cf2dfcb7b..a6888c07f 100644 --- a/tests/fast/api/test_appender.py +++ b/tests/fast/api/test_appender.py @@ -1407,6 +1407,11 @@ def test_a_key_repeated_within_one_update_from_applies_one_of_its_rows(self, con app.flush() assert table_rows(con) in ([(1, "first")], [(1, "second")]) + @pytest.mark.xfail( + strict=True, + reason="the engine updates a target row once per matching source row instead of refusing the repeated " + "match, a trade of correctness for speed it means to undo in 2.1", + ) def test_a_key_repeated_within_one_merge_raises(self, con): con.execute("INSERT INTO t VALUES (1, 'old')") app = con.query_appender( From 4d3b766355e62846bf82b19dd07010735b7bd907 Mon Sep 17 00:00:00 2001 From: DuckDB Labs GitHub Bot Date: Tue, 17 Nov 2026 20:44:46 +0000 Subject: [PATCH 47/61] Bump submodule --- external/duckdb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/external/duckdb b/external/duckdb index 0c429a4d3..efff52352 160000 --- a/external/duckdb +++ b/external/duckdb @@ -1 +1 @@ -Subproject commit 0c429a4d3c3980595c465e2470974e0006c11fdd +Subproject commit efff52352566d7909d404836d38f9393ea5580b2 From 6819cb74e9b6e5bb14f8f4435b0fbadf8c185baa Mon Sep 17 00:00:00 2001 From: DuckDB Labs GitHub Bot Date: Wed, 18 Nov 2026 05:41:42 +0000 Subject: [PATCH 48/61] Bump submodule --- external/duckdb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/external/duckdb b/external/duckdb index efff52352..fe5c8b29a 160000 --- a/external/duckdb +++ b/external/duckdb @@ -1 +1 @@ -Subproject commit efff52352566d7909d404836d38f9393ea5580b2 +Subproject commit fe5c8b29a066f32be6eca4d7b2072d54a081c735 From 25d5949b82c3949f8d1b84e84dfc56ec294ffa74 Mon Sep 17 00:00:00 2001 From: DuckDB Labs GitHub Bot Date: Wed, 18 Nov 2026 12:52:35 +0000 Subject: [PATCH 49/61] Bump submodule --- external/duckdb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/external/duckdb b/external/duckdb index fe5c8b29a..90dcc2834 160000 --- a/external/duckdb +++ b/external/duckdb @@ -1 +1 @@ -Subproject commit fe5c8b29a066f32be6eca4d7b2072d54a081c735 +Subproject commit 90dcc2834cd5dfcfff3dced2f15f657e69736e29 From fd05ced4ba53cf352ad63fb1c85ad1dbbe093774 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Thu, 19 Nov 2026 13:34:05 +0100 Subject: [PATCH 50/61] pin submodule to v2.0.1 release commit --- external/duckdb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/external/duckdb b/external/duckdb index 90dcc2834..8d78114e9 160000 --- a/external/duckdb +++ b/external/duckdb @@ -1 +1 @@ -Subproject commit 90dcc2834cd5dfcfff3dced2f15f657e69736e29 +Subproject commit 8d78114e90a53823803660bf821f6073ac87da8c From ac3eb2e0851289d9b9e155cb6bc712dcc7b805e6 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Sun, 8 Nov 2026 11:27:07 +0000 Subject: [PATCH 51/61] Silence nanobind's exit leak report in builds without assertions --- .github/workflows/assert_test.yml | 1 + .github/workflows/packaging_sdist.yml | 2 + .github/workflows/packaging_wheels.yml | 2 + _duckdb-stubs/__init__.pyi | 1 + src/duckdb_python.cpp | 14 ++ .../arrow/scan/test_python_arrow_scan_core.py | 3 + .../arrow/test_arrow_single_use_stream.py | 3 + tests/fast/test_exit_leak_report.py | 131 ++++++++++++++++++ tests/slow/test_interpreter_shutdown.py | 31 ++++- 9 files changed, 182 insertions(+), 6 deletions(-) create mode 100644 tests/fast/test_exit_leak_report.py diff --git a/.github/workflows/assert_test.yml b/.github/workflows/assert_test.yml index 91dcb7f9c..681647740 100644 --- a/.github/workflows/assert_test.yml +++ b/.github/workflows/assert_test.yml @@ -91,6 +91,7 @@ jobs: import _duckdb print(_duckdb.__file__) assert "abi3" not in _duckdb.__file__, "expected a full-API module, got " + _duckdb.__file__ + assert _duckdb._assertions, "expected a build with assertions, which keeps nanobind's exit leak report" EOF - name: Run the tests diff --git a/.github/workflows/packaging_sdist.yml b/.github/workflows/packaging_sdist.yml index 8a70cd791..f3f6e9d84 100644 --- a/.github/workflows/packaging_sdist.yml +++ b/.github/workflows/packaging_sdist.yml @@ -94,6 +94,8 @@ jobs: # torch release's, for every platform) to compute its hash UV_PROJECT_ENVIRONMENT="${{ runner.temp }}/.venv" uv sync --only-group test --no-install-project --inexact cd ${{ runner.temp }} + # an sdist install is a build without assertions, which keeps nanobind's exit leak report off + uv run python -c "import _duckdb; assert not _duckdb._assertions, 'the sdist was built with assertions'" # run tests tests_root="${{ github.workspace }}/tests" tests_dir="${tests_root}${{ inputs.testsuite == 'fast' && '/fast' || '/' }}" diff --git a/.github/workflows/packaging_wheels.yml b/.github/workflows/packaging_wheels.yml index 0f1e35c21..055984708 100644 --- a/.github/workflows/packaging_wheels.yml +++ b/.github/workflows/packaging_wheels.yml @@ -252,6 +252,8 @@ jobs: cp -r tests pyproject.toml "$testrun" cd "$testrun" uv run --no-project --python "$venv" python -c "import duckdb, sys, os; print(duckdb.__version__, sys.version, os.getcwd())" + # A wheel built with assertions would print nanobind's exit leak report to every user. + uv run --no-project --python "$venv" python -c "import _duckdb; assert not _duckdb._assertions, 'the wheel was built with assertions'" uv run --no-project --python "$venv" pytest --confcutdir=. --rootdir . -c pyproject.toml ${{ inputs.testsuite == 'fast' && './tests/fast' || './tests' }} test_pandas_2: diff --git a/_duckdb-stubs/__init__.pyi b/_duckdb-stubs/__init__.pyi index 13e98a99c..7e014e9af 100644 --- a/_duckdb-stubs/__init__.pyi +++ b/_duckdb-stubs/__init__.pyi @@ -794,6 +794,7 @@ __interactive__: bool __jupyter__: bool __standard_vector_size__: int __version__: str +_assertions: bool _clean_default_connection: typing.Any # value = apilevel: str paramstyle: str diff --git a/src/duckdb_python.cpp b/src/duckdb_python.cpp index 59d170033..8205da792 100644 --- a/src/duckdb_python.cpp +++ b/src/duckdb_python.cpp @@ -704,12 +704,25 @@ NB_EXPORT void *_force_symbol_inclusion() { } }; +// DEBUG is set only for the engine's own sources; the bindings see the build configuration through these two. +#if defined(DUCKDB_DEBUG_MODE) || defined(DUCKDB_FORCE_ASSERT) +static constexpr bool BUILD_HAS_ASSERTIONS = true; +#else +static constexpr bool BUILD_HAS_ASSERTIONS = false; +#endif + NB_MODULE(DUCKDB_PYTHON_LIB_NAME, m) { // NOLINT // DO NOT REMOVE: the below forces that we include all symbols we want to export volatile auto *keep_alive = _force_symbol_inclusion(); (void)keep_alive; // END + // Objects that another package keeps alive past finalization fill nanobind's exit report although nothing grows + // at run time, so only builds with assertions print it. + if constexpr (!BUILD_HAS_ASSERTIONS) { + nb::set_leak_warnings(false); + } + // A static initializer registered the linked extensions when the library was loaded. Repeating the call is a no-op // on a healthy build and makes a broken build fail at import instead of at the first connect. if (duckdb_register_static_extensions() != 0) { @@ -754,6 +767,7 @@ NB_MODULE(DUCKDB_PYTHON_LIB_NAME, m) { // NOLINT m.attr("__interactive__") = DuckDBPyConnection::DetectAndGetEnvironment(); m.attr("__jupyter__") = DuckDBPyConnection::IsJupyter(); m.attr("__formatted_python_version__") = DuckDBPyConnection::FormattedPythonVersion(); + m.attr("_assertions") = BUILD_HAS_ASSERTIONS; m.def("default_connection", &DuckDBPyConnection::DefaultConnection, "Retrieve the connection currently registered as the default to be used by the module"); m.def("set_default_connection", &DuckDBPyConnection::SetDefaultConnection, diff --git a/tests/fast/arrow/scan/test_python_arrow_scan_core.py b/tests/fast/arrow/scan/test_python_arrow_scan_core.py index 655a80f3d..2759f9633 100644 --- a/tests/fast/arrow/scan/test_python_arrow_scan_core.py +++ b/tests/fast/arrow/scan/test_python_arrow_scan_core.py @@ -21,6 +21,7 @@ from pathlib import Path from typing import ClassVar +import _duckdb import pytest import duckdb @@ -2563,6 +2564,8 @@ def test_interpreter_exit(self, state): assert completed.returncode == 0, completed.stderr[-2000:] assert "exiting" in completed.stdout if state != "retained_result": + if not _duckdb._assertions: + pytest.skip("a build without assertions silences nanobind's leak report") assert "nanobind: leaked" not in completed.stderr @pytest.mark.timeout(120) diff --git a/tests/fast/arrow/test_arrow_single_use_stream.py b/tests/fast/arrow/test_arrow_single_use_stream.py index e4339e8d1..07bc90d26 100644 --- a/tests/fast/arrow/test_arrow_single_use_stream.py +++ b/tests/fast/arrow/test_arrow_single_use_stream.py @@ -17,6 +17,7 @@ import time from collections import Counter +import _duckdb import pytest import duckdb @@ -614,6 +615,8 @@ def test_scan_after_the_module_left_sys_modules(self): assert "first 3" in completed.stdout assert "second raised True" in completed.stdout assert "already registered" not in completed.stderr + if not _duckdb._assertions: + pytest.skip("a build without assertions silences nanobind's leak report") assert "nanobind: leaked" not in completed.stderr diff --git a/tests/fast/test_exit_leak_report.py b/tests/fast/test_exit_leak_report.py new file mode 100644 index 000000000..d01b6e9bb --- /dev/null +++ b/tests/fast/test_exit_leak_report.py @@ -0,0 +1,131 @@ +"""What nanobind prints at interpreter exit about module objects that Python never freed. + +A package that keeps a module's globals alive past finalization leaves a fixed set of duckdb objects behind, which +nanobind reports as leaked. Builds without assertions, every wheel among them, stay silent; Debug builds and builds +with FORCE_ASSERT keep the report so that a real leak stays visible there. +""" + +from __future__ import annotations + +import importlib.util +import subprocess +import sys +import sysconfig +import textwrap +from pathlib import Path + +import _duckdb +import pytest + +REPORT = "nanobind: leaked" + + +def _needs(module: str) -> pytest.MarkDecorator: + return pytest.mark.skipif(importlib.util.find_spec(module) is None, reason=f"{module} is not installed") + + +def _run(script: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-c", textwrap.dedent(script)], capture_output=True, text=True, timeout=60, check=False + ) + + +# With numpy imported, typing's globals outlive finalization, and so does the overload registry that holds these +# signatures. +OVERLOAD_SIGNATURE_WITH_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) + """ + +POLARS_FRAME_FROM_RELATION = """ + import duckdb + import polars as pl + + pl.DataFrame(duckdb.connect().sql("select 1 as a")) + """ + +CONNECTION_TYPE_KEPT = """ + import ctypes + + import duckdb + + ctypes.pythonapi.Py_IncRef(ctypes.py_object(duckdb.DuckDBPyConnection)) + """ + +CONNECTION_KEPT = """ + import ctypes + + import duckdb + + ctypes.pythonapi.Py_IncRef(ctypes.py_object(duckdb.connect())) + """ + +HELD_BY_CONSTRUCTION = [ + pytest.param(CONNECTION_TYPE_KEPT, id="connection_type_kept"), + pytest.param(CONNECTION_KEPT, id="connection_kept"), +] + + +@pytest.mark.skipif(_duckdb._assertions, reason="a build with assertions keeps nanobind's leak report") +@pytest.mark.parametrize( + "script", + [ + pytest.param(OVERLOAD_SIGNATURE_WITH_NUMPY, id="overload_signature_with_numpy", marks=_needs("numpy")), + pytest.param(POLARS_FRAME_FROM_RELATION, id="polars_frame_from_relation", marks=_needs("polars")), + *HELD_BY_CONSTRUCTION, + ], +) +def test_objects_held_past_finalization_are_not_reported(script): + proc = _run(script) + assert proc.returncode == 0, proc.stderr[-2000:] + assert REPORT not in proc.stderr, proc.stderr[-2000:] + + +@pytest.mark.skipif(not _duckdb._assertions, reason="a build without assertions silences nanobind's leak report") +@pytest.mark.skipif( + bool(sysconfig.get_config_var("Py_GIL_DISABLED")), reason="nanobind has no leak report on a free threaded build" +) +@pytest.mark.parametrize("script", HELD_BY_CONSTRUCTION) +def test_objects_held_past_finalization_are_reported_with_assertions(script): + proc = _run(script) + assert proc.returncode == 0, proc.stderr[-2000:] + assert REPORT in proc.stderr, proc.stderr[-2000:] + + +def _build_tree_cache() -> dict[str, str] | None: + # An editable install loads the module from below its CMake build directory; an installed wheel has none. + for directory in Path(_duckdb.__file__).resolve().parents[:3]: + cache = directory / "CMakeCache.txt" + if cache.is_file(): + entries = {} + for line in cache.read_text(encoding="utf-8", errors="replace").splitlines(): + key, sep, value = line.partition("=") + if sep and not line.startswith(("#", "//")): + entries[key.split(":", 1)[0]] = value + return entries + return None + + +def _cmake_bool(value: str) -> bool: + # The rule of the $ generator expression that turns FORCE_ASSERT into DUCKDB_FORCE_ASSERT. + false = {"", "0", "false", "off", "n", "no", "ignore", "notfound"} + return value.casefold() not in false and not value.endswith("-NOTFOUND") + + +def test_the_assertions_flag_follows_the_build_configuration(): + cache = _build_tree_cache() + if cache is None: + pytest.skip("the module was not loaded from below a CMake build tree") + if cache.get("CMAKE_CONFIGURATION_TYPES"): + pytest.skip("a multi configuration build tree does not record which configuration the module was built in") + debug = cache.get("CMAKE_BUILD_TYPE", "").casefold() == "debug" + assert _duckdb._assertions is (debug or _cmake_bool(cache.get("FORCE_ASSERT", ""))) diff --git a/tests/slow/test_interpreter_shutdown.py b/tests/slow/test_interpreter_shutdown.py index 9e771ab8d..9be69aeeb 100644 --- a/tests/slow/test_interpreter_shutdown.py +++ b/tests/slow/test_interpreter_shutdown.py @@ -12,6 +12,7 @@ import sys import textwrap +import _duckdb import pytest BODY_DONE = "BODY_DONE" @@ -45,10 +46,14 @@ def _run(script: str, *args: str) -> subprocess.CompletedProcess[str]: ) +def _report(proc: subprocess.CompletedProcess[str]) -> str: + return f"exit status {proc.returncode}\nstdout:\n{proc.stdout[-2000:]}\nstderr:\n{proc.stderr[-2000:]}" + + def _assert_clean_exit( proc: subprocess.CompletedProcess[str], expected_lines: tuple[str, ...], *, leak_free: bool ) -> None: - report = f"exit status {proc.returncode}\nstdout:\n{proc.stdout[-2000:]}\nstderr:\n{proc.stderr[-2000:]}" + report = _report(proc) assert proc.returncode == 0, report lines = proc.stdout.splitlines() assert BODY_DONE in lines, report @@ -56,7 +61,15 @@ def _assert_clean_exit( assert line in lines, report assert "Fatal Python error" not in proc.stderr, report if leak_free: - assert "nanobind: leaked" not in proc.stderr, report + _assert_no_leak_report(proc) + + +def _assert_no_leak_report(*procs: subprocess.CompletedProcess[str]) -> None: + # Skipping ends the test, so a test calls this after its other checks. + if not _duckdb._assertions: + pytest.skip("a build without assertions silences nanobind's leak report") + for proc in procs: + assert "nanobind: leaked" not in proc.stderr, _report(proc) UNLISTED_IMPORT = """ @@ -723,7 +736,8 @@ def test_ordinary_shutdown_checkpoints_default_connection(tmp_path) -> None: duckdb.sql("insert into t values (3)") print("BODY_DONE", flush=True) """ - _assert_clean_exit(_run(script, str(database)), (), leak_free=True) + first = _run(script, str(database)) + _assert_clean_exit(first, (), leak_free=False) assert database.exists() assert not database.with_name(database.name + ".wal").exists() reopen = """ @@ -733,7 +747,9 @@ def test_ordinary_shutdown_checkpoints_default_connection(tmp_path) -> None: print(duckdb.connect(sys.argv[1]).sql("from t order by a").fetchall()) print("BODY_DONE", flush=True) """ - _assert_clean_exit(_run(reopen, str(database)), ("[(0,), (1,), (2,), (3,)]",), leak_free=True) + second = _run(reopen, str(database)) + _assert_clean_exit(second, ("[(0,), (1,), (2,), (3,)]",), leak_free=False) + _assert_no_leak_report(first, second) @pytest.mark.skipif(sys.platform == "win32", reason="ctypes cannot load the C library through a null name on Windows") @@ -750,7 +766,8 @@ def test_c_exit_keeps_committed_data(tmp_path, library: str) -> None: print("BODY_DONE", flush=True) ctypes.{library}(None).exit(0) """ - _assert_clean_exit(_run(script, database), (), leak_free=True) + first = _run(script, database) + _assert_clean_exit(first, (), leak_free=False) reopen = """ import sys import duckdb @@ -758,4 +775,6 @@ def test_c_exit_keeps_committed_data(tmp_path, library: str) -> None: print(duckdb.connect(sys.argv[1]).sql("from t order by a").fetchall()) print("BODY_DONE", flush=True) """ - _assert_clean_exit(_run(reopen, database), ("[(0,), (1,), (2,)]",), leak_free=True) + second = _run(reopen, database) + _assert_clean_exit(second, ("[(0,), (1,), (2,)]",), leak_free=False) + _assert_no_leak_report(first, second) From 846a95fbfc0c72d40c9e332742008f5f923cbc1b Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Tue, 10 Nov 2026 14:18:42 +0000 Subject: [PATCH 52/61] Keep the exit leak checks live through a private switch and give duckdb its own nanobind domain --- .github/actions/build-wheel/action.yml | 3 +- .github/workflows/packaging_sdist.yml | 4 +- .github/workflows/packaging_wheels.yml | 12 ++- CMakeLists.txt | 7 ++ _duckdb-stubs/__init__.pyi | 1 + src/duckdb_python.cpp | 1 + .../arrow/scan/test_python_arrow_scan_core.py | 5 +- .../arrow/test_arrow_single_use_stream.py | 5 +- tests/fast/test_exit_leak_report.py | 81 ++++++++++++++-- tests/slow/test_interpreter_shutdown.py | 97 ++++++++++++++----- 10 files changed, 172 insertions(+), 44 deletions(-) diff --git a/.github/actions/build-wheel/action.yml b/.github/actions/build-wheel/action.yml index e29347c8c..b25bece04 100644 --- a/.github/actions/build-wheel/action.yml +++ b/.github/actions/build-wheel/action.yml @@ -136,7 +136,8 @@ runs: CIBW_BEFORE_TEST: > uv sync --active --inexact --only-group test --no-install-project --directory {project} CIBW_TEST_COMMAND: > - uv run -v pytest --confcutdir=. --rootdir . -c {project}/pyproject.toml ${{ inputs.testsuite == 'fast' && './tests/fast' || './tests' }} + uv run python -c "import _duckdb; assert not _duckdb._assertions, 'the wheel was built with assertions'" + && uv run -v pytest --confcutdir=. --rootdir . -c {project}/pyproject.toml ${{ inputs.testsuite == 'fast' && './tests/fast' || './tests' }} # The stable ABI wheel must import nothing outside the stable ABI, which compiling with Py_LIMITED_API does # not prove for symbols pulled in by inline functions or dependencies. diff --git a/.github/workflows/packaging_sdist.yml b/.github/workflows/packaging_sdist.yml index f3f6e9d84..348efd058 100644 --- a/.github/workflows/packaging_sdist.yml +++ b/.github/workflows/packaging_sdist.yml @@ -85,6 +85,8 @@ jobs: cd ${{ runner.temp }} uv venv uv pip install ${{ github.workspace }}/dist/duckdb-*.tar.gz + # an sdist install is a build without assertions, which keeps nanobind's exit leak report off + uv run python -c "import _duckdb; assert not _duckdb._assertions, 'the sdist was built with assertions'" - name: Test sdist if: ${{ inputs.testsuite != 'none' }} @@ -94,8 +96,6 @@ jobs: # torch release's, for every platform) to compute its hash UV_PROJECT_ENVIRONMENT="${{ runner.temp }}/.venv" uv sync --only-group test --no-install-project --inexact cd ${{ runner.temp }} - # an sdist install is a build without assertions, which keeps nanobind's exit leak report off - uv run python -c "import _duckdb; assert not _duckdb._assertions, 'the sdist was built with assertions'" # run tests tests_root="${{ github.workspace }}/tests" tests_dir="${tests_root}${{ inputs.testsuite == 'fast' && '/fast' || '/' }}" diff --git a/.github/workflows/packaging_wheels.yml b/.github/workflows/packaging_wheels.yml index 055984708..bd9f2cb46 100644 --- a/.github/workflows/packaging_wheels.yml +++ b/.github/workflows/packaging_wheels.yml @@ -251,9 +251,17 @@ jobs: testrun=$(uv run --no-project --python "$venv" python -c 'import tempfile; print(tempfile.mkdtemp(prefix="duckdb-testrun-"))') cp -r tests pyproject.toml "$testrun" cd "$testrun" - uv run --no-project --python "$venv" python -c "import duckdb, sys, os; print(duckdb.__version__, sys.version, os.getcwd())" # A wheel built with assertions would print nanobind's exit leak report to every user. - uv run --no-project --python "$venv" python -c "import _duckdb; assert not _duckdb._assertions, 'the wheel was built with assertions'" + uv run --no-project --python "$venv" python - <<'EOF' + import os + import sys + + import _duckdb + import duckdb + + print(duckdb.__version__, sys.version, os.getcwd()) + assert not _duckdb._assertions, "the wheel was built with assertions" + EOF uv run --no-project --python "$venv" pytest --confcutdir=. --rootdir . -c pyproject.toml ${{ inputs.testsuite == 'fast' && './tests/fast' || './tests' }} test_pandas_2: diff --git a/CMakeLists.txt b/CMakeLists.txt index a9be65d0f..38aa00d50 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -167,6 +167,13 @@ target_include_directories( # link time. No-op on non-Windows. target_compile_definitions(_duckdb_dependencies INTERFACE DUCKDB_STATIC_BUILD) +# NB_DOMAIN gives the module nanobind state of its own: the exit leak report +# flag, the type registry and the exception translators are otherwise shared +# with every nanobind extension in the process that has the same ABI key. It +# must reach the object library that expands NB_MODULE, so it sits here and not +# on nanobind_add_module. +target_compile_definitions(_duckdb_dependencies INTERFACE NB_DOMAIN=duckdb) + foreach(flag IN LISTS DUCKDB_PY_ARCHITECTURE_FLAGS) target_compile_options(_duckdb_dependencies INTERFACE "$<$:${flag}>") diff --git a/_duckdb-stubs/__init__.pyi b/_duckdb-stubs/__init__.pyi index 7e014e9af..0c5ee33ed 100644 --- a/_duckdb-stubs/__init__.pyi +++ b/_duckdb-stubs/__init__.pyi @@ -765,6 +765,7 @@ def string_type(collation: str = "", *, connection: DuckDBPyConnection | None = def struct_type(fields: IntoFields, *, connection: DuckDBPyConnection | None = None) -> sqltypes.DuckDBPyType: ... def tf(*, connection: DuckDBPyConnection | None = None) -> dict[str, typing.Any]: ... def _set_arrow_sources(sources: object) -> None: ... +def _set_leak_report(enabled: bool) -> None: ... def _literal_type(value: object) -> str: ... def _value_literal(value: object) -> str: ... def _collation(type: sqltypes.DuckDBPyType) -> str | None: ... diff --git a/src/duckdb_python.cpp b/src/duckdb_python.cpp index 8205da792..bc1fdadac 100644 --- a/src/duckdb_python.cpp +++ b/src/duckdb_python.cpp @@ -789,6 +789,7 @@ NB_MODULE(DUCKDB_PYTHON_LIB_NAME, m) { // NOLINT "used for e.g., syntax highlighting", nb::arg("query")); m.def("_set_arrow_sources", &DuckDBPyConnection::SetArrowSources, nb::arg("sources")); + m.def("_set_leak_report", [](bool enabled) { nb::set_leak_warnings(enabled); }, nb::arg("enabled")); m.def("_translate_predicate", &TranslatePredicateForTesting, nb::arg("connection"), nb::arg("predicate"), nb::arg("columns").none() = nb::none(), nb::arg("schema").none() = nb::none(), nb::arg("select") = "*"); nb::enum_(m, "token_type") diff --git a/tests/fast/arrow/scan/test_python_arrow_scan_core.py b/tests/fast/arrow/scan/test_python_arrow_scan_core.py index 2759f9633..58417196c 100644 --- a/tests/fast/arrow/scan/test_python_arrow_scan_core.py +++ b/tests/fast/arrow/scan/test_python_arrow_scan_core.py @@ -21,7 +21,6 @@ from pathlib import Path from typing import ClassVar -import _duckdb import pytest import duckdb @@ -2544,6 +2543,8 @@ def test_interpreter_exit(self, state): module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) import duckdb, pyarrow as pa +import _duckdb +_duckdb._set_leak_report(True) table = pa.table({{"i": list(range(50_000))}}) con = duckdb.connect(config={{"threads": 4}}) if {state!r} in ("registered_reader", "reader_read_with_limit"): @@ -2564,8 +2565,6 @@ def test_interpreter_exit(self, state): assert completed.returncode == 0, completed.stderr[-2000:] assert "exiting" in completed.stdout if state != "retained_result": - if not _duckdb._assertions: - pytest.skip("a build without assertions silences nanobind's leak report") assert "nanobind: leaked" not in completed.stderr @pytest.mark.timeout(120) diff --git a/tests/fast/arrow/test_arrow_single_use_stream.py b/tests/fast/arrow/test_arrow_single_use_stream.py index 07bc90d26..2c0cd0315 100644 --- a/tests/fast/arrow/test_arrow_single_use_stream.py +++ b/tests/fast/arrow/test_arrow_single_use_stream.py @@ -17,7 +17,6 @@ import time from collections import Counter -import _duckdb import pytest import duckdb @@ -172,6 +171,8 @@ def scan(index): with mock.patch.dict(sys.modules): import duckdb + import _duckdb + _duckdb._set_leak_report(True) table = pa.table({{"id": [1, 2, 3]}}) sink = io.BytesIO() with pa.ipc.new_stream(sink, table.schema) as writer: @@ -615,8 +616,6 @@ def test_scan_after_the_module_left_sys_modules(self): assert "first 3" in completed.stdout assert "second raised True" in completed.stdout assert "already registered" not in completed.stderr - if not _duckdb._assertions: - pytest.skip("a build without assertions silences nanobind's leak report") assert "nanobind: leaked" not in completed.stderr diff --git a/tests/fast/test_exit_leak_report.py b/tests/fast/test_exit_leak_report.py index d01b6e9bb..c4842a95c 100644 --- a/tests/fast/test_exit_leak_report.py +++ b/tests/fast/test_exit_leak_report.py @@ -2,12 +2,16 @@ A package that keeps a module's globals alive past finalization leaves a fixed set of duckdb objects behind, which nanobind reports as leaked. Builds without assertions, every wheel among them, stay silent; Debug builds and builds -with FORCE_ASSERT keep the report so that a real leak stays visible there. +with FORCE_ASSERT keep the report so that a real leak stays visible there. The private switch +``_duckdb._set_leak_report`` turns the report on or off in any build, and the module's own nanobind domain keeps the +flag apart from other nanobind extensions in the process. """ from __future__ import annotations +import ctypes import importlib.util +import platform import subprocess import sys import sysconfig @@ -19,14 +23,39 @@ REPORT = "nanobind: leaked" +# A core dump of a process with hundreds of engine threads takes minutes to write. +NO_CORE_DUMP = """ + import resource + + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + """ + +REPORT_ON = """ + import _duckdb + + _duckdb._set_leak_report(True) + """ + +REPORT_OFF = """ + import _duckdb + + _duckdb._set_leak_report(False) + """ + def _needs(module: str) -> pytest.MarkDecorator: return pytest.mark.skipif(importlib.util.find_spec(module) is None, reason=f"{module} is not installed") -def _run(script: str) -> subprocess.CompletedProcess[str]: +def _join(*parts: str) -> str: + return "".join(textwrap.dedent(part) for part in parts) + + +def _run(*parts: str) -> subprocess.CompletedProcess[str]: + if sys.platform != "win32": + parts = (NO_CORE_DUMP, *parts) return subprocess.run( - [sys.executable, "-c", textwrap.dedent(script)], capture_output=True, text=True, timeout=60, check=False + [sys.executable, "-c", _join(*parts)], capture_output=True, text=True, timeout=60, check=False ) @@ -50,7 +79,7 @@ def connect(database): import duckdb import polars as pl - pl.DataFrame(duckdb.connect().sql("select 1 as a")) + pl.DataFrame(duckdb.connect(config={"threads": 1}).sql("select 1 as a")) """ CONNECTION_TYPE_KEPT = """ @@ -66,7 +95,7 @@ def connect(database): import duckdb - ctypes.pythonapi.Py_IncRef(ctypes.py_object(duckdb.connect())) + ctypes.pythonapi.Py_IncRef(ctypes.py_object(duckdb.connect(config={"threads": 1}))) """ HELD_BY_CONSTRUCTION = [ @@ -74,6 +103,10 @@ def connect(database): pytest.param(CONNECTION_KEPT, id="connection_kept"), ] +no_report_on_a_free_threaded_build = pytest.mark.skipif( + bool(sysconfig.get_config_var("Py_GIL_DISABLED")), reason="nanobind has no leak report on a free threaded build" +) + @pytest.mark.skipif(_duckdb._assertions, reason="a build with assertions keeps nanobind's leak report") @pytest.mark.parametrize( @@ -91,9 +124,7 @@ def test_objects_held_past_finalization_are_not_reported(script): @pytest.mark.skipif(not _duckdb._assertions, reason="a build without assertions silences nanobind's leak report") -@pytest.mark.skipif( - bool(sysconfig.get_config_var("Py_GIL_DISABLED")), reason="nanobind has no leak report on a free threaded build" -) +@no_report_on_a_free_threaded_build @pytest.mark.parametrize("script", HELD_BY_CONSTRUCTION) def test_objects_held_past_finalization_are_reported_with_assertions(script): proc = _run(script) @@ -101,6 +132,40 @@ def test_objects_held_past_finalization_are_reported_with_assertions(script): assert REPORT in proc.stderr, proc.stderr[-2000:] +@no_report_on_a_free_threaded_build +@pytest.mark.parametrize("script", HELD_BY_CONSTRUCTION) +def test_the_switch_turns_the_report_on_in_every_build(script): + proc = _run(REPORT_ON, script) + assert proc.returncode == 0, proc.stderr[-2000:] + assert REPORT in proc.stderr, proc.stderr[-2000:] + + +@pytest.mark.parametrize("script", HELD_BY_CONSTRUCTION) +def test_the_switch_turns_the_report_off_in_every_build(script): + proc = _run(REPORT_OFF, script) + assert proc.returncode == 0, proc.stderr[-2000:] + assert REPORT not in proc.stderr, proc.stderr[-2000:] + + +def _nanobind_internals_keys() -> list[str]: + # nanobind keeps one state record per domain in the interpreter's state dict, under a key that ends in the domain. + get_state, get_dict = ctypes.pythonapi.PyInterpreterState_Get, ctypes.pythonapi.PyInterpreterState_GetDict + saved = (get_state.restype, get_dict.restype, get_dict.argtypes) + try: + get_state.restype = get_dict.restype = ctypes.c_void_p + get_dict.argtypes = [ctypes.c_void_p] + state = ctypes.cast(get_dict(get_state()), ctypes.py_object).value + finally: + get_state.restype, get_dict.restype, get_dict.argtypes = saved + return [key for key in state if isinstance(key, str) and key.startswith("__nb_internals_")] + + +@pytest.mark.skipif(platform.python_implementation() != "CPython", reason="reads CPython's interpreter state dict") +def test_the_module_has_its_own_nanobind_domain(): + keys = _nanobind_internals_keys() + assert any(key.endswith("_duckdb__") for key in keys), keys + + def _build_tree_cache() -> dict[str, str] | None: # An editable install loads the module from below its CMake build directory; an installed wheel has none. for directory in Path(_duckdb.__file__).resolve().parents[:3]: diff --git a/tests/slow/test_interpreter_shutdown.py b/tests/slow/test_interpreter_shutdown.py index 9be69aeeb..9135e270d 100644 --- a/tests/slow/test_interpreter_shutdown.py +++ b/tests/slow/test_interpreter_shutdown.py @@ -12,7 +12,6 @@ import sys import textwrap -import _duckdb import pytest BODY_DONE = "BODY_DONE" @@ -46,14 +45,10 @@ def _run(script: str, *args: str) -> subprocess.CompletedProcess[str]: ) -def _report(proc: subprocess.CompletedProcess[str]) -> str: - return f"exit status {proc.returncode}\nstdout:\n{proc.stdout[-2000:]}\nstderr:\n{proc.stderr[-2000:]}" - - def _assert_clean_exit( proc: subprocess.CompletedProcess[str], expected_lines: tuple[str, ...], *, leak_free: bool ) -> None: - report = _report(proc) + report = f"exit status {proc.returncode}\nstdout:\n{proc.stdout[-2000:]}\nstderr:\n{proc.stderr[-2000:]}" assert proc.returncode == 0, report lines = proc.stdout.splitlines() assert BODY_DONE in lines, report @@ -61,15 +56,9 @@ def _assert_clean_exit( assert line in lines, report assert "Fatal Python error" not in proc.stderr, report if leak_free: - _assert_no_leak_report(proc) - - -def _assert_no_leak_report(*procs: subprocess.CompletedProcess[str]) -> None: - # Skipping ends the test, so a test calls this after its other checks. - if not _duckdb._assertions: - pytest.skip("a build without assertions silences nanobind's leak report") - for proc in procs: - assert "nanobind: leaked" not in proc.stderr, _report(proc) + # A build without assertions turns the report off; a child checked for it turns it back on after its import. + assert "_set_leak_report(True)" in proc.args[2], "the child did not turn nanobind's leak report on" + assert "nanobind: leaked" not in proc.stderr, report UNLISTED_IMPORT = """ @@ -92,6 +81,9 @@ def holder(): DROP_CLEANUP_CAPSULE = """ import sys import duckdb +import _duckdb + +_duckdb._set_leak_report(True) before = duckdb.default_connection() del duckdb._clean_default_connection @@ -181,6 +173,9 @@ def test_module_outside_sys_modules_keeps_committed_data(tmp_path) -> None: reopen = """ import sys import duckdb + import _duckdb + + _duckdb._set_leak_report(True) print(duckdb.connect(sys.argv[1]).sql("from t").fetchall()) print("BODY_DONE", flush=True) @@ -255,6 +250,9 @@ def test_state_recreated_after_release(script: str) -> None: pytest.param( """ import duckdb + import _duckdb + + _duckdb._set_leak_report(True) assert duckdb.sql("select 42").fetchall() == [(42,)] print("BODY_DONE", flush=True) @@ -266,6 +264,9 @@ def test_state_recreated_after_release(script: str) -> None: pytest.param( """ import duckdb + import _duckdb + + _duckdb._set_leak_report(True) import pandas as pd import pyarrow as pa @@ -291,6 +292,9 @@ def late(): atexit.register(late) import duckdb + import _duckdb + + _duckdb._set_leak_report(True) duckdb.sql("select 1").fetchall() print("BODY_DONE", flush=True) @@ -313,6 +317,9 @@ def late(): atexit.register(late) import duckdb + import _duckdb + + _duckdb._set_leak_report(True) duckdb.sql("select 1").fetchall() print("BODY_DONE", flush=True) @@ -326,6 +333,9 @@ def late(): """ import atexit import duckdb + import _duckdb + + _duckdb._set_leak_report(True) import pyarrow as pa tbl = pa.table({"a": [1, 2, 3]}) @@ -345,6 +355,9 @@ def late(): """ import atexit import duckdb + import _duckdb + + _duckdb._set_leak_report(True) import pyarrow as pa tbl = pa.table({"a": [1, 2, 3]}) @@ -390,6 +403,9 @@ def late(): pytest.param( """ import duckdb + import _duckdb + + _duckdb._set_leak_report(True) class Finalized: def __del__(self): @@ -406,6 +422,9 @@ def __del__(self): """ import builtins import duckdb + import _duckdb + + _duckdb._set_leak_report(True) class Finalized: def __del__(self): @@ -421,6 +440,9 @@ def __del__(self): pytest.param( """ import duckdb + import _duckdb + + _duckdb._set_leak_report(True) rel = duckdb.sql("select 42") con = duckdb.connect() @@ -434,6 +456,9 @@ def __del__(self): pytest.param( """ import duckdb + import _duckdb + + _duckdb._set_leak_report(True) import pandas as pd import pyarrow as pa @@ -454,6 +479,9 @@ def __del__(self): """ import io import duckdb + import _duckdb + + _duckdb._set_leak_report(True) rel = duckdb.read_csv(io.BytesIO(b"a\\n1\\n2\\n")) assert rel.fetchall() == [(1,), (2,)] @@ -501,6 +529,9 @@ def work(): import atexit import threading import duckdb + import _duckdb + + _duckdb._set_leak_report(True) import pyarrow as pa tbl = pa.table({"a": [1, 2, 3]}) @@ -525,6 +556,9 @@ def work(): pytest.param( """ import duckdb + import _duckdb + + _duckdb._set_leak_report(True) import numpy as np import pandas as pd @@ -554,6 +588,9 @@ def work(): """ import signal import duckdb + import _duckdb + + _duckdb._set_leak_report(True) import numpy as np import pandas as pd @@ -585,6 +622,9 @@ def work(): """ import signal import duckdb + import _duckdb + + _duckdb._set_leak_report(True) import numpy as np import pandas as pd import pyarrow as pa @@ -612,6 +652,9 @@ def work(): pytest.param( """ import duckdb + import _duckdb + + _duckdb._set_leak_report(True) import numpy as np import pyarrow as pa import pyarrow.compute as pc @@ -730,26 +773,29 @@ def test_ordinary_shutdown_checkpoints_default_connection(tmp_path) -> None: script = """ import sys import duckdb + import _duckdb + + _duckdb._set_leak_report(True) duckdb.set_default_connection(duckdb.connect(sys.argv[1])) duckdb.sql("create table t as select range as a from range(3)") duckdb.sql("insert into t values (3)") print("BODY_DONE", flush=True) """ - first = _run(script, str(database)) - _assert_clean_exit(first, (), leak_free=False) + _assert_clean_exit(_run(script, str(database)), (), leak_free=True) assert database.exists() assert not database.with_name(database.name + ".wal").exists() reopen = """ import sys import duckdb + import _duckdb + + _duckdb._set_leak_report(True) print(duckdb.connect(sys.argv[1]).sql("from t order by a").fetchall()) print("BODY_DONE", flush=True) """ - second = _run(reopen, str(database)) - _assert_clean_exit(second, ("[(0,), (1,), (2,), (3,)]",), leak_free=False) - _assert_no_leak_report(first, second) + _assert_clean_exit(_run(reopen, str(database)), ("[(0,), (1,), (2,), (3,)]",), leak_free=True) @pytest.mark.skipif(sys.platform == "win32", reason="ctypes cannot load the C library through a null name on Windows") @@ -766,15 +812,16 @@ def test_c_exit_keeps_committed_data(tmp_path, library: str) -> None: print("BODY_DONE", flush=True) ctypes.{library}(None).exit(0) """ - first = _run(script, database) - _assert_clean_exit(first, (), leak_free=False) + # The C exit skips Py_FinalizeEx, so nanobind's report never runs and a leak check here could not fail. + _assert_clean_exit(_run(script, database), (), leak_free=False) reopen = """ import sys import duckdb + import _duckdb + + _duckdb._set_leak_report(True) print(duckdb.connect(sys.argv[1]).sql("from t order by a").fetchall()) print("BODY_DONE", flush=True) """ - second = _run(reopen, database) - _assert_clean_exit(second, ("[(0,), (1,), (2,)]",), leak_free=False) - _assert_no_leak_report(first, second) + _assert_clean_exit(_run(reopen, database), ("[(0,), (1,), (2,)]",), leak_free=True) From 96dbebb1e4a867a7e5d3f05b7d1f97840dcd23e1 Mon Sep 17 00:00:00 2001 From: DuckDB Labs GitHub Bot Date: Fri, 20 Nov 2026 13:36:11 +0000 Subject: [PATCH 53/61] Bump release_version to 2.0.2 after releasing 2.0.1 --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index f5fbd1a5d..36ed90942 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -110,7 +110,7 @@ DUCKDB_PY_LTO = "" # The version this branch releases next. A release forces exactly this version, a # dev build appends .dev of the latest commit across this repository # and the DuckDB submodule. Bump it right after every release from this branch. -release_version = "2.0.1" +release_version = "2.0.2" [[tool.scikit-build.overrides]] if.env.CIBUILDWHEEL_BUILD_IDENTIFIER = true From f0bec5bf3b33e219d96ec3b1222f369382f6c1f0 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Mon, 23 Nov 2026 16:53:19 +0000 Subject: [PATCH 54/61] Let the atexit hook leave open a result whose connection a stuck thread holds --- AGENTS.md | 13 +- src/arrow/python_arrow_scan.cpp | 7 +- src/engine/result.cpp | 81 +++++--- src/include/duckdb_python/engine/result.hpp | 4 +- tests/slow/test_exit_with_open_results.py | 195 +++++++++++++++++++- 5 files changed, 261 insertions(+), 39 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c519b76ca..4a06749cb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -310,15 +310,20 @@ touches the GIL against all five. 4. **A Python error never leaves an engine task as a Python object.** Convert it under the GIL with `AsDuckDBError` (map, UDFs, the numpy scans, the Python file system do). The engine stores and formats errors later on any thread without the GIL; a `nb::python_error` there needs the GIL at a moment nobody can give it. -5. **Shutdown has an order.** The atexit hook (`OnInterpreterExit`) calls `engine::BeginExit`, then ends every live - result (`engine::Result::Live`, `EndIfRunning`) with the GIL released so their tasks can finish. From then on only +5. **Shutdown has an order.** The atexit hook (`OnInterpreterExit`) calls `engine::BeginExit`, then ends the live + results (`engine::Result::Live`, `engine::Result::EndAtExit`) with the GIL released so their tasks can finish: it + interrupts the query of every running result, retries the claims of their connections without blocking until + none is refused or one second has passed, closes each result still running once its claim is taken and clears + that connection's interrupt, and leaves the others open. From then on only the exit thread's own queries may enter Python; a query another thread starts late fails at the gate with "the Python interpreter is shutting down". Once `Py_IsInitialized()` is false, CPython still lets the exit thread in and so does the gate, but what that thread opens then admits no other thread; every other thread is refused. Results join the registry through `Result::Register` at submit and leave in their destructor. -Known gaps: five destructors reach Python through nanobind's cleanup guard during finalization; before Python 3.13 a -daemon thread woken after finalization aborts through the engine's frames (tests skip those cases on 3.12). +Known gaps: five destructors reach Python through nanobind's cleanup guard during finalization; the close of a +running result waits for every task of its query, so an engine worker stuck in a read no interrupt reaches holds +up the exit until the read returns; before Python 3.13 a daemon thread woken after finalization aborts through the +engine's frames (tests skip those cases on 3.12). ## Project structure diff --git a/src/arrow/python_arrow_scan.cpp b/src/arrow/python_arrow_scan.cpp index ba74e3c1a..956edbfce 100644 --- a/src/arrow/python_arrow_scan.cpp +++ b/src/arrow/python_arrow_scan.cpp @@ -93,12 +93,7 @@ void OnInterpreterExit() { auto results = engine::Result::Live(); { nb::gil_scoped_release release; - for (auto &result : results) { - try { - result->EndIfRunning(); - } catch (...) { // NOLINT: a result that fails to end must not keep the others running - } - } + engine::Result::EndAtExit(results); // Not bounded: a call let in may need the GIL again before it returns, which it never gets once the // interpreter finalizes, so a slow source delays the exit instead of hanging it. while (calls_in_flight.load() > 0) { diff --git a/src/engine/result.cpp b/src/engine/result.cpp index d23502845..c0b8fe7ba 100644 --- a/src/engine/result.cpp +++ b/src/engine/result.cpp @@ -5,6 +5,7 @@ #include "duckdb/common/arrow/arrow_converter.hpp" #include "duckdb/common/arrow/nanoarrow/nanoarrow.hpp" #include "duckdb/common/enums/query_result_state.hpp" +#include "duckdb/common/unordered_map.hpp" #include "duckdb/common/unordered_set.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/database.hpp" @@ -507,37 +508,67 @@ void Result::Close() { state = State::CLOSED; } -void Result::EndIfRunning() { +void Result::EndAtExit(const vector> &results) { DUCKDB_PY_ASSERT_GIL_RELEASED(); - auto context = context_owner.lock(); - if (!context) { - return; - } - // A claim another thread holds is waited for one second after interrupting its query; past that, closing - // unclaimed beats hanging the exit - unique_ptr claim; - auto try_claim = [&]() { - try { - claim = make_uniq(*connection_state, *context); - } catch (ResourceInUseException &) { // NOLINT: another thread holds the claim - } - return claim != nullptr; + struct Ending { + Result &result; + shared_ptr context; + bool unclaimable = false; }; - if (!try_claim()) { - if (!Running()) { - return; + vector running; + for (auto &result : results) { + auto context = result->context_owner.lock(); + if (!context) { + continue; } - const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(1); - do { + if (result->state == State::PENDING || result->state == State::STREAMING) { + // Only a query that may still run; a compare and swap without a lock, so it reaches a query whose thread + // holds the context lock in a task context->Interrupt(); - if (std::chrono::steady_clock::now() >= deadline) { - break; + running.push_back({*result, std::move(context), false}); + } + } + // One claim per connection, since its results share it; one second for the whole hook, since a claim another + // thread holds frees only when that thread's call ends + unordered_map> claims; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(1); + while (true) { + bool waiting = false; + for (auto &entry : running) { + auto &claim = claims[entry.result.connection_state.get()]; + if (claim || entry.unclaimable) { + continue; + } + try { + claim = make_uniq(*entry.result.connection_state, *entry.context); + } catch (ResourceInUseException &) { // NOLINT: another thread holds the claim + waiting = true; + } catch (...) { // NOLINT: a result that cannot be claimed must not keep the others from ending + entry.unclaimable = true; } - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } while (!try_claim()); + } + if (!waiting || std::chrono::steady_clock::now() >= deadline) { + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); } - if (Running()) { - Close(); + for (auto &entry : running) { + // Left open when its claim never freed: closing would wait for the context lock, held through a task that no + // interrupt reaches, such as a blocking read + if (!claims[entry.result.connection_state.get()]) { + continue; + } + // Under the claim no other call can complete the query, so a result that completed while the hook waited is + // not closed + if (entry.result.state == State::PENDING || entry.result.state == State::STREAMING) { + try { + entry.result.Close(); + } catch (...) { // NOLINT: a result that fails to end must not keep the others running + } + } + // The engine clears the flag only when a statement or a transaction begins, and a later exit handler can bind + // inside an open transaction before either + entry.context->ClearInterrupt(); } } diff --git a/src/include/duckdb_python/engine/result.hpp b/src/include/duckdb_python/engine/result.hpp index feb5cadd2..a65f1c32f 100644 --- a/src/include/duckdb_python/engine/result.hpp +++ b/src/include/duckdb_python/engine/result.hpp @@ -133,7 +133,9 @@ class Result : public enable_shared_from_this { //! Ends the query if it is still running. Idempotent, and safe while another thread is fetching. void Close(); - void EndIfRunning(); + //! For the exit hook: interrupts every running result's query, then ends each one whose connection comes free + //! within one second; the others are left open + static void EndAtExit(const vector> &results); //! Called once the shared owner exists, which Live needs static void Register(const shared_ptr &result); static vector> Live(); diff --git a/tests/slow/test_exit_with_open_results.py b/tests/slow/test_exit_with_open_results.py index 3a6cdf32f..a9b962c89 100644 --- a/tests/slow/test_exit_with_open_results.py +++ b/tests/slow/test_exit_with_open_results.py @@ -7,9 +7,11 @@ from __future__ import annotations import importlib.util +import os import subprocess import sys import textwrap +import time import pytest @@ -35,16 +37,16 @@ """ -def _run(body: str, *, head: str = FRAME) -> subprocess.CompletedProcess[str]: +def _run(body: str, *, head: str = FRAME, timeout: float = DEADLINE) -> subprocess.CompletedProcess[str]: script = textwrap.dedent(head) + textwrap.dedent(body) + f"\nprint({BODY_DONE!r}, flush=True)\n" try: return subprocess.run( [sys.executable, "-u", "-c", script], capture_output=True, text=True, - timeout=DEADLINE, + timeout=timeout, check=False, - env={"SKBUILD_EDITABLE_VERBOSE": "0", **__import__("os").environ}, + env={"SKBUILD_EDITABLE_VERBOSE": "0", **os.environ}, ) except subprocess.TimeoutExpired as hang: stdout = hang.stdout.decode() if isinstance(hang.stdout, bytes) else hang.stdout or "" @@ -180,6 +182,155 @@ def work(): """ _assert_exit(_run(body)) + def test_a_sort_left_open_by_the_main_thread_is_interrupted_before_its_close(self) -> None: + # Its workers check the interrupt and not the cancel, so without the interrupt the close waits for the sort + body = """ + import time + + query = "SELECT * FROM range(3) t(i) UNION ALL (SELECT i FROM range(100_000_000) t(i) ORDER BY hash(i))" + for _ in range(5): + con = duckdb.connect(config={"threads": 4, "memory_limit": "2GB"}) + con.execute("SET enable_progress_bar = false") + started = time.time() + con.execute(query) + print("FIRST", con.fetchone(), flush=True) + # A slow first row means the fetching thread ran the sort itself and left nothing to interrupt + if time.time() - started < 1: + print("WORKERS_SORT", flush=True) + break + con.close() + # Lets the engine workers take up the sort before the main thread returns + time.sleep(1) + print("MAIN_RETURNS", time.time(), flush=True) + """ + proc = _run(body, head="import duckdb\n", timeout=120) + exited = time.time() + _assert_exit(proc) + assert "WORKERS_SORT" in proc.stdout.splitlines(), proc.stdout + returned = next(float(line.split()[1]) for line in proc.stdout.splitlines() if line.startswith("MAIN_RETURNS")) + assert exited - returned < 2.5, f"exit took {exited - returned:.1f} s after the main thread" + + +NEEDS_FIFO = pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="needs a FIFO") + + +class TestQueryRunningOnAnotherThread: + # The hook's own bound is one second; the rest covers finalization and process teardown on a slow runner. + EXIT_BOUND = 10 + + def _exit_wait(self, fifo: os.PathLike[str], body: str) -> tuple[subprocess.CompletedProcess[str], float]: + os.mkfifo(fifo) + # Open and silent for as long as the child lives, so its read of the FIFO never returns + writer = os.open(fifo, os.O_RDWR | os.O_NONBLOCK) + try: + proc = _run(body, head="import duckdb\n", timeout=3 * self.EXIT_BOUND) + exited = time.time() + finally: + os.close(writer) + _assert_exit(proc) + returned = next(float(line.split()[1]) for line in proc.stdout.splitlines() if line.startswith("MAIN_RETURNS")) + return proc, exited - returned + + def _assert_bounded(self, wait: float) -> None: + # Sooner than the hook's one second means nothing was stuck in the read when the process exited + assert 1 <= wait < self.EXIT_BOUND, f"exit took {wait:.1f} s after the main thread" + + @NEEDS_FIFO + @pytest.mark.parametrize( + "threads", + [ + # The daemon thread runs the blocked scan itself and holds the engine's context lock while it reads + pytest.param(1, id="read_on_the_fetching_thread"), + # An engine worker or the fetching thread runs the scan, whichever takes its one task first + pytest.param(4, id="four_threads"), + ], + ) + def test_a_read_no_interrupt_reaches_does_not_hold_up_the_exit(self, tmp_path, threads: int) -> None: + fifo = tmp_path / "silent.fifo" + body = f""" + import threading + import time + + con = duckdb.connect(config={{"threads": {threads}}}) + con.execute("SET enable_progress_bar = false") + query = "SELECT * FROM read_text('{fifo}')" + + def read(): + try: + con.sql(query).fetchall() + finally: + print("READ_ENDED", flush=True) + + threading.Thread(target=read, daemon=True).start() + time.sleep(1) + print("MAIN_RETURNS", time.time(), flush=True) + """ + proc, wait = self._exit_wait(fifo, body) + assert "READ_ENDED" not in proc.stdout, proc.stdout + self._assert_bounded(wait) + + def test_an_interruptible_query_on_another_thread_is_interrupted(self) -> None: + # Registered before the import, so it runs after duckdb's exit hook and reports what the daemon thread saw + handler = """ + import atexit + import threading + + state = {"done": threading.Event()} + + def after(): + state["done"].wait(30) + print("DAEMON", state.get("outcome"), flush=True) + print("LATER", state["con"].execute("SELECT 42").fetchall(), flush=True) + + atexit.register(after) + """ + body = """ + import time + + con = duckdb.connect(config={"threads": 1}) + con.execute("SET enable_progress_bar = false") + state["con"] = con + query = "SELECT count(*) FROM range(10_000_000_000_000) t(i) WHERE i % 7 = 3" + started = threading.Event() + + def work(): + started.set() + try: + state["outcome"] = con.sql(query).fetchall() + except duckdb.Error as error: + state["outcome"] = type(error).__name__ + state["done"].set() + + threading.Thread(target=work, daemon=True).start() + started.wait() + time.sleep(0.5) + """ + proc = _run(body, head=textwrap.dedent(handler) + "import duckdb\n") + _assert_exit(proc) + assert "DAEMON InterruptException" in proc.stdout.splitlines(), proc.stdout + assert "LATER [(42,)]" in proc.stdout.splitlines(), proc.stdout + + @NEEDS_FIFO + def test_reads_stuck_on_several_connections_share_the_hooks_one_second(self, tmp_path) -> None: + fifo = tmp_path / "silent.fifo" + body = f""" + import threading + import time + + def read(): + con = duckdb.connect(config={{"threads": 1}}) + con.execute("SET enable_progress_bar = false") + con.sql("SELECT * FROM read_text('{fifo}')").fetchall() + + # More connections than the class's bound has seconds, so a bound per result cannot pass + for _ in range(12): + threading.Thread(target=read, daemon=True).start() + time.sleep(1) + print("MAIN_RETURNS", time.time(), flush=True) + """ + _, wait = self._exit_wait(fifo, body) + self._assert_bounded(wait) + class TestAfterTheHook: def test_a_later_exit_handler_still_runs_a_statement(self) -> None: @@ -258,6 +409,44 @@ def query_after_the_hook(): assert outcome.startswith("DAEMON InvalidInputException: "), proc.stdout assert outcome.endswith("the Python interpreter is shutting down"), proc.stdout + @pytest.mark.parametrize( + "left_open", + [ + pytest.param("", id="nothing_running"), + pytest.param( + """ + con.execute("SELECT * FROM range(100_000_000)") + print("FIRST", con.fetchone(), flush=True) + """, + id="streaming_result", + ), + ], + ) + def test_a_later_exit_handler_binds_inside_an_open_transaction(self, left_open: str) -> None: + # Registered before the import, so it runs after duckdb's exit hook; inside a transaction the engine clears an + # interrupt only when a statement starts, and binding the macro checks it before that + handler = """ + import atexit + + state = {} + + def after(): + print("LATER", state["con"].sql("SELECT answer()").fetchall(), flush=True) + + atexit.register(after) + """ + body = """ + con = duckdb.connect(config={"threads": 1}) + state["con"] = con + con.execute("CREATE MACRO answer() AS 42") + con.execute("BEGIN") + """ + proc = _run( + textwrap.dedent(body) + textwrap.dedent(left_open), head=textwrap.dedent(handler) + "import duckdb\n" + ) + _assert_exit(proc) + assert "LATER [(42,)]" in proc.stdout.splitlines(), proc.stdout + class TestUnchangedExits: @pytest.mark.parametrize( From e2379b4754b6632653e6e87e36a90080e423f574 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Wed, 25 Nov 2026 04:52:14 +0000 Subject: [PATCH 55/61] Push the comparisons polars 2.2 folds into the lazy frame scan --- duckdb/polars_io.py | 73 +++++++++++- .../arrow/test_polars_pushdown_literals.py | 110 ++++++++++++++++++ 2 files changed, 182 insertions(+), 1 deletion(-) diff --git a/duckdb/polars_io.py b/duckdb/polars_io.py index 87ce06760..7572e0cb3 100644 --- a/duckdb/polars_io.py +++ b/duckdb/polars_io.py @@ -331,12 +331,72 @@ def _comparison_to_sql( return f"({_operand_to_sql(lhs, schema)} {sql_op} {_operand_to_sql(rhs, schema)})" +_COMPARISONS = frozenset({"Eq", "NotEq", "Lt", "LtEq", "Gt", "GtEq"}) +_BOOLEAN_SCALARS = ({"Boolean": True}, {"Boolean": False}, {"Null": "Boolean"}) + + +def _is_null_cast_to_boolean(tree: _ExpressionTree) -> bool: + """Whether the node is the cast of an untyped NULL to Boolean that ends a when/then without otherwise.""" + cast = tree.get("Cast") + return ( + isinstance(cast, dict) + and cast.get("dtype") == {"Literal": "Boolean"} + and cast.get("expr") == {"Literal": {"Scalar": {"Null": "Null"}}} + ) + + +def _is_boolean(tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | None) -> bool: + """Whether polars types the node Boolean before it evaluates it. + + That is a comparison, an And or Or of Booleans, a null test, a Boolean literal or column, the cast of an untyped + NULL to Boolean, or a Ternary of Booleans. + """ + ternary = tree.get("Ternary") + if isinstance(ternary, dict): + return all(isinstance(part, dict) and _is_boolean(part, schema) for part in ternary.values()) + bin_expr = tree.get("BinaryExpr") + if isinstance(bin_expr, dict): + lhs, op, rhs = bin_expr.get("left"), bin_expr.get("op"), bin_expr.get("right") + if op in ("And", "Or"): + return ( + isinstance(lhs, dict) + and isinstance(rhs, dict) + and _is_boolean(lhs, schema) + and _is_boolean(rhs, schema) + ) + return op in _COMPARISONS + function = tree.get("Function") + if isinstance(function, dict): + return function.get("function") in ({"Boolean": "IsNull"}, {"Boolean": "IsNotNull"}) + column = tree.get("Column") + if isinstance(column, str): + return schema is not None and schema.get(column) == pl.Boolean + literal = tree.get("Literal") + if isinstance(literal, dict): + return literal.get("Scalar") in _BOOLEAN_SCALARS + return _is_null_cast_to_boolean(tree) + + def _predicate_to_sql(tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | None = None) -> str: """Convert a Boolean polars expression tree, a filter predicate or a conjunct of one, to a SQL string. polars applies And and Or bitwise to integers but types them Boolean only between Boolean operands, and a filter - predicate is Boolean, so an And or Or is SQL's AND or OR here and in its operands, and nowhere below. + predicate is Boolean, so an And or Or is SQL's AND or OR here and in its operands, and nowhere below. A Ternary is a + CASE here, where both send a NULL condition to the last branch, but only when polars types its condition and + branches Boolean: polars checks them only when it evaluates them, which it never does for a predicate the source + took, and the engine reads a nonzero integer as true. """ + ternary = tree.get("Ternary") + if isinstance(ternary, dict): + if not _is_boolean(tree, schema): + msg = "A when/then that polars does not type Boolean throughout cannot be pushed down" + raise NotImplementedError(msg) + when, then, otherwise = ternary["predicate"], ternary["truthy"], ternary["falsy"] + assert isinstance(when, dict), f"The predicate of a Ternary should be a dict but got {type(when)}" + assert isinstance(then, dict), f"The truthy branch of a Ternary should be a dict but got {type(then)}" + assert isinstance(otherwise, dict), f"The falsy branch of a Ternary should be a dict but got {type(otherwise)}" + when_sql, then_sql = _predicate_to_sql(when, schema), _predicate_to_sql(then, schema) + return f"(CASE WHEN {when_sql} THEN {then_sql} ELSE {_predicate_to_sql(otherwise, schema)} END)" bin_expr = tree.get("BinaryExpr") if isinstance(bin_expr, dict) and bin_expr.get("op") in ("And", "Or"): lhs, op, rhs = bin_expr["left"], bin_expr["op"], bin_expr["right"] @@ -455,6 +515,9 @@ def _pl_tree_to_sql(tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | N ): # No cast option changes how such a cast compares, so the bare column compares the same return _pl_tree_to_sql(cast_expr, schema) + if _is_null_cast_to_boolean(tree): + # A when/then without otherwise ends in this cast, which polars does not fold, and a cast NULL is NULL + return "CAST(NULL AS BOOLEAN)" # Any other cast of a column can truncate, turn an overflow into NULL or change the type the comparison runs # in, and the bare column carries none of that if "Literal" not in cast_expr: @@ -518,6 +581,14 @@ def _pl_tree_to_sql(tree: _ExpressionTree, schema: Mapping[str, pl.DataType] | N # The value is UTC; compare as an instant so the session TimeZone does not shift it return f"'{dt_timestamp!s}+00'::TIMESTAMPTZ" + if dtype == "Null": + # A folded comparison gives its NULL rows a Boolean NULL; polars folds a comparison of a column with a NULL + # of another type before a scan sees it + if value["Null"] != "Boolean": + msg = f"A NULL literal of type {value['Null']!r} cannot be pushed down" + raise NotImplementedError(msg) + return "CAST(NULL AS BOOLEAN)" + # Match simple numeric/boolean types if dtype in ( "Int8", diff --git a/tests/fast/arrow/test_polars_pushdown_literals.py b/tests/fast/arrow/test_polars_pushdown_literals.py index 65f2abc22..36aeb1837 100644 --- a/tests/fast/arrow/test_polars_pushdown_literals.py +++ b/tests/fast/arrow/test_polars_pushdown_literals.py @@ -30,6 +30,7 @@ COLUMN_UNITS = {"TIMESTAMP_S": "ms", "TIMESTAMP_MS": "ms", "TIMESTAMP": "us", "TIMESTAMP_NS": "ns"} SERIALIZED_UNITS = {"Milliseconds": "ms", "Microseconds": "us", "Nanoseconds": "ns"} POLARS_2 = parse_version(pl.__version__) >= parse_version("2") +POLARS_2_2 = parse_version(pl.__version__) >= parse_version("2.2") INTEGER_RANGES = { "TINYINT": (-(2**7), 2**7 - 1), "SMALLINT": (-(2**15), 2**15 - 1), @@ -882,6 +883,115 @@ def test_logical_and_or_is_pushed(self, duckdb_cursor, pushdowns): assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed="partly") +class TestTernaryPushdown: + # polars' when/then/otherwise sends a NULL condition to its otherwise branch as CASE sends it to ELSE; polars 2.2 + # also turns an integer column compared with a value none of its values equals into one, alike for each non NULL row + @pytest.fixture + def lazy_df(self, duckdb_cursor): + duckdb_cursor.execute("CREATE TABLE t (a TINYINT, b TINYINT, x DOUBLE, s VARCHAR)") + duckdb_cursor.executemany( + "INSERT INTO t VALUES (?, ?, ?, ?)", + list(itertools.product([-128, -1, 0, 1, 127, None], [2, None], [1.0, -1.0, None], ["x", None])), + ) + return duckdb_cursor.table("t").pl(lazy=True) + + @pytest.mark.parametrize("literal", [1000, 1.5, 200.5, -126.99999999999999]) + def test_an_equality_no_value_meets_is_pushed(self, lazy_df, pushdowns, literal): + [tree] = assert_pushdown_matches_polars(lazy_df, pushdowns, pl.col("a") == literal, pushed=True) + # polars 2 before 2.2 compares a float with the column's Float64 cast, polars 1 an integer with a wider cast + assert ("Ternary" in tree) == (POLARS_2_2 or (POLARS_2 and isinstance(literal, int))) + + @pytest.mark.parametrize("literal", [1000, 1.5]) + def test_an_inequality_no_value_meets_is_pushed_where_polars_folds_it(self, lazy_df, pushdowns, literal): + # The translator has no !=, which polars 2 before 2.2 sends for a float and polars 1 for both + pushed = POLARS_2_2 or (POLARS_2 and isinstance(literal, int)) + [tree] = assert_pushdown_matches_polars(lazy_df, pushdowns, pl.col("a") != literal, pushed=pushed) + assert ("Ternary" in tree) == pushed + + @pytest.mark.parametrize("literal", [1000, 1.5]) + def test_a_fold_under_or_is_pushed(self, lazy_df, pushdowns, literal): + # The fold is never TRUE, so x above 0 alone keeps a row, one with a NULL a included + predicate = (pl.col("a") == literal) | (pl.col("x") > 0) + assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=True) + + def test_when_then_otherwise_is_pushed(self, lazy_df, pushdowns): + predicate = pl.when(pl.col("x") > 0).then(pl.col("a") > 0).otherwise(pl.col("a") < 0) + [tree] = assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=True) + assert "Ternary" in tree + # A NULL condition takes the otherwise branch + assert (-1, None) in lazy_df.filter(predicate).select("a", "x").collect().rows() + # Without otherwise, polars sends the last branch as a NULL cast to Boolean + [tree] = assert_pushdown_matches_polars( + lazy_df, pushdowns, pl.when(pl.col("x") > 0).then(pl.col("a") > 0), pushed=True + ) + assert "Ternary" in tree + # A chained when/then is a Ternary in the last branch, which a NULL first condition falls through to + predicate = ( + pl.when(pl.col("x") > 0) + .then(pl.col("a") > 0) + .when(pl.col("a") < 0) + .then(pl.col("b").is_null()) + .otherwise(pl.col("a") == 0) + ) + [tree] = assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=True) + assert "Ternary" in tree["Ternary"]["falsy"] + assert (-1, None, None) in lazy_df.filter(predicate).select("a", "b", "x").collect().rows() + + @pytest.mark.parametrize( + "predicate", + [ + pytest.param(pl.when(pl.col("a")).then(pl.col("x") > 0).otherwise(pl.col("x") < 0), id="integer_condition"), + pytest.param(pl.when(pl.col("x") > 0).then(pl.lit(1)).otherwise(pl.lit(0)), id="integer_branches"), + pytest.param( + pl.when(pl.col("a") & pl.col("b")).then(pl.col("x") > 0).otherwise(pl.col("x") < 0), + id="bitwise_and_condition", + ), + ], + ) + def test_a_when_then_polars_does_not_type_boolean_is_not_pushed(self, lazy_df, pushdowns, predicate): + # polars types the parts only when it evaluates them, and pushed, the engine would read a nonzero integer as + # true where polars raises + with pytest.raises(pl.exceptions.PolarsError): + lazy_df.filter(predicate).collect() + [(tree, expression, error)] = pushdowns + assert "Ternary" in tree + assert expression is None + assert error is NotImplementedError + + def test_a_when_then_of_an_and_and_a_boolean_column_is_pushed(self, duckdb_cursor, pushdowns): + duckdb_cursor.execute("CREATE TABLE t (f BOOLEAN, a TINYINT, x DOUBLE)") + duckdb_cursor.executemany( + "INSERT INTO t VALUES (?, ?, ?)", + list(itertools.product([True, False, None], [-1, 0, 1, None], [1.0, -1.0, None])), + ) + lazy_df = duckdb_cursor.table("t").pl(lazy=True) + predicate = pl.when(pl.col("f") & (pl.col("a") > 0)).then(pl.col("f")).otherwise(pl.col("x") < 0) + [tree] = assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=True) + assert "Ternary" in tree + + @pytest.mark.parametrize( + "predicate", + [ + pytest.param( + pl.when(pl.col("x") > 0).then(pl.col("a")).otherwise(pl.col("b")) > 0, id="operand_of_a_comparison" + ), + pytest.param( + pl.when(pl.col("x") > 0).then(pl.col("s").str.contains("x")).otherwise(pl.col("a") > 0), + id="branch_that_does_not_translate", + ), + ], + ) + def test_a_ternary_that_does_not_translate_is_not_pushed(self, lazy_df, pushdowns, predicate): + # CASE and polars type branches that are not Boolean differently, and a part that does not translate stays + [tree] = assert_pushdown_matches_polars(lazy_df, pushdowns, predicate, pushed=False) + assert "Ternary" in json.dumps(tree) + + def test_only_a_boolean_null_literal_translates(self): + assert _pl_tree_to_sql({"Literal": {"Scalar": {"Null": "Boolean"}}}) == "CAST(NULL AS BOOLEAN)" + with pytest.raises(NotImplementedError): + _pl_tree_to_sql({"Literal": {"Scalar": {"Null": "Int32"}}}) + + class TestDecimalLiteralPushdown: @pytest.mark.parametrize( ("unscaled", "scale"), From f5d8d78979cd84e60d9816191ca10023448beb5e Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Tue, 24 Nov 2026 18:14:25 +0000 Subject: [PATCH 56/61] End a result whose streaming fetch fails with the engine's error --- src/engine/result.cpp | 8 ++- tests/fast/api/test_streaming_result.py | 44 +++++++++++++ tests/slow/test_exit_with_open_results.py | 75 +++++++++++++++++++++++ 3 files changed, 126 insertions(+), 1 deletion(-) diff --git a/src/engine/result.cpp b/src/engine/result.cpp index c0b8fe7ba..748646a32 100644 --- a/src/engine/result.cpp +++ b/src/engine/result.cpp @@ -197,7 +197,13 @@ unique_ptr Result::FetchStreamUnit(const InterruptCheck &che return nullptr; } if (query_state == QueryResultState::EXECUTION_ERROR) { - typed.GetErrorObject().Throw(); + // An engine error ends the query, as on the other paths that drive it; its stream already closed itself + try { + typed.GetErrorObject().Throw(); + } catch (...) { + CloseAfterFailure(std::current_exception()); + throw; + } } check(); query_state = typed.ExecuteTask(); diff --git a/tests/fast/api/test_streaming_result.py b/tests/fast/api/test_streaming_result.py index 3d7340275..bd7d6bd88 100644 --- a/tests/fast/api/test_streaming_result.py +++ b/tests/fast/api/test_streaming_result.py @@ -176,6 +176,50 @@ def test_error_surfaces_on_the_fetch_that_reaches_it(self, duckdb_cursor): with pytest.raises(duckdb.ConversionException): drain(duckdb_cursor) + FAILS_AFTER_ITS_FIRST_ROWS = f""" + SELECT CASE WHEN i < {ROW_COUNT} THEN i ELSE concat('hello', i::VARCHAR)::INT END AS i + FROM range({ROW_COUNT} + 1) t(i) + """ + + @pytest.mark.parametrize("failure", ["engine_error", "interrupt"]) + def test_a_later_fetch_after_a_failed_streaming_fetch_raises_the_same_error(self, duckdb_cursor, failure): + duckdb_cursor.execute(f"SET max_streaming_buffer_size='{SMALL_BUFFER}'") + if failure == "engine_error": + duckdb_cursor.execute(self.FAILS_AFTER_ITS_FIRST_ROWS) + else: + duckdb_cursor.execute("SELECT i FROM range(100_000_000) t(i)") + assert duckdb_cursor.fetchone() == (0,) + if failure == "interrupt": + duckdb_cursor.interrupt() + with pytest.raises(duckdb.Error) as first: + duckdb_cursor.fetchall() + for later in ( + lambda: duckdb_cursor.fetch_df_chunk(0), + duckdb_cursor.fetchall, + duckdb_cursor.fetchone, + duckdb_cursor.fetchnumpy, + ): + with pytest.raises(type(first.value)) as again: + later() + assert str(again.value) == str(first.value) + assert duckdb_cursor.execute("SELECT 42").fetchall() == [(42,)] + + def test_a_later_read_of_a_failed_arrow_reader_raises_the_same_error(self, duckdb_cursor): + pytest.importorskip("pyarrow") + duckdb_cursor.execute(f"SET max_streaming_buffer_size='{SMALL_BUFFER}'") + reader = duckdb_cursor.sql(self.FAILS_AFTER_ITS_FIRST_ROWS).to_arrow_reader(1024) + assert len(reader.read_next_batch()) == 1024 + with pytest.raises(OSError, match="hello") as first: + reader.read_all() + with pytest.raises(OSError, match="hello") as again: + reader.read_next_batch() + assert str(again.value) == str(first.value) + + duckdb_cursor.close() + with pytest.raises(OSError, match="hello") as after_close: + reader.read_next_batch() + assert str(after_close.value) == str(first.value) + def test_a_returning_write_applies_when_its_rows_are_read(self, duckdb_cursor): duckdb_cursor.execute("CREATE TABLE t (i INTEGER)") diff --git a/tests/slow/test_exit_with_open_results.py b/tests/slow/test_exit_with_open_results.py index a9b962c89..b17f75cdf 100644 --- a/tests/slow/test_exit_with_open_results.py +++ b/tests/slow/test_exit_with_open_results.py @@ -135,6 +135,28 @@ def _assert_exit(proc: subprocess.CompletedProcess[str], *, status: int = 0, bod ] +FAILED_FETCHES = { + "dbapi_fetch": """ + con.execute("SELECT * FROM range(1_000_000)") + con.fetchone() + con.interrupt() + try: + con.fetchall() + except duckdb.InterruptException: + print("FETCH_FAILED", flush=True) + """, + "arrow_reader": """ + failed = con.sql("SELECT * FROM range(10_000_000) t(i)").to_arrow_reader(1000) + failed.read_next_batch() + con.interrupt() + try: + failed.read_all() + except OSError: + print("FETCH_FAILED", flush=True) + """, +} + + class TestOpenResultAtExit: @pytest.mark.parametrize("body", OPEN_RESULT_CASES) def test_exits_with_an_open_result_over_an_object_column(self, body: str) -> None: @@ -210,6 +232,59 @@ def test_a_sort_left_open_by_the_main_thread_is_interrupted_before_its_close(sel returned = next(float(line.split()[1]) for line in proc.stdout.splitlines() if line.startswith("MAIN_RETURNS")) assert exited - returned < 2.5, f"exit took {exited - returned:.1f} s after the main thread" + @pytest.mark.skipif(importlib.util.find_spec("pyarrow") is None, reason="needs pyarrow") + @pytest.mark.parametrize("failed_fetch", list(FAILED_FETCHES)) + def test_a_sort_left_open_beside_a_failed_fetch_of_its_connection_is_interrupted_before_its_close( + self, failed_fetch: str + ) -> None: + # A fetch that fails while streaming must end its result: one left counted as running gives the hook two + # results of one connection, and the second closes after the first cleared the interrupt. The order the hook + # meets them in follows the registry's hash layout, which Python cannot choose; the cursor counts change that + # layout, so both orders occur. + body = """ + import time + + # A sort key slow to compute keeps the workers from seeing an interrupt that is set only for a moment + query = ( + "SELECT * FROM range(3) t(i) UNION ALL " + "(SELECT i FROM range(20_000_000) t(i) ORDER BY hash(repeat(i::VARCHAR, 200)))" + ) + for _ in range(5): + con = duckdb.connect(config={{"threads": 4, "memory_limit": "2GB"}}) + con.execute("SET enable_progress_bar = false") +{failed_fetch} + started = time.time() + reader = con.sql(query).to_arrow_reader(1) + reader.read_next_batch() + # A first batch as slow as the sort means the fetching thread ran it itself and left nothing to interrupt + if time.time() - started < 5: + print("WORKERS_SORT", flush=True) + break + con.close() + else: + raise SystemExit("the fetching thread ran the sort in every attempt") + cursors = [] + for _ in range({cursors}): + cursor = con.cursor() + cursor.execute("SELECT 1") + cursors.append(cursor) + time.sleep(1) + print("MAIN_RETURNS", time.time(), flush=True) + """ + step = textwrap.indent(textwrap.dedent(FAILED_FETCHES[failed_fetch]).strip("\n"), " " * 12) + waits = {} + for cursors in range(10, 28, 2): + proc = _run(body.format(cursors=cursors, failed_fetch=step), head="import duckdb\n", timeout=120) + exited = time.time() + _assert_exit(proc) + lines = proc.stdout.splitlines() + assert "FETCH_FAILED" in lines, proc.stdout + assert "WORKERS_SORT" in lines, proc.stdout + returned = next(float(line.split()[1]) for line in lines if line.startswith("MAIN_RETURNS")) + waits[cursors] = round(exited - returned, 1) + slow = {cursors: wait for cursors, wait in waits.items() if wait >= 2.5} + assert not slow, f"seconds from the main thread's return to the exit, by cursor count: {slow}" + NEEDS_FIFO = pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="needs a FIFO") From 454263f4a5d447e2f4a241952943cb5f4f54e061 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Wed, 25 Nov 2026 19:40:49 +0000 Subject: [PATCH 57/61] Read __main__ from sys.modules when detecting an interactive session --- src/pyconnection.cpp | 7 +++-- tests/fast/api/test_query_progress.py | 43 +++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/src/pyconnection.cpp b/src/pyconnection.cpp index f0fd94d0c..acbfb47cb 100644 --- a/src/pyconnection.cpp +++ b/src/pyconnection.cpp @@ -209,9 +209,10 @@ void DuckDBPyConnection::DetectEnvironment() { int minor = nb::cast(version_info.attr("minor")); GetModuleState().formatted_python_version = std::to_string(major) + "." + std::to_string(minor); - // If __main__ does not have a __file__ attribute, we are in interactive mode - auto main_module = nb::module_::import_("__main__"); - if (nb::hasattr(main_module, "__file__")) { + // If __main__ does not have a __file__ attribute, we are in interactive mode. It is read from sys.modules, not + // imported: some hosts remove it, and an import would then search sys.path, raise or run a stray __main__.py. + auto main_module = sys.attr("modules").attr("get")("__main__", nb::none()); + if (main_module.is_none() || nb::hasattr(main_module, "__file__")) { return; } GetModuleState().environment = PythonEnvironmentType::INTERACTIVE; diff --git a/tests/fast/api/test_query_progress.py b/tests/fast/api/test_query_progress.py index c57a88c3b..b29011ceb 100644 --- a/tests/fast/api/test_query_progress.py +++ b/tests/fast/api/test_query_progress.py @@ -1,5 +1,7 @@ import contextlib import platform +import subprocess +import sys import threading import time @@ -61,3 +63,44 @@ def test_query_progress_closed_connection(self): conn.close() with pytest.raises(duckdb.ConnectionException): conn.query_progress() + + +_MAIN_STATE = """ +import sys +import types + +state = sys.argv[1] +if state == "none": + sys.modules["__main__"] = None +elif state == "without_file": + sys.modules["__main__"] = types.ModuleType("__main__") +else: + del sys.modules["__main__"] +sys.path[:0] = sys.argv[2:] +import duckdb + +print("enabled", duckdb.connect().execute("SELECT current_setting('enable_progress_bar')").fetchone()[0]) +print("main", "__main__" in sys.modules) +""" + + +@pytest.mark.parametrize( + ("state", "stray_main_on_path", "expected"), + [ + ("removed", False, ["enabled False", "main False"]), + ("removed", True, ["enabled False", "main False"]), + ("none", False, ["enabled False", "main True"]), + ("without_file", False, ["enabled True", "main True"]), + ], +) +def test_main_module_state_at_import(tmp_path, state, stray_main_on_path, expected): + # Some hosts, such as the Azure Functions worker, remove __main__ from sys.modules; the client must neither fail + # to import nor run a __main__.py found on sys.path, and treats a missing or None entry as not interactive. + (tmp_path / "__main__.py").write_text("print('stray main ran')\n") + path = [str(tmp_path)] if stray_main_on_path else [] + child = subprocess.run( + [sys.executable, "-c", _MAIN_STATE, state, *path], capture_output=True, text=True, timeout=60, check=False + ) + assert child.returncode == 0, child.stderr + reported = [line for line in child.stdout.splitlines() if line.startswith(("enabled", "main", "stray"))] + assert reported == expected From 115aebcc73a679e3d1f653100e392089ce1eaff1 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Thu, 26 Nov 2026 14:36:21 +0000 Subject: [PATCH 58/61] Skip the connection checks after a lazy polars join on polars 2.2.0 --- tests/fast/api/test_execute_contract.py | 69 ++++++++++++++++++++----- 1 file changed, 57 insertions(+), 12 deletions(-) diff --git a/tests/fast/api/test_execute_contract.py b/tests/fast/api/test_execute_contract.py index df91e510e..f617c00b8 100644 --- a/tests/fast/api/test_execute_contract.py +++ b/tests/fast/api/test_execute_contract.py @@ -1,4 +1,5 @@ import gc +import importlib.metadata import importlib.util import re import subprocess @@ -8,6 +9,7 @@ import time import pytest +from packaging.version import Version import duckdb from duckdb.sqltypes import BIGINT @@ -25,10 +27,32 @@ REFUSED = f"{OPEN_RESULT}|{BUSY}" needs_polars = pytest.mark.skipif(importlib.util.find_spec("polars") is None, reason="polars not installed") +POLARS_VERSION = Version(importlib.metadata.version("polars")) if importlib.util.find_spec("polars") else None +LEFT_IN_ITS_FIRST_CALL = ( + "polars 2.2.0's streaming engine returns from a failed collect() while a source it started is still in its first " + "call, so the connection is still held" +) +OPEN_UNTIL_ANOTHER_QUERY = ( + f"{LEFT_IN_ITS_FIRST_CALL}, and a source whose frame is dropped during that call stays open until polars runs " + "another query" +) needs_pandas = pytest.mark.skipif(importlib.util.find_spec("pandas") is None, reason="pandas not installed") needs_pyarrow = pytest.mark.skipif(importlib.util.find_spec("pyarrow") is None, reason="pyarrow not installed") +def join_two_lazy_polars_frames(connection): + """The joined frame and either the refusal's text or the joined keys.""" + connection.execute("CREATE TABLE a AS SELECT range::INT AS k FROM range(5)") + connection.execute("CREATE TABLE b AS SELECT range::INT AS k FROM range(3)") + joined = connection.table("a").pl(lazy=True).join(connection.table("b").pl(lazy=True), on="k") + # Whether polars opens both sources at once depends on its scheduling, so a refusal (either kind, since the second + # call may land during engine work) and the joined rows are both correct + try: + return joined, None, sorted(joined.collect()["k"].to_list()) + except Exception as error: + return joined, str(error), None + + @pytest.fixture def con(): connection = duckdb.connect() @@ -38,6 +62,20 @@ def con(): connection.close() +@pytest.fixture +def con_of_lazy_polars_frames(): + connection = duckdb.connect() + connection.execute("SET threads = 1") + yield connection + try: + connection.close() + except duckdb.ResourceInUseException: + # polars 2.2.0 can still be running a source of this connection after collect() raised, and close() refuses a + # busy connection instead of waiting, so the process end closes it + if Version("2.2.0") != POLARS_VERSION: + raise + + @pytest.fixture def produced(con): count = [0] @@ -477,22 +515,29 @@ def test_a_lazy_polars_frame_cannot_open_while_a_result_is_open(self, con): @needs_polars @needs_pyarrow - def test_joining_two_lazy_polars_frames_of_one_connection_settles(self, con): - con.execute("CREATE TABLE a AS SELECT range::INT AS k FROM range(5)") - con.execute("CREATE TABLE b AS SELECT range::INT AS k FROM range(3)") - joined = con.table("a").pl(lazy=True).join(con.table("b").pl(lazy=True), on="k") - # Whether polars opens both sources at once depends on its scheduling, so a refusal (either kind, since the - # second call may land during engine work) and the joined rows are both correct; the connection must work after. - refused = None - try: - rows = sorted(joined.collect()["k"].to_list()) - except Exception as error: - refused, rows = str(error), None + def test_joining_two_lazy_polars_frames_of_one_connection_is_refused_or_joined(self, con_of_lazy_polars_frames): + _, refused, rows = join_two_lazy_polars_frames(con_of_lazy_polars_frames) if refused is not None: assert re.search(REFUSED, refused) else: assert rows == [0, 1, 2] - assert con.execute("SELECT 42").fetchall() == [(42,)] + + @needs_polars + @needs_pyarrow + @pytest.mark.skipif(Version("2.2.0") == POLARS_VERSION, reason=LEFT_IN_ITS_FIRST_CALL) + def test_the_connection_works_right_after_joining_two_lazy_polars_frames(self, con_of_lazy_polars_frames): + # The frame stays referenced, as a caller's does while it handles the error + _joined, _, _ = join_two_lazy_polars_frames(con_of_lazy_polars_frames) + assert con_of_lazy_polars_frames.execute("SELECT 42").fetchall() == [(42,)] + + @needs_polars + @needs_pyarrow + @pytest.mark.skipif(Version("2.2.0") == POLARS_VERSION, reason=OPEN_UNTIL_ANOTHER_QUERY) + def test_the_connection_works_once_the_joined_polars_frame_is_dropped(self, con_of_lazy_polars_frames): + joined, _, _ = join_two_lazy_polars_frames(con_of_lazy_polars_frames) + # Dropped at once, while the source polars 2.2.0 left running is still in its first call + del joined + assert con_of_lazy_polars_frames.execute("SELECT 42").fetchall() == [(42,)] @pytest.mark.parametrize( "callback", From ed6e011e9b4618802511226034927085a34ed36c Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Sun, 29 Nov 2026 20:11:31 +0000 Subject: [PATCH 59/61] Skip the lazy polars join test on polars 2.2.0 --- tests/fast/api/test_execute_contract.py | 71 ++++++------------------- 1 file changed, 17 insertions(+), 54 deletions(-) diff --git a/tests/fast/api/test_execute_contract.py b/tests/fast/api/test_execute_contract.py index f617c00b8..d29a20d03 100644 --- a/tests/fast/api/test_execute_contract.py +++ b/tests/fast/api/test_execute_contract.py @@ -28,31 +28,10 @@ needs_polars = pytest.mark.skipif(importlib.util.find_spec("polars") is None, reason="polars not installed") POLARS_VERSION = Version(importlib.metadata.version("polars")) if importlib.util.find_spec("polars") else None -LEFT_IN_ITS_FIRST_CALL = ( - "polars 2.2.0's streaming engine returns from a failed collect() while a source it started is still in its first " - "call, so the connection is still held" -) -OPEN_UNTIL_ANOTHER_QUERY = ( - f"{LEFT_IN_ITS_FIRST_CALL}, and a source whose frame is dropped during that call stays open until polars runs " - "another query" -) needs_pandas = pytest.mark.skipif(importlib.util.find_spec("pandas") is None, reason="pandas not installed") needs_pyarrow = pytest.mark.skipif(importlib.util.find_spec("pyarrow") is None, reason="pyarrow not installed") -def join_two_lazy_polars_frames(connection): - """The joined frame and either the refusal's text or the joined keys.""" - connection.execute("CREATE TABLE a AS SELECT range::INT AS k FROM range(5)") - connection.execute("CREATE TABLE b AS SELECT range::INT AS k FROM range(3)") - joined = connection.table("a").pl(lazy=True).join(connection.table("b").pl(lazy=True), on="k") - # Whether polars opens both sources at once depends on its scheduling, so a refusal (either kind, since the second - # call may land during engine work) and the joined rows are both correct - try: - return joined, None, sorted(joined.collect()["k"].to_list()) - except Exception as error: - return joined, str(error), None - - @pytest.fixture def con(): connection = duckdb.connect() @@ -62,20 +41,6 @@ def con(): connection.close() -@pytest.fixture -def con_of_lazy_polars_frames(): - connection = duckdb.connect() - connection.execute("SET threads = 1") - yield connection - try: - connection.close() - except duckdb.ResourceInUseException: - # polars 2.2.0 can still be running a source of this connection after collect() raised, and close() refuses a - # busy connection instead of waiting, so the process end closes it - if Version("2.2.0") != POLARS_VERSION: - raise - - @pytest.fixture def produced(con): count = [0] @@ -515,29 +480,27 @@ def test_a_lazy_polars_frame_cannot_open_while_a_result_is_open(self, con): @needs_polars @needs_pyarrow - def test_joining_two_lazy_polars_frames_of_one_connection_is_refused_or_joined(self, con_of_lazy_polars_frames): - _, refused, rows = join_two_lazy_polars_frames(con_of_lazy_polars_frames) + @pytest.mark.skipif( + Version("2.2.0") == POLARS_VERSION, + reason="polars 2.2.0 returns from a failed collect() while a source it started is still running, so the " + "connection is still held", + ) + def test_joining_two_lazy_polars_frames_of_one_connection_settles(self, con): + con.execute("CREATE TABLE a AS SELECT range::INT AS k FROM range(5)") + con.execute("CREATE TABLE b AS SELECT range::INT AS k FROM range(3)") + joined = con.table("a").pl(lazy=True).join(con.table("b").pl(lazy=True), on="k") + # Whether polars opens both sources at once depends on its scheduling, so a refusal (either kind, since the + # second call may land during engine work) and the joined rows are both correct; the connection must work after. + refused = None + try: + rows = sorted(joined.collect()["k"].to_list()) + except Exception as error: + refused, rows = str(error), None if refused is not None: assert re.search(REFUSED, refused) else: assert rows == [0, 1, 2] - - @needs_polars - @needs_pyarrow - @pytest.mark.skipif(Version("2.2.0") == POLARS_VERSION, reason=LEFT_IN_ITS_FIRST_CALL) - def test_the_connection_works_right_after_joining_two_lazy_polars_frames(self, con_of_lazy_polars_frames): - # The frame stays referenced, as a caller's does while it handles the error - _joined, _, _ = join_two_lazy_polars_frames(con_of_lazy_polars_frames) - assert con_of_lazy_polars_frames.execute("SELECT 42").fetchall() == [(42,)] - - @needs_polars - @needs_pyarrow - @pytest.mark.skipif(Version("2.2.0") == POLARS_VERSION, reason=OPEN_UNTIL_ANOTHER_QUERY) - def test_the_connection_works_once_the_joined_polars_frame_is_dropped(self, con_of_lazy_polars_frames): - joined, _, _ = join_two_lazy_polars_frames(con_of_lazy_polars_frames) - # Dropped at once, while the source polars 2.2.0 left running is still in its first call - del joined - assert con_of_lazy_polars_frames.execute("SELECT 42").fetchall() == [(42,)] + assert con.execute("SELECT 42").fetchall() == [(42,)] @pytest.mark.parametrize( "callback", From cdaa3c4b1bfb1648313295956fbd6799cd7c6700 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Mon, 30 Nov 2026 12:38:48 +0000 Subject: [PATCH 60/61] Bound the exit tests with a sort on runners where the fetching thread runs it --- tests/slow/test_exit_with_open_results.py | 71 +++++++++++++++++++---- 1 file changed, 59 insertions(+), 12 deletions(-) diff --git a/tests/slow/test_exit_with_open_results.py b/tests/slow/test_exit_with_open_results.py index b17f75cdf..6c60c2a77 100644 --- a/tests/slow/test_exit_with_open_results.py +++ b/tests/slow/test_exit_with_open_results.py @@ -207,26 +207,49 @@ def work(): def test_a_sort_left_open_by_the_main_thread_is_interrupted_before_its_close(self) -> None: # Its workers check the interrupt and not the cancel, so without the interrupt the close waits for the sort body = """ + import threading import time query = "SELECT * FROM range(3) t(i) UNION ALL (SELECT i FROM range(100_000_000) t(i) ORDER BY hash(i))" + + def stop(con, ran_long): + ran_long.set() + con.interrupt() + for _ in range(5): con = duckdb.connect(config={"threads": 4, "memory_limit": "2GB"}) con.execute("SET enable_progress_bar = false") - started = time.time() - con.execute(query) - print("FIRST", con.fetchone(), flush=True) - # A slow first row means the fetching thread ran the sort itself and left nothing to interrupt - if time.time() - started < 1: + # The sort's scan is one task, and when the fetching thread takes it before a worker does, the first row + # waits for the whole sort and leaves nothing to interrupt; the timer ends such an attempt early + ran_long = threading.Event() + timer = threading.Timer(2, stop, args=(con, ran_long)) + timer.start() + try: + con.execute(query) + print("FIRST", con.fetchone(), flush=True) + except duckdb.InterruptException: + if not ran_long.is_set(): + raise + timer.cancel() + # A timer that fired before the cancel finishes its interrupt before the attempt is judged + timer.join() + if not ran_long.is_set(): print("WORKERS_SORT", flush=True) break + con.interrupt() con.close() + else: + print("FETCHING_THREAD_SORTED", flush=True) + raise SystemExit(0) # Lets the engine workers take up the sort before the main thread returns time.sleep(1) print("MAIN_RETURNS", time.time(), flush=True) """ proc = _run(body, head="import duckdb\n", timeout=120) exited = time.time() + if "FETCHING_THREAD_SORTED" in proc.stdout.splitlines(): + _assert_exit(proc, body_done=False) + pytest.skip("the fetching thread ran the sort itself in every attempt, so no worker sorted at the exit") _assert_exit(proc) assert "WORKERS_SORT" in proc.stdout.splitlines(), proc.stdout returned = next(float(line.split()[1]) for line in proc.stdout.splitlines() if line.startswith("MAIN_RETURNS")) @@ -242,6 +265,7 @@ def test_a_sort_left_open_beside_a_failed_fetch_of_its_connection_is_interrupted # meets them in follows the registry's hash layout, which Python cannot choose; the cursor counts change that # layout, so both orders occur. body = """ + import threading import time # A sort key slow to compute keeps the workers from seeing an interrupt that is set only for a moment @@ -249,20 +273,38 @@ def test_a_sort_left_open_beside_a_failed_fetch_of_its_connection_is_interrupted "SELECT * FROM range(3) t(i) UNION ALL " "(SELECT i FROM range(20_000_000) t(i) ORDER BY hash(repeat(i::VARCHAR, 200)))" ) + + def stop(con, ran_long): + ran_long.set() + con.interrupt() + for _ in range(5): con = duckdb.connect(config={{"threads": 4, "memory_limit": "2GB"}}) con.execute("SET enable_progress_bar = false") {failed_fetch} - started = time.time() - reader = con.sql(query).to_arrow_reader(1) - reader.read_next_batch() - # A first batch as slow as the sort means the fetching thread ran it itself and left nothing to interrupt - if time.time() - started < 5: + # The sort's scan is one task, and when the fetching thread takes it before a worker does, the first batch + # waits for the whole sort and leaves nothing to interrupt; the timer ends such an attempt early + ran_long = threading.Event() + timer = threading.Timer(2, stop, args=(con, ran_long)) + timer.start() + try: + reader = con.sql(query).to_arrow_reader(1) + reader.read_next_batch() + except (duckdb.InterruptException, OSError): + # Every failure of an Arrow read arrives as an OSError, so only the timer's own means a slow attempt + if not ran_long.is_set(): + raise + timer.cancel() + # A timer that fired before the cancel finishes its interrupt before the attempt is judged + timer.join() + if not ran_long.is_set(): print("WORKERS_SORT", flush=True) break + con.interrupt() con.close() else: - raise SystemExit("the fetching thread ran the sort in every attempt") + print("FETCHING_THREAD_SORTED", flush=True) + raise SystemExit(0) cursors = [] for _ in range({cursors}): cursor = con.cursor() @@ -276,12 +318,17 @@ def test_a_sort_left_open_beside_a_failed_fetch_of_its_connection_is_interrupted for cursors in range(10, 28, 2): proc = _run(body.format(cursors=cursors, failed_fetch=step), head="import duckdb\n", timeout=120) exited = time.time() - _assert_exit(proc) lines = proc.stdout.splitlines() + if "FETCHING_THREAD_SORTED" in lines: + _assert_exit(proc, body_done=False) + continue + _assert_exit(proc) assert "FETCH_FAILED" in lines, proc.stdout assert "WORKERS_SORT" in lines, proc.stdout returned = next(float(line.split()[1]) for line in lines if line.startswith("MAIN_RETURNS")) waits[cursors] = round(exited - returned, 1) + if not waits: + pytest.skip("the fetching thread ran the sort itself in every attempt, so no worker sorted at the exit") slow = {cursors: wait for cursors, wait in waits.items() if wait >= 2.5} assert not slow, f"seconds from the main thread's return to the exit, by cursor count: {slow}" From 3cb427c17c04f839c94b2170e6fd9ea37c5d897a Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Mon, 30 Nov 2026 21:02:22 +0000 Subject: [PATCH 61/61] Follow main's engine in the fixes merged from v2.0-cyanoptera --- duckdb/polars_io.py | 4 +++- src/numpy/numpy_scan.cpp | 2 +- src/pyconnection.cpp | 4 ++-- tests/slow/test_interpreter_shutdown.py | 3 +++ 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/duckdb/polars_io.py b/duckdb/polars_io.py index 7572e0cb3..03ad1f14a 100644 --- a/duckdb/polars_io.py +++ b/duckdb/polars_io.py @@ -693,7 +693,9 @@ def _stands_for(dtype: pl.DataType, engine_type: str) -> bool: return engine_type in _DATETIME_ENGINE_TYPES.get(dtype.time_unit, ()) if isinstance(dtype, pl.Categorical): return engine_type.startswith("ENUM(") - return engine_type in _ENGINE_TYPES.get(str(dtype), ()) + names = _ENGINE_TYPES.get(str(dtype), ()) + # The engine prints a collated VARCHAR with its collation, as VARCHAR('NOCASE'). + return engine_type in names or ("VARCHAR" in names and engine_type.startswith("VARCHAR(")) def duckdb_source(relation: duckdb.DuckDBPyRelation, schema: pl.schema.Schema) -> pl.LazyFrame: diff --git a/src/numpy/numpy_scan.cpp b/src/numpy/numpy_scan.cpp index 671269dce..6104838ec 100644 --- a/src/numpy/numpy_scan.cpp +++ b/src/numpy/numpy_scan.cpp @@ -282,7 +282,7 @@ class DeclaredCasts { } Entry entry {source, set.GetCastFunction(source, target, get_input), nullptr}; if (entry.function.HasInitLocalState()) { - CastLocalStateParameters parameters(get_input.context, entry.function.GetCastData()); + CastLocalStateParameters parameters(context, entry.function.GetCastData()); entry.local_state = entry.function.InitLocalState(parameters); } casts.push_back(std::move(entry)); diff --git a/src/pyconnection.cpp b/src/pyconnection.cpp index 98a0bdd46..49960d552 100644 --- a/src/pyconnection.cpp +++ b/src/pyconnection.cpp @@ -407,7 +407,7 @@ static unique_ptr WrapFilesystem(const nb::object &filesystem) void DuckDBPyConnection::RegisterFilesystem(nb::object filesystem) { nb::gil_scoped_acquire gil; auto wrapped = WrapFilesystem(filesystem); - con.GetDatabase().GetFileSystem().RegisterSubSystem(std::move(wrapped)); + VirtualFileSystem::Get(*con.GetDatabase().instance).RegisterSubSystem(std::move(wrapped)); } nb::list DuckDBPyConnection::ListFilesystems() { @@ -1875,7 +1875,7 @@ ModifiedMemoryFileSystem &DuckDBPyConnection::GetObjectFileSystem() { auto wrapped = WrapFilesystem(*built); if (!store->filesystem) { D_ASSERT(!FileSystemIsRegistered(PathLike::OBJECT_STORE_PROTOCOL)); - con.GetDatabase().GetFileSystem().RegisterSubSystem(std::move(wrapped)); + VirtualFileSystem::Get(*con.GetDatabase().instance).RegisterSubSystem(std::move(wrapped)); store->filesystem = std::move(built); } } diff --git a/tests/slow/test_interpreter_shutdown.py b/tests/slow/test_interpreter_shutdown.py index afd7c074e..6df2a2c21 100644 --- a/tests/slow/test_interpreter_shutdown.py +++ b/tests/slow/test_interpreter_shutdown.py @@ -368,6 +368,9 @@ def late(): atexit.register(late) import duckdb + import _duckdb + + _duckdb._set_leak_report(True) import fsspec fs = fsspec.filesystem("memory")