Skip to content

feat(arrow-select): add minify kernel to drop unreferenced buffer data - #12184

Open
adriangb wants to merge 11 commits into
apache:mainfrom
adriangb:minify-kernel
Open

adriangb wants to merge 11 commits into
apache:mainfrom
adriangb:minify-kernel

Conversation

@adriangb

@adriangb adriangb commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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::minify module with minify(&dyn Array) -> Result<ArrayRef, ArrowError>. The result is logically equal to the input, has offset zero, and its buffers hold only referenced data. minify recurses into children, dictionary values and run-end encoded values.

Type Behavior
Primitive (incl. decimal, temporal, interval), Boolean, FixedSizeBinary Copy the visible range. Boolean bit offsets become zero.
Null buffers Copy the visible bits. Drop the buffer if it has no nulls.
Utf8 / LargeUtf8 / Binary / LargeBinary Rebase offsets to zero and copy only the bytes of valid rows. Null rows get an empty range.
Utf8View / BinaryView Merge the distinct byte ranges of the valid views. Keep a data buffer only if the views reference all of its bytes. Copy the other ranges once into new buffers, so views that share bytes keep sharing them. Unreferenced buffers go away. Null rows get an empty view.
List / LargeList / Map Keep only the child ranges of valid rows, rebase offsets, recurse. Null rows get an empty range.
ListView / LargeListView Merge the child ranges of the valid views into disjoint ranges and copy them back to back (drops gaps). Overlapping views stay shared. Null rows get offset and size zero.
FixedSizeList, Struct, sparse Union Recurse into the (already sliced) children.
Dense Union Keep each referenced child row once, in ascending child order, and remap offsets. Rows that share a child row keep sharing it. A child that the rows use in full stays shared. The children are gathered with gather_ranges, not take.
RunEndEncoded Narrow runs and values to the slice, rebase run ends, recurse. Gathered rows (for example dictionary values) go through gather_run, which keeps the runs of the input and copies each run value once, also when many gathered ranges hit one run.
Dictionary Prune unreferenced values like garbage_collect_dictionary, but gather the kept values with gather_ranges, then recurse into keys and values.

Reuse policy: minify copies 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, so minify(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: minify always 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), minify slices 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:

  • Moving the IPC writer logic onto this kernel is left for a follow-up.
  • A shared buffer counts as oversized, so minify copies it even if other arrays keep it alive. The docs call this out.
  • A buffer that appears more than once inside the input (two struct columns over one array, two dictionaries over one values array) could be copied once per reference. Equal struct columns now share one minified column. If the result would still use more memory than the input, minify returns the input unchanged.
  • Null rows of struct and fixed size list arrays, and unselected rows of sparse union children, keep their child data. The module doc lists this under Limitations.

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 shared check helper slices each array several ways and asserts that the result:

  • is logically equal to the slice and passes validate_full,
  • has offset zero and the same data type,
  • allocates no more (and for small slices strictly less) buffer memory than the slice,
  • reuses all buffers when minified a second time.

Benchmarks are in arrow/benches/minify_kernels.rs.

How to review

Read the PR commit by commit:

  1. feat: add minify for flat types (reuse policy, null buffers, primitive, boolean, null, fixed size binary, byte and byte view arrays). The dispatch matches every DataType variant without a wildcard. Nested types return NotYetImplemented in this commit only.
  2. feat: add nested, union, dictionary and run-end encoded types. They share the gather_ranges path. 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.
  3. bench: add the minify_kernels benchmark.
  4. fix: review follow-ups. Byte views count distinct referenced bytes and drop null row bytes and unused buffers (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.
  5. fix: copy each run value once in gather_run, number dense union child rows in ascending order, use usize for view ranges, and make dictionary garbage collection O(keys + span of used keys).
  6. bench: more minify_kernels cases 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

@boring-cyborg boring-cyborg Bot added arrow-kernels Crates that transform arrow data (e.g. compute, cast) arrow-core Core crates related to representing arrow data labels Nov 11, 2026
@adriangb

Copy link
Copy Markdown
Contributor Author

Benchmark results for arrow/benches/minify_kernels.rs, on a GCP c4a-standard-16 VM. Each case slices 8192 rows from a parent of 100k rows unless noted.

Results
Case Time
i32 slice 571 ns
utf8 slice, no nulls 29.7 µs
utf8 slice, null ranges 54.0 µs
utf8view sparse 33.9 µs
list slice 258 µs
listview slice 18.8 µs
dense union slice 58.1 µs
dictionary, few referenced 31.5 µs
run-end encoded slice 2.72 µs
list, already minimal 8.5 µs
utf8, already minimal (alternating nulls) 11.7 µs
utf8, 4M rows, null ranges 181 ms

adriangb and others added 3 commits November 11, 2026 17:21
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>
adriangb added a commit to adriangb/datafusion that referenced this pull request Nov 12, 2026
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>
adriangb and others added 3 commits November 13, 2026 17:34
…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>
@Jefffrey

Copy link
Copy Markdown
Contributor

would having this kernel supersede the need for

?

(or at least mean we only need the implementation in minify here and reuse them for ipc writing)

@adriangb

Copy link
Copy Markdown
Contributor Author

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.

@Jefffrey Jefffrey left a comment

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.

just an initial look

// 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

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.

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

Comment thread arrow-select/src/minify.rs Outdated
//!
//! # Limitations
//!
//! * `minify` does not deduplicate dictionary values or merge equal runs.

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.

i wonder if deduping dicts/run arrays is something we should consider in a followup

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, I think that's worth a follow-up. I'll file an issue if this merges.

Comment thread arrow-select/src/minify.rs Outdated
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()));

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.

