Skip to content

[Data] Add batch_size to MCAPDatasource for streaming reads - #66190

Open
lorenzozanee wants to merge 1 commit into
ray-project:masterfrom
lorenzozanee:restore/pr-65787
Open

lorenzozanee wants to merge 1 commit into
ray-project:masterfrom
lorenzozanee:restore/pr-65787

Conversation

@lorenzozanee

Copy link
Copy Markdown

Description

MCAPDatasource._read_stream previously accumulated all messages of a file into a single block and yielded once at the end. For large MCAP recordings this makes peak memory scale with file size times concurrent read tasks and prevents downstream stages from overlapping with the read within a file.

This change adds an optional batch_size (message count) to MCAPDatasource and ray.data.read_mcap. When set, _read_stream yields one block per batch instead of one block per file. batch_size=None (default) keeps the current behavior exactly; output schema and predicate pushdown are unchanged, only block boundaries change. The implementation follows the existing Iterator[Block] protocol already used by CSV/JSON/Parquet datasources and aligns with Daft's read_mcap(batch_size=1000) precedent.

Related issues

Closes #65641

No open PR currently addresses this issue. The change is limited to the MCAP datasource and its public read API.

Additional information

  • Validation: stubbed local reproduction with mcap 1.4.0 + pyarrow 25.0.1 confirms batch boundaries (5 messages: None -> [5], 2 -> [2,2,1], 1 -> [1,1,1,1,1]), invalid batch_size raises ValueError, empty file yields 0 blocks, topic-filtered reads respect filtered count, and schemas are stable across batches. python -m py_compile and git diff --check pass.
  • Compatibility: default None preserves byte-identical behavior; existing test_mcap.py expectations remain valid. Full test_mcap.py suite requires a complete Ray build and is expected to run in CI.

Supercedes #65787(原PR分支已删,按原提交重建)

@lorenzozanee
lorenzozanee requested a review from a team as a code owner September 15, 2026 22:45

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces a batch_size parameter to read_mcap and MCAPDatasource to allow yielding blocks of message data per batch instead of per file. The review feedback highlights two important issues: first, a potential schema compatibility error (e.g., ArrowInvalid) when a batch contains only messages without a schema, which can be resolved by casting null-type metadata columns to their expected types before yielding; second, the batch_size validation should explicitly disallow boolean values since bool is a subclass of int in Python.

Comment on lines +180 to +182
if self._batch_size is not None and builder.num_rows() >= self._batch_size:
yield builder.build()
builder = DelegatingBlockBuilder()

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.

high

When streaming reads are batched using batch_size, different batches may contain different sets of messages. If a batch happens to contain only messages without a schema (e.g., when reading from channels that do not define schemas, or if schemas are only present on some channels), the columns schema_name, schema_encoding, and schema_data will be entirely None in that batch.

DelegatingBlockBuilder (which delegates to ArrowBlockBuilder / PyArrow) will infer these columns as null type for that block. However, other blocks that contain messages with schemas will have these columns inferred as string or binary types. When Ray Data attempts to merge or process these blocks downstream, PyArrow will raise a schema compatibility error (e.g., ArrowInvalid: Schema migration not supported) due to the mismatch between null type and string/binary types.

To prevent this, we should ensure schema consistency across all yielded blocks by casting any null-type metadata columns to their expected types (string for schema_name/schema_encoding, and binary for schema_data) before yielding.

Please apply this same casting logic to the final block yielded at the end of _read_stream as well (or refactor it into a helper method).

            if self._batch_size is not None and builder.num_rows() >= self._batch_size:
                block = builder.build()
                import pyarrow as pa
                if isinstance(block, pa.Table):
                    schema = block.schema
                    casts = {}
                    if "schema_name" in schema.names and schema.field("schema_name").type == pa.null():
                        casts["schema_name"] = pa.string()
                    if "schema_encoding" in schema.names and schema.field("schema_encoding").type == pa.null():
                        casts["schema_encoding"] = pa.string()
                    if "schema_data" in schema.names and schema.field("schema_data").type == pa.null():
                        casts["schema_data"] = pa.binary()
                    if casts:
                        new_fields = [pa.field(f.name, casts.get(f.name, f.type)) for f in schema]
                        block = block.cast(pa.schema(new_fields))
                yield block
                builder = DelegatingBlockBuilder()

Comment on lines +124 to +128
if batch_size is not None:
if not isinstance(batch_size, int) or batch_size <= 0:
raise ValueError(
f"batch_size must be a positive integer, got {batch_size!r}"
)

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.

medium

In Python, bool is a subclass of int (i.e., isinstance(True, int) is True). Consequently, passing batch_size=True will bypass this validation and be treated as batch_size=1, which can lead to severe performance degradation due to extremely small block sizes. We should explicitly disallow boolean values.

Suggested change
if batch_size is not None:
if not isinstance(batch_size, int) or batch_size <= 0:
raise ValueError(
f"batch_size must be a positive integer, got {batch_size!r}"
)
if batch_size is not None:
if isinstance(batch_size, bool) or not isinstance(batch_size, int) or batch_size <= 0:
raise ValueError(
f"batch_size must be a positive integer, got {batch_size!r}"
)

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Sep 16, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Sep 30, 2026
@marwan116

Copy link
Copy Markdown
Contributor

Thanks for reviving this; the per-batch yield is the right shape and pairs well with opening the file for random access (the seeking reader can then prune chunks by topic and time, and with log_time_order=True it merges chunks instead of sorting the whole file). Three things that would help it land:

  1. DCO. The commit is unsigned, so the DCO check blocks the merge. git commit --amend -s --no-edit and a force-push of this branch fixes it.
  2. Interplay with two open MCAP PRs that wrap the yield. [Data] Dictionary-encode schema_data in MCAP blocks, and document the format #65913 wraps builder.build() in _dictionary_encode_schema_data(...) and [Data] Surface MCAP channel metadata as a map column #65916 appends a channel_metadata column built from a list collected alongside the builder. Both edit the single yield at the end of _read_stream; this PR adds a second yield inside the loop. Whichever lands second needs a small rebase: apply the same wrapper at the new yield, and for [Data] Surface MCAP channel metadata as a map column #65916 reset the metadata list together with the builder, or the column length will not match the block. Happy to do that rebase on my side if this merges first.
  3. bool is an int. As the bot noted, batch_size=True passes the current check and behaves as batch_size=1; isinstance(batch_size, bool) in the guard closes that.

For context, the stale label landed yesterday; a push resets it.

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Oct 2, 2026
@marwan116

Copy link
Copy Markdown
Contributor

FYI, #66653 lands the pieces this PR's yield pairs with: it opens the file for random access (so the seeking reader prunes chunks by topic and time), cuts blocks by estimated bytes against DataContext.target_max_block_size, and exposes log_time_order. It does not add batch_size; blocks are sized by bytes, the knob the other Ray Data readers use, which covers the memory-bounding goal of #65641 without a new parameter. If a row-count cap is still wanted on top, this PR's check would become a second condition at the same in-loop yield, and the three points above still apply.

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

community-contribution Contributed by the community data Ray Data-related issues unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data] MCAPDatasource: batched (streaming) message reads to reduce peak memory and enable intra-file pipelining

2 participants