Skip to content

feat(data): Support split and parallel scans - Part-4: bounded parallel Arrow reader - #1167

Merged
wgtmac merged 9 commits into
apache:mainfrom
kamcheungting-db:feat/parallel-task-reader
Dec 1, 2026
Merged

wgtmac merged 9 commits into
apache:mainfrom
kamcheungting-db:feat/parallel-task-reader

Conversation

@kamcheungting-db

@kamcheungting-db kamcheungting-db commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does

Adds ParallelScanReader (iceberg/data/parallel_scan_reader.h), which reads the groups of a FileScanTaskGroupStream (from #1113) with a fixed set of workers on a caller-provided executor and returns one Arrow C stream.

auto groups = scan->PlanTasksStream();
auto stream = ParallelScanReader::Open(
    std::move(*groups), {.reader_options = reader_options,
                         .executor = &executor,
                         .worker_count = 8,
                         .max_queued_batches = 16,
                         .max_queued_bytes = 64 << 20});

How it works

                          ParallelScanReader::Open(groups, options)
                                       │ validate options, build the projected Arrow schema,
                                       │ make one FileScanTaskReader + ArrowBatchSizer per worker
                                       v
  ┌──────────────────────────────── workers 1..N ────────────────────────────────┐
  │                                                                              │
  │  ClaimGroup()                                                                │
  │    yield if busy; otherwise call groups->Next() outside all locks            │
  │    (one worker at a time)          │                                         │
  │                                    ├─ group ──> release token, read it       │
  │                                    ├─ end   ──> destroy group stream, done   │
  │                                    └─ error ──> Stop(error)                  │
  │                                                                              │
  │  for each task in the group, in order:                                       │
  │    reader.Open(task) ──> check task schema == projected schema               │
  │      for each batch:                                                         │
  │        sizer.Measure(batch)   preflight overflow checks, then sum buffer     │
  │                               spans (children, dictionaries, variadic)       │
  │        TryEnqueue(worker)      admit the head ticket if it fits;             │
  │                                otherwise keep the batch and yield            │
  └───────────────────────────────────────┬──────────────────────────────────────┘
                                          v
                ┌──────────── output queue ─────────────┐
                │ admit when:                           │
                │   count < max_queued_batches  AND     │
                │   charge <= max_queued_bytes:         │
                │     queued + charge <= budget         │
                │   charge >  max_queued_bytes:         │
                │     queue is empty (sole batch)       │
                └───────────────────┬───────────────────┘
                                    v
                    get_next ──> pop front, subtract charge, wake producers
                                 (caller owns the array from here)
                    end of stream when all workers finished and the queue is empty

  Stop(error)  (first error wins)        release() between callbacks
    stop new work                           stop new work
    release queued batches                  release queued batches
    get_next returns EIO;                   wait for running callbacks and submissions
    get_last_error() gives the message      destroy the group stream
                                            returned arrays stay valid
  • Planning. Workers claim groups through a planning token: only one calls the single-pass group stream at a time, and never under a lock. The stream is destroyed as soon as it is exhausted, so planning metrics are reported at EOF.
  • Reading. Each worker owns a FileScanTaskReader. Residual filters are always enforced (apply_residuals is forced on). The projected schema must contain every field referenced by the task residual. Each task stream's schema is compared with the projected schema before its batches are read.
  • Queue. Batches enter a queue bounded by count (max_queued_batches) and by charged bytes (max_queued_bytes). Producers are admitted in FIFO order. A batch larger than the byte budget enters only an empty queue, as its sole batch. Zero-byte batches still count toward the batch limit. A worker holds at most one completed batch while it waits and yields its executor thread.
  • Charging. ArrowBatchSizer currently estimates a batch's charge as the checked sum of the spans of all present buffers, including children, dictionaries, and variadic buffers. Before nanoarrow sizes anything, it checks offsets, lengths, buffer, child, and dictionary counts, and every layout-dependent size product for overflow. List views and run-end encoded arrays are rejected.
  • Errors and release. The first planning, read, schema, or sizing error stops new work, releases queued batches, and is returned from the next get_next as EIO. For task read errors, get_last_error() includes the file path and, for splits, the byte range. Releasing the stream between callbacks stops the workers, releases batches that were not returned, and waits for running callbacks; batches already returned stay valid. Queued executor callbacks that run later see the stop flag and return.

iceberg_data now links Threads::Threads unconditionally, including with ICEBERG_SPDLOG=OFF.

The queue limits bound admission, not process memory: format reader buffers, delete indexes, and arrays already returned to the caller are outside the budget. The header documents this, the per-worker memory estimate, and the preconditions (registered format factories, a FileIO that supports concurrent reads, immutable task metadata, a read executor that outlives the stream and its accepted callbacks, a planning executor that outlives the stream, and matching case_sensitive).

Tests

The parallel reader and batch sizer tests are part of scan_test (ICEBERG_BUILD_BUNDLE=ON). The parallel reader unit tests use hand-built groups and a scoped fake reader registered for Parquet and Avro:

  • zero, one, and many groups; 1 versus N workers return the same rows; mixed formats in a group; residuals enforced
  • task-local order across interleaved groups
  • executor submission failures, planning handoff, and workers yielding under queue backpressure
  • schema mismatch, open failure, read failure (with the file range in the message), reader exceptions, and planning failures and exceptions; errors are sticky
  • bytes binding before count, count binding before bytes, zero-byte batches, oversized singletons, and mixed small and oversized batches
  • releasing between callbacks while producers wait, releasing without reading, and callers keeping a returned array after release; every fake array is released exactly once
  • the group stream is destroyed at the end of planning, and its destructor can query metrics
  • ArrowBatchSizer: fixed width, sliced, variable width, nested, dictionary, string view, zero-column structs, unsupported list views, and overflow and malformed-count rejections

A planned historical scan also checks that a missing residual field is reported rather than silently dropping rows. The bundle-enabled scan_test passes locally. Real Parquet and Avro tables are covered in Part-5. pre-commit is clean.

Related

Part 1 #976 · Part 2a #1002 · Part 2b #1062 · Part 2c #1065 · Part 3 #1113 · Part 3.5 #1166 (makes residual evaluation scale across workers) · Part 5 #1168 (end-to-end validation and benchmark).

This pull request and its description were written by Isaac.

ICEBERG_PRECHECK(options.reader_options.projected_schema != nullptr,
"Projected schema must not be null");

options.reader_options.apply_residuals = true;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

On an unpartitioned table, try selecting only name with id IS NOT NULL on a required id. The scan drops id from the projection, but the task still has the filter. Binding it here fails. Can we cover this with a planned scan?

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.

Done.

  • Predicates are now simplified against the full table schema before binding to the read projection.
  • Added a unit test here.

// Enqueue() reports a stop, so no separate check is needed per batch.
while (true) {
ArrowArray batch{};
if (int code = stream.get_next(&stream, &batch); code != 0) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can we check the stop flag before calling get_next? If the stream was released while get_schema was running, this call can still read the rest of the file looking for a match.

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.

Done.

  • Added a stop check before reading each batch, including after get_schema returns.
  • Added StopAfterSchemaSkipsGetNext to cover this case.

if (batch.release == nullptr) {
return {};
}
auto charge = sizer.Measure(batch);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can we use ArrowArrayGuard here and release the guard once the batch is in the queue? If sizing or push_back throws, nothing releases the batch.

@kamcheungting-db kamcheungting-db Nov 29, 2026 •

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.

Done.

  • Added ArrowArrayGuard around batch reading and sizing.
  • Pending batches remain owned by the worker until queue admission succeeds, so exceptions also release them.

/// Options for the per-worker task readers. `apply_residuals` is forced on.
FileScanTaskReader::Options reader_options;
/// Number of worker threads. Must be positive.
int32_t worker_count = 0;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Could we take a caller-provided Executor and keep worker_count as the limit for one scan? WriteManifestsWith already follows that pattern. With this API, ten scans with eight workers each start 80 threads.

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.

Done.

  • Added a caller-provided Executor, with worker_count retained as the per-scan concurrency limit.
  • Added executor validation and submission-failure tests.

snapshot.peak_held_bytes = std::max(snapshot.peak_held_bytes, held_bytes_);
});

