This is an automated email from the ASF dual-hosted git repository.
HTHou pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git
The following commit(s) were added to refs/heads/master by this push:
new 16762f926bf Preserve trailing zero bytes in Python NumpyTablet BLOB
values (#19434)
16762f926bf is described below
commit 16762f926bf72a319695c1114e5cd56cfcc1c4ea
Author: DaZuiZui <[email protected]>
AuthorDate: Mon Nov 30 09:25:29 2026 +0800
Preserve trailing zero bytes in Python NumpyTablet BLOB values (#19434)
* Preserve trailing zero bytes in Python NumpyTablet BLOB values
* Copy and normalize NumPy BLOB columns at construction
---
iotdb-client/client-py/README.md | 12 +++
iotdb-client/client-py/iotdb/utils/NumpyTablet.py | 44 +++++++--
.../client-py/tests/unit/test_numpy_tablet.py | 100 +++++++++++++++++++++
3 files changed, 148 insertions(+), 8 deletions(-)
diff --git a/iotdb-client/client-py/README.md b/iotdb-client/client-py/README.md
index 47ca3e908aa..7c7daa0f520 100644
--- a/iotdb-client/client-py/README.md
+++ b/iotdb-client/client-py/README.md
@@ -225,6 +225,8 @@ With less memory footprint and time cost of serialization,
the insert performanc
1. time and value columns in Tablet are ndarray.
2. recommended to use the specific dtypes to each ndarray, see the example
below
(if not, the default dtypes are also ok).
+3. For a BLOB column, use `dtype=object` directly on the original Python
`bytes` to preserve trailing zero bytes.
+ Arrays created with `TSDataType.BLOB.np_dtype()` use fixed-width byte
strings that lose the original lengths.
```python
import numpy as np
@@ -272,6 +274,16 @@ np_tablet_with_none = NumpyTablet(
device_id, measurements_, data_types_, np_values_, np_timestamps_,
np_bitmaps_
)
session.insert_tablet(np_tablet_with_none)
+
+blobs = [b"A\x00\x00", b""]
+blob_tablet = NumpyTablet(
+ device_id,
+ ["payload"],
+ [TSDataType.BLOB],
+ [np.array(blobs, dtype=object)],
+ np.array([1, 2], TSDataType.INT64.np_dtype()),
+)
+session.insert_tablet(blob_tablet)
```
* Insert multiple Tablets
diff --git a/iotdb-client/client-py/iotdb/utils/NumpyTablet.py
b/iotdb-client/client-py/iotdb/utils/NumpyTablet.py
index b484d12e055..f293c1ce12c 100644
--- a/iotdb-client/client-py/iotdb/utils/NumpyTablet.py
+++ b/iotdb-client/client-py/iotdb/utils/NumpyTablet.py
@@ -56,6 +56,9 @@ class NumpyTablet(object):
:param column_names: Str List, names of columns
:param data_types: TSDataType List, specify value types for columns
:param values: ndarray List, one ndarray contains the value of one
column
+ For BLOB columns, use np.array(blobs, dtype=object) on the original
+ Python bytes to preserve trailing zeros. Fixed-width byte arrays
+ treat trailing zeros as padding.
:param timestamps: ndarray, contains the timestamps
:param bitmaps: BitMap list, one bitmap records the position of none
value in a column
:param column_types: ColumnType List, marking the type of each column,
can be none for tree-view interfaces.
@@ -69,6 +72,7 @@ class NumpyTablet(object):
"Input error! len(values) does not equal to len(data_types)!"
)
+ values = list(values)
if not self.check_sorted(timestamps):
index = timestamps.argsort()
timestamps = timestamps[index]
@@ -79,9 +83,17 @@ class NumpyTablet(object):
if timestamps.dtype != TSDataType.INT64.np_dtype():
timestamps = timestamps.astype(TSDataType.INT64.np_dtype())
- for i in range(len(values)):
- if values[i].dtype != data_types[i].np_dtype():
- values[i] = values[i].astype(data_types[i].np_dtype())
+ for i, data_type in enumerate(data_types):
+ column = values[i]
+ dtype = data_type.np_dtype()
+ if (
+ data_type == TSDataType.BLOB
+ and column.dtype.kind in "OV"
+ and column.dtype.names is None
+ ):
+ values[i] = self._copy_blob_column(column)
+ elif column.dtype != dtype:
+ values[i] = column.astype(dtype)
self.__values = values
self.__timestamps = timestamps
@@ -98,6 +110,23 @@ class NumpyTablet(object):
else:
self.__column_types = column_types
+ @staticmethod
+ def _copy_blob_column(column):
+ # Object dtype preserves the length of each BLOB, including trailing
zeros.
+ result = column.astype(object)
+ for row, cell in enumerate(result):
+ if isinstance(cell, bytes):
+ continue
+ if cell is None:
+ # Preserve the payload of NumPy's bytes cast for bitmap-marked
nulls.
+ result[row] = b"None"
+ elif isinstance(cell, (bytearray, memoryview)):
+ result[row] = bytes(cell)
+ else:
+ # Keep NumPy's scalar conversion and rejection of nested
sequences.
+ result[row] = result[row : row + 1].astype(np.bytes_)[0]
+ return result
+
@staticmethod
def _sort_bitmap(bitmap, index):
if bitmap is None:
@@ -162,12 +191,11 @@ class NumpyTablet(object):
elif data_type == 5 or data_type == 11 or data_type == 10:
format_str_list = [">"]
values_tobe_packed = []
- for str_list in value:
- # For TEXT, it's same as the original solution
- if isinstance(str_list, str):
- value_bytes = bytes(str_list, "utf-8")
+ for cell in value:
+ if isinstance(cell, str):
+ value_bytes = bytes(cell, "utf-8")
else:
- value_bytes = str_list
+ value_bytes = cell
format_str_list.append("i")
format_str_list.append(str(len(value_bytes)))
format_str_list.append("s")
diff --git a/iotdb-client/client-py/tests/unit/test_numpy_tablet.py
b/iotdb-client/client-py/tests/unit/test_numpy_tablet.py
index 812e93a0534..02c7f5d1fda 100644
--- a/iotdb-client/client-py/tests/unit/test_numpy_tablet.py
+++ b/iotdb-client/client-py/tests/unit/test_numpy_tablet.py
@@ -62,6 +62,106 @@ def test_numpy_tablet_serialization():
assert tablet_.get_binary_values() == np_tablet_.get_binary_values()
+def test_numpy_tablet_preserves_blob_bytes():
+ blobs = [b"A\x00\x00", b"\x00\x00", b"", b"A\x00B", b"A"]
+ timestamps = list(range(len(blobs)))
+ types = [TSDataType.BLOB]
+ tablet = NumpyTablet(
+ "root.sg.d", ["s"], types, [np.array(blobs, dtype=object)],
np.array(timestamps)
+ )
+ expected = Tablet("root.sg.d", ["s"], types, [[b] for b in blobs],
timestamps)
+ assert tablet.get_binary_values() == expected.get_binary_values()
+
+
+def test_numpy_tablet_copies_object_blob_column():
+ column = np.array([b"first\x00"], dtype=object)
+ values = [column]
+ types = [TSDataType.BLOB]
+ tablet = NumpyTablet("root.sg.d", ["s"], types, values, np.array([1]))
+
+ column[0] = b"second"
+ values[0] = np.array([b"third"], dtype=object)
+ expected = Tablet("root.sg.d", ["s"], types, [[b"first\x00"]], [1])
+ assert tablet.get_binary_values() == expected.get_binary_values()
+
+
+def test_numpy_tablet_fixed_width_blob_padding():
+ column = np.array([b"A", b"XYZ"], dtype="S4")
+ types = [TSDataType.BLOB]
+ tablet = NumpyTablet("root.sg.d", ["s"], types, [column], np.array([1, 2]))
+ expected = Tablet("root.sg.d", ["s"], types, [[b"A"], [b"XYZ"]], [1, 2])
+ assert tablet.get_binary_values() == expected.get_binary_values()
+
+
+def test_numpy_tablet_blob_dtype_zero_initialization():
+ column = np.zeros(2, dtype=TSDataType.BLOB.np_dtype())
+ tablet = NumpyTablet(
+ "root.sg.d", ["s"], [TSDataType.BLOB], [column], np.array([1, 2])
+ )
+ assert tablet.get_binary_values() == bytes(8)
+
+
+def test_numpy_tablet_single_field_blob_records():
+ records = np.array(
+ [(1, b"ab"), (2, b"cd")], dtype=[("id", "i4"), ("payload", "S4")]
+ )
+ column = records[["payload"]]
+ types = [TSDataType.BLOB]
+ tablet = NumpyTablet("root.sg.d", ["s"], types, [column], np.array([1, 2]))
+ expected = Tablet("root.sg.d", ["s"], types, [[b"ab"], [b"cd"]], [1, 2])
+ assert tablet.get_binary_values() == expected.get_binary_values()
+
+
[email protected]("cast_with_helper", [False, True])
[email protected](
+ "column, expected",
+ [
+ (np.array([0.1], dtype=np.float32), b"0.1"),
+ (
+ np.array(["2024-01-01"], dtype="datetime64[ns]"),
+ b"2024-01-01T00:00:00.000000000",
+ ),
+ ],
+)
+def test_numpy_tablet_blob_native_dtype_conversion(column, expected,
cast_with_helper):
+ types = [TSDataType.BLOB]
+ if cast_with_helper:
+ column = column.astype(TSDataType.BLOB.np_dtype())
+ tablet = NumpyTablet("root.sg.d", ["s"], types, [column], np.array([1]))
+ assert tablet.get_binary_values() == len(expected).to_bytes(4, "big") +
expected
+
+
[email protected]("buffer_type", [bytearray, memoryview])
+def test_numpy_tablet_blob_buffers(buffer_type):
+ blobs = [b"A", b"\xff\x00", b""]
+ column = np.empty(len(blobs), dtype=object)
+ for i, blob in enumerate(blobs):
+ column[i] = buffer_type(blob)
+ timestamps = list(range(len(blobs)))
+ types = [TSDataType.BLOB]
+ tablet = NumpyTablet("root.sg.d", ["s"], types, [column],
np.array(timestamps))
+ expected = Tablet("root.sg.d", ["s"], types, [[b] for b in blobs],
timestamps)
+ assert tablet.get_binary_values() == expected.get_binary_values()
+
+
+def test_numpy_tablet_blob_rejects_nested_sequence():
+ column = np.array([b"A", [65]], dtype=object)
+ with pytest.raises(ValueError):
+ NumpyTablet("root.sg.d", ["s"], [TSDataType.BLOB], [column],
np.array([1, 2]))
+
+
+def test_numpy_tablet_blob_scalar_conversion_with_bitmap():
+ column = np.array([None, 123, b"A\x00"], dtype=object)
+ nulls = BitMap(3)
+ nulls.mark(0)
+ tablet = NumpyTablet(
+ "root.sg.d", ["s"], [TSDataType.BLOB], [column], np.array([1, 2, 3]),
[nulls]
+ )
+ assert tablet.get_binary_values() == bytes.fromhex(
+ "00000004 4e6f6e65 00000003 313233 00000002 4100 01 01"
+ )
+
+
def test_numpy_tablet_with_none_serialization():
measurements_ = ["s_01", "s_02", "s_03", "s_04", "s_05", "s_06"]