Skip to content

Share word-at-a-time primitives instead of optimizing each call site separately #12467

Done

Description

@mbutrovich

Is your feature request related to a problem or challenge?

Many recent performance PRs make the same kind of change at one call site: process bytes or bits a word at a time instead of a byte at a time or through a libc call. Each PR tunes, tests, and benchmarks its own copy. This has three costs.

The tunings conflict. common_prefix_length in parquet (source, from #10549) compares 32-byte blocks inline because an out-of-line bcmp at 64 bytes measured slower. #12460 compares 8-byte chunks and hands values with a common length above 64 bytes to memcmp because memcmp measured faster there. Both run in the same file of the parquet arrow writer.

Gains don't reach the other copies. #11818 sped up UnalignedBitChunk::count_ones on aarch64. parquet has two count_set_bits functions of its own. The one in the arrow reader (source) calls UnalignedBitChunk::count_ones and got the gain. The one used to skip bit-packed definition levels (source) builds without the arrow feature, where arrow-buffer isn't available, so it has its own loop and didn't get the gain. compare_greater in the parquet column writer (source) still compares slices with a > b while #12460 speeds up the arrow writer's copy of the same comparison.

Work gets duplicated. #12024 and #12042 wrote the same multiply-based bool packing for BooleanBufferBuilder::append_slice at the same time. arrow-buffer has two identical read_u64 functions (bit_util.rs, bit_chunk_iterator.rs). byte_view_key in arrow-ord rank (source) and is_greater_bytes in #12460 (source) each build their own order-preserving integer key from a byte prefix.

Describe the solution you'd like

Give these primitives one home in arrow_buffer::util, next to bit_util and bit_chunk_iterator. Each primitive has one implementation, a test against a naive reference, and benchmark cases for both well-predicted and random input. Add a paragraph to the Performance Improvements section of CONTRIBUTING.md: before adding a word-at-a-time loop at a call site, check arrow_buffer::util and extend or add a primitive there. A PR that tunes a primitive shows results on both x86-64 and aarch64, because every caller inherits the tuning.

For byte comparison, the copies above share a structure with two parts that need different tuning. Most values that differ do so in their first word, so that word should be compared inline in the caller's loop. Values with a long shared prefix need a scan tuned for throughput, kept out of line so it doesn't bloat every caller. #12460 found both effects: inlining its chunk loop cost 2 to 4 points on random strings, and its out-of-line function had to stay a leaf to keep its gain. That suggests three functions:

  1. prefix_key(s: &[u8]) -> u64 returns the first 8 bytes as a big-endian integer, zero-padded when s is shorter. prefix_key(a) < prefix_key(b) implies a < b. Equal keys say nothing. A u128 variant covers 16-byte keys like byte_view_key. Only the u128 variant has a caller outside cmp_bytes so far, so the u64 one could stay private until it gets one.
  2. common_prefix_len(a: &[u8], b: &[u8]) -> usize is the out-of-line scan. The choice between inline blocks and memcmp, and its bound per target, gets made here once. The DELTA_BYTE_ARRAY encoders, which inline today's scan, would make one call per value.
  3. cmp_bytes(a: &[u8], b: &[u8]) -> Ordering compares the first 8 bytes inline when both values have that many. Shorter values and ties go to an out-of-line function that compares the prefix keys, then scans with common_prefix_len and compares the byte at the mismatch or the lengths. Its result matches a.cmp(b) for every input.

A prototype showed that this split has to be forced with attributes, because #[inline] alone doesn't hold across crates. With the default release profile, LLVM declined to inline a #[inline] cmp_bytes into parquet's ByteArrayEncoder::write_gather, which inlines the statistics loop of every array type, and kept 24 calls to an out-of-line copy. Marking all of cmp_bytes #[inline(always)] grew write_gather by 18%. Marking only the first-word comparison #[inline(always)], with the rest #[inline(never)], kept it at its current size. With every inlining decision set by an attribute, the split shouldn't depend on each consumer's LTO and codegen-unit settings, though I have checked it only without LTO. The out-of-line scan also lost its leaf status in the prototype to a bounds check whose panic path needed a stack frame. Details like these are easy to break at one call site, which is another reason to review them in one place.

For bitmaps, UnalignedBitChunk and BitChunks already exist. Once parquet can depend on the shared primitives without the arrow feature, it can keep one count_set_bits that calls UnalignedBitChunk::count_ones. arrow-buffer can keep one read_u64.

Each move would be its own PR with benchmark results.

Describe alternatives you've considered

Keeping the current approach costs nothing up front, and each PR stays small. The costs above grow with every new copy.

A generic chunked-scan abstraction, such as a const-generic block width with a closure per block, would cover more cases with one type. It would leave the inlining decisions above to each caller's instantiation, so each caller's generated code would need its own review, and it would be a larger public API to keep stable.

A new crate for these primitives would keep them out of arrow-buffer's API. It would be one more crate to version and release, and parquet would still need it without the arrow feature.

Each crate could keep pub(crate) copies and consolidate within the crate. That avoids new public API, but parquet, arrow-ord, and arrow-buffer would still tune separately.

Additional context

Anything shared between crates has to be pub, so each primitive becomes permanent API under the stability policy. That argues for a few concrete functions with results defined for every input.

parquet uses these primitives in code that builds without the arrow feature, where arrow-buffer is optional. arrow-buffer depends only on bytes, num-bigint, num-traits, and half (Cargo.toml), and parquet already depends on all four without the feature (Cargo.toml), so a required dependency would add no third-party crates.

Is arrow-buffer the right home, and is a required arrow-buffer dependency acceptable for parquet?

cc @alamb @Jefffrey @etseidl @Rich-T-kid @neilconway @adriangb @YUZHEthefool @viirya @waynexia @mightsleep @shanielh

Activity

  1. mbutrovich commented on Nov 25, 2026

    @mbutrovich
    ContributorAuthor

    I will try to draft a POC PR today just to understand blast radius and potential tradeoffs to consolidating this sort of stuff (inlining challenges, LTO, etc.).

  2. alamb commented on Nov 25, 2026

    @alamb
    Contributor

    Thank yoU @mbutrovich -- I like the idea of consolidating all our bit manipulation hackery/ tricks. It would be really nice.

    For bitmaps, UnalignedBitChunk and BitChunks already exist. parquet's second count_set_bits can call UnalignedBitChunk::count_ones, and arrow-buffer can keep one read_u64.

    A new crate for these primitives would keep them out of arrow-buffer's API. It would be one more crate to version and release, and parquet would still need it without the arrow feature.

    This is my preference -- perhaps arrow-bitutils or something?

  3. alamb commented on Nov 25, 2026

    @alamb
    Contributor

    So if people are generally ok with a new crate for this, I would recommend a POC that:

    1. Creates a new crate
    2. find a common duplicated pattern in arrow and paruqet
    3. SHow how a refactor to the common crate would look like
  4. mbutrovich commented on Nov 25, 2026

    @mbutrovich
    ContributorAuthor

    So if people are generally ok with a new crate for this, I would recommend a POC that:

    1. Creates a new crate
    2. find a common duplicated pattern in arrow and paruqet
    3. SHow how a refactor to the common crate would look like

    I'll give this a shot, thanks for the feedback!

  5. etseidl commented on Nov 25, 2026

    @etseidl
    Contributor

    I wonder if we should roll up some of the ULEB and zigzag decoding as well 🤔 That seems to repeat throughout the various crates.

  6. mbutrovich commented on Nov 25, 2026

    @mbutrovich
    ContributorAuthor

    I wonder if we should roll up some of the ULEB and zigzag decoding as well 🤔 That seems to repeat throughout the various crates.

    I think it fits. It needs no Arrow types, parquet needs it without the arrow feature, and parquet already keeps it in util/bit_util.rs. The three decoders disagree on an overlong varint:

    • arrow-avro read_varint returns None.
    • parquet read_vlq shifts with wrapping_shl and returns a wrong value.
    • parquet BitReader::get_vlq_int panics on an assert!. It reads RLE run headers and DELTA_BINARY_PACKED headers.

    The encoders are copied the same way (avro, BitWriter, thrift).

  7. mbutrovich commented on Nov 25, 2026

    @mbutrovich
    ContributorAuthor

    The draft POC is up in #12470, following the steps in #12467 (comment). It adds arrow-bitutils, a crate with no dependencies, and moves these into it:

    The commits read in order, starting with the pure move. The PR description has a table of which copy was kept for each duplicate and why.

    parquet uses these without the arrow feature. Tuning that went into one copy, such as #11818's aarch64 popcount or #12460's comparison, now reaches every caller. The column writer's compare_greater gets the #12460 comparison that the PR left for a follow-up.

    The PR also lists the costs. arrow-buffer's own calls to BitChunks::new now cross a crate boundary. Tests and doc examples in the new crate can't use Buffer. Sharing a pub(crate) helper such as read_u64 would need a new public function.

    cmp_bytes inlines everything except the scan of a long shared prefix. That differs from the split sketched in the issue description, which kept only the first-word comparison inline. The ULEB128 and zigzag consolidation @etseidl suggested isn't in the POC. Benchmark bot runs will follow on the PR.

  8. viirya commented on Nov 25, 2026

    @viirya
    Member

    +1 on consolidating. A few points for the POC:

    • cmp_bytes slow path: I'd keep memcmp (a[k..].cmp(&b[k..])) for long shared prefixes instead of scanning with common_prefix_len and comparing the byte at the mismatch. perf(parquet): compare byte-array statistics 8 bytes at a time #12460 added its 64-byte bound because a chunk loop lost to memcmp there (+22% on large_string_non_null, +26% on small_string_shared_prefix). The 32-byte block scan was only measured on aarch64, where widths from 16 up tie. Nothing shows it keeps up with glibc's AVX2 memcmp. Relatedly, perf(parquet): scan DELTA_BYTE_ARRAY shared prefixes a block at a time #10549 and perf(parquet): compare byte-array statistics 8 bytes at a time #12460 don't really conflict. One needs the mismatch position, which memcmp can't return. The other needs only the order. Both avoid a per-block out-of-line call.
    • Bitmaps in a new crate: parquet still can't reach UnalignedBitChunk without arrow-buffer. The popcount kernel (count_ones_words) would have to move into the new crate, with arrow-buffer delegating to it. parquet's skip_and_count_ones calls count_set_bits once per bit-packed run, often a short range. UnalignedBitChunk::new's setup (align_to, prefix/suffix masks) needs a benchmark on short ranges before switching.
    • Inlining across crates: moving a primitive into another crate changes the inlining decisions perf(parquet): compare byte-array statistics 8 bytes at a time #12460 measured within one crate. Each caller needs re-measuring, with LTO as well as without, since downstream users like DataFusion often enable it.
    • What to make public: I'd only add a primitive once it has two real callers. The u64 prefix_key could wait until it does.
    • perf(parquet): compare byte-array statistics 8 bytes at a time #12460: I wouldn't hold it for this. It can merge with private helpers and move once the shared home exists.
    • VLQ panic: separate from consolidation, BitReader::get_vlq_int can be triggered by a corrupt file. The RLE run header (rle.rs:719) and the DELTA_BINARY_PACKED headers read through it, so an overlong varint in page data panics instead of returning an error. That's worth its own fix now. A shared decoder shaped like avro's read_varint(&[u8]) -> Option<(u64, usize)> would let each crate map the failure to its own error type.
    • Naming: if byte comparison and VLQ land there too, arrow-bitutils may be too narrow a name.
  9. mbutrovich commented on Nov 25, 2026

    @mbutrovich
    ContributorAuthor

    Thanks @viirya.

    I'd keep memcmp (a[k..].cmp(&b[k..])) for long shared prefixes instead of scanning with common_prefix_len and comparing the byte at the mismatch.

    The amd64 arrow_writer runs on #12470 include large_string_non_null and small_string_shared_prefix, so they will show whether the block scan keeps up with glibc's memcmp. If it doesn't, where should the bound go? Inside the inlined cmp_bytes, memcmp adds a second call target to every caller's loop. Inside the out-of-line scan, the function stops being a leaf, which #12460 found lost its gain.

    Relatedly, #10549 and #12460 don't really conflict.

    Fair, one needs the position and the other only the order.

    The popcount kernel (count_ones_words) would have to move into the new crate, with arrow-buffer delegating to it.

    #12470 does this: 8041ad3 moves bit_chunk_iterator, kernel included, into arrow-bitutils, and arrow-buffer re-exports it.

    UnalignedBitChunk::new's setup (align_to, prefix/suffix masks) needs a benchmark on short ranges before switching.

    Agreed, and no existing benchmark reaches that path. The arrow reader skips flat optional columns through PackedDecoder (mod.rs#L118, definition_levels.rs#L467-L483), which already counts with UnalignedBitChunk. BitReader::skip_and_count_ones only runs when max_def_level is 1 and the levels go through DefinitionLevelDecoderImpl (decoder.rs#L493, bit_util.rs#L1069). A micro-benchmark of the two on 8 to 504 bit ranges would cover it.

    Each caller needs re-measuring, with LTO as well as without, since downstream users like DataFusion often enable it.

    The bot builds with thin LTO. cmp_bytes fixes its split with #[inline(always)] and #[inline(never)], so the split doesn't depend on the LTO setting. BitChunks::new is the open one: arrow-buffer's own calls to it now cross a crate boundary, and the boolean_append_packed runs will show what that costs.

    I'd only add a primitive once it has two real callers.

    Agreed. prefix_key is private in #12470. prefix_key_u128 has one caller, so I'll drop it too.

    I wouldn't hold it for this.

    Agreed.

    That's worth its own fix now.

    Agreed that it needs its own issue. I'm not planning to take it on.

    if byte comparison and VLQ land there too, arrow-bitutils may be too narrow a name.

    Agreed. I'm open to suggestions.

  10. mbutrovich commented on Nov 25, 2026

    @mbutrovich
    ContributorAuthor

    I'd keep memcmp (a[k..].cmp(&b[k..])) for long shared prefixes instead of scanning with common_prefix_len and comparing the byte at the mismatch.

    @viirya you were right. With the scan, large_string_non_null was 0.76x to 0.89x in every configuration, and string_dictionary_1pct_cardinality was 0.73x to 0.86x on amd64 (for example, amd64 aligned). #12470 now compares the first 8 bytes inline and calls a.cmp(b) for everything else. Both cases are back to 0.94x to 1.07x, and the gains hold: string_dictionary_low_cardinality_400 is 1.35x to 1.76x and short_string_non_null 1.19x to 1.46x (amd64 aligned, arm64 aligned). The DELTA_BYTE_ARRAY cases recovered along with plain encoding, so common_prefix_len wasn't the cause.

  11. mbutrovich commented on Nov 30, 2026

    @mbutrovich
    ContributorAuthor

    Closing in favor of #12516, which tracks the work. The proof of concept and its benchmark results are in #12470.

    Here is where each part of the proposal ended up:

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions