arrow icon indicating copy to clipboard operation
arrow copied to clipboard

[C++][Compute] Allow reusing hash table across multiple `is_in` / SetLookup kernel calls

Open owenowenisme opened this issue 9 months ago • 6 comments

Describe the enhancement requested

Problem

The is_in kernel (and other set lookup operations) rebuilds the internal hash table (MemoTable) from value_set on every invocation, even when value_set is identical across calls. There is currently no API to pre-build and reuse the hash table.

This becomes a significant bottleneck when the same value_set is used to filter many arrays (e.g., in a streaming/batch processing pipeline).

Use Case

In Ray Data Checkpointing, we want to use pc.is_in to perform an anti-join: filtering out already-processed row IDs from each incoming block of data. The checkpoint ID set (value_set) is the same across all blocks, but the hash table is rebuilt for every block.

# value_set is the same across all calls — hash table is rebuilt each time
for block in blocks:
    membership = pc.is_in(block["id"], value_set=checkpoint_ids)
    filtered = block.filter(pc.invert(membership))

With 100M checkpoint IDs and 20 blocks, the hash table construction alone takes ~250s (extrapolating from #36059 benchmarks), doing identical work 20 times.

Benchmark

Building on the benchmarks from #36059, the cost of rebuilding becomes clear when multiplied across calls:

import pyarrow as pa
import pyarrow.compute as pc
import numpy as np

value_set = pa.array(np.arange(10_000_000))
blocks = [pa.array(np.random.choice(np.arange(1000), 100)) for _ in range(20)]

# Current: ~25s total (rebuilds hash table 20 times)
for block in blocks:
    pc.is_in(block, value_set)

# Ideal: ~1.3s (build once, probe 20 times)

Proposed API

Option A — Prepared/materialized value set object:

# Build hash table once
lookup = pc.SetLookup(value_set)  # or pc.prepare_set(value_set)

# Reuse across calls — probes only, no rebuild
for block in blocks:
    mask = lookup.is_in(block)

Option B — Caching in SetLookupOptions:

options = pc.SetLookupOptions(value_set, cache=True)

# First call builds hash table; subsequent calls reuse it
for block in blocks:
    mask = pc.is_in(block, options=options)

Option C — Lower-level hash set exposure:

hash_set = pc.HashSet(value_set)  # builds MemoTable

for block in blocks:
    mask = hash_set.is_in(block)
    # or: mask = pc.is_in(block, options=pc.SetLookupOptions(hash_set))

Impact

This would benefit any workload that probes the same set repeatedly:

  • Streaming anti-joins / semi-joins
  • Incremental processing (checkpoint filtering)
  • Repeated dictionary lookups
  • Any ETL pipeline filtering against a static blocklist/allowlist

Related

  • #36059 — Performance of building up HashTable (MemoTable) in is_in kernel (addressed MemoTable speed, but not reuse)

Component(s)

C++

owenowenisme avatar Feb 10 '26 12:02 owenowenisme

Thanks for a well researched issue @owenowenisme ! This sounds like something Arrow should tackle. I think we probably need to start from C++/Acero side of things and perhaps @westonpace could suggest where to start.

rok avatar Feb 10 '26 15:02 rok

@rok Thanks for the fast response! I'm happy to implement this if you think the proposal aligns with Arrow's design goals.

owenowenisme avatar Feb 10 '26 16:02 owenowenisme

@owenowenisme happy to hear! We should really hear from someone more familiar with memo tables and such before you jump in. @zanmato1984 do you have some input perhaps?

rok avatar Feb 10 '26 17:02 rok

Hi @owenowenisme , I think this is a good finding and quite reasonable suggestions. However I do want to point out that by using the expression evaluation (via ExecuteScalarExpression - bind once, run acorss batches), the MemoTable, built at the bind time, seems to get reused across batches. Maybe you can see if this is an appropriate for your use case?

That said, I do also think enabling MemoTable reusing is still valid for low-level function invocations (via CallFunction). I would also ask @pitrou for opinions.

Thanks for this!

zanmato1984 avatar Feb 11 '26 07:02 zanmato1984

Maybe some valuable benchmark, the FunctionExecutor abstraction you might be looking for is available in the C++ api, so this issue could be solved by exposing it to python:

#include <arrow/api.h>
#include <arrow/array/data.h>
#include <arrow/buffer.h>
#include <arrow/compute/api.h>
#include <arrow/compute/exec.h>
#include <arrow/compute/function.h>
#include <arrow/compute/initialize.h>

#include <chrono>
#include <iostream>
#include <memory>
#include <random>
#include <vector>

using arrow::Array;
using arrow::ArrayData;
using arrow::ArraySpan;
using arrow::Datum;
using arrow::Int64Builder;
using arrow::TypeHolder;
namespace cp = arrow::compute;

static arrow::Result<std::shared_ptr<Array>> MakeRange(int64_t n) {
  Int64Builder builder;
  ARROW_RETURN_NOT_OK(builder.Reserve(n));
  for (int64_t i = 0; i < n; ++i) builder.UnsafeAppend(i);
  std::shared_ptr<Array> out;
  ARROW_RETURN_NOT_OK(builder.Finish(&out));
  return out;
}

static arrow::Result<std::shared_ptr<Array>> MakeRandomBlock(std::mt19937_64& rng, int64_t n,
                                              int64_t high) {
  std::uniform_int_distribution<int64_t> dist(0, high - 1);
  Int64Builder builder;
  ARROW_RETURN_NOT_OK(builder.Reserve(n));
  for (int64_t i = 0; i < n; ++i) builder.UnsafeAppend(dist(rng));
  std::shared_ptr<Array> out;
  ARROW_RETURN_NOT_OK(builder.Finish(&out));
  return out;
}

// Defined below main(); prevents the optimizer from discarding the timed work.
void benchmark_keep_alive(const Datum& d);

arrow::Status runBenchmark() {
  constexpr int64_t kValueSetLen = 10'000'000;
  constexpr int kNumBlocks = 20;
  constexpr int64_t kBlockLen = 100;
  constexpr int64_t kBlockHigh = 1000;

  ARROW_RETURN_NOT_OK(  cp::Initialize());

  std::cout << "Building value_set (" << kValueSetLen << " int64) and " << kNumBlocks
            << " blocks of " << kBlockLen << " ...\n";

  ARROW_ASSIGN_OR_RAISE(auto value_set, MakeRange(kValueSetLen));
  std::mt19937_64 rng(42);
  std::vector<std::shared_ptr<Array>> blocks;
  blocks.reserve(kNumBlocks);
  for (int i = 0; i < kNumBlocks; ++i) {
    ARROW_ASSIGN_OR_RAISE(auto block,MakeRandomBlock(rng, kBlockLen, kBlockHigh));
    blocks.push_back(std::move(block));
  }

  cp::SetLookupOptions options{Datum(value_set)};

  // Warm up the function registry / first hash-table build so neither approach
  // pays a one-off cost the other doesn't.
  (void)cp::IsIn(Datum(blocks[0]), options);

  // ---------------------------------------------------------------------------
  // Approach A: IsIn call for every block
  // ---------------------------------------------------------------------------

  double time_a;
  {
    auto start = std::chrono::steady_clock::now();
    for (const auto& block : blocks) {
      ARROW_ASSIGN_OR_RAISE(Datum result, cp::IsIn(Datum(block), options));
      benchmark_keep_alive(result);
    }
    auto end = std::chrono::steady_clock::now();
    time_a = std::chrono::duration<double>(end - start).count();
  }

  // ---------------------------------------------------------------------------
  // Approach B: reuse FunctionExecutor
  // ---------------------------------------------------------------------------

  // Resolve the is_in kernel for an int64 input.
  std::vector<TypeHolder> in_types = {TypeHolder(arrow::int64())};
  ARROW_ASSIGN_OR_RAISE(auto function_executor, cp::GetFunctionExecutor("is_in", in_types, &options));

  double time_b;
  {
    auto start = std::chrono::steady_clock::now();
    for (const auto& block : blocks) {
      ARROW_ASSIGN_OR_RAISE(auto out_data, function_executor->Execute({block}));
      benchmark_keep_alive(out_data);
    }
    auto end = std::chrono::steady_clock::now();
    time_b = std::chrono::duration<double>(end - start).count();
  }

  std::cout << "\nResults over " << kNumBlocks << " blocks:\n";
  std::cout << "  A: " << time_a
            << " s\n";
  std::cout << "  B: " << time_b
            << " s\n";
  std::cout << "  speedup (A / B): " << (time_a / time_b) << "x\n";
  return arrow::Status::OK();
}

int main() {
  auto error = runBenchmark();
  return error == arrow::Status::OK();
}

// Defined out-of-line to keep the timed lambdas readable; prevents the optimizer
// from discarding the work.
void benchmark_keep_alive(const Datum& d) {
  asm volatile("" : : "r,m"(d.kind()) : "memory");
}

yields this result:

Results over 20 blocks:
  A: 54.1688 s
  B: 3.90086 s
  speedup (A / B): 13.8864x

taepper avatar Jun 23 '26 16:06 taepper

Thanks @taepper ! I can help expose this in Python if you think it's the right approach. cc @zanmato1984

owenowenisme avatar Jun 24 '26 21:06 owenowenisme