we can use the new to_arc() here from #12420

Comment thread arrow-select/src/minify.rs Outdated
Ok(Arc::new(minify_primitive(array.as_primitive::<$t>())))
};
}
match array.data_type() {

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.

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}")),
        ),
    };

Comment thread arrow-select/src/minify.rs Outdated
Comment on lines +101 to +104
/// `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.

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.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread arrow-select/src/minify.rs Outdated
let values = if start == O::zero() {
minify_scalar_buffer(offsets.inner())
} else {
offsets.iter().map(|o| *o - start).collect()

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.

should we consider using OffsetBuffer::subtract here? though it'll require a clone upfront 🤔

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good call, switched to subtract. It still allocates since the array holds the buffer, but benchmarks are unchanged and it reads nicer.

Comment thread arrow-select/src/minify.rs Outdated
Comment on lines +1305 to +1311
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)
};

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.

Suggested change
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();

Comment thread arrow-select/src/minify.rs Outdated

/// 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.

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.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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?

Comment thread arrow-select/src/minify.rs Outdated
fn dense_union_rows(
array: &UnionArray,
fields: &UnionFields,
rows: impl Iterator<Item = usize> + Clone,

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.

do we strictly need rows as a separate argument here?

Comment thread arrow-select/src/minify.rs Outdated
}

/// Merges the child ranges of `views`, given as `(valid, offset, size)`.
fn list_view_child(views: impl Iterator<Item = (bool, usize, usize)>) -> ListViewChild {

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.

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

adriangb and others added 5 commits November 26, 2026 22:55
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>
@adriangb

Copy link
Copy Markdown
Contributor Author

Thanks @Jefffrey! I'll mark this as ready.

@adriangb
adriangb marked this pull request as ready for review November 27, 2026 18:01
@adriangb

Copy link
Copy Markdown
Contributor Author

@Jefffrey one design question that popped up by reviewing apache/datafusion#27391

Should minify merge many small view data buffers? Today it only copies a view data buffer if some of its bytes are unreferenced, or its allocation is oversized. A buffer that is fully used is kept as is. That means this case is a no-op:

// 50 one-row arrays, each owning one small data buffer
let parts: Vec<StringViewArray> = ...;
let merged = concat(&parts)?;
data buffers
after concat 50
after minify 50
after gc() 1

No bytes are wasted, so by the current definition there is nothing to do. But arrays like this are expensive in other ways: every Buffer has its own allocation and refcount, and anything that copies the buffer list per row goes quadratic. That is exactly what bit DataFusion in apache/datafusion#27390 (5.9 s vs 30 ms). The fix there (apache/datafusion#27391) adds a recursive gc helper, and DataFusion has a second one for array_agg. I'd like minify to be able to replace both, and right now it can't.

Options I see:

Behavior Cost
A Keep as is, list it under "Limitations" Callers that care about buffer count still need their own recursive gc
B Also merge small buffers: if an array has 2+ data buffers under some size, copy those into one Copies bytes that weren't wasted. Bounded to the small buffers, big ones are still reused
C Same as B but behind an option (minify_with_options) More API surface for a new kernel

I lean towards B. With a size threshold it keeps the properties we / callers of minify care about:

  • still a no-op on arrays that are already in good shape (at most one small buffer left, so a second call copies nothing)
  • large, fully used buffers are never copied
  • the extra CPU is proportional to the bytes in small buffers, which is the case where the copy pays for itself

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 minify_with_options later doesn't break anything. Changing the default later is the part that would be awkward, which is why I'm asking now.

What do you think?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arrow-core Core crates related to representing arrow data arrow-kernels Crates that transform arrow data (e.g. compute, cast)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Minify Kernel

2 participants