Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 23 additions & 26 deletions rust/perspective-python/src/client/polars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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<String> = table.getattr("column_names")?.extract()?;
let mut new_names: Vec<String> = 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<String> = 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<String> = 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,))?;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

write_ipc_stream and to_arrow are not same - this raises the compatibility level to "newest" by default, which Perspective's reader does not fully support yet (fails on utf8_view and categorical columns ingest). See test_table_polars_from_schema_str, arrow_loader.cpp convert_type

let pybytes = buffer.call_method0("getvalue")?.cast_into::<PyBytes>()?;
Ok(pybytes)
}
2 changes: 1 addition & 1 deletion rust/perspective-python/src/client/pyarrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub fn to_arrow_bytes<'py>(

{
let writer = pyarrow.call_method1(
"RecordBatchFileWriter",
"RecordBatchStreamWriter",
(sink.clone(), table.getattr("schema")?),
)?;

Expand Down
99 changes: 99 additions & 0 deletions rust/perspective-server/cpp/perspective/src/cpp/arrow_loader.cpp
Comment thread
21anaghar marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
#include <arrow/util/base64.h>
#include <arrow/util/decimal.h>
#include <perspective/scalar_json.h>
#include <arrow/c/abi.h>
#include <arrow/c/bridge.h>
#include <arrow/type.h>
#include <arrow/type_fwd.h>
#include <algorithm>
Expand Down Expand Up @@ -142,6 +144,53 @@ load_file(
};
}

void
load_c_data(
ArrowArray* array,
ArrowSchema* schema,
std::shared_ptr<arrow::Table>& 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<arrow::RecordBatch> 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<arrow::Table>& 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<arrow::RecordBatchReader> 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;
Expand Down Expand Up @@ -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<t_normalized_table>(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<t_normalized_table>(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<std::shared_ptr<arrow::Field>>&
ArrowLoader::fields() const {
return m_normalized ? m_normalized->fields : m_table->schema()->fields();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
#include <optional>
#include <date/date.h>
#include <arrow/api.h>
#include <arrow/c/abi.h>
#include <arrow/c/bridge.h>
#include <arrow/util/decimal.h>
#include <arrow/io/memory.h>
#include <arrow/ipc/reader.h>
Expand Down Expand Up @@ -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.
Expand Down