Skip to content
Draft
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
5 changes: 4 additions & 1 deletion bindings/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,10 +152,13 @@ plan = scan.plan()
batches = read_builder.new_read().read(plan.splits())

# Core schedules a bounded set of split readers and owns their global limit.
# By default, filtered reads without a limit use up to 64 splits for
# descriptors or 32 when the table may resolve BLOBs. Other reads retain
# the single-split default. The split count always caps the worker count.
# Set ordered=True to retain the supplied split order. The default emits
# whichever split group is ready first. Ordered parallel reads disable background
# Parquet row-group prefetch; split workers still read concurrently.
reader = read_builder.new_read().read_arrow(plan.splits(), parallelism=4, ordered=False)
reader = read_builder.new_read().read_arrow(plan.splits())
try:
for batch in reader:
print(batch)
Expand Down
88 changes: 82 additions & 6 deletions bindings/python/src/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -992,15 +992,64 @@ pub struct PyTableRead {
include_row_kind: bool,
}

const DEFAULT_DESCRIPTOR_SPLIT_PARALLELISM: usize = 64;
const DEFAULT_BLOB_SPLIT_PARALLELISM: usize = 32;

fn default_split_parallelism(
split_count: usize,
resolves_blob: bool,
filtered_without_limit: bool,
) -> usize {
let cap = if !filtered_without_limit {
1
} else if resolves_blob {
DEFAULT_BLOB_SPLIT_PARALLELISM
} else {
DEFAULT_DESCRIPTOR_SPLIT_PARALLELISM
};
split_count.min(cap).max(1)
}

fn is_managed_blob_type(data_type: &DataType) -> bool {
match data_type {
DataType::Blob(_) => true,
DataType::Array(array) => array.element_type().is_blob_type(),
DataType::Map(map) => map.value_type().is_blob_type(),
_ => false,
}
}

