From 4e4ae3eb192fd9c58a1af7c0fd783a9f9a1f5319 Mon Sep 17 00:00:00 2001 From: DogerW <51895873+DogerW666@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:26:46 +0800 Subject: [PATCH] fix(python): preserve NumPy timedelta units in table updates (#5317) Fixes #5316. Writing `np.timedelta64(3_000_000, "ns")` to a millisecond duration column succeeds but stores 3,000,000 ms. NumPy duration scalars also match the integer serializer, which drops the unit before the update reaches Arrow. Give `np.timedelta64` its own serializer. It reads the dtype's unit and multiplier, then reuses the Arrow duration serializer. Weeks through minutes are expressed in seconds. Calendar and sub-nanosecond units raise a conversion error, and `NaT` writes a null. The regression tests read back Arrow's integer counts to check cross-unit writes, exact nanoseconds, a negative value with a scaled dtype, and nulls. They also check that rejected inputs leave the stored value intact. ### Validation - Reproduced the incorrect stored value on the published 0.42.1 Python SDK. - Ran the checkout's converter with the 0.42.1 SDK and native extension. Before the fix, seven of the eight new regression cases failed. After the fix, all 74 update-value tests and 24 related SQL conversion and update tests passed. Also verified four asynchronous updates against an Embedded table. - Ruff lint and formatting checks passed for the Python SDK. The overflow check and additional NumPy duration conversion tests come from #5319. Co-authored-by: tonydzi <194927794+tonydzi@users.noreply.github.com> --------- Co-authored-by: Xuanwo Co-authored-by: tonydzi <194927794+tonydzi@users.noreply.github.com> --- python/python/lancedb/util.py | 18 +++++++++++ python/python/tests/test_util.py | 30 +++++++++++++++++++ .../python/tests/test_util_update_values.py | 26 ++++++++++++++++ 3 files changed, 74 insertions(+) diff --git a/python/python/lancedb/util.py b/python/python/lancedb/util.py index 1f5b527e7..be50aaada 100644 --- a/python/python/lancedb/util.py +++ b/python/python/lancedb/util.py @@ -491,6 +491,7 @@ _ARROW_TIME_UNITS = { "us": "Microsecond", "ns": "Nanosecond", } +_SECONDS_PER_NUMPY_UNIT = {"W": 604_800, "D": 86_400, "h": 3600, "m": 60} @value_to_sql.register(pa.DurationScalar) @@ -543,6 +544,23 @@ def _(value: np.datetime64): return value_to_sql(str(np.datetime_as_string(value, unit="ns", timezone="UTC"))) +@value_to_sql.register(np.timedelta64) +def _(value: np.timedelta64): + if np.isnat(value): + return value_to_sql(None) + unit, step = np.datetime_data(value.dtype) + # A dtype such as timedelta64[2ms] counts pairs of milliseconds. + count = int(value.view(np.int64)) * step + if unit in _SECONDS_PER_NUMPY_UNIT: + count *= _SECONDS_PER_NUMPY_UNIT[unit] + unit = "s" + elif unit not in _ARROW_TIME_UNITS: + raise ValueError(f"Cannot represent NumPy timedelta64 unit {unit!r} in Arrow") + if not -(2**63) <= count < 2**63: + raise ValueError("timedelta64 value is out of range for a SQL duration") + return value_to_sql(pa.scalar(count, type=pa.duration(unit))) + + def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted diff --git a/python/python/tests/test_util.py b/python/python/tests/test_util.py index 15ad167c3..03588868d 100644 --- a/python/python/tests/test_util.py +++ b/python/python/tests/test_util.py @@ -24,6 +24,7 @@ from lancedb.table import ( has_nan_values, sanitize_create_table, ) +import numpy as np import pyarrow as pa import polars as pl import pytest @@ -271,6 +272,35 @@ def test_value_to_sql_time_and_timedelta(tmp_path): assert table.search().where(where).to_arrow()["id"].to_pylist() == [1] +@pytest.mark.parametrize( + "value,count,unit", + [ + (np.timedelta64(3_000_000, "ns"), 3_000_000, "Nanosecond"), + (np.timedelta64(3, "ms"), 3, "Millisecond"), + (np.timedelta64(-2, "s"), -2, "Second"), + (np.timedelta64(1, "D"), 86400, "Second"), + (np.timedelta64(-2, "W"), -1209600, "Second"), + (np.timedelta64(2, "h"), 7200, "Second"), + (np.timedelta64(2, "m"), 120, "Second"), + (np.timedelta64(3, "2ms"), 6, "Millisecond"), + ], +) +def test_value_to_sql_numpy_timedelta(value, count, unit): + assert value_to_sql(value) == f"arrow_cast({count}, 'Duration({unit})')" + + +def test_value_to_sql_numpy_timedelta_special_values(): + assert value_to_sql(np.timedelta64("NaT")) == "NULL" + with pytest.raises(ValueError, match="NumPy timedelta64 unit"): + value_to_sql(np.timedelta64(5)) + + +@pytest.mark.parametrize("count", [2**62, -(2**62)]) +def test_value_to_sql_numpy_timedelta_overflow(count): + with pytest.raises(ValueError, match="out of range"): + value_to_sql(np.timedelta64(count, "D")) + + def test_value_to_sql_keeps_nanoseconds(tmp_path): # Arrow scalars and pandas.Timedelta values can hold nanoseconds, which a # Python timedelta or time would round to microseconds. diff --git a/python/python/tests/test_util_update_values.py b/python/python/tests/test_util_update_values.py index fdef867da..44ccddef1 100644 --- a/python/python/tests/test_util_update_values.py +++ b/python/python/tests/test_util_update_values.py @@ -40,6 +40,32 @@ async def test_update_array_values_async(tmp_path, value, expected): assert (await table.to_arrow())["array"].to_pylist() == [expected] +@pytest.mark.parametrize( + "value,unit,expected", + [ + (np.timedelta64(3_000_000, "ns"), "ms", 3), + (np.timedelta64(1001, "ns"), "ns", 1001), + (np.timedelta64(-3, "2ms"), "us", -6000), + (np.timedelta64(2, "D"), "s", 172800), + (np.timedelta64("NaT", "ms"), "ms", None), + ], +) +def test_update_numpy_timedelta(mem_db, value, unit, expected): + data = pa.table({"elapsed": pa.array([0], type=pa.duration(unit))}) + table = mem_db.create_table("measurements", data) + table.update(values={"elapsed": value}) + assert table.to_arrow()["elapsed"].cast(pa.int64()).to_pylist() == [expected] + + +@pytest.mark.parametrize("unit", ["Y", "M", "ps"]) +def test_update_rejects_unsupported_numpy_timedelta_unit(mem_db, unit): + data = pa.table({"elapsed": pa.array([0], type=pa.duration("ns"))}) + table = mem_db.create_table("measurements", data) + with pytest.raises(ValueError, match="NumPy timedelta64 unit"): + table.update(values={"elapsed": np.timedelta64(1, unit)}) + assert table.to_arrow()["elapsed"].cast(pa.int64()).to_pylist() == [0] + + TIME_VALUES = [ np.datetime64("2025", "Y"), np.datetime64("2025-01", "M"),