diff --git a/rust/perspective-python/src/client/polars.rs b/rust/perspective-python/src/client/polars.rs index 7fa4d333bd..df8a571cd6 100644 --- a/rust/perspective-python/src/client/polars.rs +++ b/rust/perspective-python/src/client/polars.rs @@ -12,7 +12,7 @@ use pyo3::exceptions::PyValueError; use pyo3::prelude::*; -use pyo3::types::{PyAny, PyBytes, PyList}; +use pyo3::types::{PyAny, PyBytes, PyDict, PyList}; use super::pyarrow; @@ -75,35 +75,32 @@ pub fn polars_to_arrow_bytes<'py>( } let is_lazyframe = df.is_instance(&lf_class)?; - let table = if is_lazyframe { - df.call_method0("collect")?.call_method0("to_arrow")? + let mut df = if is_lazyframe { + df.call_method0("collect")? } else { - df.call_method0("to_arrow")? + df.clone() }; // rename from __index_level_0__ to index - let old_names: Vec = table.getattr("column_names")?.extract()?; - let mut new_names: Vec = old_names - .into_iter() - .map(|e| { - if e == "__index_level_0__" { - "index".to_string() - } else { - e - } - }) - .collect(); - - let names = PyList::new(py, new_names.clone())?; - let table = table.call_method1("rename_columns", (names,))?; + let old_names: Vec = df.getattr("columns")?.extract()?; + if old_names.iter().any(|c| c == "__index_level_0__") { + let rename_dict = PyDict::new(py); + rename_dict.set_item("__index_level_0__", "index")?; + df = df.call_method1("rename", (rename_dict,))?; + } - // move the index column to be the first column. - if new_names[new_names.len() - 1] == "index" { - new_names.rotate_right(1); - let order = PyList::new(py, new_names)?; - let table = table.call_method1("select", (order,))?; - pyarrow::to_arrow_bytes(py, &table) - } else { - pyarrow::to_arrow_bytes(py, &table) + let current_names: Vec = df.getattr("columns")?.extract()?; + if current_names.last().map(|s| s.as_str()) == Some("index") { + let mut new_order = current_names; + new_order.rotate_right(1); + let order = PyList::new(py, new_order)?; + df = df.call_method1("select", (order,))?; } + + // Direct Polars Arrow IPC stream serialization avoiding PyArrow conversion and memory duplication + let io = PyModule::import(py, "io")?; + let buffer = io.getattr("BytesIO")?.call0()?; + df.call_method1("write_ipc_stream", (&buffer,))?; + let pybytes = buffer.call_method0("getvalue")?.cast_into::()?; + Ok(pybytes) } diff --git a/rust/perspective-python/src/client/pyarrow.rs b/rust/perspective-python/src/client/pyarrow.rs index 57bcbacb4c..be47c4e469 100644 --- a/rust/perspective-python/src/client/pyarrow.rs +++ b/rust/perspective-python/src/client/pyarrow.rs @@ -52,7 +52,7 @@ pub fn to_arrow_bytes<'py>( { let writer = pyarrow.call_method1( - "RecordBatchFileWriter", + "RecordBatchStreamWriter", (sink.clone(), table.getattr("schema")?), )?; diff --git a/rust/perspective-server/cpp/perspective/src/cpp/arrow_loader.cpp b/rust/perspective-server/cpp/perspective/src/cpp/arrow_loader.cpp index e121b04fe3..8959f8891f 100644 --- a/rust/perspective-server/cpp/perspective/src/cpp/arrow_loader.cpp +++ b/rust/perspective-server/cpp/perspective/src/cpp/arrow_loader.cpp @@ -19,6 +19,8 @@ #include #include #include +#include +#include #include #include #include @@ -142,6 +144,53 @@ load_file( }; } +void +load_c_data( + ArrowArray* array, + ArrowSchema* schema, + std::shared_ptr& table +) { + auto result = arrow::ImportRecordBatch(array, schema); + if (!result.ok()) { + std::stringstream ss; + ss << "Failed to import Arrow C Data RecordBatch: " + << result.status().ToString() << "\n"; + PSP_COMPLAIN_AND_ABORT(ss.str()); + } + std::shared_ptr batch = *result; + auto table_result = arrow::Table::FromRecordBatches({batch}); + if (!table_result.ok()) { + std::stringstream ss; + ss << "Failed to create Table from imported RecordBatch: " + << table_result.status().ToString() << "\n"; + PSP_COMPLAIN_AND_ABORT(ss.str()); + } + table = deduplicate_table(std::move(*table_result)); +} + +void +load_c_stream( + ArrowArrayStream* stream, + std::shared_ptr& table +) { + auto result = arrow::ImportRecordBatchReader(stream); + if (!result.ok()) { + std::stringstream ss; + ss << "Failed to import Arrow C Stream: " + << result.status().ToString() << "\n"; + PSP_COMPLAIN_AND_ABORT(ss.str()); + } + std::shared_ptr reader = *result; + auto table_result = reader->ToTable(); + if (!table_result.ok()) { + std::stringstream ss; + ss << "Failed to read Table from Arrow C Stream: " + << table_result.status().ToString() << "\n"; + PSP_COMPLAIN_AND_ABORT(ss.str()); + } + table = deduplicate_table(std::move(*table_result)); +} + using namespace perspective; ArrowLoader::ArrowLoader() = default; @@ -241,6 +290,56 @@ ArrowLoader::initialize( } } +void +ArrowLoader::initialize_c_data( + ArrowArray* array, ArrowSchema* schema, t_flatten_mode mode +) { + load_c_data(array, schema, m_table); + + const auto validation = m_table->ValidateFull(); + if (!validation.ok()) { + PSP_COMPLAIN_AND_ABORT(validation.ToString()); + } + + m_mode = mode; + if (!normalize_table_is_noop(*m_table, mode)) { + m_expanded = normalize_table_expands(*m_table, mode); + m_normalized = + std::make_unique(normalize_table(m_table, mode) + ); + } + + for (const auto& field : fields()) { + m_names.push_back(field->name()); + m_types.push_back(convert_type(field->type()->name())); + } +} + +void +ArrowLoader::initialize_c_stream( + ArrowArrayStream* stream, t_flatten_mode mode +) { + load_c_stream(stream, m_table); + + const auto validation = m_table->ValidateFull(); + if (!validation.ok()) { + PSP_COMPLAIN_AND_ABORT(validation.ToString()); + } + + m_mode = mode; + if (!normalize_table_is_noop(*m_table, mode)) { + m_expanded = normalize_table_expands(*m_table, mode); + m_normalized = + std::make_unique(normalize_table(m_table, mode) + ); + } + + for (const auto& field : fields()) { + m_names.push_back(field->name()); + m_types.push_back(convert_type(field->type()->name())); + } +} + const std::vector>& ArrowLoader::fields() const { return m_normalized ? m_normalized->fields : m_table->schema()->fields(); diff --git a/rust/perspective-server/cpp/perspective/src/include/perspective/arrow_loader.h b/rust/perspective-server/cpp/perspective/src/include/perspective/arrow_loader.h index 1328f8b3eb..f499bcda6b 100644 --- a/rust/perspective-server/cpp/perspective/src/include/perspective/arrow_loader.h +++ b/rust/perspective-server/cpp/perspective/src/include/perspective/arrow_loader.h @@ -21,6 +21,8 @@ #include #include #include +#include +#include #include #include #include @@ -50,6 +52,29 @@ namespace apachearrow { const std::uint8_t* ptr, std::uint32_t, t_flatten_mode mode = {} ); + /** + * @brief Initialize the arrow loader from Arrow C Data Interface structs + * (zero-copy pointer transfer without IPC serialization). + * + * @param array + * @param schema + * @param mode + */ + void initialize_c_data( + ArrowArray* array, ArrowSchema* schema, t_flatten_mode mode = {} + ); + + /** + * @brief Initialize the arrow loader from an Arrow C Stream Interface struct + * (zero-copy pointer transfer without IPC serialization). + * + * @param stream + * @param mode + */ + void initialize_c_stream( + ArrowArrayStream* stream, t_flatten_mode mode = {} + ); + /** * @brief The name of an index column whose value repeats across the * rows of an expansion, or `nullopt` if indexing is safe.