impl PyTableRead {
fn read_stream(
&self,
py: Python<'_>,
splits: &Bound<'_, PyAny>,
parallelism: usize,
parallelism: Option<usize>,
ordered: bool,
) -> PyResult<ArrowRecordBatchStream> {
let splits = extract_splits(splits)?;
let parallelism = parallelism.unwrap_or_else(|| {
let options = self.table.schema().core_options();
// Favor the payload cap whenever this table may resolve a BLOB.
// Projection and filters can introduce hidden BLOB operands, so a
// wider default is only safe for descriptor-only reads.
let has_blob = !options.blob_fields().is_empty()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Use the descriptor cap for unresolved BLOB views.

If a table's only BLOB column is a blob-view-field and blob-view.resolve.enabled=false, Core returns the stored references. blob_fields() still includes the view, and the schema check also counts it as a scalar BLOB. With the default blob-as-descriptor=false, a filtered read with more than 32 splits therefore gets the payload cap. Please exclude view fields from the ordinary BLOB checks and use the REST and resolution conditions for views, as Core does.

|| self
.table
.schema()
.fields()
.iter()
.any(|field| is_managed_blob_type(field.data_type()));
let resolves_blob = (!options.blob_as_descriptor() && has_blob)
|| (self.table.rest_env().is_some()
&& options.blob_view_resolve_enabled()
&& !options.blob_view_fields().is_empty());
default_split_parallelism(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P1] Bound buffered BLOB bytes before enabling automatic parallelism.

The first poll starts a read for each split worker, and each worker can retain a materialized batch. The BLOB range-read permits are released when the I/O finishes. I reproduced this with 32 splits and a 16 MiB payload batch per split. After consuming and releasing the first read_arrow() batch and pausing, RSS was about 621 MiB with the default and 113 MiB with parallelism=1 on the same wheel. Larger image or video batches can exhaust memory even when the caller processes one batch at a time. Please keep the BLOB default at one worker until a shared byte budget covers the batches waiting to be consumed.

splits.len(),
resolves_blob,
self.filter.is_some() && self.limit.is_none(),
)
});
py.detach(|| {
let mut builder = self.table.new_read_builder();
apply_read_config(
Expand Down Expand Up @@ -1044,12 +1093,15 @@ impl PyTableRead {
/// Lazily read the given splits as PyArrow RecordBatches.
/// Core owns split scheduling, the global row limit and cancellation.
/// ordered=True retains the supplied split order; the default emits ready groups first.
#[pyo3(signature = (splits, *, parallelism = 1, ordered = false))]
/// Without an explicit parallelism, filtered reads without a limit use up
/// to 64 splits for descriptors or 32 for BLOB payloads. Other reads keep
/// the existing single-split default.
#[pyo3(signature = (splits, *, parallelism = None, ordered = false))]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Update the shipped type stubs for both methods.

read() and read_arrow() now accept parallelism=None. The corresponding signatures in bindings/python/python/pypaimon_rust/datafusion.pyi still declare parallelism: int = 1 for both. The wheel ships py.typed, so type checkers reject an explicit None and editors show the old default. Please declare parallelism: int | None = None in both stubs and document when automatic parallelism applies.

fn read_arrow(
&self,
py: Python<'_>,
splits: &Bound<'_, PyAny>,
parallelism: usize,
parallelism: Option<usize>,
ordered: bool,
) -> PyResult<PyRecordBatchReader> {
Ok(PyRecordBatchReader::from_stream(self.read_stream(
Expand All @@ -1061,12 +1113,12 @@ impl PyTableRead {
}

/// Read the given splits into a list of PyArrow RecordBatches.
#[pyo3(signature = (splits, *, parallelism = 1, ordered = false))]
#[pyo3(signature = (splits, *, parallelism = None, ordered = false))]
fn read(
&self,
py: Python<'_>,
splits: &Bound<'_, PyAny>,
parallelism: usize,
parallelism: Option<usize>,
ordered: bool,
) -> PyResult<Vec<Py<PyAny>>> {
let stream = self.read_stream(py, splits, parallelism, ordered)?;
Expand Down Expand Up @@ -1404,11 +1456,35 @@ mod tests {

use paimon::catalog::Identifier;
use paimon::io::FileIOBuilder;
use paimon::spec::{IntType, Schema, TableSchema};
use paimon::spec::{ArrayType, BlobType, IntType, MapType, Schema, TableSchema, VarCharType};
use pyo3::types::PyList;

use super::*;

#[test]
fn default_parallelism_follows_split_count_and_payload_cap() {
assert_eq!(default_split_parallelism(0, false, true), 1);
assert_eq!(default_split_parallelism(20, false, true), 20);
assert_eq!(default_split_parallelism(100, false, true), 64);
assert_eq!(default_split_parallelism(20, true, true), 20);
assert_eq!(default_split_parallelism(100, true, true), 32);
assert_eq!(default_split_parallelism(100, false, false), 1);
}

#[test]
fn payload_policy_includes_nested_managed_blob_fields() {
let blob = DataType::Blob(BlobType::new());
assert!(is_managed_blob_type(&blob));
assert!(is_managed_blob_type(&DataType::Array(ArrayType::new(
blob.clone()
))));
assert!(is_managed_blob_type(&DataType::Map(MapType::new(
DataType::VarChar(VarCharType::string_type()),
blob,
))));
assert!(!is_managed_blob_type(&DataType::Int(IntType::new())));
}

#[test]
fn row_id_plan_binding_routes_arrow_and_keeps_read_selection_separate() {
Python::attach(|py| {
Expand Down
15 changes: 10 additions & 5 deletions bindings/python/tests/test_read.py
Original file line number Diff line number Diff line change
Expand Up @@ -1868,15 +1868,15 @@ def test_append_row_position_slices_and_shards_are_native_readable(row_tracking)
):
plan = builder.new_scan().with_row_position_slice(start, end).plan()
restored = [Split.deserialize(split.serialize()) for split in plan.splits()]
batches = builder.new_read().read(restored)
batches = builder.new_read().read(restored, ordered=True)
actual = pa.Table.from_batches(batches).column("id").to_pylist() if batches else []
assert actual == expected
assert plan.snapshot_id() == 3

shards = []
for index, expected in enumerate(([0, 1, 2], [3, 4], [5, 6], [7, 8])):
plan = builder.new_scan().with_row_position_shard(index, 4).plan()
actual = pa.Table.from_batches(builder.new_read().read(plan.splits()))
actual = pa.Table.from_batches(builder.new_read().read(plan.splits(), ordered=True))
values = actual.column("id").to_pylist()
assert values == expected
shards.extend(values)
Expand All @@ -1898,9 +1898,14 @@ def test_append_row_positions_follow_stats_pruned_file_order_before_limit(row_tr
plan = builder.new_scan().with_row_position_slice(1, 5).plan()
# Stats remove the first file before positions are assigned. LIMIT
# must not truncate the candidate files before applying the slice.
full_selection = table.new_read_builder().with_projection(["id"]).new_read().read(plan.splits())
full_selection = (
table.new_read_builder()
.with_projection(["id"])
.new_read()
.read(plan.splits(), ordered=True)
)
assert pa.Table.from_batches(full_selection).column("id").to_pylist() == [4, 5, 6, 7]
actual = pa.Table.from_batches(builder.new_read().read(plan.splits()))
actual = pa.Table.from_batches(builder.new_read().read(plan.splits(), ordered=True))
# The configured reader enforces the final LIMIT after selection.
assert actual.column("id").to_pylist() == expected

Expand All @@ -1919,7 +1924,7 @@ def test_append_incremental_row_positions_use_combined_delta_order():
.plan()
)
restored = [pickle.loads(pickle.dumps(split)) for split in plan.splits()]
actual = pa.Table.from_batches(builder.new_read().read(restored))
actual = pa.Table.from_batches(builder.new_read().read(restored, ordered=True))
assert actual.column("id").to_pylist() == expected


Expand Down
Loading