Skip to content

[Data] Estimate MCAP in-memory size from sampled messages, not file size - #65912

Closed
marwan116 wants to merge 8 commits into
masterfrom
marwan/mcap-datasource-fixes
Closed

marwan116 wants to merge 8 commits into
masterfrom
marwan/mcap-datasource-fixes

Conversation

@marwan116

@marwan116 marwan116 commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Description

MCAPDatasource does not override estimate_inmemory_data_size(), so it inherits FileBasedDatasource's implementation, which sums on-disk file sizes. The value returned is not an approximation of the in-memory size — it is exactly the file size:

file size on disk       14,302 B
Ray's estimate          14,302 B
actual in memory     1,188,720 B

estimate == on-disk size : True
understated by           : 83x

Two effects compound. MCAP chunks are usually compressed, so the file is smaller on disk than in memory. And the datasource materializes per-message columns — topic, timestamps and, when include_metadata is set, the schema — that have no per-message on-disk equivalent at all. Ray Data derives both the read parallelism and the memory it provisions for the read from this number, so both are wrong for every MCAP read.

Fix. Follow the ParquetDatasource precedent: sample a bounded number of files (1% of the input, clamped to [2, 10], evenly spaced so size-ordered inputs don't bias the sample), read at most 100 messages from each, build a block through the datasource's own _message_to_dict + DelegatingBlockBuilder path, and scale the total on-disk size by the measured in-memory to on-disk ratio. The sample is extrapolated per channel using the exact per-channel message counts the summary carries, so the mix of topics that happens to land in the first 100 messages does not move the estimate. Under a time_range, counts are scaled by the share of the file's span the window covers.

Accuracy on a real recording. Eight zstd-compressed shards of a ROS 2 log (IMU at ~200 Hz, lidar, two compressed camera streams; 20k messages, 771 MB in memory), include_metadata=True:

read master this PR measured
whole files 586 MiB (20% under) 742 MiB (1% over) 735 MiB
topics={"/livox/imu"} 586 MiB (12x over) 49 MiB (2% under) 50 MiB

Master reports the on-disk size of the whole file regardless of the filter. Sampling two of the eight files took 0.02 s each: the summary is read from the footer, and at most 100 messages per file are decoded.

Related issues

Related to #65640, #65641 and #65787 — none of them duplicates this. #65787 (batch_size) modifies __init__ and _read_stream only; #65640 and #65641 concern block granularity and batched reads. No open issue or PR covers estimate_inmemory_data_size for MCAP.

Additional information

Two MCAP-specific implementation details worth review.

Measure a materialized block rather than undoing compression. The chunk index reports a ~37x decompression ratio, but the true expansion is 83x — the gap is the per-row metadata columns. Building a real block keeps the estimate correct automatically as include_metadata, include_paths and filters change.

Open sampled files seekable. _open_input_source yields a non-seekable BufferedInputStream, which makes make_reader return a NonSeekingReader whose get_summary() rescans the whole file and is single-use. Sampling uses open_input_file so make_reader returns a SeekingReader and reads the summary from the footer index. Message counts come from statistics.channel_message_counts; a topic filter is resolved exactly from them.

Filters. If the per-file iteration finishes before reaching the 100-message cap, it has seen the whole selection, so the measured size is used unscaled rather than extrapolated. This is the usual case for a narrow time_range or a message_types filter, neither of which the summary can resolve. When the cap is hit under a time_range, per-channel counts are scaled by the fraction of the file's time span the window covers, which assumes a channel publishes at a roughly constant rate. The ratio floor of 1 that guards against reporting a decompressed file as smaller than its compressed form is not applied under a filter: there the ratio is selected in-memory bytes over total on-disk bytes, and is legitimately far below 1.

Failure behaviour. Gated on DataContext.decoding_size_estimation. Every failure path falls back to a default ratio of 5 and logs a warning — over-estimating is the safe direction, consistent with the comment in _estimate_files_encoding_ratio, but a silent fallback would quietly restore the behaviour this change exists to replace. A file whose filter selects nothing is a measurement of zero, not a failure.

Approximations that remain, each documented at the site: messages are sampled as a prefix of each file in log-time order rather than spread through it, so a recording whose message sizes drift is estimated from its opening; a channel absent from the sample is charged the mean row size of the sample, which suits rare small topics and underestimates rare large ones; message_types has no equivalent in the summary, so when the cap is hit the extrapolation is an upper bound.

Since the draft. #65914 landed, so test_mcap.py now runs in CI and mcap's types are visible to pyrefly; the pyrefly errors that surfaced are fixed here.

Tests

PYTHONPATH=python/ray/data/tests python -u -m pytest \
    python/ray/data/tests/datasource/test_mcap.py -v

32 passed. Master is 18 passed.

14 new tests cover: estimate exceeds on-disk size, estimate tracks include_metadata, estimate respects a topic filter, multi-file aggregation, files with no summary statistics, sampling disabled via DataContext, include_paths (which adds a column downstream of _read_stream, so sampling has to add it too), a narrow time_range, a time window wider than the sample cap, a filter that selects nothing, per-channel weighting against a mixed-rate file, an estimate below the on-disk size under a filter, log-time ordering (the fixture is written in descending log time, so passing requires the reader's sort rather than the file layout), and binary payload round-trip.

Lint: black, ruff and pyrefly clean on both changed files.

Self-contained repro (needs only ray[data] and mcap)
import os
import tempfile
from pathlib import Path

import ray
from mcap.writer import CompressionType, Writer

SCHEMA = b"uint8[] data\nstring format\n" * 100  # a realistic ros2msg definition

f = Path(tempfile.mkdtemp()) / "d1.mcap"
with f.open("wb") as fh:
    w = Writer(fh, compression=CompressionType.ZSTD)
    w.start(profile="", library="d1")
    sid = w.register_schema(
        name="foxglove.CompressedVideo", encoding="ros2msg", data=SCHEMA
    )
    cid = w.register_channel(topic="/cam", message_encoding="cdr", schema_id=sid)
    for i in range(360):  # 12 s of 30 fps video
        w.add_message(
            cid,
            log_time=i * 33_000_000,
            publish_time=i * 33_000_000,
            data=b"\x00\x00\x00\x01" + bytes([i % 256]) * 504,
            sequence=i,
        )
    w.finish()

ray.init(num_cpus=2, include_dashboard=False, log_to_driver=False, configure_logging=False)

from ray.data._internal.datasource.mcap_datasource import MCAPDatasource

estimate = MCAPDatasource(paths=[str(f)]).estimate_inmemory_data_size()
on_disk = os.path.getsize(f)
in_memory = ray.data.read_mcap(str(f)).materialize().size_bytes()

print(f"  file size on disk   {on_disk:>10,} B")
print(f"  Ray's estimate      {estimate:>10,} B")
print(f"  actual in memory    {in_memory:>10,} B")
print(f"  estimate == on-disk size : {estimate == on_disk}")
print(f"  understated by           : {in_memory / estimate:.0f}x")

AI assistance (Claude) was used for this change. I reviewed every changed line and ran the tests locally.

MCAPDatasource did not override estimate_inmemory_data_size(), so it
inherited FileBasedDatasource's sum of on-disk file sizes. The value
returned is not an approximation of the in-memory size, it is exactly the
file size: 14,302 B against 1,188,720 B materialized, an 83x
understatement on a 360-message recording. MCAP chunks are compressed,
and the datasource materializes per-message columns -- topic, timestamps
and, when include_metadata is set, the schema -- that have no per-message
on-disk equivalent. Ray Data derives both the read parallelism and the
memory it provisions for the read from this number.

Sample a bounded number of files (1%, clamped to [2, 10], evenly spaced
so that size-ordered inputs do not bias the sample), read at most 100
messages from each through the datasource's own conversion path, and
scale the total on-disk size by the measured in-memory to on-disk ratio,
following the ParquetDatasource precedent. Sampled files are opened
seekable so that make_reader returns a SeekingReader and reads the
summary from the footer index rather than rescanning the file.

When the per-file iteration finishes before reaching the message cap it
has seen the whole selection, so the measured size is used unscaled.
Without that, a time_range selecting 1% of a recording is estimated as if
the whole file were selected, since the summary cannot express a time
range.

Gated on DataContext.decoding_size_estimation. Every failure path falls
back to a default ratio of 5 and logs a warning, since a silent fallback
would restore the behaviour this change exists to replace.

Also fixes a pre-existing assertion in test_read_mcap_invalid_time_range
that can never match: the regex omits the values the error message
interpolates. It fails on clean master, and is not caught in CI because
mcap appears in no requirements file, so the whole module is skipped.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Marwan Sarieddine <[email protected]>
@marwan116
marwan116 requested a review from a team as a code owner September 4, 2026 02:35

@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 implements in-memory size estimation for the MCAP datasource in Ray Data by sampling files and calculating an encoding ratio, addressing the issue where compressed MCAP files are significantly underestimated. It also adds comprehensive unit tests to validate this estimation logic. The review feedback correctly identifies a bug where an estimated size of zero is ignored due to a truthiness check, and suggests using an explicit is not None check instead.

@marwan116 marwan116 self-assigned this Sep 4, 2026
@marwan116 marwan116 added the go add ONLY when ready to merge, run all tests label Sep 4, 2026

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

marwan116 and others added 2 commits September 3, 2026 19:48
`_estimate_file_inmemory_size` returns None when a file cannot be sampled
and 0 when the topic, time or message-type filter selects nothing from
it. The caller tested truthiness, so it discarded the measured zero
alongside the failures. A mixed input biased the mean ratio upward, and
an input where every sampled file is empty under the filter fell back to
the default ratio of 5 for a read that returns no rows at all.

The ratio lower bound still floors the result at 1, so the empty case now
estimates the on-disk size rather than five times it.

Reported independently by gemini-code-assist and Cursor Bugbot on #65912.

Also document the two properties of the MCAP format this module depends
on -- the summary section sitting at the end of the file, addressed by an
offset in the footer, and schemas being stored once per file rather than
once per message -- and link the format specification.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Marwan Sarieddine <[email protected]>
…count

The sample window is the first 100 messages a file yields, and its mean row
size was scaled by the file's whole message count. On multi-topic data that
makes the estimate depend on how many messages of each topic happen to land
in the window rather than on the file.

Measured on a 105-second FAST-LIVO ROS 2 recording (24,456 messages: a
200 Hz Livox IMU, a lidar, and two compressed camera streams), the window
spans 0.417s. The three heavy topics each hold a 4.3% share of the file, so
the window catches five of each where the file average is 4.3 -- one message
of quantization on the topics carrying nearly all of the bytes. That alone
put the estimate 18% over.

Weight per channel instead, using the exact per-channel counts the summary
already carries. Only a channel's row size is sampled, never the mix between
channels. Messages within a channel are near-uniform in size while channels
differ by orders of magnitude, so this removes the dominant error term.

    corpus                          truth      before     after
    8 zstd shards, 27x gradient     770.8 MB   +2.9%      +0.9%
    single 845 MiB recording        946.4 MB   +18.0%     +2.6%

The estimate is also no longer sensitive to the window size: per-channel
lands at 102.6% of truth for every window from 10 to 800 messages, where
scaling by the total count ranges from 228% to 104% across the same span.

A channel absent from the sample falls back to the mean row size across the
whole sample, and a summary carrying no per-channel breakdown falls back to
the previous whole-sample scaling.

Reported by a reviewer testing the branch against real ROS 2 recordings
rather than synthetic files.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Marwan Sarieddine <[email protected]>
marwan116 and others added 2 commits September 3, 2026 20:29
Two defects in the sampled estimate, both surfacing only when a filter
selects a small part of a file. A reviewer found them on a video-dominated
robotics episode; neither existing test could reach them.

The encoding ratio was floored at
MCAP_ENCODING_RATIO_ESTIMATE_LOWER_BOUND = 1. That guard exists so a
decompressed file is never reported as smaller than its compressed form.
Under a filter the quantity is not a decompression ratio at all -- it is
selected in-memory bytes over *total* on-disk bytes -- and on a recording
whose bytes are nearly all camera frames, reading only the state topics is
legitimately far below 1. The per-channel estimator computed the right
number and the clamp discarded it, reporting the whole file. Apply the
floor only when no filter narrows the read.

Separately, once sampling stopped at the message cap, the extrapolation
used whole-file per-channel counts. The summary cannot express a time
range, so a one-second window on a twenty-second recording was scaled by
twenty seconds of messages -- an error of exactly the ratio of the two
durations, and unbounded as windows shrink. Scale each channel's count by
the share of the file's span the window covers, which the summary does
carry as message_start_time/message_end_time. That assumes a roughly
constant publish rate per channel, which is what a sensor recording does.

Measured on a 21.8 MB episode (2 cameras of incompressible frames, 200 Hz
proprio, 50 Hz action), estimate over actual:

    no filter                    1.00x -> 1.00x
    state topics only           24.30x -> 1.00x
    state topics + 1 s window  485.90x -> 1.00x

A filter selecting nothing now estimates zero rather than the file's
on-disk size, completing the zero-sample fix in 195bee3: the floor was
what stopped the measured zero from being used.

New tests cover both, on a fixture with camera-dominated payloads and a
window above the sampling cap -- the regime the previous time-range test
could not reach, since its window selected fewer messages than the cap and
so was measured outright rather than extrapolated.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Marwan Sarieddine <[email protected]>
`MCAP_ENCODING_RATIO_ESTIMATE_LOWER_BOUND` was used only by the assertion
that a filter selecting nothing floors at the on-disk size. That behaviour
changed in the previous commit -- nothing selected now estimates zero -- so
the import went stale with it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Marwan Sarieddine <[email protected]>
marwan116 and others added 2 commits September 4, 2026 08:57
…ly see

pyrefly.toml lists "mcap.*" under ignore-missing-imports, and the comment at
the foot of that file explains the consequence: ignore-missing-imports covers
modules that cannot be found, not installed ones. mcap is in no requirements
file, so the ray/data pyrefly job resolves every mcap type as Any and reports
nothing. Installing mcap and running the same check surfaces 31 errors across
these two files -- 13 in the datasource, 18 in its tests.

Four classes, all real:

- iter_messages yields Optional[Schema]: a channel need not declare one.
  _should_include_message and _message_to_dict were typed Schema, at four call
  sites now that sampling calls them too.
- summary.statistics is Optional. _estimate_file_inmemory_size narrows it, but
  the helpers it calls take the Summary and reach through to .statistics
  themselves, which pyrefly cannot follow across a call. Narrow in each.
- fill_column is defined on ArrowBlockAccessor and PandasBlockAccessor, not on
  the BlockAccessor base. Carry the include_paths column in the row dict
  instead, which needs no downstream fill and is what the read path's own
  conversion would do.
- _file_sizes() returns List[float], so _sample_files receives
  list[tuple[str, float]] against a list[tuple[str, int]] annotation.

The tests compared Optional[int] estimates directly; they now go through one
narrowing helper rather than eighteen scattered assertions.

pyrefly reports 0 errors with mcap installed. Estimates are unchanged:
no filter, topic-filtered, time-windowed and include_paths=True all still land
at 1.00x of measured on a 21.8 MB episode, and the two real ROS 2 corpora are
byte-identical to before.

The Optional[Schema] class overlaps #65914, which changes the same two
signatures. Fixing it here lets that PR stay confined to CI plumbing.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Marwan Sarieddine <[email protected]>
Other datasource modules carry a one-line docstring or none at all;
parquet_datasource.py and image_datasource.py have none. Keep the format
specification link and drop the explanatory prose.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Marwan Sarieddine <[email protected]>
richardliaw pushed a commit that referenced this pull request Sep 9, 2026
…65914)

## Description

`python/ray/data/tests/datasource/test_mcap.py` guards its whole module
with
`pytestmark = skipif(not MCAP_AVAILABLE)`, and `mcap` appears in no
requirements file
anywhere in the repo. `//python/ray/data:test_mcap` has therefore
reported success
since the datasource landed in #55716 without executing a single one of
its 18 tests.

This PR adds `mcap` to
`python/requirements/ml/data-test-requirements.txt` — the file
consumed by the Data CI image (`ci/env/install-dependencies.sh:303`,
`ci/ci.sh:60`) and
by `ci/raydepsets/configs/ci_data.depsets.yaml:19` — and regenerates the
locks that
depend on it.

## Related issues

Related to #65912, which fixes `estimate_inmemory_data_size` for this
datasource. The
two PRs are independent: both carry the identical one-line fix to
`test_read_mcap_invalid_time_range`, deliberately, so neither blocks the
other. Being
byte-identical, whichever lands second should rebase without a conflict.

Related to #61222 (audit and refactor file-based datasource tests),
which covers
adjacent ground but not this.

## Additional information

### What turning the tests on exposed

Three defects were sitting behind that skip. Each is fixed in its own
commit here,
because without them the target goes red on its first real run:

1. **`test_read_mcap_invalid_time_range` can never pass.** It searches
for
   `"start_time must be less than end_time"`; the code raises
`"start_time (2000) must be less than end_time (1000)"`. Fails on
unmodified master.

2. **`_should_include_message` and `_message_to_dict` annotate `schema`
as a bare
   `Schema`,** but `McapReader.iter_messages()` yields
`Tuple[Optional[Schema], Channel, Message]` — a channel may declare no
schema. Both
bodies already guard with `if schema else None`, so this is an
annotation fix only.
It was invisible while `mcap` was absent: pyrefly could not resolve
`mcap.reader`,
treated the return as `Any`, and reported nothing. With the package
installed its
`py.typed` annotations apply and `ci/lint/pyrefly-check.sh` fails on the
two
   pre-existing call sites in `_read_stream`.

3. **`python/requirements_compiled.txt` was missing `mcap`.** That file
is a separate
lock from `python/deplocks/`, compiled by `compile_pip_dependencies` in
`ci/ci.sh`
   from an input list that includes `data-test-requirements.txt`.

### The dependency itself costs the image nothing

The regenerated locks introduce exactly one package:

```
mcap==1.4.0 \
    --hash=sha256:0528e2f86a61bfec73779e0628e6cf27af83d01d89e20b27d5ec9f0b556a63ac \
    --hash=sha256:0b48b1cc951b8d5aabd2599e60d410bae4f1be1819094f54117b7cbf6b3ee2e9
    # via -r python/requirements/ml/data-test-requirements.txt
```

mcap's own dependencies, `lz4` and `zstandard`, are already present via
`clickhouse-connect`, `dask`, `ray` and `pyiceberg`. Every other changed
line across the
ten `python/deplocks/ci/*.lock` files and `requirements_compiled.txt` is
a `# via`
comment recording mcap as a new consumer.

### How the locks were produced

`python/deplocks/*.lock` with the repo's own tooling, using the same
command the
`raydepsets: compile all dependencies` job runs:

```
bazelisk run //ci/raydepsets:raydepsets -- build --all-configs
bazelisk run //ci/raydepsets:raydepsets -- build --all-configs --check
# Lock files are up to date.
```

`python/requirements_compiled.txt` could not be regenerated locally:
`compile_pip_dependencies` returns early on arm64 (`ci/ci.sh:20-27`).
Its four added
lines were reconstructed from the `dependencies` job's own diff and land
at the exact
line numbers it reported — mcap at 1093–1094, zstandard's `# via` entry
at 2712.

**Worth knowing for anyone adding a dependency here:** the two lock
systems are coupled
through a symlink. `python/requirements_compiled_py3.10` … `py3.13` are
all symlinks to
`requirements_compiled.txt` (only `py3.14` is a real file), and
`ci/raydepsets/pre_hooks/remove-compiled-headers.sh` copies
`python/requirements_compiled_py3.13.txt` into `/tmp/ray-deps/`, where
it becomes the
constraint the data depsets compile against. So adding a package to
`requirements_compiled.txt` changes the `# via` provenance recorded in
`python/deplocks/ci/*.lock` — uv then lists the package as coming from
both the
constraint and `data-test-requirements.txt`. Regenerating one lock
system without the
other leaves the tree inconsistent, which is why this PR has a separate
commit for it.

### Tests

With `mcap` installed on unmodified master, the previously-skipped
module runs and one
test fails — what the target would have been reporting all along:

```
1 failed, 17 passed in 15.50s
FAILED test_read_mcap_invalid_time_range
E   AssertionError: Regex pattern did not match.
E    Regex: 'start_time must be less than end_time'
E    Input: 'start_time (2000) must be less than end_time (1000)'
```

With the fixes in this PR:

```
PYTHONPATH=python/ray/data/tests python -u -m pytest \
    python/ray/data/tests/datasource/test_mcap.py -v
18 passed in 10.95s
```

pyrefly, run exactly as `ci/lint/pyrefly-check.sh` does, reports no
errors in
`mcap_datasource.py`. Lint hooks `black`, `ruff`, `pydoclint`,
`docstyle`, `check-ast`,
`check-import-order`, `trailing-whitespace` and `end-of-file-fixer` all
pass on the
changed files.

`size = "small"` is left as-is: the 18 tests take ~11s, and `test_json`
is `small` with
58 tests, so the 60-second budget has ample headroom.

---

AI assistance (Claude) was used for this change. I reviewed every
changed line and ran
the commands above locally.

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
NightWing1998 pushed a commit to NightWing1998/ray that referenced this pull request Sep 11, 2026
…ay-project#65914)

## Description

`python/ray/data/tests/datasource/test_mcap.py` guards its whole module
with
`pytestmark = skipif(not MCAP_AVAILABLE)`, and `mcap` appears in no
requirements file
anywhere in the repo. `//python/ray/data:test_mcap` has therefore
reported success
since the datasource landed in ray-project#55716 without executing a single one of
its 18 tests.

This PR adds `mcap` to
`python/requirements/ml/data-test-requirements.txt` — the file
consumed by the Data CI image (`ci/env/install-dependencies.sh:303`,
`ci/ci.sh:60`) and
by `ci/raydepsets/configs/ci_data.depsets.yaml:19` — and regenerates the
locks that
depend on it.

## Related issues

Related to ray-project#65912, which fixes `estimate_inmemory_data_size` for this
datasource. The
two PRs are independent: both carry the identical one-line fix to
`test_read_mcap_invalid_time_range`, deliberately, so neither blocks the
other. Being
byte-identical, whichever lands second should rebase without a conflict.

Related to ray-project#61222 (audit and refactor file-based datasource tests),
which covers
adjacent ground but not this.

## Additional information

### What turning the tests on exposed

Three defects were sitting behind that skip. Each is fixed in its own
commit here,
because without them the target goes red on its first real run:

1. **`test_read_mcap_invalid_time_range` can never pass.** It searches
for
   `"start_time must be less than end_time"`; the code raises
`"start_time (2000) must be less than end_time (1000)"`. Fails on
unmodified master.

2. **`_should_include_message` and `_message_to_dict` annotate `schema`
as a bare
   `Schema`,** but `McapReader.iter_messages()` yields
`Tuple[Optional[Schema], Channel, Message]` — a channel may declare no
schema. Both
bodies already guard with `if schema else None`, so this is an
annotation fix only.
It was invisible while `mcap` was absent: pyrefly could not resolve
`mcap.reader`,
treated the return as `Any`, and reported nothing. With the package
installed its
`py.typed` annotations apply and `ci/lint/pyrefly-check.sh` fails on the
two
   pre-existing call sites in `_read_stream`.

3. **`python/requirements_compiled.txt` was missing `mcap`.** That file
is a separate
lock from `python/deplocks/`, compiled by `compile_pip_dependencies` in
`ci/ci.sh`
   from an input list that includes `data-test-requirements.txt`.

### The dependency itself costs the image nothing

The regenerated locks introduce exactly one package:

```
mcap==1.4.0 \
    --hash=sha256:0528e2f86a61bfec73779e0628e6cf27af83d01d89e20b27d5ec9f0b556a63ac \
    --hash=sha256:0b48b1cc951b8d5aabd2599e60d410bae4f1be1819094f54117b7cbf6b3ee2e9
    # via -r python/requirements/ml/data-test-requirements.txt
```

mcap's own dependencies, `lz4` and `zstandard`, are already present via
`clickhouse-connect`, `dask`, `ray` and `pyiceberg`. Every other changed
line across the
ten `python/deplocks/ci/*.lock` files and `requirements_compiled.txt` is
a `# via`
comment recording mcap as a new consumer.

### How the locks were produced

`python/deplocks/*.lock` with the repo's own tooling, using the same
command the
`raydepsets: compile all dependencies` job runs:

```
bazelisk run //ci/raydepsets:raydepsets -- build --all-configs
bazelisk run //ci/raydepsets:raydepsets -- build --all-configs --check
# Lock files are up to date.
```

`python/requirements_compiled.txt` could not be regenerated locally:
`compile_pip_dependencies` returns early on arm64 (`ci/ci.sh:20-27`).
Its four added
lines were reconstructed from the `dependencies` job's own diff and land
at the exact
line numbers it reported — mcap at 1093–1094, zstandard's `# via` entry
at 2712.

**Worth knowing for anyone adding a dependency here:** the two lock
systems are coupled
through a symlink. `python/requirements_compiled_py3.10` … `py3.13` are
all symlinks to
`requirements_compiled.txt` (only `py3.14` is a real file), and
`ci/raydepsets/pre_hooks/remove-compiled-headers.sh` copies
`python/requirements_compiled_py3.13.txt` into `/tmp/ray-deps/`, where
it becomes the
constraint the data depsets compile against. So adding a package to
`requirements_compiled.txt` changes the `# via` provenance recorded in
`python/deplocks/ci/*.lock` — uv then lists the package as coming from
both the
constraint and `data-test-requirements.txt`. Regenerating one lock
system without the
other leaves the tree inconsistent, which is why this PR has a separate
commit for it.

### Tests

With `mcap` installed on unmodified master, the previously-skipped
module runs and one
test fails — what the target would have been reporting all along:

```
1 failed, 17 passed in 15.50s
FAILED test_read_mcap_invalid_time_range
E   AssertionError: Regex pattern did not match.
E    Regex: 'start_time must be less than end_time'
E    Input: 'start_time (2000) must be less than end_time (1000)'
```

With the fixes in this PR:

```
PYTHONPATH=python/ray/data/tests python -u -m pytest \
    python/ray/data/tests/datasource/test_mcap.py -v
18 passed in 10.95s
```

pyrefly, run exactly as `ci/lint/pyrefly-check.sh` does, reports no
errors in
`mcap_datasource.py`. Lint hooks `black`, `ruff`, `pydoclint`,
`docstyle`, `check-ast`,
`check-import-order`, `trailing-whitespace` and `end-of-file-fixer` all
pass on the
changed files.

`size = "small"` is left as-is: the 18 tests take ~11s, and `test_json`
is `small` with
58 tests, so the 60-second budget has ample headroom.

---

AI assistance (Claude) was used for this change. I reviewed every
changed line and ran
the commands above locally.

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
@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 19, 2026
@richardliaw richardliaw removed the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Sep 19, 2026
@marwan116
marwan116 marked this pull request as ready for review September 23, 2026 14:42
@marwan116 marwan116 added the data Ray Data-related issues label Sep 23, 2026

@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 implements an accurate in-memory data size estimation for the MCAP datasource in Ray Data by sampling files and measuring the in-memory size of blocks, correcting the default on-disk size underestimate. It also adds comprehensive unit tests to validate the estimation logic under various configurations, filters, and file structures. The review feedback highlights a potential AttributeError in _selected_channel_message_counts if summary.statistics.channel_message_counts is None, and suggests adding a guard to handle this gracefully.

@marwan116 marwan116 added the unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. label Oct 1, 2026

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 05ae78c. Configure here.

nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…ay-project#65914)

## Description

`python/ray/data/tests/datasource/test_mcap.py` guards its whole module
with
`pytestmark = skipif(not MCAP_AVAILABLE)`, and `mcap` appears in no
requirements file
anywhere in the repo. `//python/ray/data:test_mcap` has therefore
reported success
since the datasource landed in ray-project#55716 without executing a single one of
its 18 tests.

This PR adds `mcap` to
`python/requirements/ml/data-test-requirements.txt` — the file
consumed by the Data CI image (`ci/env/install-dependencies.sh:303`,
`ci/ci.sh:60`) and
by `ci/raydepsets/configs/ci_data.depsets.yaml:19` — and regenerates the
locks that
depend on it.

## Related issues

Related to ray-project#65912, which fixes `estimate_inmemory_data_size` for this
datasource. The
two PRs are independent: both carry the identical one-line fix to
`test_read_mcap_invalid_time_range`, deliberately, so neither blocks the
other. Being
byte-identical, whichever lands second should rebase without a conflict.

Related to ray-project#61222 (audit and refactor file-based datasource tests),
which covers
adjacent ground but not this.

## Additional information

### What turning the tests on exposed

Three defects were sitting behind that skip. Each is fixed in its own
commit here,
because without them the target goes red on its first real run:

1. **`test_read_mcap_invalid_time_range` can never pass.** It searches
for
   `"start_time must be less than end_time"`; the code raises
`"start_time (2000) must be less than end_time (1000)"`. Fails on
unmodified master.

2. **`_should_include_message` and `_message_to_dict` annotate `schema`
as a bare
   `Schema`,** but `McapReader.iter_messages()` yields
`Tuple[Optional[Schema], Channel, Message]` — a channel may declare no
schema. Both
bodies already guard with `if schema else None`, so this is an
annotation fix only.
It was invisible while `mcap` was absent: pyrefly could not resolve
`mcap.reader`,
treated the return as `Any`, and reported nothing. With the package
installed its
`py.typed` annotations apply and `ci/lint/pyrefly-check.sh` fails on the
two
   pre-existing call sites in `_read_stream`.

3. **`python/requirements_compiled.txt` was missing `mcap`.** That file
is a separate
lock from `python/deplocks/`, compiled by `compile_pip_dependencies` in
`ci/ci.sh`
   from an input list that includes `data-test-requirements.txt`.

### The dependency itself costs the image nothing

The regenerated locks introduce exactly one package:

```
mcap==1.4.0 \
    --hash=sha256:0528e2f86a61bfec73779e0628e6cf27af83d01d89e20b27d5ec9f0b556a63ac \
    --hash=sha256:0b48b1cc951b8d5aabd2599e60d410bae4f1be1819094f54117b7cbf6b3ee2e9
    # via -r python/requirements/ml/data-test-requirements.txt
```

mcap's own dependencies, `lz4` and `zstandard`, are already present via
`clickhouse-connect`, `dask`, `ray` and `pyiceberg`. Every other changed
line across the
ten `python/deplocks/ci/*.lock` files and `requirements_compiled.txt` is
a `# via`
comment recording mcap as a new consumer.

### How the locks were produced

`python/deplocks/*.lock` with the repo's own tooling, using the same
command the
`raydepsets: compile all dependencies` job runs:

```
bazelisk run //ci/raydepsets:raydepsets -- build --all-configs
bazelisk run //ci/raydepsets:raydepsets -- build --all-configs --check
# Lock files are up to date.
```

`python/requirements_compiled.txt` could not be regenerated locally:
`compile_pip_dependencies` returns early on arm64 (`ci/ci.sh:20-27`).
Its four added
lines were reconstructed from the `dependencies` job's own diff and land
at the exact
line numbers it reported — mcap at 1093–1094, zstandard's `# via` entry
at 2712.

**Worth knowing for anyone adding a dependency here:** the two lock
systems are coupled
through a symlink. `python/requirements_compiled_py3.10` … `py3.13` are
all symlinks to
`requirements_compiled.txt` (only `py3.14` is a real file), and
`ci/raydepsets/pre_hooks/remove-compiled-headers.sh` copies
`python/requirements_compiled_py3.13.txt` into `/tmp/ray-deps/`, where
it becomes the
constraint the data depsets compile against. So adding a package to
`requirements_compiled.txt` changes the `# via` provenance recorded in
`python/deplocks/ci/*.lock` — uv then lists the package as coming from
both the
constraint and `data-test-requirements.txt`. Regenerating one lock
system without the
other leaves the tree inconsistent, which is why this PR has a separate
commit for it.

### Tests

With `mcap` installed on unmodified master, the previously-skipped
module runs and one
test fails — what the target would have been reporting all along:

```
1 failed, 17 passed in 15.50s
FAILED test_read_mcap_invalid_time_range
E   AssertionError: Regex pattern did not match.
E    Regex: 'start_time must be less than end_time'
E    Input: 'start_time (2000) must be less than end_time (1000)'
```

With the fixes in this PR:

```
PYTHONPATH=python/ray/data/tests python -u -m pytest \
    python/ray/data/tests/datasource/test_mcap.py -v
18 passed in 10.95s
```

pyrefly, run exactly as `ci/lint/pyrefly-check.sh` does, reports no
errors in
`mcap_datasource.py`. Lint hooks `black`, `ruff`, `pydoclint`,
`docstyle`, `check-ast`,
`check-import-order`, `trailing-whitespace` and `end-of-file-fixer` all
pass on the
changed files.

`size = "small"` is left as-is: the 18 tests take ~11s, and `test_json`
is `small` with
58 tests, so the 60-second budget has ample headroom.

---

AI assistance (Claude) was used for this change. I reviewed every
changed line and ran
the commands above locally.

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
@marwan116

Copy link
Copy Markdown
Contributor Author

Closing in favour of DataSource V2 (#66654): it sizes read tasks from each chunk's uncompressed size in the file summary, so this estimate isn't needed.

@marwan116 marwan116 closed this Oct 7, 2026
richardliaw pushed a commit that referenced this pull request Nov 6, 2026
…, row_id (#66654)

## Description

Part 1 of 3 of the `read_mcap` move to Datasource V2, based on master.
#67166 is stacked on it, and #67167 on #67166. The rest of the
`read_mcap` stack (#67189 onward) sits on top.

**Problem.** One task reads one whole file:

- Parallelism is capped by the file count: ten 30 GB recordings are ten
tasks.
- Every file is opened, even when its index shows it holds nothing
selected.
- Rows have no stable id, so a checkpointed pipeline cannot resume.

**Change.** `read_mcap` moves to Datasource V2, on by default as for
`read_parquet` (`DataContext.use_datasource_v2`). The legacy datasource
stays as the fallback.

```
files
  │  listing: read each file's index (a few ranged reads)
  │           one row per chunk, weighted by the memory reading it takes
  │           drop chunks that cannot match topics / time_range
  ▼
chunk rows
  │  packing: about 128 MiB per read task
  │           one big file ──► many tasks;  small files ──► one task
  │           with preserve_order: one task per file, in listing order
  ▼
read tasks: seek to their chunks, merge them by log time
```

- New code lives in `datasource_v2/formats/mcap/`. The V2 interfaces do
not change.
- Columns and types match the legacy path, with two changes.
`schema_data` is dictionary-encoded. A new `channel_metadata` column
holds each channel's metadata map as JSON text, dictionary-encoded, so a
block stores it once per channel.
- `data` holds decoded JSON only when every selected channel is JSON.
Otherwise it holds bytes. Planning types it from the selected messages
of the first chunk that holds one, as a read task types the messages it
holds.
- `row_id` is `<path>#c=<chunk offset>:<index>`, stable however the read
is split. It is on with `include_row_id=True`, or automatically under
`CheckpointConfig(id_column="row_id")`.
- New `log_time_order` argument, default `True`. Each task returns each
of its files in `log_time` order. With `preserve_order`, each file is
read by one task, so it comes out in order from start to end, and files
come out in the order they were listed. #67166 splits a large file there
too, only where its order holds.
- A file whose summary cannot be read gets a read task of its own, so
`max_errored_blocks` can skip it alone.
- The task size is `RAY_DATA_MCAP_BIN_PACKING_BYTES` (128 MiB).

**Changed after the first review round.** Each is its own commit:

- Summaries and chunks are read in a few ranged requests, not a few
bytes per GET.
- An unreadable file gets a read task of its own.
- Tables are built column by column, cut counting every column, and
chunks are weighted by the memory reading them takes.
- The read stops at the row limit.
- A file without a chunk index is sorted by log time.
- `channel_metadata` is JSON text, stored once per block.
- With `preserve_order`, each file is kept in one read task, and files
keep their listing order.
- Planning skips a chunk it cannot decode, and types `data` from the
first chunk's messages.

**Measured** on an 845 MB recording with 1,052 chunks: reading its 125
KB summary took about 20,000 GETs and now takes 3.

**Decisions to confirm:**

- Splitting is on by default. Block boundaries change; rows do not.
- With `preserve_order`, this PR reads each file in one task, as the
legacy reader does. #67166 lets it split a large file where its log-time
order holds.
- `ds.schema()` comes from the first chunk that holds a selected
message. A field that first appears later is missing from it; the
docstring says so.

## Related issues

- Related to #65640 and #65641.
- No open PR moves MCAP to Datasource V2. #66524 (ORC) and #66182
(Iceberg) are other formats moving to V2.
- The generated-ID stack (#65886 to #65888) is orthogonal.
- `log_time_order` comes from my #66653, now closed. My legacy-path PRs
#65912, #65913 and #65916 are closed in favour of this one.

## Additional information

```
PYTHONPATH=python/ray/data/tests pytest python/ray/data/tests/datasource/test_mcap.py \
  python/ray/data/tests/unit/datasource_v2/test_mcap_*.py \
  python/ray/data/tests/unit/datasource_v2/test_online_bin_packer.py
```

178 passed, 3 skipped. pre-commit and pyrefly clean.

AI assistance (Claude Code) was used to draft this change; I reviewed
every line and ran the tests above locally.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues go add ONLY when ready to merge, run all tests 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.

2 participants