Repository navigation
[Data] Add flag-gated arrow-rs Parquet reader for DataSource V2 - #65117
AarryaSaraf wants to merge 25 commits into
Conversation
Introduce an optional native (Rust/PyO3) Parquet reader for the DataSource V2 read path, gated by a new DataContext flag `use_arrow_rs_parquet_reader` (default False, active only under `use_datasource_v2`). When enabled, `ParquetScanner.create_reader()` returns `ArrowRsParquetFileReader`, which footer-reads each file via the `ray_data_arrow_rs` crate and decodes supported row groups natively, falling back to the PyArrow reader for unsupported files/types/ filesystems. This targets scheduler-invisible Parquet decode memory (ray#49158): the native path bounds the decode working set instead of materializing whole decoded row groups. Changes: - New Rust crate `ray_data_arrow_rs` (maturin/PyO3, out of the Bazel build) exposing native row-group reads over an Arrow C-stream. - New `ArrowRsParquetFileReader` + `native_metadata` helpers. - Base `FileReader` refactor (behavior-preserving): extract `_split_columns`/`_postprocess`/`_dispatch_fragment_reads` for reuse. - `DataContext.use_arrow_rs_parquet_reader` flag + scanner toggle. - Full parity/fallback test suite. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces an experimental native Parquet reader implemented in Rust for Ray Data to improve performance and memory efficiency. The changes include a new Rust crate, configuration flags, and integration logic to allow switching between the existing PyArrow reader and the new native reader. The review feedback highlights critical issues, including potential precision loss in Rust-based numeric comparisons, a Python TypeError in the casting logic, performance bottlenecks caused by blocking the Python GIL during I/O operations, and bugs in S3 path parsing.
| pub fn partial_cmp(&self, other: &Value) -> Option<Ordering> { | ||
| match (self, other) { | ||
| (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)), | ||
| (Value::Float(a), Value::Float(b)) => a.partial_cmp(b), | ||
| // Mixed int/float: promote to f64 (e.g. `float_col > 5`). | ||
| (Value::Int(a), Value::Float(b)) => (*a as f64).partial_cmp(b), | ||
| (Value::Float(a), Value::Int(b)) => a.partial_cmp(&(*b as f64)), | ||
| (Value::Str(a), Value::Str(b)) => Some(a.cmp(b)), | ||
| (Value::Bool(a), Value::Bool(b)) => Some(a.cmp(b)), | ||
| _ => None, | ||
| } | ||
| } |
There was a problem hiding this comment.
Casting i64 to f64 for mixed-type comparisons (e.g., Value::Int vs Value::Float) can lose precision for integers outside the safe range of f64 (i.e., absolute value > 9,007,199,254,740,991). This loss of precision can lead to incorrect comparisons, causing can_match to return false and incorrectly prune a row group that actually contains matching rows. To ensure soundness, mixed-type comparisons should return None (incomparable) if the integer value is outside the safe float range, which safely defaults to keeping the row group.
pub fn partial_cmp(&self, other: &Value) -> Option<Ordering> {
const MAX_SAFE_INT: i64 = 9_007_199_254_740_991;
const MIN_SAFE_INT: i64 = -9_007_199_254_740_991;
match (self, other) {
(Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
(Value::Float(a), Value::Float(b)) => a.partial_cmp(b),
// Mixed int/float: promote to f64 (e.g. `float_col > 5`).
// Prevent precision loss for integers outside the safe float range.
(Value::Int(a), Value::Float(b)) => {
if *a >= MIN_SAFE_INT && *a <= MAX_SAFE_INT {
(*a as f64).partial_cmp(b)
} else {
None
}
}
(Value::Float(a), Value::Int(b)) => {
if *b >= MIN_SAFE_INT && *b <= MAX_SAFE_INT {
a.partial_cmp(&(*b as f64))
} else {
None
}
}
(Value::Str(a), Value::Str(b)) => Some(a.cmp(b)),
(Value::Bool(a), Value::Bool(b)) => Some(a.cmp(b)),
_ => None,
}
}| if allow_time_truncate: | ||
| column = column.cast( | ||
| options=pc.CastOptions(target, allow_time_truncate=True) | ||
| ) |
There was a problem hiding this comment.
The pyarrow.compute.CastOptions constructor does not accept a DataType as its first positional argument. Calling pc.CastOptions(target, allow_time_truncate=True) will raise a TypeError. The target type should be passed as the first argument to column.cast, and options should be passed as a keyword argument.
| if allow_time_truncate: | |
| column = column.cast( | |
| options=pc.CastOptions(target, allow_time_truncate=True) | |
| ) | |
| if allow_time_truncate: | |
| column = column.cast( | |
| target, options=pc.CastOptions(allow_time_truncate=True) | |
| ) |
| fn read_row_groups( | ||
| path: String, | ||
| row_groups: Option<Vec<usize>>, | ||
| columns: Option<Vec<String>>, | ||
| batch_size: usize, | ||
| decode_budget_bytes: u64, | ||
| k: usize, | ||
| split_threshold_bytes: u64, | ||
| // Optional predicate IR (JSON, built from the Ray `Expr`) for statistics | ||
| // row-group pruning. None = no pushdown. Row-level filtering still happens | ||
| // in Python post-decode, so this only avoids IO/decode, never changes rows. | ||
| predicate_json: Option<String>, | ||
| ) -> PyResult<ArrowStream> { | ||
| let reader = open_local_reader( | ||
| path, | ||
| row_groups, | ||
| columns, | ||
| batch_size, | ||
| decode_budget_bytes, | ||
| k, | ||
| split_threshold_bytes, | ||
| predicate_json, | ||
| ) | ||
| .map_err(to_py)?; | ||
| Ok(into_py_stream(reader)) | ||
| } |
There was a problem hiding this comment.
The function read_row_groups performs synchronous file I/O operations (opening files and reading metadata) while holding the Python GIL. This will block other Python threads (such as those in Ray's thread pool) from executing in parallel. Releasing the GIL using py.allow_threads during blocking operations is highly recommended to prevent serialization of I/O.
fn read_row_groups(
py: Python<'_>,
path: String,
row_groups: Option<Vec<usize>>,
columns: Option<Vec<String>>,
batch_size: usize,
decode_budget_bytes: u64,
k: usize,
split_threshold_bytes: u64,
// Optional predicate IR (JSON, built from the Ray `Expr`) for statistics
// row-group pruning. None = no pushdown. Row-level filtering still happens
// in Python post-decode, so this only avoids IO/decode, never changes rows.
predicate_json: Option<String>,
) -> PyResult<ArrowStream> {
let reader = py.allow_threads(|| {
open_local_reader(
path,
row_groups,
columns,
batch_size,
decode_budget_bytes,
k,
split_threshold_bytes,
predicate_json,
)
})
.map_err(to_py)?;
Ok(into_py_stream(reader))
}| fn read_row_groups_s3( | ||
| bucket: String, | ||
| key: String, | ||
| region: String, | ||
| anonymous: bool, | ||
| // Full S3 config, recovered from the pyarrow S3FileSystem on the Python side | ||
| // (fs.__reduce__()[1][0]) so credentialed / custom-endpoint (MinIO, moto) / | ||
| // anonymous buckets all decode identically to PyArrow. Empty/None → unset. | ||
| endpoint: Option<String>, | ||
| access_key_id: Option<String>, | ||
| secret_access_key: Option<String>, | ||
| session_token: Option<String>, | ||
| allow_http: bool, | ||
| virtual_hosted_style: bool, | ||
| row_groups: Option<Vec<usize>>, | ||
| columns: Option<Vec<String>>, | ||
| batch_size: usize, | ||
| decode_budget_bytes: u64, | ||
| fetch_window_mb: u64, | ||
| k: usize, | ||
| split_threshold_bytes: u64, | ||
| prefetch_windows: usize, | ||
| // See `read_row_groups`: statistics row-group pruning only. | ||
| predicate_json: Option<String>, | ||
| ) -> PyResult<ArrowStream> { |
There was a problem hiding this comment.
To prevent blocking the Python GIL during network requests to S3, add py: Python<'_> to the signature of read_row_groups_s3 so that the blocking rt.block_on call can be wrapped in py.allow_threads.
fn read_row_groups_s3(
py: Python<'_>,
bucket: String,
key: String,
region: String,
anonymous: bool,
// Full S3 config, recovered from the pyarrow S3FileSystem on the Python side
// (fs.__reduce__()[1][0]) so credentialed / custom-endpoint (MinIO, moto) /
// anonymous buckets all decode identically to PyArrow. Empty/None → unset.
endpoint: Option<String>,
access_key_id: Option<String>,
secret_access_key: Option<String>,
session_token: Option<String>,
allow_http: bool,
virtual_hosted_style: bool,
row_groups: Option<Vec<usize>>,
columns: Option<Vec<String>>,
batch_size: usize,
decode_budget_bytes: u64,
fetch_window_mb: u64,
k: usize,
split_threshold_bytes: u64,
prefetch_windows: usize,
// See `read_row_groups`: statistics row-group pruning only.
predicate_json: Option<String>,
) -> PyResult<ArrowStream> {| let (meta, mask, schema) = rt | ||
| .block_on(async { | ||
| let opts = reader_options(PageIndexPolicy::Optional); | ||
| let mut probe = ParquetObjectReader::new(store.clone(), obj_path.clone()); | ||
| let meta = ArrowReaderMetadata::load_async(&mut probe, opts).await?; | ||
| let mask = projection_mask(meta.metadata().file_metadata().schema_descr(), &columns); | ||
| let schema = ParquetRecordBatchStreamBuilder::new_with_metadata( | ||
| ParquetObjectReader::new(store.clone(), obj_path.clone()), | ||
| meta.clone(), | ||
| ) | ||
| .with_projection(mask.clone()) | ||
| .with_row_groups(vec![]) | ||
| .build()? | ||
| .schema() | ||
| .clone(); | ||
| Ok::<_, parquet::errors::ParquetError>((meta, mask, schema)) | ||
| }) | ||
| .map_err(to_py)?; |
There was a problem hiding this comment.
Wrap the synchronous rt.block_on call in py.allow_threads to release the Python GIL while fetching metadata from S3. This avoids serializing S3 metadata requests across concurrent Python threads.
| let (meta, mask, schema) = rt | |
| .block_on(async { | |
| let opts = reader_options(PageIndexPolicy::Optional); | |
| let mut probe = ParquetObjectReader::new(store.clone(), obj_path.clone()); | |
| let meta = ArrowReaderMetadata::load_async(&mut probe, opts).await?; | |
| let mask = projection_mask(meta.metadata().file_metadata().schema_descr(), &columns); | |
| let schema = ParquetRecordBatchStreamBuilder::new_with_metadata( | |
| ParquetObjectReader::new(store.clone(), obj_path.clone()), | |
| meta.clone(), | |
| ) | |
| .with_projection(mask.clone()) | |
| .with_row_groups(vec![]) | |
| .build()? | |
| .schema() | |
| .clone(); | |
| Ok::<_, parquet::errors::ParquetError>((meta, mask, schema)) | |
| }) | |
| .map_err(to_py)?; | |
| let (meta, mask, schema) = py.allow_threads(|| { | |
| rt.block_on(async { | |
| let opts = reader_options(PageIndexPolicy::Optional); | |
| let mut probe = ParquetObjectReader::new(store.clone(), obj_path.clone()); | |
| let meta = ArrowReaderMetadata::load_async(&mut probe, opts).await?; | |
| let mask = projection_mask(meta.metadata().file_metadata().schema_descr(), &columns); | |
| let schema = ParquetRecordBatchStreamBuilder::new_with_metadata( | |
| ParquetObjectReader::new(store.clone(), obj_path.clone()), | |
| meta.clone(), | |
| ) | |
| .with_projection(mask.clone()) | |
| .with_row_groups(vec![]) | |
| .build()? | |
| .schema() | |
| .clone(); | |
| Ok::<_, parquet::errors::ParquetError>((meta, mask, schema)) | |
| }) | |
| }) | |
| .map_err(to_py)?; |
| fn read_metadata(path: String) -> PyResult<ParquetFileMetadata> { | ||
| let opts = reader_options(PageIndexPolicy::Skip); | ||
| let meta = | ||
| ArrowReaderMetadata::load(&File::open(&path).map_err(to_py)?, opts).map_err(to_py)?; | ||
| Ok(build_file_metadata(&meta)) | ||
| } |
There was a problem hiding this comment.
Release the Python GIL using py.allow_threads during local metadata reads to avoid blocking concurrent threads.
| fn read_metadata(path: String) -> PyResult<ParquetFileMetadata> { | |
| let opts = reader_options(PageIndexPolicy::Skip); | |
| let meta = | |
| ArrowReaderMetadata::load(&File::open(&path).map_err(to_py)?, opts).map_err(to_py)?; | |
| Ok(build_file_metadata(&meta)) | |
| } | |
| fn read_metadata(py: Python<'_>, path: String) -> PyResult<ParquetFileMetadata> { | |
| let opts = reader_options(PageIndexPolicy::Skip); | |
| let meta = py.allow_threads(|| { | |
| let file = File::open(&path)?; | |
| ArrowReaderMetadata::load(&file, opts) | |
| }) | |
| .map_err(to_py)?; | |
| Ok(build_file_metadata(&meta)) | |
| } |
| fn read_metadata_s3( | ||
| bucket: String, | ||
| key: String, | ||
| region: String, | ||
| anonymous: bool, | ||
| endpoint: Option<String>, | ||
| access_key_id: Option<String>, | ||
| secret_access_key: Option<String>, | ||
| session_token: Option<String>, | ||
| allow_http: bool, | ||
| virtual_hosted_style: bool, | ||
| ) -> PyResult<ParquetFileMetadata> { | ||
| let store = build_s3_store( | ||
| &bucket, | ||
| ®ion, | ||
| anonymous, | ||
| endpoint, | ||
| access_key_id, | ||
| secret_access_key, | ||
| session_token, | ||
| allow_http, | ||
| virtual_hosted_style, | ||
| ) | ||
| .map_err(to_py)?; | ||
| let obj_path = ObjPath::from(key); | ||
| let rt = shared_runtime(); | ||
| let meta = rt | ||
| .block_on(async { | ||
| let opts = reader_options(PageIndexPolicy::Skip); | ||
| let mut probe = ParquetObjectReader::new(store.clone(), obj_path.clone()); | ||
| ArrowReaderMetadata::load_async(&mut probe, opts).await | ||
| }) | ||
| .map_err(to_py)?; | ||
| Ok(build_file_metadata(&meta)) | ||
| } |
There was a problem hiding this comment.
Release the Python GIL using py.allow_threads during S3 metadata reads to avoid blocking concurrent threads.
fn read_metadata_s3(
py: Python<'_>,
bucket: String,
key: String,
region: String,
anonymous: bool,
endpoint: Option<String>,
access_key_id: Option<String>,
secret_access_key: Option<String>,
session_token: Option<String>,
allow_http: bool,
virtual_hosted_style: bool,
) -> PyResult<ParquetFileMetadata> {
let store = build_s3_store(
&bucket,
®ion,
anonymous,
endpoint,
access_key_id,
secret_access_key,
session_token,
allow_http,
virtual_hosted_style,
)
.map_err(to_py)?;
let obj_path = ObjPath::from(key);
let rt = shared_runtime();
let meta = py.allow_threads(|| {
rt.block_on(async {
let opts = reader_options(PageIndexPolicy::Skip);
let mut probe = ParquetObjectReader::new(store.clone(), obj_path.clone());
ArrowReaderMetadata::load_async(&mut probe, opts).await
})
})
.map_err(to_py)?;
Ok(build_file_metadata(&meta))
}| fn select_row_groups(path: String, predicate_json: Option<String>) -> PyResult<Vec<usize>> { | ||
| let opts = reader_options(PageIndexPolicy::Skip); | ||
| let meta = | ||
| ArrowReaderMetadata::load(&File::open(&path).map_err(to_py)?, opts).map_err(to_py)?; | ||
| let all: Vec<usize> = (0..meta.metadata().num_row_groups()).collect(); | ||
| Ok(apply_predicate(&meta, all, &predicate_json)) | ||
| } |
There was a problem hiding this comment.
Release the Python GIL using py.allow_threads during local row group selection reads to avoid blocking concurrent threads.
fn select_row_groups(py: Python<'_>, path: String, predicate_json: Option<String>) -> PyResult<Vec<usize>> {
let opts = reader_options(PageIndexPolicy::Skip);
let meta = py.allow_threads(|| {
let file = File::open(&path)?;
ArrowReaderMetadata::load(&file, opts)
})
.map_err(to_py)?;
let all: Vec<usize> = (0..meta.metadata().num_row_groups()).collect();
Ok(apply_predicate(&meta, all, &predicate_json))
}| if isinstance(filesystem, S3FileSystem): | ||
| bucket, _, key = path.partition("/") |
There was a problem hiding this comment.
If path starts with s3://, the partition logic path.partition("/") will return ("s3:", "/", "/bucket/key"), resulting in an invalid bucket name of "s3:". Strip the s3:// prefix if present to ensure the bucket and key are correctly extracted.
if isinstance(filesystem, S3FileSystem):
if path.startswith("s3://"):
path = path[5:]
bucket, _, key = path.partition("/")| if isinstance(fs, S3FileSystem): | ||
| bucket, _, key = path.partition("/") | ||
| cfg = _s3_config(fs) |
There was a problem hiding this comment.
If path starts with s3://, the partition logic path.partition("/") will return ("s3:", "/", "/bucket/key"), resulting in an invalid bucket name of "s3:". Strip the s3:// prefix if present to ensure the bucket and key are correctly extracted.
fs = self._filesystem
if isinstance(fs, S3FileSystem):
if path.startswith("s3://"):
path = path[5:]
bucket, _, key = path.partition("/")Review fixes: - predicate.rs: mixed int/float comparison returns None (incomparable, keep the row group) when the integer is outside f64's exactly- representable range, so a precision-lossy promotion can't wrongly prune a matching row group. - lib.rs: release the GIL (py.allow_threads) around blocking footer / metadata I/O in read_row_groups, read_row_groups_s3, read_metadata, read_metadata_s3, and select_row_groups so Ray's fragment-pool threads decode/fetch in parallel instead of serializing on the GIL. - native_metadata.py / arrow_rs reader: strip a leading "s3://" before the bucket/key split (defensive; pyarrow paths are scheme-less). - parquet_file_reader.py: restore the arrow_rs_* tuning-kwarg pop + validation in __init__ (dropped when the file was reconciled to upstream) so ArrowRsParquetFileReader._tuning works and typo'd knobs raise a clear ValueError. - arrow_rs reader: _filesystem_supported now treats filesystem=None as the default local filesystem, matching the metadata/read paths, so eligible local reads no longer silently fall back to PyArrow. Lint: apply ruff import-ordering fixes in the reader and its test. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit f1024bd. Configure here.
| // Int96 (legacy timestamps) and FixedLenByteArray: not ordered here. | ||
| _ => (None, None), | ||
| } | ||
| } |
There was a problem hiding this comment.
Unsound stats type mapping
High Severity
stat_min_max treats every Int32/Int64 page statistic as a signed integer, ignoring logical types such as UINT32/UINT64 and DECIMAL. Pruning can then drop row groups that still contain matches. Post-decode filtering never sees those rows, so filters on those columns can silently lose data—breaking the module's conservative soundness contract.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit f1024bd. Configure here.
stat_min_max mapped every INT32/INT64 page statistic to a signed Value::Int, ignoring the column's logical type. For a UINT_32/UINT_64 column, Parquet orders stats by unsigned comparison, so a value with the high bit set (e.g. u32 max) is stored as a negative i32/i64 and reads back inverting min/max — can_match could then prune a row group that actually contains matching rows, silently dropping data (the pruning layer's soundness contract is "never prune a group that might match"). DECIMAL (unscaled int != the decimal literal) and DATE/TIME/TIMESTAMP (encoding may not match the predicate literal) have the same hazard. Gate the INT32/INT64 arms on is_plain_signed_int(descr), which consults the ColumnDescriptor's logical/converted type and only allows genuine signed integers; everything else returns no bound (conservative keep). Adds Rust unit tests covering signed/unsigned/date cases. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
end-of-file-fixer (pre-commit) requires exactly one trailing newline. Ran the full pre-commit suite over every file in the PR this time so no later hook stage surprises CI again. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
The premerge pyrefly job failed on the new arrow-rs files (exit 123), cascading the data-test and docs-go jobs to "broken". Fixes: - pyrefly.toml: add ray_data_arrow_rs.* to ignore-missing-imports (the crate is not in the wheel, so pyrefly can't resolve the import — same treatment as other optional deps like daft/lance/deltalake). - native_metadata.py: annotate s3_config with a directly-imported S3FileSystem instead of pa.fs.S3FileSystem (drops the now-unused `import pyarrow as pa` and the implicit-import error). - arrow_rs_parquet_file_reader.py: split the tuning resolver into resolve()/resolve_optional() so the four int-typed _ArrowRsTuning knobs get a non-Optional int (they always have a non-None default), fixing the bad-argument-type errors; drop the broken `self._allow_pickle_object_columns` guard (that attribute never existed — raise_on_pickle_object_columns already honors RAY_DATA_AUTOLOAD_PICKLE_OBJECT_SCALAR internally, matching the pyarrow reader). - pyrefly-excluded-files.txt: exclude test_arrow_rs_parquet_reader.py, as every sibling datasource test is already excluded. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
…lease suite DO NOT MERGE — drop this commit before opening the PR (git reset --hard HEAD~1). Makes every release test that reads Parquet exercise the Rust ray_data_arrow_rs decoder, with visible log confirmation of which path each read took. - context.py: flip use_arrow_rs_parquet_reader default to True (shipping default MUST stay False/opt-in — hence revert-before-PR). - byod_arrow_rs_parquet.sh: build the crate from source in the image (rustc + pip-install via maturin backend, branch head) so the flipped default has a crate to load. - release_data_tests.yaml: add the post_build_script to the DEFAULTS byod so every data-test image inherits the crate install. - parquet_scanner.create_reader: log (driver-side) when the arrow-rs reader is selected. - arrow_rs reader: log once per worker when native decode actually runs, and always warn (with reason) on any PyArrow fallback, so the logs show exactly where Rust ran vs fell back. grep the run for "ARROW-RS". Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
The native chunked-read path read `chunk_metadata["row_group_start"]` / `["row_group_end"]` — keys from the row-group-aware chunker (PR ray-project#64301) that was reverted upstream (PR ray-project#64541). The current `ParquetFileChunker` emits a relative `(chunk_idx, total_num_chunks)` descriptor and defers row-group resolution to read time, so any chunked read raised `KeyError: 'row_group_start'` (seen in the `read_large_parquet` release tests). Resolve the descriptor with the same `_calculate_row_group_range` helper the PyArrow reader uses, in both `_native_fragments_for_file` and `_native_count_fragments`, so native fragments line up byte-for-byte with the PyArrow path (identical row_hash offsets and limit slicing) and the planner-over-estimated case (`None`) is handled. Update `test_native_chunked_read_row_hash_parity` to build metadata with the real schema; validated end-to-end that the chunked native read matches PyArrow. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
test_chunker_native_metadata_matches_pyarrow and test_chunker_native_metadata_makes_no_pyarrow_footer_read asserted that the ParquetFileChunker reads Parquet footers through the native crate at chunk time — a capability from the row-group-aware chunker (PR ray-project#64301) that was reverted upstream (PR ray-project#64541). The current chunker splits by byte size and reads no footer during chunking, so both tests reference a dead generate_chunk_metadatas(path, size, fs) signature and dead metadata keys. The reader's own native footer read stays covered by test_native_read_is_pyarrow_free. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
… read path `page_checksum_verification` is a *scan* option. `_make_format` sets it on the format's `default_fragment_scan_options`, but `_arrow_scanner_kwargs` handed the scanner an explicit `ParquetFragmentScanOptions(use_buffered_stream, buffer_size)` that overrode that default — so an explicit `page_checksum_verification=True` was silently dropped (pyarrow defaults to no verification) and corrupt pages read clean. Thread the option through the explicit scan options so it is actually honored, matching the arrow-rs crate (which always verifies). This is a base V2 reader fix and affects PyArrow reads regardless of the arrow-rs flag; it makes `test_page_checksum_verification_true_native`'s parity-of-error assertion hold on the PyArrow side. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
…hema fix) Parquet files written by Ray 2.49–2.54 under RAY_DATA_AUTOLOAD_CLOUDPICKLE_TENSOR_METADATA=1 embed the tensor extension type as a cloudpickle blob in the footer's `ARROW:schema` IPC metadata. arrow-rs's IPC verifier rejects that non-UTF8 value (`Utf8Error` at custom_metadata → value), so native decode crashed on these files (release build 102757, wide_schema_pipeline_tensors). Fixed natively — no widened fallback: - Crate: `load_meta_local`/`load_meta_s3` catch *that specific* parse error and reload the footer `with_skip_arrow_metadata(true)`, decoding the parquet storage type instead of crashing, and set a new `arrow_schema_skipped` flag on `ParquetFileMetadata`. Files whose footer parses normally are untouched. - Python: for a skipped file, `_read_native_metadata` reads the file's own footer schema via `pq.read_schema` (pyarrow parses the binary metadata fine) and passes it to `_plan_column_alignment` as a per-file `target_schema`; the alignment casts storage → extension (pyarrow does the list→large_list offset-width change and the extension wrap in one `.cast()`, byte-identical). The per-file override is needed because `_file_dataset_schema` returns None for any extension-typed caller schema. A `_reconcile_to_expected` cast keeps the legacy per-fragment path safe. Verified end-to-end through `ray.data.read_parquet` (parity under RAY_DATA_ARROW_RS_STRICT=1, native decode active). Adds `test_cloudpickle_tensor_metadata_native_parity` and tidies `test_arrow_rs_supported_gate`. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
…de USS The release log's only memory metric is object-store peak, which can't see the decode-side working set the arrow-rs migration is about. Add `collect_operator_metrics(ds)` to benchmark.py: it walks the dataset stats and emits, per operator, wall/cpu/udf time, output rows/bytes, and `avg_max_uss_per_task_bytes` (per-task decode USS from `extra_metrics["average_max_uss_per_task"]`, Linux-only), plus top-level `read_*` convenience fields for the first Read operator. Wire it into read_and_consume_benchmark's `benchmark_fn` so every read/count/iter/write run carries the read operator's decode USS into the log — the metric that actually answers the arrow-rs-vs-PyArrow memory question. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
… run Adds release/nightly_tests/dataset/arrow_rs_probe/ — a self-contained harness to reproduce and optimize the two cases where arrow-rs was worse in the release run (imagenet time 1.67x, wide_schema mem 1.50x) on one node instead of a cluster: - read_probe.py: runs either V2 reader against a path (S3 presets for the two release reads) and reports wall time, worker cpu_over_wall (the CPU-bound-vs-IO diagnostic at --concurrency 1), and peak worker RSS/USS. USS is the metric of record and is Linux-only; the crate's page-sized S3 working set only engages on the S3 path, so the memory case must be run against real S3. - scale_sweep.py: local fixture sweeps that separate a scaling effect from the S3/Linux effect (imagenet bytes; wide_schema row-group size). - README.md: standalone Linux-workspace setup (crate build, Anyscale gotchas) + run commands + an allocator A/B, since this branch does not carry the full runbook. Working/measurement harness — not intended for the upstream PR. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
…runner for arrow-rs probe Two scratch scripts to reproduce the two release regressions on a bucket we own: - gen_s3_fixtures.py: writes wide_schema (1 big row group/file) + imagenet (many tiny row groups) layouts to S3 via aws s3 sync. - run_matrix.py: runs the full diag/mem/alloc A/B matrix, one process per cell, tees per-cell logs, prints arrow_rs/pyarrow ratios. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
…probe Ports the dev-branch memtrace setup.sh next to the probe scripts so a fresh workspace is a single command after clone: commit-matched Ray nightly + setup-dev symlink, rustup + maturin crate build, aiohttp/awscli/psutil, end-to-end verify. Tail now points at gen_s3_fixtures.py + run_matrix.py and exports a Ray memory monitor guard (threshold 0.8) so an over-allocating read task is killed before the OS OOM-killer takes down the raylet and terminates the workspace. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
The S3 windowed reader sliced a row group into fetch windows sized purely by a compressed-byte budget (window_rows_for). A RowSelection can only skip whole *pages*, never rows within a page, so when a window was narrower than a column's data page, every window overlapping that page decoded the whole page — decoding the row group once per window. This is the wide_schema pathology: a many-column/short-row row group has one data page per column, so an N-window split re-decoded all columns N times. Measured on a 5000-col / 200-row S3 fixture (concurrency=1): 260s / 5.4GB with windowing vs 42s / 4.4GB with windowing disabled (fetch_window_mb=0) — a 6x CPU-bound time regression, entirely re-decode. Fix: clamp each fetch window up to at least the coarsest projected column's largest page (max_page_rows, from the offset index the S3 path already loads). A group whose largest page spans the whole range (wide/short) collapses to a single window (parity with no windowing); a tall multi-page group still splits and keeps the bounded-working-set memory win, with page-boundary re-decode bounded to O(1) per window instead of O(pages). No offset index -> single window (windowing can't skip pages without it anyway). Pure step logic factored into effective_window_step with unit tests; max_page_rows reads the offset index. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
The peak_uss psutil sampler had ~1.6 GB run-to-run variance on identical configs (a no-op env knob produced a clean monotonic "trend"), which made every fine memory comparison untrustworthy. Two causes, both fixed: - 10 Hz sampling missed the short 5000-column builder-flush spike on some runs. Raise to 50 Hz. - The sampler summed every ``ray::`` process on the box, including the managed workspace Ray (:6379). Restrict to OUR raylet's descendant workers via ``_global_node`` (ray:: proctitles can't be matched by session dir). - RAY_ADDRESS=local next to :6379 made the stats re-resolution ambiguous, so Ray's deterministic per-task ``max_uss`` (read_avg_max_uss_gb) errored out every run. Pin the explicit gcs address after init so it populates. read_avg_max_uss_gb (recorded by MemoryProfiler, no sampling) is now the metric of record; the psutil peak is the backup. Also report sampled_workers to verify isolation. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
Bounds the column dimension on wide/short row groups where row-windowing collapses to the whole group. partition_columns_by_budget splits projected column chunks into <=column_fetch_mb compressed groups read SEQUENTIALLY (each group's InMemoryRowGroup + decoder scratch freed before the next), hstacked zero-copy. Knob: RAY_DATA_ARROW_RS_COLUMN_FETCH_MB / arrow_rs_column_fetch_mb. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
…ow S3 path Sequential column groups left the decoder idle during every S3 fetch (and the network idle during every decode). Now an admission loop acquires KiB-denominated semaphore permits per group (sized exactly from footer chunk metadata) and spawns its ranged GET; fetches run concurrently up to a compressed-byte budget while decode stays strictly one-group-at-a-time (the wide-schema scratch bound). Dropping a decoded group's bytes releases its permits, waking the next fetch: constant memory pressure, concurrency self-adjusts to the fetch:decode ratio. Knob: arrow_rs_column_prefetch_budget_mb / RAY_DATA_ARROW_RS_COLUMN_PREFETCH_BUDGET_MB (default 64; 0 = old sequential behavior). Also: column_fetch_mb default 256->16 (measured knee: 4.30 GB vs PyArrow 6.78 GB fanned-out, byte-identical output) and adds both column knobs to ARROW_RS_TUNING_KWARGS (dataset_kwargs path previously raised "Unknown arrow-rs tuning kwargs" for them). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
…dep verify - ensure upstream remote + fetch before the wheel merge-base pick - generate arrow_rs_probe/env.sh (venv+cargo activation, RAY_* exports, memory guard, AWS_DEFAULT_REGION=us-west-2, fixture paths) + idempotent ~/.bashrc hook - verify aiohttp/psutil/numpy/pyarrow import loudly (missing aiohttp hangs ray.init) Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
One tunable (column_fetch_mb, the column-group batch size); the prefetch bucket the byte-semaphore keeps full defaults to 4 batches (one decoding + ~3 in flight), so scaling the batch knob scales the bucket with it. Explicit arrow_rs_column_prefetch_budget_mb / env still overrides (0 = sequential, the benchmark A/B escape hatch). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
…river
Previously the crate had two prefetch mechanisms on S3: row-windowed
streaming used a fixed count-based pipeline (prefetch_windows=2 windows in
flight), while the wide-schema column-windowing path used a byte-denominated
semaphore ("bucket"). A fixed depth is the wrong shape for prefetch: if a
window fetches 5x slower than it decodes, depth 2 starves the decoder; if it
fetches faster, depth N overshoots memory by N windows.
Every S3 read shape now decomposes into prefetchable *units* — row windows
(~fetch_window_mb compressed of all projected columns, page-aligned via the
offset index) or column groups (~column_fetch_mb of some columns, all rows) —
and all units flow through ONE driver (drive_s3): an admission loop acquires
semaphore permits equal to each unit's exact compressed size (from the
footer) and spawns its ranged GET; a single in-order decoder serves entirely
from the prefetched bytes; dropping a decoded unit releases its permits and
wakes the next fetch. Fetch concurrency self-adjusts to the fetch:decode
ratio and peak prefetch memory is the bucket size by construction. K-split
survives as pure dispatch (K row partitions, each running the same driver,
each with its own bucket) since parallel decode is the point of that shape.
Changes:
- drive_unit + spawn_window + drive_colwindowed replaced by plan_s3_units +
drive_s3 (+ window_fetch_plan, which computes the exact byte ranges a
window decode requests: dictionary page + overlapping data-page span per
leaf, off the same offset index the decoder's RowSelection uses).
- prefetch_windows knob removed; column_prefetch_budget_mb generalized to
prefetch_budget_mb (env RAY_DATA_ARROW_RS_PREFETCH_BUDGET_MB, dataset_kwarg
arrow_rs_prefetch_budget_mb; default derives 4 x max(fetch_window_mb,
column_fetch_mb)).
- Column partitioning now sizes/expands by schema ROOT (a struct column is
one indivisible unit summing its leaf chunks), fixing a latent
nested-schema bug where leaf indices were assumed == root indices.
- New Rust tests: window plans vs whole chunks, sub-window strictness, an
end-to-end proof that decode is served entirely from planned ranges at
non-page-aligned offsets, and the windows-vs-hstack planning decision.
Rust 33/33; arrow-rs suite 88 passed (incl. moto S3 order tests at bucket
sizes 0/1/64); parquet suites 284+13 passed.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
Release tests currently report only total wall time and aggregate object-store peak, which cannot attribute a memory change to the read operator or see per-worker decode memory. This adds: - MemoryProfiler: track max RSS alongside the existing max-USS estimate (same poll; memory_info() returns both). RSS counts shared pages (e.g. mapped object-store blocks) that USS excludes, so the pair separates a task's private working set from its OS-visible footprint. - TaskExecWorkerStats.max_rss_bytes, populated by MapOperator next to max_uss_bytes. - OpRuntimeMetrics: max_rss_bytes DistributionTracker plus max_uss_per_task / average_max_rss_per_task / max_rss_per_task metric properties (worst-task values, since the average can hide one task decoding an outlier file). - benchmark.py collect_operator_metrics(): per-operator wall time, output bytes/rows, and avg/max USS/RSS per task merged into the release result JSON, with read_* top-level conveniences; wired into the wide_schema and read_from_uris benchmarks. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aarrya <[email protected]>
Signed-off-by: AarryaSaraf <[email protected]>
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |


Draft PR to run release tests