Repository navigation
Conversation
|
Benchmark results for Results
|
9471a40 to
5b9e6cd
Compare
5b9e6cd to
e3e488f
Compare
Sliced arrays and view arrays can keep memory alive that their rows do not reference. Callers such as spilling and IPC writers each work around this on their own. `minify` returns a logically equal array with offset zero whose buffers hold only referenced data. This commit adds the reuse policy and the null buffer handling, and supports the flat types: primitive, temporal, decimal, interval, boolean, null, fixed size binary, byte and byte view arrays. Null rows of byte arrays get empty ranges. `view_data_len` and `keeps_view_buffers` hold the view array decision, so that later code can share it. The dispatch matches every `DataType` variant without a wildcard, so a new variant in arrow-schema fails to compile until `minify` handles it. Nested, union, dictionary and run-end encoded types return `NotYetImplemented`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…oded types in `minify` Sliced lists and maps share the full child array. Dictionaries can hold values that no key references, and dense unions can hold child rows that no row references. `minify` needs to recurse into these types to drop that memory. This commit adds List, LargeList, Map, FixedSizeList, Struct, ListView, LargeListView, sparse and dense Union, Dictionary and RunEndEncoded. Null rows of lists and maps get empty ranges. These types share one gather path, `gather_ranges`. It gathers dense unions, list views and run-end encoded arrays by their parts, so child rows that several rows share stay shared. `list_view_child` and `dense_union_rows` hold the child row selection of list views and dense unions, so that later code can share it. `minify`, `gathers_parts` and `gather_ranges` match every `DataType` variant without a wildcard. The dispatch passes the list field and the union fields to the helpers, so they need no `unreachable!` arm. Invalid dictionary key, run end and time unit types return `InvalidArgumentError`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The `minify` kernel has no benchmarks, so performance changes cannot be measured. This adds `minify_kernels` with slices of 8192 rows from parents of 100k rows for each main type, an already minimal input, null-heavy strings with non-empty null ranges, and one large 4M-row case. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
e3e488f to
940d911
Compare
A spill batch has at most batch_size rows, whatever its size in bytes. A merge of spill files reserves memory for the largest batch of each file, so wide rows make that reservation larger than the pool. An operator needs a way to bound the batches it spills by bytes. This commit adds SpillManager::with_max_batch_bytes (crate-private) and SpillPieces. A bounded writer cuts each appended batch into row ranges by SpilledRowSizes, copies each range, and writes it as its own IPC message. The recorded size of a bounded writer counts the IPC padding of each buffer, so a batch read back never exceeds it. A slice of a list, run-end encoded array, union or list view keeps whole children or values, so its measured size is far above what the IPC reader allocates for it. compact_batch copies each range into fresh buffers that hold only its rows, so the measure is exact for every type and no type has to be written whole. It uses arrow take, plus fixes for what take keeps whole: view buffers, unused dictionary values and list view children. Rows of a list view can share a child range, so it copies the covered range once, and the halving of a piece stops when the halves do not get smaller. arrow-rs minify (apache/arrow-rs#12184) replaces the copy. A dictionary that the rows of a split batch share is written once per piece. A batch within the bound is written as before. No operator sets a bound yet, and an unbounded writer records the same size as before, so this commit changes no behavior. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…iased buffers Review found inputs where `minify` kept or created memory that the rows do not need. Repeated views counted shared bytes once per view, so `minify` kept a 1 MB buffer for 100 distinct bytes or made `gc` write the bytes once per view. Null view rows kept their bytes. The slack of 64 bytes per data buffer kept thousands of unreferenced small buffers. A buffer aliased twice inside one array was copied twice, so memory grew. The dense union lookup table was as long as the child. View arrays now merge the distinct ranges that valid views reference. `minify` keeps a data buffer only if the views reference all of its bytes and it is not oversized. It copies the other ranges once into new buffers and gives null rows an empty view. Equal struct columns share one minified column. If the result still uses more memory than the input, `minify` returns the input unchanged. The dense union table spans only the visible offsets. The module doc lists the parents that keep child data of null rows. The `allocated` test helper counts each allocation once. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…in `minify` `gather_run` copied a run value once per gathered range. A list whose null rows keep their child ranges, or a dense union over a run-end encoded child, then gathered many ranges of one run. A 183 KB input reached a 1 GB peak, and the fallback returned the input unchanged although nothing was aliased. A range that starts in the run where the previous range ended now extends that run. Dense union child rows are numbered in ascending order, so gathered ranges never go back and coalesce. The offsets keep the logical rows unchanged, and a child that is used in full stays shared. `view_data` adds view offsets and lengths as `usize`, because a data buffer can be longer than `u32::MAX`. Dictionary garbage collection costs O(keys + span of used keys) and not O(values). New tests pin the run fix, the view range math, the fallback threshold, the null comparisons of `same_data`, the paths for all-valid null buffers, `push_range`, `gathers_parts` and the exact byte capacity of a gather. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The cases cover already compact arrays, small slices of large utf8, view, dictionary and dense union parents, reversed views and arrays with one data buffer per row. `gc`, `take` and `garbage_collect_dictionary` run as baselines that do comparable work. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
would having this kernel supersede the need for
? (or at least mean we only need the implementation in |
|
I think we may be able to share some code but ultimately it would be nice to avoid materializing a minify step and instead minify directly into the output buffers. In any case I'm more worried about getting the high level public APIs right and we can later come and refactor shared code, etc. |
| // SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership | ||
| // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements | ||
|
|
||
| //! [`minify`]: Copy an array into buffers that hold only the data its rows reference |
There was a problem hiding this comment.
this detail might be better on the function doc; users i assume will mainly look at the doc of the function, and the function doc just redirects to module do for more details
| //! | ||
| //! # Limitations | ||
| //! | ||
| //! * `minify` does not deduplicate dictionary values or merge equal runs. |
There was a problem hiding this comment.
i wonder if deduping dicts/run arrays is something we should consider in a followup
There was a problem hiding this comment.
Agreed, I think that's worth a follow-up. I'll file an issue if this merges.
| let (after, allocations) = allocated_memory(&minified.to_data()); | ||
| let (before, _) = allocated_memory(&array.to_data()); | ||
| if grew(before, after, allocations) { | ||
| return Ok(make_array(array.to_data())); |
| Ok(Arc::new(minify_primitive(array.as_primitive::<$t>()))) | ||
| }; | ||
| } | ||
| match array.data_type() { |
There was a problem hiding this comment.
we can use downcast_primitive_array!() to cut down boilerplate
return downcast_primitive_array! {
array => Ok(Arc::new(minify_primitive(array))),
DataType::Null => Ok(Arc::new(NullArray::new(array.len()))),
DataType::Utf8 => Ok(Arc::new(minify_bytes(array.as_bytes::<Utf8Type>()))),
// other non-primitive types
t => Err(
ArrowError::InvalidArgumentError(format!("invalid data type: {t}")),
),
};| /// `minify` returns `InvalidArgumentError` for a time type with an invalid | ||
| /// unit, a dictionary with an invalid key type and a run-end encoded array | ||
| /// with an invalid run end type. It also returns the error of an array | ||
| /// constructor that rejects the minified parts. |
There was a problem hiding this comment.
Could simplify to just say it returns error on invalid array types (we could even just decide to panic, since this seems an extreme edge case to cater for)
It also returns the error of an array constructor that rejects the minified parts
i think we should either clarify what cases this could happen for, or just drop it
There was a problem hiding this comment.
Simplified the doc, it now just says it errors on invalid data types. I think we should keep Result: take and filter return one too, and it leaves us room to add real error cases later without breaking the signature.
| let values = if start == O::zero() { | ||
| minify_scalar_buffer(offsets.inner()) | ||
| } else { | ||
| offsets.iter().map(|o| *o - start).collect() |
There was a problem hiding this comment.
should we consider using OffsetBuffer::subtract here? though it'll require a clone upfront 🤔
There was a problem hiding this comment.
Good call, switched to subtract. It still allocates since the array holds the buffer, but benchmarks are unchanged and it reads nicer.
| let values = if run_ends.is_empty() { | ||
| array.values().slice(0, 0) | ||
| } else { | ||
| let start = run_ends.get_start_physical_index(); | ||
| let end = run_ends.get_end_physical_index(); | ||
| array.values().slice(start, end - start + 1) | ||
| }; |
There was a problem hiding this comment.
| let values = if run_ends.is_empty() { | |
| array.values().slice(0, 0) | |
| } else { | |
| let start = run_ends.get_start_physical_index(); | |
| let end = run_ends.get_end_physical_index(); | |
| array.values().slice(start, end - start + 1) | |
| }; | |
| let values = array.values_slice(); |
|
|
||
| /// Like [`garbage_collect_dictionary`], but copies the values with | ||
| /// [`gather_ranges`]. `gather_ranges` keeps child rows that the values share, | ||
| /// and does not merge equal runs of run-end encoded values as `take` does. |
There was a problem hiding this comment.
whats the significance of using gather_ranges to copy here? could we enhance garbage_collect_dictionary instead, or we need to keep these two versions distinct?
There was a problem hiding this comment.
Two reasons. garbage_collect_dictionary does work proportional to the whole values array, which hurts for a small slice of a big dictionary. And its filter copies shared child rows once per reference for dense union / list view values, and re-splits run-end encoded ones, so the result can end up bigger than it needs to be.
I think the right fix is to improve garbage_collect_dictionary itself and delete this one. It's private so we can do that any time, but it changes a public kernel's output so I'd rather do it as its own PR. Sound ok?
| fn dense_union_rows( | ||
| array: &UnionArray, | ||
| fields: &UnionFields, | ||
| rows: impl Iterator<Item = usize> + Clone, |
There was a problem hiding this comment.
do we strictly need rows as a separate argument here?
| } | ||
|
|
||
| /// Merges the child ranges of `views`, given as `(valid, offset, size)`. | ||
| fn list_view_child(views: impl Iterator<Item = (bool, usize, usize)>) -> ListViewChild { |
There was a problem hiding this comment.
i find it a little confusing why we're passing in an iterator here, instead of giving just the array and doing the iteration inside this function
The review asked for less boilerplate and simpler helper signatures. This commit changes no behavior, except the text of the error for an invalid time unit. - Use `downcast_primitive_array!` for the primitive types. The macro nests its matches, so the match needs a wildcard arm. - Use `Array::to_arc` and `RunArray::values_slice`. - Return a `Range` from `rebase_offsets`. - `dense_union_rows` and `list_view_child` take the array and iterate over its rows themselves. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Users read the function doc first, and it only pointed to the module doc for the reuse policy, the null row handling and the limitations. Move these sections to the function doc. Also shorten the errors section: `minify` only fails for an array with an invalid data type. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The review suggested `subtract` in place of the hand-written offset arithmetic. The array still shares the buffer, so `subtract` allocates as the `collect` did, and the benchmarks do not change. The remaining `unsafe` block covers only the branch that keeps the offsets as they are. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…ment The comment said that `garbage_collect_dictionary` copies the values with `take`. It uses `filter`, which splits a shared run where the comment claimed a merge. A safety comment also named the wrong function. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
Thanks @Jefffrey! I'll mark this as ready. |
|
@Jefffrey one design question that popped up by reviewing apache/datafusion#27391 Should // 50 one-row arrays, each owning one small data buffer
let parts: Vec<StringViewArray> = ...;
let merged = concat(&parts)?;
No bytes are wasted, so by the current definition there is nothing to do. But arrays like this are expensive in other ways: every Options I see:
I lean towards B. With a size threshold it keeps the properties we / callers of
The downsides are that the threshold is a magic number (builder block size, 8 KiB? something else?), and that if another array still holds the old buffers, memory goes up until it drops them. The second one is already true for oversized shared buffers and is documented. If B feels like too much policy for a kernel, we can do A in this PR and C as a follow-up. Adding What do you think? |
Which issue does this PR close?
Rationale for this change
Sliced arrays, view arrays, dictionaries and dense unions can keep memory alive that their rows do not reference. Downstream users (for example DataFusion spilling) each work around this on their own. The issue asks for one kernel in
arrow-select.What changes are included in this PR?
A new
arrow_select::minifymodule withminify(&dyn Array) -> Result<ArrayRef, ArrowError>. The result is logically equal to the input, has offset zero, and its buffers hold only referenced data.minifyrecurses into children, dictionary values and run-end encoded values.gather_ranges, nottake.gather_run, which keeps the runs of the input and copies each run value once, also when many gathered ranges hit one run.garbage_collect_dictionary, but gather the kept values withgather_ranges, then recurse into keys and values.Reuse policy:
minifycopies a buffer only when its allocation is larger than the visible data needs (rounded up to 64 bytes). Already-minimal arrays are returned without copies, sominify(minify(a))copies nothing. New allocations also round up to 64 bytes, so a tiny input whose buffers are already exact-size can grow slightly.Null rows:
minifyalways gives null rows of byte, list, map and list view arrays an empty value range (and null rows of byte view arrays an empty view), as #9970 proposed. There is no option for this. A fast path keeps it cheap. One O(rows) check over the offsets and the null bitmap finds out if any null row has a non-empty range. If none has (including arrays with no nulls),minifyslices or copies the referenced range in one piece. Otherwise it copies the child range of each run of valid rows, so contiguous runs stay single copies. The result has no reclaimable null ranges, so a second call copies nothing.Open questions for reviewers:
minifycopies it even if other arrays keep it alive. The docs call this out.minifyreturns the input unchanged.Are these changes tested?
Yes. Unit tests cover every type above, null rows with non-empty ranges (bytes, map, and a list of strings with nulls at both levels, also inside a dictionary and a struct), the no-null fast path, plus nested combinations: dictionary of
Utf8View, dictionary of list, dictionary inside struct and list children, run-end encoded dictionary, fixed-size list of struct, dense union of lists, and lists over sliced children. A sharedcheckhelper slices each array several ways and asserts that the result:validate_full,Benchmarks are in
arrow/benches/minify_kernels.rs.How to review
Read the PR commit by commit:
minifyfor flat types (reuse policy, null buffers, primitive, boolean, null, fixed size binary, byte and byte view arrays). The dispatch matches everyDataTypevariant without a wildcard. Nested types returnNotYetImplementedin this commit only.gather_rangespath. The row selection helpers (list_view_child,dense_union_rows) exist from the commit that first needs them, so feat(arrow-select): add compacted_size, row_sizes and split_by_size next to minify #12190 can reuse them.minify_kernelsbenchmark.view_data,keeps_view_buffer). Aliased buffers cannot make the result larger than the input. The dense union lookup table spans only the visible offsets.gather_run, number dense union child rows in ascending order, useusizefor view ranges, and make dictionary garbage collection O(keys + span of used keys).minify_kernelscases for small slices of large parents.Are there any significant user-facing changes?
New public API only:
arrow_select::minify::minify.AI usage disclosure
Claude Code wrote the implementation, tests and this description under my direction.
🤖 Generated with Claude Code