producer_cv_.wait(lock, [&] {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

If we use a shared executor, can the reader yield when the queue fills? If all the pool threads are waiting here, none are available for manifest planning.

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.

Done.

  • Workers now park when queue admission is blocked and resume when space becomes available, freeing executor threads for other work.
  • Added tests covering backpressure and manifest planning on a shared executor.

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.

new test cases added to cover this part.

Comment thread src/iceberg/data/arrow_batch_sizer.cc Outdated
return {};
};

const int fixed_buffers = FixedBufferCount(view);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can we use ArrowArrayViewGetNumBuffers and ArrowArrayViewGetBufferView here? They cover variadic buffers too. We could keep the overflow checks and drop the separate loop.

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.

Done

  • Switched buffer summation to ArrowArrayViewGetNumBuffers and ArrowArrayViewGetBufferView, including variadic buffers.
  • Kept the preflight overflow checks.

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.

new test cases added to cover this part.

kamcheungting-db and others added 4 commits November 29, 2026 21:30
…el Arrow reader

Add ParallelScanReader, which reads the groups of a FileScanTaskGroupStream
with a fixed set of workers and returns one Arrow C stream.

- Each worker owns a FileScanTaskReader with residual enforcement forced on.
  Workers claim groups through a planning token: only one calls the group
  stream at a time, outside all locks.
- Completed batches enter an output queue bounded by batch count and by
  charged bytes. Producers are admitted in FIFO order; a batch larger than
  the byte budget is admitted only into an empty queue.
- ArrowBatchSizer charges a batch as the checked sum of its Arrow buffer
  spans, after preflighting offsets, lengths, buffer counts, and every
  layout-dependent size product for overflow. List views and run-end
  encoded arrays are rejected.
- Each task stream's schema is compared with the projected schema before
  its batches are read.
- The first planning, read, schema, or sizing error stops new work,
  releases queued batches, and is reported from get_next as EIO with the
  file and byte range in get_last_error. Releasing the stream between
  callbacks stops and joins the workers.
- iceberg_data now links Threads unconditionally.

Co-authored-by: Isaac <[email protected]>
…date

GCC and AppleClang reject a template parameter that shares the member
function's name. Also replace C-style arrays in the batch sizer tests.

Co-authored-by: Isaac <[email protected]>
Use std::cmp_* for signed/unsigned comparisons and std::ranges::is_sorted.

Co-authored-by: Isaac <[email protected]>
- Take a required Options::executor and keep worker_count as the
  per-scan concurrency limit; the reader no longer creates threads.
- Park workers when the output queue or planning token is busy instead
  of blocking executor threads, so shared pools can still run planning.
- Check for cancellation before every task stream callback.
- Guard each returned batch with ArrowArrayGuard until it is queued.
- Simplify residuals against the table schema before binding them to the
  projected schema, so planned scans can drop filter-only columns.
- Build NameMapping and MappedFields indexes at construction so shared
  mappings are safe for concurrent lookups.
- Size buffers with ArrowArrayViewGetNumBuffers and
  ArrowArrayViewGetBufferView, keeping the overflow checks.

Co-authored-by: Isaac <[email protected]>
@kamcheungting-db
kamcheungting-db force-pushed the feat/parallel-task-reader branch from c73b360 to dbb93ed Compare November 29, 2026 21:35
@wgtmac

wgtmac commented Dec 1, 2026

Copy link
Copy Markdown
Member

I removed ResidualSimplifier because the reader was folding predicates against the current table schema. On a historical scan, the same name can refer to a different field. That can turn a valid filter into false and silently drop rows. With this change, a missing filter column gives an error. If we want to fold it away, the planner has the right snapshot schema to do that.

I also fixed the planning handoff. Marking a worker ready wasn’t enough: if the first file was slow to produce a batch, the next group could sit idle. We now submit that worker as soon as the planning token is available.

@wgtmac
wgtmac merged commit 60447e7 into apache:main Dec 1, 2026
13 of 20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants