diff --git a/benchmarks/vector_deserialize.py b/benchmarks/vector_deserialize.py new file mode 100644 index 0000000000..e1a17f07d4 --- /dev/null +++ b/benchmarks/vector_deserialize.py @@ -0,0 +1,316 @@ +#!/usr/bin/env python +# Copyright ScyllaDB, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Benchmark for VectorType deserialization performance. + +Tests different optimization strategies: +1. Current implementation (Python with struct.unpack/numpy) +2. Python struct.unpack only +3. Numpy frombuffer + tolist() +4. Cython DesVectorType deserializer + +Run with: python benchmarks/vector_deserialize.py +""" + +import sys +import time +import struct + +# Add parent directory to path +sys.path.insert(0, '.') + +from cassandra.cqltypes import FloatType, DoubleType, Int32Type, LongType +from cassandra.marshal import float_pack, double_pack, int32_pack, int64_pack + + +def create_test_data(vector_size, element_type): + """Create serialized test data for a vector.""" + if element_type == FloatType: + values = [float(i * 0.1) for i in range(vector_size)] + pack_fn = float_pack + elif element_type == DoubleType: + values = [float(i * 0.1) for i in range(vector_size)] + pack_fn = double_pack + elif element_type == Int32Type: + values = list(range(vector_size)) + pack_fn = int32_pack + elif element_type == LongType: + values = list(range(vector_size)) + pack_fn = int64_pack + else: + raise ValueError(f"Unsupported element type: {element_type}") + + # Serialize the vector + serialized = b''.join(pack_fn(v) for v in values) + + return serialized, values + + +def benchmark_current_implementation(vector_type, serialized_data, iterations=10000): + """Benchmark the current VectorType.deserialize implementation.""" + protocol_version = 4 + + start = time.perf_counter() + for _ in range(iterations): + result = vector_type.deserialize(serialized_data, protocol_version) + end = time.perf_counter() + + elapsed = end - start + per_op = (elapsed / iterations) * 1_000_000 # microseconds + + return elapsed, per_op, result + + +def benchmark_struct_optimization(vector_type, serialized_data, iterations=10000): + """Benchmark struct.unpack optimization.""" + vector_size = vector_type.vector_size + subtype = vector_type.subtype + + # Determine format string - subtype is a class, use identity or issubclass + if subtype is FloatType or (isinstance(subtype, type) and issubclass(subtype, FloatType)): + format_str = f'>{vector_size}f' + elif subtype is DoubleType or (isinstance(subtype, type) and issubclass(subtype, DoubleType)): + format_str = f'>{vector_size}d' + elif subtype is Int32Type or (isinstance(subtype, type) and issubclass(subtype, Int32Type)): + format_str = f'>{vector_size}i' + elif subtype is LongType or (isinstance(subtype, type) and issubclass(subtype, LongType)): + format_str = f'>{vector_size}q' + else: + return None, None, None + + start = time.perf_counter() + for _ in range(iterations): + result = list(struct.unpack(format_str, serialized_data)) + end = time.perf_counter() + + elapsed = end - start + per_op = (elapsed / iterations) * 1_000_000 # microseconds + + return elapsed, per_op, result + + +def benchmark_numpy_optimization(vector_type, serialized_data, iterations=10000): + """Benchmark numpy.frombuffer optimization.""" + try: + import numpy as np + except ImportError: + return None, None, None + + vector_size = vector_type.vector_size + subtype = vector_type.subtype + + # Determine dtype + if subtype is FloatType or (isinstance(subtype, type) and issubclass(subtype, FloatType)): + dtype = '>f4' + elif subtype is DoubleType or (isinstance(subtype, type) and issubclass(subtype, DoubleType)): + dtype = '>f8' + elif subtype is Int32Type or (isinstance(subtype, type) and issubclass(subtype, Int32Type)): + dtype = '>i4' + elif subtype is LongType or (isinstance(subtype, type) and issubclass(subtype, LongType)): + dtype = '>i8' + else: + return None, None, None + + start = time.perf_counter() + for _ in range(iterations): + arr = np.frombuffer(serialized_data, dtype=dtype, count=vector_size) + result = arr.tolist() + end = time.perf_counter() + + elapsed = end - start + per_op = (elapsed / iterations) * 1_000_000 # microseconds + + return elapsed, per_op, result + + +def benchmark_cython_deserializer(vector_type, serialized_data, iterations=10000): + """Benchmark Cython DesVectorType deserializer.""" + try: + from cassandra.deserializers import find_deserializer + except ImportError: + return None, None, None + + protocol_version = 4 + + # Get the Cython deserializer + deserializer = find_deserializer(vector_type) + + # Check if we got the Cython deserializer + if deserializer.__class__.__name__ != 'DesVectorType': + return None, None, None + + start = time.perf_counter() + for _ in range(iterations): + result = deserializer.deserialize_bytes(serialized_data, protocol_version) + end = time.perf_counter() + + elapsed = end - start + per_op = (elapsed / iterations) * 1_000_000 # microseconds + + return elapsed, per_op, result + + +def verify_results(expected, *results): + """Verify that all results match expected values.""" + for i, result in enumerate(results): + if result is None: + continue + if len(result) != len(expected): + print(f" ❌ Result {i} length mismatch: {len(result)} vs {len(expected)}") + return False + for j, (a, b) in enumerate(zip(result, expected)): + # Use relative tolerance for floating point comparison + if isinstance(a, float) and isinstance(b, float): + # Allow 0.01% relative error for floats + if abs(a - b) > max(abs(a), abs(b)) * 1e-4 + 1e-7: + print(f" ❌ Result {i} value mismatch at index {j}: {a} vs {b}") + return False + elif abs(a - b) > 1e-9: + print(f" ❌ Result {i} value mismatch at index {j}: {a} vs {b}") + return False + return True + + +def run_benchmark_suite(vector_size, element_type, type_name, iterations=10000): + """Run complete benchmark suite for a given vector configuration.""" + print(f"\n{'='*80}") + print(f"Benchmark: Vector<{type_name}, {vector_size}>") + print(f"{'='*80}") + print(f"Iterations: {iterations:,}") + + # Create test data + from cassandra.cqltypes import lookup_casstype + cass_typename = f'org.apache.cassandra.db.marshal.{element_type.__name__}' + vector_typename = f'org.apache.cassandra.db.marshal.VectorType({cass_typename}, {vector_size})' + vector_type = lookup_casstype(vector_typename) + + serialized_data, expected_values = create_test_data(vector_size, element_type) + data_size = len(serialized_data) + + print(f"Serialized size: {data_size:,} bytes") + print() + + # Run benchmarks + results = [] + + # 1. Current implementation (baseline) + print("1. Current implementation (baseline)...") + elapsed, per_op, result_current = benchmark_current_implementation( + vector_type, serialized_data, iterations) + results.append(result_current) + print(f" Total: {elapsed:.4f}s, Per-op: {per_op:.2f} μs") + baseline_time = per_op + + # 2. Struct optimization + print("2. Python struct.unpack optimization...") + elapsed, per_op, result_struct = benchmark_struct_optimization( + vector_type, serialized_data, iterations) + results.append(result_struct) + if per_op is not None: + speedup = baseline_time / per_op + print(f" Total: {elapsed:.4f}s, Per-op: {per_op:.2f} μs, Speedup: {speedup:.2f}x") + else: + print(" Not applicable for this type") + + # 3. Numpy with tolist() + print("3. Numpy frombuffer + tolist()...") + elapsed, per_op, result_numpy = benchmark_numpy_optimization( + vector_type, serialized_data, iterations) + results.append(result_numpy) + if per_op is not None: + speedup = baseline_time / per_op + print(f" Total: {elapsed:.4f}s, Per-op: {per_op:.2f} μs, Speedup: {speedup:.2f}x") + else: + print(" Numpy not available") + + # 4. Cython deserializer + print("4. Cython DesVectorType deserializer...") + elapsed, per_op, result_cython = benchmark_cython_deserializer( + vector_type, serialized_data, iterations) + if per_op is not None: + results.append(result_cython) + speedup = baseline_time / per_op + print(f" Total: {elapsed:.4f}s, Per-op: {per_op:.2f} μs, Speedup: {speedup:.2f}x") + else: + print(" Cython deserializers not available") + + # Verify results + print("\nVerifying results...") + if verify_results(expected_values, *results): + print(" ✓ All results match!") + else: + print(" ✗ Result mismatch detected!") + + return baseline_time + + +def main(): + """Run all benchmarks.""" + # Pin to single CPU core for consistent measurements + try: + import os + os.sched_setaffinity(0, {0}) # Pin to CPU core 0 + print("Pinned to CPU core 0 for consistent measurements") + except (AttributeError, OSError) as e: + print(f"Could not pin to single core: {e}") + print("Running without CPU affinity...") + + print("="*80) + print("VectorType Deserialization Performance Benchmark") + print("="*80) + + # Test configurations: (vector_size, element_type, type_name, iterations) + test_configs = [ + # Small vectors + (3, FloatType, "float", 50000), + (4, FloatType, "float", 50000), + + # Medium vectors (common in ML) + (128, FloatType, "float", 10000), + (384, FloatType, "float", 10000), + + # Large vectors (embeddings) + (768, FloatType, "float", 5000), + (1536, FloatType, "float", 2000), + + # Other types (smaller iteration counts) + (128, DoubleType, "double", 10000), + (768, DoubleType, "double", 5000), + (1536, DoubleType, "double", 2000), + (64, Int32Type, "int", 15000), + (128, Int32Type, "int", 10000), + ] + + summary = [] + + for vector_size, element_type, type_name, iterations in test_configs: + baseline = run_benchmark_suite(vector_size, element_type, type_name, iterations) + summary.append((f"Vector<{type_name}, {vector_size}>", baseline)) + + # Print summary + print("\n" + "="*80) + print("SUMMARY - Current Implementation Performance") + print("="*80) + for config, baseline_time in summary: + print(f"{config:30s}: {baseline_time:8.2f} μs") + + print("\n" + "="*80) + print("Benchmark complete!") + print("="*80) + + +if __name__ == '__main__': + main() diff --git a/cassandra/buffer.pxd b/cassandra/buffer.pxd index 0bbb1d5f57..7711546f34 100644 --- a/cassandra/buffer.pxd +++ b/cassandra/buffer.pxd @@ -41,18 +41,13 @@ cdef inline char *buf_read(Buffer *buf, Py_ssize_t size) except NULL: raise IndexError("Requested more than length of buffer") return buf.ptr -cdef inline int slice_buffer(Buffer *buf, Buffer *out, - Py_ssize_t start, Py_ssize_t size) except -1: - if size < 0: - raise ValueError("Length must be positive") +cdef inline void from_ptr_and_size(char *ptr, Py_ssize_t size, Buffer *buf): + """Initialize buf from ptr and size. - if start + size > buf.size: - raise IndexError("Buffer slice out of bounds") + Negative sizes are valid sentinel values: -1 means NULL, -2 means not-set. + Callers should check buf.size < 0 to detect these cases. + """ + buf.ptr = ptr + buf.size = size - out.ptr = buf.ptr + start - out.size = size - return 0 -cdef inline void from_ptr_and_size(char *ptr, Py_ssize_t size, Buffer *out): - out.ptr = ptr - out.size = size diff --git a/cassandra/cqltypes.py b/cassandra/cqltypes.py index 99018eef03..e6a88a7d6f 100644 --- a/cassandra/cqltypes.py +++ b/cassandra/cqltypes.py @@ -51,6 +51,20 @@ vints_pack, vints_unpack, uvint_unpack, uvint_pack) from cassandra import util +# Determine numpy availability independently rather than importing the flag +# from cassandra.cython_deps: this module sits on cassandra.row_parser's +# import chain (row_parser -> deserializers -> cqltypes), and +# cassandra.cython_deps determines HAVE_CYTHON by importing +# cassandra.row_parser. Importing cython_deps from here would re-enter the +# still-initializing cython_deps module and raise ImportError on the +# partially initialized module, which cython_deps then misinterprets as +# "Cython is unavailable". +try: + import numpy as np + HAVE_NUMPY = True +except ImportError: + HAVE_NUMPY = False + _little_endian_flag = 1 # we always serialize LE import ipaddress @@ -1432,6 +1446,9 @@ class VectorType(_CassandraType): typename = 'org.apache.cassandra.db.marshal.VectorType' vector_size = 0 subtype = None + _vector_struct = None # Cached struct.Struct for bulk deserialization + _struct_format_map = {} # Populated after FloatType etc. are defined + _numpy_dtype = None # Cached numpy dtype string for large vector deserialization @classmethod def serial_size(cls): @@ -1443,7 +1460,16 @@ def apply_parameters(cls, params, names): assert len(params) == 2 subtype = lookup_casstype(params[0]) vsize = params[1] - return type('%s(%s)' % (cls.cass_parameterized_type_with([]), vsize), (cls,), {'vector_size': vsize, 'subtype': subtype}) + # Cache a struct.Struct for bulk deserialization of known numeric types + vector_struct = None + numpy_dtype = None + for base_type, fmt_char in cls._struct_format_map.items(): + if subtype is base_type or (isinstance(subtype, type) and issubclass(subtype, base_type)): + vector_struct = struct.Struct(f'>{vsize}{fmt_char}') + numpy_dtype = cls._numpy_dtype_map.get(fmt_char) + break + return type('%s(%s)' % (cls.cass_parameterized_type_with([]), vsize), (cls,), + {'vector_size': vsize, 'subtype': subtype, '_vector_struct': vector_struct, '_numpy_dtype': numpy_dtype}) @classmethod def deserialize(cls, byts, protocol_version): @@ -1454,25 +1480,55 @@ def deserialize(cls, byts, protocol_version): raise ValueError( "Expected vector of type {0} and dimension {1} to have serialized size {2}; observed serialized size of {3} instead"\ .format(cls.subtype.typename, cls.vector_size, expected_byte_size, len(byts))) - indexes = (serialized_size * x for x in range(0, cls.vector_size)) - return [cls.subtype.deserialize(byts[idx:idx + serialized_size], protocol_version) for idx in indexes] + # Optimization: bulk deserialization for common numeric types + # For small vectors: use cached struct.Struct (avoids per-call format string allocation) + # For large vectors with numpy: use numpy.frombuffer (1.3-1.5x faster for 128+ elements) + # Threshold at 32 elements balances simplicity with performance + if cls._vector_struct is not None: + if HAVE_NUMPY and cls.vector_size >= 32 and cls._numpy_dtype is not None: + return np.frombuffer(byts, dtype=cls._numpy_dtype, count=cls.vector_size).tolist() + return list(cls._vector_struct.unpack(byts)) + # Fallback: element-by-element deserialization for other fixed-size types + result = [None] * cls.vector_size + subtype_deserialize = cls.subtype.deserialize + offset = 0 + for i in range(cls.vector_size): + result[i] = subtype_deserialize(byts[offset:offset + serialized_size], protocol_version) + offset += serialized_size + return result + + # Variable-size subtype path + result = [None] * cls.vector_size idx = 0 - rv = [] - while (len(rv) < cls.vector_size): + byts_len = len(byts) + subtype_deserialize = cls.subtype.deserialize + + for i in range(cls.vector_size): + if idx >= byts_len: + raise ValueError("Error reading additional data during vector deserialization after successfully adding {} elements"\ + .format(i)) + try: size, bytes_read = uvint_unpack(byts[idx:]) - idx += bytes_read - rv.append(cls.subtype.deserialize(byts[idx:idx + size], protocol_version)) - idx += size - except: + except (IndexError, KeyError): + raise ValueError("Error reading additional data during vector deserialization after successfully adding {} elements"\ + .format(i)) + + idx += bytes_read + + if idx + size > byts_len: raise ValueError("Error reading additional data during vector deserialization after successfully adding {} elements"\ - .format(len(rv))) + .format(i)) + + result[i] = subtype_deserialize(byts[idx:idx + size], protocol_version) + idx += size - # If we have any additional data in the serialized vector treat that as an error as well - if idx < len(byts): + # Check for additional data + if idx < byts_len: raise ValueError("Additional bytes remaining after vector deserialization completed") - return rv + + return result @classmethod def serialize(cls, v, protocol_version): @@ -1483,6 +1539,9 @@ def serialize(cls, v, protocol_version): .format(cls.vector_size, cls.subtype.typename, v_length)) serialized_size = cls.subtype.serial_size() + # Bulk serialization for known numeric types (symmetric with struct.unpack in deserialize) + if cls._vector_struct is not None and serialized_size is not None: + return cls._vector_struct.pack(*v) buf = io.BytesIO() for item in v: item_bytes = cls.subtype.serialize(item, protocol_version) @@ -1494,3 +1553,23 @@ def serialize(cls, v, protocol_version): @classmethod def cql_parameterized_type(cls): return "%s<%s, %s>" % (cls.typename, cls.subtype.cql_parameterized_type(), cls.vector_size) + + +# Populate VectorType._struct_format_map now that all types are defined +# Note: ShortType (smallint) is intentionally excluded. Cassandra's +# AbstractType.valueLengthIfFixed() (and ShortType.java specifically) does not +# override the variable-length default, so smallint vector elements are +# vint-length-prefixed on the wire, not fixed 2-byte values. Treating it as +# fixed-width here would be both dead code (VectorType.deserialize/serialize +# gate on subtype.serial_size() before ever consulting this map, and +# ShortType.serial_size() correctly returns None) and, if ever consulted +# directly (e.g. by numpy_parser), incorrect. +VectorType._struct_format_map = { + FloatType: 'f', + DoubleType: 'd', + Int32Type: 'i', + LongType: 'q', +} + +# Map struct format chars to numpy dtype strings for large vector deserialization +VectorType._numpy_dtype_map = {'f': '>f4', 'd': '>f8', 'i': '>i4', 'q': '>i8'} diff --git a/cassandra/cython_marshal.pyx b/cassandra/cython_marshal.pyx index 0a926b6eef..ac07b6378f 100644 --- a/cassandra/cython_marshal.pyx +++ b/cassandra/cython_marshal.pyx @@ -19,6 +19,19 @@ from libc.stdint cimport (int8_t, int16_t, int32_t, int64_t, from libc.string cimport memcpy from cassandra.buffer cimport Buffer, buf_read, to_bytes +# Use ntohs/ntohl for efficient big-endian to native conversion (single bswap instruction on x86) +# Platform-specific header: arpa/inet.h on POSIX, winsock2.h on Windows +cdef extern from *: + """ + #ifdef _WIN32 + #include + #else + #include + #endif + """ + uint16_t ntohs(uint16_t netshort) nogil + uint32_t ntohl(uint32_t netlong) nogil + cdef bint is_little_endian from cassandra.util import is_little_endian @@ -36,35 +49,40 @@ ctypedef fused num_t: cdef inline num_t unpack_num(Buffer *buf, num_t *dummy=NULL): # dummy pointer because cython wants the fused type as an arg """ - Copy to aligned destination, conditionally swapping to native byte order + Copy to aligned destination, conditionally swapping to native byte order. + Uses ntohs/ntohl for 16/32-bit types (compiles to single bswap instruction). """ - cdef Py_ssize_t start, end, i + cdef Py_ssize_t i cdef char *src = buf_read(buf, sizeof(num_t)) - cdef num_t ret = 0 + cdef num_t ret cdef char *out = &ret + cdef uint32_t temp32 # For float byte-swapping + + # Copy to aligned location first + memcpy(&ret, src, sizeof(num_t)) + + if not is_little_endian: + return ret - if is_little_endian: + # Use optimized byte-swap intrinsics for 16-bit and 32-bit types + if num_t is int16_t or num_t is uint16_t: + return ntohs(ret) + elif num_t is int32_t or num_t is uint32_t: + return ntohl(ret) + elif num_t is float: + # For float, reinterpret bits as uint32, swap, then reinterpret back + temp32 = (&ret)[0] + temp32 = ntohl(temp32) + return (&temp32)[0] + else: + # 64-bit, double, or 8-bit: use byte-swap loop (8-bit loop is no-op) for i in range(sizeof(num_t)): out[sizeof(num_t) - i - 1] = src[i] - else: - memcpy(out, src, sizeof(num_t)) - - return ret + return ret cdef varint_unpack(Buffer *term): """Unpack a variable-sized integer""" return varint_unpack_py3(to_bytes(term)) -# TODO: Optimize these two functions cdef varint_unpack_py3(bytes term): - val = int(''.join(["%02x" % i for i in term]), 16) - if (term[0] & 128) != 0: - shift = len(term) * 8 # * Note below - val -= 1 << shift - return val - -# * Note * -# '1 << (len(term) * 8)' Cython tries to do native -# integer shifts, which overflows. We need this to -# emulate Python shifting, which will expand the long -# to accommodate + return int.from_bytes(term, byteorder='big', signed=True) diff --git a/cassandra/deserializers.pyx b/cassandra/deserializers.pyx index 98e8676bbc..5bba972e66 100644 --- a/cassandra/deserializers.pyx +++ b/cassandra/deserializers.pyx @@ -13,10 +13,11 @@ # limitations under the License. -from libc.stdint cimport int32_t, uint16_t +from libc.stdint cimport int32_t, int64_t, int16_t, uint16_t, uint32_t +from libc.string cimport memcpy include 'cython_marshal.pyx' -from cassandra.buffer cimport Buffer, to_bytes, slice_buffer +from cassandra.buffer cimport Buffer, to_bytes, from_ptr_and_size from cassandra.cython_utils cimport datetime_from_timestamp, datetime_from_ms_timestamp from cython.view cimport array as cython_array @@ -29,6 +30,19 @@ from uuid import UUID from cassandra import cqltypes from cassandra import util +# Determine numpy availability independently rather than importing the flag +# from cassandra.cython_deps: this module sits on cassandra.row_parser's import +# chain (row_parser -> deserializers), and cassandra.cython_deps determines +# HAVE_CYTHON by importing cassandra.row_parser. Importing cython_deps from +# here would re-enter the still-initializing cython_deps module and raise +# ImportError on the partially initialized module, which cython_deps then +# misinterprets as "Cython is unavailable". +try: + import numpy as np + HAVE_NUMPY = True +except ImportError: + HAVE_NUMPY = False + cdef class Deserializer: """Cython-based deserializer class for a cqltype""" @@ -58,10 +72,11 @@ cdef class DesBytesTypeByteArray(Deserializer): # TODO: Use libmpdec: http://www.bytereef.org/mpdecimal/index.html cdef class DesDecimalType(Deserializer): cdef deserialize(self, Buffer *buf, int protocol_version): - cdef Buffer varint_buf - slice_buffer(buf, &varint_buf, 4, buf.size - 4) - cdef int32_t scale = unpack_num[int32_t](buf) + + # Create a view of the remaining bytes (after the 4-byte scale) + cdef Buffer varint_buf + from_ptr_and_size(buf.ptr + 4, buf.size - 4, &varint_buf) unscaled = varint_unpack(&varint_buf) return Decimal('%de%d' % (unscaled, -scale)) @@ -181,8 +196,213 @@ cdef class DesVarcharType(DesUTF8Type): pass +#-------------------------------------------------------------------------- +# Vector deserialization + +cdef inline bint _is_float_type(object subtype): + return subtype is cqltypes.FloatType or issubclass(subtype, cqltypes.FloatType) + +cdef inline bint _is_double_type(object subtype): + return subtype is cqltypes.DoubleType or issubclass(subtype, cqltypes.DoubleType) + +cdef inline bint _is_int32_type(object subtype): + return subtype is cqltypes.Int32Type or issubclass(subtype, cqltypes.Int32Type) + +cdef inline bint _is_int64_type(object subtype): + return subtype is cqltypes.LongType or issubclass(subtype, cqltypes.LongType) + +cdef inline list _deserialize_numpy_vector(Buffer *buf, int vector_size, str dtype): + """Unified numpy deserialization for large vectors""" + return np.frombuffer(buf.ptr[:buf.size], dtype=dtype, count=vector_size).tolist() + +cdef class DesVectorType(Deserializer): + """ + Optimized Cython deserializer for VectorType. + + For float and double vectors, uses direct memory access with C-level casting + for significantly better performance than Python-level deserialization. + """ + + cdef int vector_size + cdef object subtype + + def __init__(self, cqltype): + super().__init__(cqltype) + self.vector_size = cqltype.vector_size + self.subtype = cqltype.subtype + + def deserialize_bytes(self, bytes data, int protocol_version): + """Python-callable wrapper for deserialize that takes bytes.""" + cdef Buffer buf + buf.ptr = data + buf.size = len(data) + return self.deserialize(&buf, protocol_version) + + cdef deserialize(self, Buffer *buf, int protocol_version): + cdef int expected_size + cdef int elem_size + cdef bint use_numpy = HAVE_NUMPY and self.vector_size >= 32 + + # Determine element type, size, and dispatch appropriately + if _is_float_type(self.subtype): + elem_size = 4 + expected_size = self.vector_size * elem_size + if buf.size == expected_size: + if use_numpy: + return _deserialize_numpy_vector(buf, self.vector_size, '>f4') + return self._deserialize_float(buf) + raise ValueError( + f"Expected vector of type {self.subtype.typename} and dimension {self.vector_size} " + f"to have serialized size {expected_size}; observed serialized size of {buf.size} instead") + elif _is_double_type(self.subtype): + elem_size = 8 + expected_size = self.vector_size * elem_size + if buf.size == expected_size: + if use_numpy: + return _deserialize_numpy_vector(buf, self.vector_size, '>f8') + return self._deserialize_double(buf) + raise ValueError( + f"Expected vector of type {self.subtype.typename} and dimension {self.vector_size} " + f"to have serialized size {expected_size}; observed serialized size of {buf.size} instead") + elif _is_int32_type(self.subtype): + elem_size = 4 + expected_size = self.vector_size * elem_size + if buf.size == expected_size: + if use_numpy: + return _deserialize_numpy_vector(buf, self.vector_size, '>i4') + return self._deserialize_int32(buf) + raise ValueError( + f"Expected vector of type {self.subtype.typename} and dimension {self.vector_size} " + f"to have serialized size {expected_size}; observed serialized size of {buf.size} instead") + elif _is_int64_type(self.subtype): + elem_size = 8 + expected_size = self.vector_size * elem_size + if buf.size == expected_size: + if use_numpy: + return _deserialize_numpy_vector(buf, self.vector_size, '>i8') + return self._deserialize_int64(buf) + raise ValueError( + f"Expected vector of type {self.subtype.typename} and dimension {self.vector_size} " + f"to have serialized size {expected_size}; observed serialized size of {buf.size} instead") + else: + # Unsupported type, use generic deserialization + return self._deserialize_generic(buf, protocol_version) + + cdef inline list _deserialize_float(self, Buffer *buf): + """Deserialize float vector using direct C-level access with byte swapping""" + cdef Py_ssize_t i + cdef list result + cdef float temp + cdef uint32_t temp32 + + result = [None] * self.vector_size + for i in range(self.vector_size): + # Copy to aligned local, then convert from big-endian + memcpy(&temp32, buf.ptr + i * 4, 4) + temp32 = ntohl(temp32) + temp = (&temp32)[0] + result[i] = temp + + return result + + cdef inline list _deserialize_double(self, Buffer *buf): + """Deserialize double vector using direct C-level access with byte swapping""" + cdef Py_ssize_t i + cdef list result + cdef double temp + cdef char *src_bytes + cdef char *out_bytes + cdef int j + + result = [None] * self.vector_size + for i in range(self.vector_size): + src_bytes = buf.ptr + i * 8 + out_bytes = &temp + + # Swap bytes for big-endian to native conversion + if is_little_endian: + for j in range(8): + out_bytes[7 - j] = src_bytes[j] + else: + memcpy(&temp, src_bytes, 8) + + result[i] = temp + + return result + + cdef inline list _deserialize_int32(self, Buffer *buf): + """Deserialize int32 vector using direct C-level access with ntohl""" + cdef Py_ssize_t i + cdef list result + cdef int32_t temp + cdef uint32_t temp32 + + result = [None] * self.vector_size + for i in range(self.vector_size): + # Copy to aligned local, then convert from big-endian + memcpy(&temp32, buf.ptr + i * 4, 4) + temp = ntohl(temp32) + result[i] = temp + + return result + + cdef inline list _deserialize_int64(self, Buffer *buf): + """Deserialize int64/long vector using direct C-level access with byte swapping""" + cdef Py_ssize_t i + cdef list result + cdef int64_t temp + cdef char *src_bytes + cdef char *out_bytes + cdef int j + + result = [None] * self.vector_size + for i in range(self.vector_size): + src_bytes = buf.ptr + i * 8 + out_bytes = &temp + + # Swap bytes for big-endian to native conversion + if is_little_endian: + for j in range(8): + out_bytes[7 - j] = src_bytes[j] + else: + memcpy(&temp, src_bytes, 8) + + result[i] = temp + + return result + + cdef inline list _deserialize_generic(self, Buffer *buf, int protocol_version): + """Fallback: element-by-element deserialization for non-optimized types""" + cdef Py_ssize_t i + cdef Buffer elem_buf + cdef int offset = 0 + cdef list result = [None] * self.vector_size + + _serialized_size = self.subtype.serial_size() + if _serialized_size is None: + raise ValueError( + f"VectorType with variable-size subtype {self.subtype.typename} " + "is not supported in Cython deserializer") + cdef int serialized_size = _serialized_size + + # Validate total size before processing + cdef int expected_size = self.vector_size * serialized_size + if buf.size != expected_size: + raise ValueError( + f"Expected vector of type {self.subtype.typename} and dimension {self.vector_size} " + f"to have serialized size {expected_size}; observed serialized size of {buf.size} instead") + + for i in range(self.vector_size): + from_ptr_and_size(buf.ptr + offset, serialized_size, &elem_buf) + result[i] = self.subtype.deserialize(to_bytes(&elem_buf), protocol_version) + offset += serialized_size + + return result + + cdef class _DesParameterizedType(Deserializer): + cdef object subtypes cdef Deserializer[::1] deserializers cdef Py_ssize_t subtypes_len @@ -247,22 +467,40 @@ cdef inline int subelem( Read the next element from the buffer: first read the size (in bytes) of the element, then fill elem_buf with a newly sliced buffer of this size (and the right offset). + + Protocol: n >= 0: n bytes follow + n == -1: NULL value + n == -2: not set value + n < -2: invalid """ cdef int32_t elemlen _unpack_len(buf, offset[0], &elemlen) offset[0] += sizeof(int32_t) - slice_buffer(buf, elem_buf, offset[0], elemlen) - offset[0] += elemlen - return 0 + # Happy path: non-negative length element that fits in buffer + if elemlen >= 0: + if offset[0] + elemlen <= buf.size: + from_ptr_and_size(buf.ptr + offset[0], elemlen, elem_buf) + offset[0] += elemlen + return 0 + raise IndexError("Element length %d at offset %d exceeds buffer size %d" % (elemlen, offset[0], buf.size)) + # NULL value (-1) or not set value (-2) + elif elemlen == -1 or elemlen == -2: + from_ptr_and_size(NULL, elemlen, elem_buf) + return 0 + # Invalid value (n < -2) + else: + raise ValueError("Invalid element length %d at offset %d" % (elemlen, offset[0])) -cdef int _unpack_len(Buffer *buf, int offset, int32_t *output) except -1: - cdef Buffer itemlen_buf - slice_buffer(buf, &itemlen_buf, offset, sizeof(int32_t)) - - output[0] = unpack_num[int32_t](&itemlen_buf) +cdef inline int _unpack_len(Buffer *buf, int offset, int32_t *output) except -1: + """Read a big-endian int32 at the given offset using memcpy for alignment safety.""" + if offset + sizeof(int32_t) > buf.size: + raise IndexError("Cannot read length field: offset %d + 4 exceeds buffer size %d" % (offset, buf.size)) + cdef uint32_t temp + memcpy(&temp, buf.ptr + offset, sizeof(uint32_t)) + output[0] = ntohl(temp) return 0 #-------------------------------------------------------------------------- @@ -320,9 +558,9 @@ cdef class DesTupleType(_DesParameterizedType): cdef deserialize(self, Buffer *buf, int protocol_version): cdef Py_ssize_t i, p cdef int32_t itemlen + cdef uint32_t _tuple_tmp cdef tuple res = tuple_new(self.subtypes_len) cdef Buffer item_buf - cdef Buffer itemlen_buf cdef Deserializer deserializer # collections inside UDTs are always encoded with at least the @@ -333,16 +571,25 @@ cdef class DesTupleType(_DesParameterizedType): values = [] for i in range(self.subtypes_len): item = None - if p < buf.size: - slice_buffer(buf, &itemlen_buf, p, 4) - itemlen = unpack_num[int32_t](&itemlen_buf) + if p + 4 <= buf.size: + # Read itemlen using memcpy for alignment safety + memcpy(&_tuple_tmp, buf.ptr + p, 4) + itemlen = ntohl(_tuple_tmp) p += 4 - if itemlen >= 0: - slice_buffer(buf, &item_buf, p, itemlen) + + if itemlen >= 0 and p + itemlen <= buf.size: + from_ptr_and_size(buf.ptr + p, itemlen, &item_buf) p += itemlen deserializer = self.deserializers[i] item = from_binary(deserializer, &item_buf, protocol_version) + elif itemlen < 0: + # NULL value, item stays None + pass + else: + raise IndexError("Tuple item length %d at offset %d exceeds buffer size %d" % (itemlen, p, buf.size)) + elif p < buf.size: + raise IndexError("Cannot read tuple item length at offset %d: only %d bytes remain" % (p, buf.size - p)) tuple_set(res, i, item) @@ -365,7 +612,7 @@ cdef class DesCompositeType(_DesParameterizedType): cdef deserialize(self, Buffer *buf, int protocol_version): cdef Py_ssize_t i, idx, start cdef Buffer elem_buf - cdef int16_t element_length + cdef uint16_t element_length cdef Deserializer deserializer cdef tuple res = tuple_new(self.subtypes_len) @@ -384,15 +631,23 @@ cdef class DesCompositeType(_DesParameterizedType): break element_length = unpack_num[uint16_t](buf) - slice_buffer(buf, &elem_buf, 2, element_length) - deserializer = self.deserializers[i] - item = from_binary(deserializer, &elem_buf, protocol_version) - tuple_set(res, i, item) + # Validate that we have enough data for the element and EOC byte (happy path check) + if 2 + element_length + 1 <= buf.size: + from_ptr_and_size(buf.ptr + 2, element_length, &elem_buf) + + deserializer = self.deserializers[i] + item = from_binary(deserializer, &elem_buf, protocol_version) + tuple_set(res, i, item) - # skip element length, element, and the EOC (one byte) - start = 2 + element_length + 1 - slice_buffer(buf, buf, start, buf.size - start) + # skip element length, element, and the EOC (one byte) + # Advance buffer in-place with direct assignment + start = 2 + element_length + 1 + buf.ptr = buf.ptr + start + buf.size = buf.size - start + else: + raise IndexError("Composite element length %d requires %d bytes but only %d remain" % + (element_length, 2 + element_length + 1, buf.size)) return res @@ -474,6 +729,19 @@ cpdef Deserializer find_deserializer(cqltype): cls = DesReversedType elif issubclass(cqltype, cqltypes.FrozenType): cls = DesFrozenType + elif issubclass(cqltype, cqltypes.VectorType): + # Only subtypes that are actually fixed-width as vector elements + # (per VectorType._struct_format_map) benefit from -- and are + # supported by -- the optimized Cython path. Variable-length + # subtypes (e.g. UTF8Type, ShortType/smallint) must go through + # GenericDeserializer, which delegates to the already-correct + # pure-Python VectorType.deserialize(). Without this check, + # DesVectorType would be selected regardless of subtype and would + # only discover it can't handle the data after construction, via + # the ValueError in _deserialize_generic -- which nothing upstream + # catches, so real queries against e.g. Vector columns + # would crash during row parsing. + cls = DesVectorType if cqltype.subtype in cqltypes.VectorType._struct_format_map else GenericDeserializer else: cls = GenericDeserializer diff --git a/cassandra/ioutils.pyx b/cassandra/ioutils.pyx index b0ab4f16cb..f1e489c7cf 100644 --- a/cassandra/ioutils.pyx +++ b/cassandra/ioutils.pyx @@ -15,7 +15,8 @@ include 'cython_marshal.pyx' from cassandra.buffer cimport Buffer, from_ptr_and_size -from libc.stdint cimport int32_t +from libc.stdint cimport int32_t, uint32_t +from libc.string cimport memcpy from cassandra.bytesio cimport BytesIOReader @@ -41,7 +42,8 @@ cdef inline int get_buf(BytesIOReader reader, Buffer *buf_out) except -1: return 0 cdef inline int32_t read_int(BytesIOReader reader) except ?0xDEAD: - cdef Buffer buf - buf.ptr = reader.read(4) - buf.size = 4 - return unpack_num[int32_t](&buf) + """Read a big-endian int32 directly from the reader using memcpy for alignment safety.""" + cdef char *src = reader.read(4) + cdef uint32_t temp + memcpy(&temp, src, 4) + return ntohl(temp) diff --git a/cassandra/marshal.py b/cassandra/marshal.py index 413e1831d4..a7238ea4b7 100644 --- a/cassandra/marshal.py +++ b/cassandra/marshal.py @@ -40,11 +40,7 @@ def _make_packer(format_string): def varint_unpack(term): - val = int(''.join("%02x" % i for i in term), 16) - if (term[0] & 128) != 0: - len_term = len(term) # pulling this out of the expression to avoid overflow in cython optimized code - val -= 1 << (len_term * 8) - return val + return int.from_bytes(term, byteorder='big', signed=True) def bit_length(n): diff --git a/cassandra/numpy_parser.pyx b/cassandra/numpy_parser.pyx index 0ad34f66e2..f6a047e980 100644 --- a/cassandra/numpy_parser.pyx +++ b/cassandra/numpy_parser.pyx @@ -26,6 +26,7 @@ include "ioutils.pyx" cimport cython from libc.stdint cimport uint64_t, uint8_t +from libc.string cimport memset from cpython.ref cimport Py_INCREF, PyObject from cassandra.bytesio cimport BytesIOReader @@ -52,12 +53,14 @@ ctypedef struct ArrDesc: int stride # should be large enough as we allocate contiguous arrays int is_object Py_uintptr_t mask_ptr + int mask_stride arrDescDtype = np.dtype( [ ('buf_ptr', np.uintp) , ('stride', np.dtype('i')) , ('is_object', np.dtype('i')) , ('mask_ptr', np.uintp) + , ('mask_stride', np.dtype('i')) ], align=True) _cqltype_to_numpy = { @@ -112,7 +115,7 @@ def make_arrays(ParseDesc desc, array_size): (e.g. this can be fed into pandas.DataFrame) """ array_descs = np.empty((desc.rowsize,), arrDescDtype) - arrays = [] + arrays = [None] * desc.rowsize for i, coltype in enumerate(desc.coltypes): arr = make_array(coltype, array_size) @@ -121,9 +124,11 @@ def make_arrays(ParseDesc desc, array_size): array_descs[i]['is_object'] = arr.dtype is obj_dtype try: array_descs[i]['mask_ptr'] = arr.mask.ctypes.data + array_descs[i]['mask_stride'] = arr.mask.strides[0] except AttributeError: array_descs[i]['mask_ptr'] = 0 - arrays.append(arr) + array_descs[i]['mask_stride'] = 1 + arrays[i] = arr return array_descs, arrays @@ -131,7 +136,32 @@ def make_arrays(ParseDesc desc, array_size): def make_array(coltype, array_size): """ Allocate a new NumPy array of the given column type and size. + For VectorType, creates a 2D array (array_size x vector_dimension). """ + # Check if this is a VectorType + if issubclass(coltype, cqltypes.VectorType): + # VectorType - create 2D array (rows x vector_dimension) + vector_size = coltype.vector_size + subtype = coltype.subtype + # Only subtypes that are fixed-width *as vector elements* (per + # VectorType._struct_format_map) are eligible for the accelerated + # 2D-array path. This is deliberately not the same set as + # _cqltype_to_numpy: a subtype can be fixed-width when serialized as + # its own scalar column (e.g. ShortType/smallint, which is always 2 + # bytes there) while still being variable-length (vint-prefixed) when + # serialized as a vector element, per Cassandra's actual wire format. + # Reusing _cqltype_to_numpy here would silently misparse those types. + if subtype in cqltypes.VectorType._struct_format_map: + dtype = _cqltype_to_numpy[subtype] + a = np.ma.empty((array_size, vector_size), dtype=dtype) + a.mask = np.zeros((array_size, vector_size), dtype=bool) + else: + # Unsupported (or variable-length-as-vector-element) subtype - + # fall back to object array + a = np.empty((array_size,), dtype=obj_dtype) + return a + + # Scalar types try: a = np.ma.empty((array_size,), dtype=_cqltype_to_numpy[coltype]) a.mask = np.zeros((array_size,), dtype=bool) @@ -160,13 +190,26 @@ cdef inline int unpack_row( Py_INCREF(val) ( arr.buf_ptr)[0] = val elif buf.size >= 0: + # buf.size comes straight off the wire. It must match the fixed + # column width the destination array slot was allocated with + # (arr.stride); otherwise the memcpy below would read/write past + # the end of that slot and corrupt adjacent array memory. + if buf.size != arr.stride: + raise ValueError( + f"Expected column value to have serialized size {arr.stride}; " + f"observed serialized size of {buf.size} instead") memcpy( arr.buf_ptr, buf.ptr, buf.size) else: - memcpy(arr.mask_ptr, &mask_true, 1) + # Non-object (fixed-width) arrays are always allocated as masked + # arrays in make_array(), so mask_ptr is only ever 0 for object + # arrays (see make_arrays()/make_array()) -- and those are always + # handled by the arr.is_object branch above, so this memset never + # actually runs against a NULL mask_ptr. + memset(arr.mask_ptr, 1, arr.mask_stride) # Update the pointer into the array for the next time arrays[i].buf_ptr += arr.stride - arrays[i].mask_ptr += 1 + arrays[i].mask_ptr += arr.mask_stride return 0 @@ -174,6 +217,7 @@ cdef inline int unpack_row( def make_native_byteorder(arr): """ Make sure all values have a native endian in the NumPy arrays. + Handles both 1D (scalar types) and 2D (VectorType) arrays. """ if is_little_endian and not arr.dtype.kind == 'O': # We have arrays in big-endian order. First swap the bytes diff --git a/setup.py b/setup.py index 52e04a63e5..1bee7bb961 100644 --- a/setup.py +++ b/setup.py @@ -329,6 +329,11 @@ def _setup_extensions(self): cython_candidates = ['cluster', 'concurrent', 'connection', 'cqltypes', 'metadata', 'pool', 'protocol', 'query', 'util', 'shard_info'] compile_args = [] if is_windows else ['-Wno-unused-function'] + # cython_marshal.pyx (included by deserializers.pyx, and by ioutils.pyx which + # is in turn included by numpy_parser.pyx/obj_parser.pyx/row_parser.pyx) declares + # ntohs/ntohl via winsock2.h on Windows. Those symbols are implemented in + # ws2_32.lib, so every *.pyx extension needs to link against it on Windows. + platform_libraries = ['ws2_32'] if is_windows else [] self.extensions.extend(cythonize( [Extension('cassandra.%s' % m, ['cassandra/%s.py' % m], extra_compile_args=compile_args) @@ -339,7 +344,8 @@ def _setup_extensions(self): )) self.extensions.extend(cythonize( - NoPatchExtension("*", ["cassandra/*.pyx"], extra_compile_args=compile_args), + NoPatchExtension("*", ["cassandra/*.pyx"], extra_compile_args=compile_args, + libraries=platform_libraries), nthreads=build_concurrency, compiler_directives={'language_level': 3}, )) diff --git a/tests/unit/cython/test_cython_deps.py b/tests/unit/cython/test_cython_deps.py new file mode 100644 index 0000000000..b60b262c32 --- /dev/null +++ b/tests/unit/cython/test_cython_deps.py @@ -0,0 +1,119 @@ +# Copyright ScyllaDB, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Regression test for a circular import that made cassandra.cython_deps.HAVE_CYTHON +incorrectly report False, depending on which module a process happened to import +first. + +cassandra.cython_deps determines HAVE_CYTHON by importing cassandra.row_parser. +cassandra.row_parser (via cassandra.deserializers, and cassandra.deserializers' +import of cassandra.cqltypes) used to import HAVE_NUMPY back out of +cassandra.cython_deps. When cassandra.cython_deps was the first cassandra module +touched in a process, Python would register it in sys.modules before running its +body, so that re-entrant "from cassandra.cython_deps import HAVE_NUMPY" would hit +the partially initialized module and raise ImportError -- which cassandra.cython_deps +then swallowed via its own `except ImportError: HAVE_CYTHON = False`, permanently +(and incorrectly) marking Cython as unavailable for the rest of the process. + +Because the bug only manifests when cassandra.cython_deps is the *first* +cassandra-related import, it must be exercised in a fresh interpreter -- importing +things in the "wrong" order in-process within the existing test run would not +reproduce it (whatever ran earlier already primed sys.modules). +""" + +import subprocess +import sys +import unittest +from pathlib import Path + +try: + from tests import VERIFY_CYTHON +except ImportError: + VERIFY_CYTHON = False + +# Deliberately avoid tests.unit.cython.utils.cythontest / cassandra.cython_deps.HAVE_CYTHON +# here: whether that flag is (correctly) True is exactly what this module is testing, and +# by the time this test module is collected some other test/import may already have primed +# sys.modules['cassandra.cython_deps'] in a way that hides a regression. Instead, probe +# for the compiled extension directly and independently of cython_deps's own bookkeeping. +try: + import cassandra.row_parser # noqa: F401 + _CYTHON_EXTENSION_BUILT = True +except ImportError: + _CYTHON_EXTENSION_BUILT = False + +cythonbuilt = unittest.skipUnless(_CYTHON_EXTENSION_BUILT or VERIFY_CYTHON, + 'Cython extensions are not built') + + +def _run_first_import(first_import_statement): + """ + Run `first_import_statement` as the very first cassandra-related statement + in a brand new interpreter, then report HAVE_CYTHON/HAVE_NUMPY. + """ + driver_path = str(Path(__file__).parent.parent.parent.parent) + script = ( + "import sys\n" + # Append (not insert at 0) so an installed/compiled build of the driver + # takes precedence over the in-tree source if both are on sys.path. + "sys.path.append({driver_path!r})\n" + "{first_import_statement}\n" + "from cassandra.cython_deps import HAVE_CYTHON, HAVE_NUMPY\n" + "print('HAVE_CYTHON=%s' % HAVE_CYTHON)\n" + "print('HAVE_NUMPY=%s' % HAVE_NUMPY)\n" + ).format(driver_path=driver_path, first_import_statement=first_import_statement) + + result = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == 0, ( + "subprocess failed\nstdout:\n%s\nstderr:\n%s" % (result.stdout, result.stderr) + ) + return result.stdout + + +class CythonDepsImportOrderTest(unittest.TestCase): + """ + Verify that cassandra.cython_deps.HAVE_CYTHON is reported consistently + regardless of which cassandra module a fresh process imports first. + + Skipped unless the compiled Cython extensions are actually available, + since that's the only scenario where HAVE_CYTHON is expected to be True. + """ + + @cythonbuilt + def test_cython_deps_imported_first(self): + # This is the case that used to trigger the circular import: nothing + # else has touched the cassandra package yet. + output = _run_first_import("from cassandra.cython_deps import HAVE_CYTHON") + self.assertIn("HAVE_CYTHON=True", output) + + @cythonbuilt + def test_row_parser_imported_first(self): + output = _run_first_import("import cassandra.row_parser") + self.assertIn("HAVE_CYTHON=True", output) + + @cythonbuilt + def test_deserializers_imported_first(self): + output = _run_first_import("import cassandra.deserializers") + self.assertIn("HAVE_CYTHON=True", output) + + @cythonbuilt + def test_cqltypes_imported_first(self): + output = _run_first_import("import cassandra.cqltypes") + self.assertIn("HAVE_CYTHON=True", output) diff --git a/tests/unit/cython/test_types.py b/tests/unit/cython/test_types.py index 996be266c0..dc1cb9fd3c 100644 --- a/tests/unit/cython/test_types.py +++ b/tests/unit/cython/test_types.py @@ -27,3 +27,11 @@ def test_datetype(self): @cythontest def test_date_side_by_side(self): types_testhelper.test_date_side_by_side() + + @cythontest + def test_composite_long_element(self): + types_testhelper.test_composite_long_element() + + @cythontest + def test_tuple_itemlen_int32_max_no_overflow(self): + types_testhelper.test_tuple_itemlen_int32_max_no_overflow() diff --git a/tests/unit/cython/types_testhelper.pyx b/tests/unit/cython/types_testhelper.pyx index 81f9dca114..c2240984ae 100644 --- a/tests/unit/cython/types_testhelper.pyx +++ b/tests/unit/cython/types_testhelper.pyx @@ -14,12 +14,14 @@ import calendar import datetime +import struct import time include '../../../cassandra/ioutils.pyx' import io +from cassandra import cqltypes from cassandra.cqltypes import DateType from cassandra.protocol import write_value from cassandra.deserializers import find_deserializer @@ -72,6 +74,75 @@ def test_datetype(): assert deserialize(expected) == datetime.datetime(2038, 12, 31, 10, 10, 10, 123000) +def test_composite_long_element(): + """ + Regression test: DesCompositeType.deserialize used to store the + wire-provided (unsigned) 2-byte element length in a signed int16_t + local. Any element length greater than INT16_MAX (32767) would then + wrap around to a negative number, corrupting both the bounds check + and the buffer-advancing arithmetic that follows (element_length is + now a uint16_t, matching the actual wire type). + """ + cdef Deserializer des + cdef BytesIOReader reader + cdef Buffer buf + + element_length = 40000 # > INT16_MAX (32767) + payload = b'x' * element_length + + composite_type = cqltypes.CompositeType.apply_parameters([cqltypes.UTF8Type]) + des = find_deserializer(composite_type) + + # Composite wire format: 2-byte big-endian length, element bytes, 1 EOC byte + blob = struct.pack('>H', element_length) + payload + b'\x00' + reader = BytesIOReader(blob) + buf.ptr = reader.read() + buf.size = reader.size + + result = from_binary(des, &buf, 0) + assert result == (payload.decode('utf-8'),) + + +def test_tuple_itemlen_int32_max_no_overflow(): + """ + Confirms a reported false-positive: DesTupleType.deserialize checks + `p + itemlen <= buf.size` where `p` is Py_ssize_t (64-bit) and `itemlen` + is int32_t. Because C's usual arithmetic conversions promote the + narrower int32_t operand to match the wider Py_ssize_t before the + addition, this cannot wrap around even when itemlen == INT32_MAX -- the + addition happens in 64-bit space, not 32-bit. This test constructs a + tuple value whose declared item length is INT32_MAX against a buffer far + too small to hold it, and confirms the bounds check correctly rejects it + (raises IndexError) rather than silently passing and creating an + out-of-bounds buffer view. + """ + cdef Deserializer des + cdef BytesIOReader reader + cdef Buffer buf + + INT32_MAX = 2147483647 + + tuple_type = cqltypes.TupleType.apply_parameters([cqltypes.Int32Type]) + des = find_deserializer(tuple_type) + + # Only the 4-byte big-endian item length is present -- no payload bytes + # follow. If `p + itemlen` ever overflowed (e.g. computed as plain 32-bit + # arithmetic), it would wrap negative and incorrectly satisfy `<= buf.size`, + # which would then attempt to build a Buffer view spanning ~2GiB past the + # end of a 4-byte allocation. + blob = struct.pack('>i', INT32_MAX) + reader = BytesIOReader(blob) + buf.ptr = reader.read() + buf.size = reader.size + + try: + from_binary(des, &buf, 3) + except IndexError as e: + assert "exceeds buffer size" in str(e) + else: + assert False, "expected IndexError from oversized tuple item length" + + def test_date_side_by_side(): # Test pure python and cython date deserialization side-by-side # This is meant to detect inconsistent rounding or conversion (PYTHON-480 for example) diff --git a/tests/unit/test_numpy_parser.py b/tests/unit/test_numpy_parser.py new file mode 100644 index 0000000000..dcc1ed39cf --- /dev/null +++ b/tests/unit/test_numpy_parser.py @@ -0,0 +1,358 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import struct +import unittest + +try: + import numpy as np + from cassandra.numpy_parser import NumpyParser, make_array + from cassandra.bytesio import BytesIOReader + from cassandra.parsing import ParseDesc + from cassandra.deserializers import obj_array + HAVE_NUMPY = True +except ImportError: + HAVE_NUMPY = False + +from cassandra import cqltypes + + +@unittest.skipUnless(HAVE_NUMPY, "NumPy not available") +class TestNumpyParserVectorType(unittest.TestCase): + """Tests for VectorType support in NumpyParser""" + + def _create_vector_type(self, subtype, vector_size): + """Helper to create a VectorType class""" + return type( + f'VectorType({vector_size})', + (cqltypes.VectorType,), + {'vector_size': vector_size, 'subtype': subtype} + ) + + def _serialize_vectors(self, vectors, format_char): + """Serialize a list of vectors using struct.pack""" + buffer = bytearray() + # Write row count + buffer.extend(struct.pack('>i', len(vectors))) + # Write each vector + for vector in vectors: + # Write byte size of vector (doesn't include size prefix in CQL) + byte_size = len(vector) * struct.calcsize(f'>{format_char}') + buffer.extend(struct.pack('>i', byte_size)) + # Write vector elements + buffer.extend(struct.pack(f'>{len(vector)}{format_char}', *vector)) + return bytes(buffer) + + def test_vector_float_2d_array(self): + """Test that VectorType creates and populates a 2D NumPy array""" + vector_size = 4 + vector_type = self._create_vector_type(cqltypes.FloatType, vector_size) + + # Create test data: 3 rows of 4-dimensional float vectors + vectors = [ + [1.0, 2.0, 3.0, 4.0], + [5.0, 6.0, 7.0, 8.0], + [9.0, 10.0, 11.0, 12.0], + ] + + # Serialize the data + serialized = self._serialize_vectors(vectors, 'f') + + # Parse with NumpyParser + parser = NumpyParser() + reader = BytesIOReader(serialized) + + desc = ParseDesc( + colnames=['vec'], + coltypes=[vector_type], + column_encryption_policy=None, + coldescs=None, + deserializers=obj_array([None]), + protocol_version=5 + ) + + result = parser.parse_rows(reader, desc) + + # Verify result structure + self.assertIn('vec', result) + arr = result['vec'] + + # Verify it's a 2D array with correct shape + self.assertEqual(arr.ndim, 2) + self.assertEqual(arr.shape, (3, 4)) + + # Verify the data + expected = np.array(vectors, dtype=' creates and populates a 2D NumPy array""" + vector_size = 3 + vector_type = self._create_vector_type(cqltypes.DoubleType, vector_size) + + # Create test data: 2 rows of 3-dimensional double vectors + vectors = [ + [1.5, 2.5, 3.5], + [4.5, 5.5, 6.5], + ] + + serialized = self._serialize_vectors(vectors, 'd') + + parser = NumpyParser() + reader = BytesIOReader(serialized) + + desc = ParseDesc( + colnames=['embedding'], + coltypes=[vector_type], + column_encryption_policy=None, + coldescs=None, + deserializers=obj_array([None]), + protocol_version=5 + ) + + result = parser.parse_rows(reader, desc) + + arr = result['embedding'] + self.assertEqual(arr.shape, (2, 3)) + + expected = np.array(vectors, dtype=' creates and populates a 2D NumPy array""" + vector_size = 128 + vector_type = self._create_vector_type(cqltypes.Int32Type, vector_size) + + # Create test data: 2 rows of 128-dimensional int vectors + vectors = [ + list(range(0, 128)), + list(range(128, 256)), + ] + + serialized = self._serialize_vectors(vectors, 'i') + + parser = NumpyParser() + reader = BytesIOReader(serialized) + + desc = ParseDesc( + colnames=['features'], + coltypes=[vector_type], + column_encryption_policy=None, + coldescs=None, + deserializers=obj_array([None]), + protocol_version=5 + ) + + result = parser.parse_rows(reader, desc) + + arr = result['features'] + self.assertEqual(arr.shape, (2, 128)) + + expected = np.array(vectors, dtype=' creates and populates a 2D NumPy array""" + vector_size = 5 + vector_type = self._create_vector_type(cqltypes.LongType, vector_size) + + vectors = [ + [100, 200, 300, 400, 500], + [600, 700, 800, 900, 1000], + ] + + serialized = self._serialize_vectors(vectors, 'q') + + parser = NumpyParser() + reader = BytesIOReader(serialized) + + desc = ParseDesc( + colnames=['ids'], + coltypes=[vector_type], + column_encryption_policy=None, + coldescs=None, + deserializers=obj_array([None]), + protocol_version=5 + ) + + result = parser.parse_rows(reader, desc) + + arr = result['ids'] + self.assertEqual(arr.shape, (2, 5)) + + expected = np.array(vectors, dtype=' allocation falls back to a 1D object + array instead of the fixed-width 2D fast path. + + ShortType (smallint) vector elements are vint-length-prefixed on the + wire (ShortType.serial_size() is None, matching Cassandra's real + encoding: neither AbstractType.valueLengthIfFixed() nor + ShortType.java override the variable-length default), not fixed + 2-byte values. So ShortType is intentionally excluded from + VectorType._struct_format_map / the numpy fast path -- allocating a + fixed 2D 'i', 2)) # row count + + # Row 1: id=1, vec=[1.0, 2.0, 3.0] + buffer.extend(struct.pack('>i', 4)) # int32 size + buffer.extend(struct.pack('>i', 1)) # id value + buffer.extend(struct.pack('>i', 12)) # vector size (3 floats) + buffer.extend(struct.pack('>3f', 1.0, 2.0, 3.0)) + + # Row 2: id=2, vec=[4.0, 5.0, 6.0] + buffer.extend(struct.pack('>i', 4)) + buffer.extend(struct.pack('>i', 2)) + buffer.extend(struct.pack('>i', 12)) + buffer.extend(struct.pack('>3f', 4.0, 5.0, 6.0)) + + parser = NumpyParser() + reader = BytesIOReader(bytes(buffer)) + + desc = ParseDesc( + colnames=['id', 'vec'], + coltypes=[cqltypes.Int32Type, vector_type], + column_encryption_policy=None, + coldescs=None, + deserializers=obj_array([None, None]), + protocol_version=5 + ) + + result = parser.parse_rows(reader, desc) + + # Verify id column (1D array) + self.assertEqual(result['id'].shape, (2,)) + np.testing.assert_array_equal(result['id'], np.array([1, 2], dtype='i', 1)) # row count + + # Int32Type has a fixed 4-byte width, but the wire here declares an + # 8-byte value -- this must be rejected rather than overflowing the + # destination array slot via memcpy. + buffer.extend(struct.pack('>i', 8)) + buffer.extend(struct.pack('>2i', 1, 2)) + + parser = NumpyParser() + reader = BytesIOReader(bytes(buffer)) + + desc = ParseDesc( + colnames=['id'], + coltypes=[cqltypes.Int32Type], + column_encryption_policy=None, + coldescs=None, + deserializers=obj_array([None]), + protocol_version=5 + ) + + with self.assertRaises(ValueError): + parser.parse_rows(reader, desc) + + def test_row_value_smaller_than_stride_raises(self): + buffer = bytearray() + buffer.extend(struct.pack('>i', 1)) # row count + + # LongType has a fixed 8-byte width, but the wire here declares only + # 4 bytes. + buffer.extend(struct.pack('>i', 4)) + buffer.extend(struct.pack('>i', 1)) + + parser = NumpyParser() + reader = BytesIOReader(bytes(buffer)) + + desc = ParseDesc( + colnames=['ctr'], + coltypes=[cqltypes.LongType], + column_encryption_policy=None, + coldescs=None, + deserializers=obj_array([None]), + protocol_version=5 + ) + + with self.assertRaises(ValueError): + parser.parse_rows(reader, desc) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/unit/test_types.py b/tests/unit/test_types.py index 11aab2748d..51e8db9b64 100644 --- a/tests/unit/test_types.py +++ b/tests/unit/test_types.py @@ -525,6 +525,273 @@ def test_deserialization_variable_size_too_big(self): with pytest.raises(ValueError, match="Additional bytes remaining after vector deserialization completed"): ctype_four.deserialize(ctype_five_bytes, 0) + def test_vector_cython_deserializer(self): + """ + Test that VectorType uses the Cython DesVectorType deserializer + and correctly deserializes vectors of supported numeric types. + + @since 3.x + @expected_result Cython deserializer exists and correctly deserializes vector data + + @test_category data_types:vector + """ + import struct + try: + from cassandra.deserializers import find_deserializer + except ImportError: + self.skipTest("Cython deserializers not available") + + # Test float vector + vt_float = VectorType.apply_parameters(['FloatType', 4], {}) + des_float = find_deserializer(vt_float) + self.assertEqual(des_float.__class__.__name__, 'DesVectorType') + + data_float = struct.pack('>4f', 1.0, 2.0, 3.0, 4.0) + result_float = vt_float.deserialize(data_float, 5) + self.assertEqual(result_float, [1.0, 2.0, 3.0, 4.0]) + + # Test double vector + from cassandra.cqltypes import DoubleType + vt_double = VectorType.apply_parameters(['DoubleType', 3], {}) + des_double = find_deserializer(vt_double) + self.assertEqual(des_double.__class__.__name__, 'DesVectorType') + + data_double = struct.pack('>3d', 1.5, 2.5, 3.5) + result_double = vt_double.deserialize(data_double, 5) + self.assertEqual(result_double, [1.5, 2.5, 3.5]) + + # Test int32 vector + vt_int32 = VectorType.apply_parameters(['Int32Type', 4], {}) + des_int32 = find_deserializer(vt_int32) + self.assertEqual(des_int32.__class__.__name__, 'DesVectorType') + + data_int32 = struct.pack('>4i', 1, 2, 3, 4) + result_int32 = vt_int32.deserialize(data_int32, 5) + self.assertEqual(result_int32, [1, 2, 3, 4]) + + # Test int64/long vector + vt_int64 = VectorType.apply_parameters(['LongType', 2], {}) + des_int64 = find_deserializer(vt_int64) + self.assertEqual(des_int64.__class__.__name__, 'DesVectorType') + + data_int64 = struct.pack('>2q', 100, 200) + result_int64 = vt_int64.deserialize(data_int64, 5) + self.assertEqual(result_int64, [100, 200]) + + # Test int16/short vector + # Note: ShortType (smallint) is intentionally not part of the + # fixed-width vector fast path. Cassandra's AbstractType.valueLengthIfFixed() + # (and ShortType.java specifically) does not override the variable-length + # default, so smallint vector elements are vint-length-prefixed on the + # wire rather than fixed 2-byte values. find_deserializer() routes it to + # GenericDeserializer (not DesVectorType) accordingly -- see + # test_find_deserializer_vector_dispatch. We round-trip through + # serialize()/deserialize() instead of assuming a fixed-width wire + # format, the same way test_vector_cython_deserializer_variable_size_subtype + # does for UTF8Type below. + vt_int16 = VectorType.apply_parameters(['ShortType', 3], {}) + des_int16 = find_deserializer(vt_int16) + self.assertEqual(des_int16.__class__.__name__, 'GenericDeserializer') + + data_int16 = vt_int16.serialize([10, 20, 30], 5) + result_int16 = vt_int16.deserialize(data_int16, 5) + self.assertEqual(result_int16, [10, 20, 30]) + + # Test error handling: wrong buffer size + with self.assertRaises(ValueError) as cm: + vt_float.deserialize(struct.pack('>3f', 1.0, 2.0, 3.0), 5) # 3 floats instead of 4 + self.assertIn('Expected vector', str(cm.exception)) + self.assertIn('serialized size', str(cm.exception)) + + + def test_vector_cython_deserializer_variable_size_subtype(self): + """ + Test that find_deserializer() routes variable-size vector subtypes + (e.g. UTF8Type) to GenericDeserializer rather than DesVectorType, and + that this deserializer correctly round-trips real data. + + DesVectorType only supports the fixed-width subtypes listed in + VectorType._struct_format_map (float/double/int32/bigint); anything + else -- text, smallint, varint, etc. -- must go through + GenericDeserializer, which delegates to the pure-Python + VectorType.deserialize(). Before this dispatch was made subtype-aware, + DesVectorType was selected unconditionally for any VectorType and + would only discover it couldn't handle the data after construction + (via a ValueError raised deep in _deserialize_generic, with nothing + upstream positioned to catch it) -- meaning real queries against + e.g. Vector columns would crash during row parsing. See + test_desvectortype_rejects_variable_size_subtype for that internal + safety net, which is no longer reachable through normal dispatch. + + @since 3.x + @expected_result find_deserializer() returns GenericDeserializer for + variable-size vector subtypes, and it correctly + deserializes real data. + + @test_category data_types:vector + """ + try: + from cassandra.deserializers import find_deserializer, make_deserializers + except ImportError: + self.skipTest('Cython deserializers not available') + + vt_text = VectorType.apply_parameters(['UTF8Type', 3], {}) + des_text = find_deserializer(vt_text) + self.assertEqual(des_text.__class__.__name__, 'GenericDeserializer') + + # Pure Python path should work correctly + data = vt_text.serialize(['abc', 'def', 'ghi'], 5) + result = vt_text.deserialize(data, 5) + self.assertEqual(result, ['abc', 'def', 'ghi']) + + # GenericDeserializer has no Python-callable deserialize_bytes() + # convenience wrapper (that's specific to DesVectorType), so drive it + # through the actual production row-parsing pipeline instead -- this + # is the exact path (make_deserializers -> find_deserializer -> + # from_binary -> Deserializer.deserialize) that would previously + # raise ValueError for a Vector column. + import struct + from cassandra.obj_parser import ListParser + from cassandra.parsing import ParseDesc + from cassandra.bytesio import BytesIOReader + from cassandra.policies import ColDesc + + buf = bytearray() + buf += struct.pack('>i', 1) # row count + buf += struct.pack('>i', len(data)) + buf += data + + desc = ParseDesc( + colnames=['vec'], + coltypes=[vt_text], + column_encryption_policy=None, + coldescs=[ColDesc('ks', 'table', 'vec')], + deserializers=make_deserializers([vt_text]), + protocol_version=5 + ) + rows = ListParser().parse_rows(BytesIOReader(bytes(buf)), desc) + self.assertEqual(rows, [(['abc', 'def', 'ghi'],)]) + + def test_desvectortype_rejects_variable_size_subtype(self): + """ + Test that DesVectorType._deserialize_generic still raises ValueError + for variable-size subtypes when the class is used directly. + + After making find_deserializer() dispatch subtype-aware, + DesVectorType is never handed a variable-size subtype through normal + dispatch (see test_vector_cython_deserializer_variable_size_subtype + and test_find_deserializer_vector_dispatch). This test bypasses + find_deserializer() to construct DesVectorType directly, confirming + the ValueError safety net inside _deserialize_generic is still + intact as an internal invariant check (defense-in-depth), even + though it's no longer a user-facing error path. + + @since 3.x + @expected_result DesVectorType raises ValueError for variable-size + subtypes when constructed directly + + @test_category data_types:vector + """ + try: + from cassandra.deserializers import DesVectorType + except ImportError: + self.skipTest('Cython deserializers not available') + + vt_text = VectorType.apply_parameters(['UTF8Type', 3], {}) + des_text = DesVectorType(vt_text) + + data = vt_text.serialize(['abc', 'def', 'ghi'], 5) + with self.assertRaises(ValueError) as cm: + des_text.deserialize_bytes(data, 5) + self.assertIn('variable-size subtype', str(cm.exception)) + + def test_find_deserializer_vector_dispatch(self): + """ + Test that find_deserializer() picks the right deserializer class + per VectorType subtype: DesVectorType (the Cython fast path) for + subtypes in VectorType._struct_format_map, GenericDeserializer + (delegating to the pure-Python VectorType.deserialize()) for + everything else. + + @since 3.x + @expected_result Fixed-width subtypes get DesVectorType; + variable-size subtypes get GenericDeserializer + + @test_category data_types:vector + """ + try: + from cassandra.deserializers import find_deserializer + except ImportError: + self.skipTest('Cython deserializers not available') + + # Fixed-width subtypes: fast Cython path + for subtype_name in ('FloatType', 'DoubleType', 'Int32Type', 'LongType'): + vt = VectorType.apply_parameters([subtype_name, 3], {}) + des = find_deserializer(vt) + self.assertEqual(des.__class__.__name__, 'DesVectorType', + "expected DesVectorType for Vector<%s>" % subtype_name) + + # Variable-size (or otherwise unoptimized) subtypes: generic fallback + for subtype_name in ('UTF8Type', 'ShortType', 'IntegerType'): + vt = VectorType.apply_parameters([subtype_name, 3], {}) + des = find_deserializer(vt) + self.assertEqual(des.__class__.__name__, 'GenericDeserializer', + "expected GenericDeserializer for Vector<%s>" % subtype_name) + + def test_vector_numpy_large_deserialization(self): + """ + Test that large vectors (>= 32 elements) use the numpy deserialization path + and return correct results for all supported numeric types. + + @since 3.x + @expected_result Large vectors are correctly deserialized (via numpy when available) + + @test_category data_types:vector + """ + import struct + from cassandra.cqltypes import DoubleType + + vector_size = 64 # >= 32 threshold for numpy path + + # Float vector + float_data = list(range(vector_size)) + float_values = [float(x) for x in float_data] + vt_float = VectorType.apply_parameters(['FloatType', vector_size], {}) + packed = struct.pack('>%df' % vector_size, *float_values) + result = vt_float.deserialize(packed, 5) + self.assertEqual(len(result), vector_size) + for i in range(vector_size): + self.assertAlmostEqual(result[i], float_values[i], places=5) + + # Double vector + double_values = [float(x) * 1.1 for x in range(vector_size)] + vt_double = VectorType.apply_parameters(['DoubleType', vector_size], {}) + packed = struct.pack('>%dd' % vector_size, *double_values) + result = vt_double.deserialize(packed, 5) + self.assertEqual(len(result), vector_size) + for i in range(vector_size): + self.assertAlmostEqual(result[i], double_values[i], places=10) + + # Int32 vector + int32_values = list(range(vector_size)) + vt_int32 = VectorType.apply_parameters(['Int32Type', vector_size], {}) + packed = struct.pack('>%di' % vector_size, *int32_values) + result = vt_int32.deserialize(packed, 5) + self.assertEqual(result, int32_values) + + # Int64/Long vector + int64_values = list(range(vector_size)) + vt_int64 = VectorType.apply_parameters(['LongType', vector_size], {}) + packed = struct.pack('>%dq' % vector_size, *int64_values) + result = vt_int64.deserialize(packed, 5) + self.assertEqual(result, int64_values) + + # ShortType is intentionally skipped here: smallint vector elements + # are vint-length-prefixed on the wire (ShortType.serial_size() is + # None, matching Cassandra's real encoding), not fixed 2-byte values, + # so it is not part of the fixed-width/numpy fast path and this + # large-vector struct-packing test doesn't apply to it. + ZERO = datetime.timedelta(0)