Skip to content

[Data] Bound Iceberg read task memory - #64813

Merged
richardliaw merged 3 commits into
ray-project:masterfrom
dossett:iceberg-read-memory
Aug 19, 2026
Merged

richardliaw merged 3 commits into
ray-project:masterfrom
dossett:iceberg-read-memory

Conversation

@dossett

@dossett dossett commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

I used CODEX to analyze this problem and create this PR. I've reviewed the code and tests and stand by them. This summary is written completely by a human (me) other than very light copy editing by an LLM.

Currently _generate_tables() scans all files associated with the FileScanTasks to produce one Arrow table and then yields the results in batches. The implication is that the memory consumption is what's needed to process all FileScanTasks at once.

This change processes one FileScanTask at a time and yields the result in batches. This reduces the memory consumption to a function of the largest requirement for any single FileScanTask.

This can be a meaningful benefit at scale when multiple files are processed per Ray task.

UPDATE: @abhishekverma-ray points out in a comment that this subtly changes the PyArrow field data type, with respect to width of offsets. Before, the use to_table() allowed for promotion to large_string / large_list when needed. But with this PR's use of to_record_batches() that needs to always happen. An alternative idea would be to keep using to_table but yield back results at the file level. That reduces the memory footprint relative to the current behavior, which processes all files at once, but take more memory than the current approach in this PR which is to yield back at the batch level.

I will defer to the guidance of the project maintainers on what the best tradeoff is here between the memory and the breaking(?) change of the returned types.

CODEX generated summary follows:

Ray's Iceberg reader passes every FileScanTask assigned to a Ray read task into one PyIceberg ArrowScan. PyIceberg materializes the files in its executor before Ray can consume the resulting batches, so transient worker memory scales with the number and size of files assigned to that task. In our production-shaped workload, workers OOMed before downstream processing made meaningful progress.

By default, this change calls PyIceberg's public to_record_batches() API separately for each FileScanTask. That bounds the Ray task's high-water mark to one file, preserves the task-wide row limit, and casts every result to the projected Iceberg schema so blocks do not alternate between small- and large-offset Arrow types. PyIceberg still materializes a complete file before Ray receives its batches, so this is a file-level—not batch-level—memory bound.

DataContext.iceberg_config.read_file_tasks_sequentially defaults to True for that bounded behavior. Setting it to False restores the prior to_table(tasks=tasks) path, including PyIceberg's within-task cross-file parallelism and shared delete-file reuse. Disable it when a task has many small files, their combined input comfortably fits in memory, and throughput matters more than the memory bound.

Results

A local six-file Iceberg benchmark scanned 12 million rows: two million rows per file with eight random int64 columns. Peak process memory fell from 1.855 GiB to approximately 650 MiB, a 65% reduction (2.85x lower), with the same output rows and no measurable hot-cache slowdown.

As an end-to-end validation, the original reader OOMed after roughly 242 completed read tasks. The bounded reader, combined with an explicit 5 GiB Ray task-memory reservation, reached 2,343 completed reads with zero failures; peak worker-node memory was 102.5/160 GiB. The local benchmark isolates this code change; the cluster result validates the reader together with separate scheduling configuration.

Testing

  • /Users/aniskodedossett/development/ray/.venv/bin/pytest -q python/ray/data/tests/datasource/test_iceberg.py -k 'get_read_task or read_basic' — 5 passed, 52 deselected
  • pre-commit run --files python/ray/data/_internal/datasource/iceberg_datasource.py python/ray/data/context.py python/ray/data/tests/datasource/test_iceberg.py — passed
  • git diff --check — passed

I searched open ray-project/ray pull requests for Iceberg memory, read_iceberg memory, and ArrowScan Iceberg changes and found no active duplicate.

AI assistance was used to investigate, implement, test, benchmark, and draft this PR. The submitter must review every changed line and validate the results before requesting upstream review.

@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 refactors the PyIceberg integration (for PyIceberg >= 0.9.0) in _get_read_task to scan files one at a time and stream results as record batches, which avoids materializing all batches at once and respects row limits. It also normalizes batch schemas to a target schema and adds corresponding unit tests. The reviewer identified an issue where the row limit could be exceeded if to_record_batches yields multiple batches for a single task, as subsequent batches are not sliced or skipped once rows_remaining reaches zero. A code suggestion was provided to slice the batch and break early.

@dossett
dossett marked this pull request as ready for review July 16, 2026 16:15
@dossett
dossett requested a review from a team as a code owner July 16, 2026 16:15
@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Jul 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 Jul 31, 2026
@richardliaw richardliaw added go add ONLY when ready to merge, run all tests and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Jul 31, 2026
@dossett

dossett commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

@richardliaw Thank you running the tests, there were failures but they seem unrelated to this change:

ERROR: /opt/cache/bazel/external/boost/BUILD.bazel:1147:14: @@boost//:iostreams depends on @@org_lzma_lzma//:lzma in repository @@org_lzma_lzma which failed to fetch. no such package '@@org_lzma_lzma//': java.io.IOException: Error downloading [https://cfhcable.dl.sourceforge.net/project/lzmautils/xz-5.2.7.tar.gz, https://superb-sea2.dl.sourceforge.net/project/lzmautils/xz-5.2.7.tar.gz, https://ayera.dl.sourceforge.net/project/lzmautils/xz-5.2.7.tar.gz, https://astuteinternet.dl.sourceforge.net/project/lzmautils/xz-5.2.7.tar.gz] to /opt/cache/bazel/external/org_lzma_lzma/temp2284657188369287395/xz-5.2.7.tar.gz: Unknown host: astuteinternet.dl.sourceforge.net

goutamvenkat-anyscale pushed a commit that referenced this pull request Aug 11, 2026
## Description

`Dataset.count()` returns a wrong row count for three common Iceberg
queries, in
both directions — too low and too high. On a local Iceberg table of 100
rows, 10
of which have `id < 10` (full repro script under Additional
information):

```
ray 2.56.1   pyiceberg 0.11.1   pyarrow 25.0.0

table has 100 rows; 10 of them have id < 10

query                                                     count()  truth  verdict
----------------------------------------------------------------------------------------
read_iceberg().count()                                        100    100  ok
select_columns(['country']).count()                           100    100  ok
filter(col('id') < 10).count()                                  0     10  WRONG (take_all() yields 10)
filter(lambda r: r['id'] < 10).count()                         10     10  ok
filter(col('id')<10).select_columns(['country']).count()        0     10  WRONG (take_all() yields 10)
read_iceberg(row_filter=id<10).count()                        100     10  WRONG (take_all() yields 10)
select_columns(['country']).materialize().count()             100    100  ok

3 of 7 queries report a wrong count.
```

Note row four: the *same* filter written as a UDF returns the correct
10. The bug
is not in filtering, it is in what happens when a filter is pushed down
into the
Iceberg read. And `count()` fails silently — nothing raises, nothing
warns, the
number is simply wrong.

Both directions of failure are the same class of defect: **the
datasource claims
a row count it does not deliver.** Two causes, plus an unrelated
dict-mutation
bug in the same constructor:

1. **An empty column projection loses every row.** `count()` projects
zero
columns — it needs a row count, not values. PyIceberg builds its output
by
   *reconstructing* a table against the projected schema, and a table
reconstructed from zero columns reports zero rows however many the scan
   matched. Fixed by reading one cheap column and slicing it away.
2. **Read-task metadata ignores pushed-down filters.** `num_rows` came
from the
manifests' `record_count`, written when the data was written and
therefore
filter-blind. Fixed by reporting the count only when it is provably
exact.
3. **`read_iceberg` mutated caller-owned dicts** — `catalog_kwargs` was
stored by
reference then `pop("name")`-ed, so a second read with the same dict
raised
   `NoSuchTableError`. Fixed by copying.

After this change the repro reports `0 of 7 queries report a wrong
count.`

```
$ pytest python/ray/data/tests/datasource/test_iceberg.py
before:  10 failed, 60 passed
after:   70 passed
```

## Related issues

Fixes #63913.

**The symptom reported in that issue no longer reproduces on master, but
the
defect does.** `read_iceberg(...).select_columns([...]).count()` is
correct today
because `Project.can_modify_num_rows` is `False`, so `num_rows`
propagates
through the projection and `count()` takes the metadata shortcut without
ever
asking the reader for an empty projection. That masked the reported
symptom; it
did not fix the reader. Add anything that erases the metadata — any
filter — and
the defect resurfaces, as the three failing rows above show. The repro
under
Additional information covers the forms that are still live.

Not a duplicate: no open PR addresses this issue (`gh pr list --search
"63913
in:body"` returns nothing), and the other open Iceberg PRs (#64811,
#64813,
#65042, #64485) address unrelated concerns — read-task state
deduplication,
read-task memory bounds, decoded-size estimation, and incremental reads.

## Additional information

### Cause 1 — an empty column projection loses every row

`count()` has a fast path that projects zero columns, which is safe as
long as an
empty projection preserves the row count. It does not for PyIceberg,
because
PyIceberg rebuilds rather than slices:

```python
>>> pa.RecordBatch.from_arrays([], schema=pa.schema([])).num_rows
0                                    # rebuilding: count lost
>>> pa.table({"x": range(101)}).select([]).num_rows
101                                  # slicing: count preserved
```

So the read returns nothing and `count()` reports 0.

Reaching this needs two optimizer passes, which is why it only appears
alongside
a filter: `PredicatePushdown` deletes the `Filter` node, and *that* is
what
leaves the `Project` directly above the read for `ProjectionPushdown` to
fold in
on the next pass.

**Fix:** when the pushed-down projection is empty, ask Iceberg for a
single
optional field that exists in no schema version, named after Ray's
existing
`__bsp_stub` placeholder. Iceberg fills a missing optional field with
nulls — the
same rule that lets it read a file written before a column was added —
so the row
count arrives in a column carrying no data. The read task then passes
the block
through Ray's zero-column projection helper
(`BlockAccessor.select([])`), which
retypes the stub to `null`, making the block byte-identical to what the
Parquet
readers produce for an empty projection.

This makes the Iceberg reader satisfy the same empty-projection contract
as
`parquet_datasource.py` and `datasource_v2/readers/file_reader.py`
rather than
adding a second convention, and it needs no knowledge of the table's
schema —
nothing is chosen, so a `snapshot_id` pinned to a snapshot missing a
column
cannot break it.

### Cause 2 — read-task metadata ignores pushed-down filters

`get_read_tasks()` reported `num_rows` from the Iceberg manifests'
`record_count`. That value is filter-blind, so a selective filter still
reported
every row in every surviving file. With a read-time `row_filter` there
is no
`Filter` node in the plan at all, so `count()` trusts the metadata
directly and
returns 100 instead of 10.

**Fix:** report the count only when it is provably exact. PyIceberg
exposes what
is left of a filter after partition pruning as `FileScanTask.residual`;
`AlwaysTrue` means pruning resolved the filter completely — e.g. a
filter on a
partition column that dropped whole files — so the manifest counts still
hold.
Anything else needs row-by-row evaluation, and we report `None`
(unknown), which
makes `count()` do the read.

This deliberately keeps the free count for partition-column filters
rather than
abandoning the optimization wholesale, and
`test_reported_num_rows_matches_rows_read` pins both sides of that
boundary so a
later change can't quietly turn a free count into a full scan.

A `scan_kwargs` `limit` also suppresses the count: the read stops early,
so no
manifest arithmetic describes what comes back. Note that `limit` is
handed to
each read task rather than applied across the scan, so the rows returned
depend
on how files were chunked — another reason not to try to predict it.
That
per-task behaviour looks like a separate pre-existing bug and is left
alone
here; reporting an unknown count keeps `count()` faithful to whatever
the read
actually delivers.

Ordering note: cause 1 has to be fixed first. Fixing cause 2 alone
routes
`count()` off the metadata shortcut and into the empty-projection path,
turning a
wrong 100 into a wrong 0.

**Pushdown clones must re-plan.** `residual` is only meaningful if the
plan files
were planned *with* the predicate. `apply_predicate` and
`apply_projection`
shallow-copy the datasource, so a clone inherits `_plan_files` — and if
that cache
was populated first (`estimate_inmemory_data_size()` reads it, which is
how Ray
autodetects parallelism), every residual in it is `AlwaysTrue`, because
nothing
was filtered at plan time. `counts_are_exact` would then report the
unfiltered
manifest total: the same overcount, via a different route. Both methods
are now
overridden to drop the clone's inherited cache, and
`test_pushdown_does_not_inherit_stale_plan_files` covers it. Not
reachable
through the `Dataset` API today — each pushdown rule clones before
anything warms
the cache — but `IcebergDatasource` is a `@DeveloperAPI`, and it is
reachable
directly, so it is fixed rather than documented.

While there: `plan_files` now caches `list(data_scan.plan_files())`.
PyIceberg
returns a list today, but the method is annotated
`Iterable[FileScanTask]` and
this cache is read more than once, so materializing removes the
dependence on an
unspecified return type. (Existing code already relied on it —
`get_read_tasks`
called `len(list(plan_files))` twice — so a generator would have
silently yielded
zero read tasks.)

### The dict mutation

```
caller's dict before: ['name', 'uri', 'warehouse']
first  read_iceberg  -> count() 100
caller's dict after : ['uri', 'warehouse']        <-- 'name' is gone
second read_iceberg  -> NoSuchTableError: Table does not exist: db.t
```

The same call works once and fails the second time. `scan_kwargs` fails
silently
instead — a reused dict has `snapshot_id` written into it, pinning later
reads to
a stale snapshot with no error at all. Corroboration that this already
bites
people: the existing test file works around it with
`_CATALOG_KWARGS.copy()` at
35 call sites.

### Tests

The Iceberg suite had no `count()` or `num_rows` assertions at all,
which is how
both bugs survived. This adds 16, asserting an **invariant** rather than
hardcoded numbers — the row count the datasource claims must equal the
rows it
produces — so pushdowns added later are covered by the same tests:

- `test_count_matches_rows_actually_produced` (7 cases) — `count()` vs
`take_all()` at the user level. Includes a UDF-filter control case, so
the bug
  cannot be "fixed" by disabling predicate pushdown.
- `test_empty_projection_preserves_row_count` — cause 1 at the
datasource level,
  with Ray's execution engine out of the picture.
- `test_reported_num_rows_matches_rows_read` (3 cases) — claimed
metadata vs rows
actually read, pinning both that partition-only filters keep their exact
count
  and that row-level filters report unknown.
- `test_pushdown_does_not_inherit_stale_plan_files` (2 cases) — that a
pushdown
  clone re-plans its scan instead of inheriting a cache built before the
  predicate existed, and that the cache survives being read twice.
- `test_reported_num_rows_is_unknown_when_scan_stops_early` — that a
`limit`
suppresses the count, with no row filter present so the limit is the
only
  reason it cannot be trusted.
- `test_empty_projection_respects_pinned_snapshot_schema` — evolves the
schema,
  then reads an empty projection pinned to the pre-evolution snapshot.
- `test_read_iceberg_does_not_mutate_caller_kwargs` — the dict mutation,
plus
  that a second identical read still succeeds.

Each new test was confirmed to reproduce the bug before the fix and to
pass
after it. Run against the unfixed datasource, the 10 that target these
bugs all
fail; with the fix, all 70 pass:

```
$ pytest python/ray/data/tests/datasource/test_iceberg.py     # WITHOUT the fix
FAILED test_count_matches_rows_actually_produced[expr_filter]              <- cause 1
FAILED test_count_matches_rows_actually_produced[expr_filter_then_select]  <- cause 1
FAILED test_count_matches_rows_actually_produced[read_time_row_filter]     <- cause 2
FAILED test_empty_projection_preserves_row_count                           <- cause 1
FAILED test_reported_num_rows_matches_rows_read[row_level_filter]          <- cause 2
FAILED test_pushdown_does_not_inherit_stale_plan_files[predicate]           <- cause 2
FAILED test_pushdown_does_not_inherit_stale_plan_files[predicate_then_...]  <- cause 2
FAILED test_reported_num_rows_is_unknown_when_scan_stops_early              <- cause 2
FAILED test_empty_projection_respects_pinned_snapshot_schema                <- cause 1
FAILED test_read_iceberg_does_not_mutate_caller_kwargs                     <- dict mutation
10 failed, 60 passed

$ pytest python/ray/data/tests/datasource/test_iceberg.py     # WITH the fix
70 passed
```

Environment: macOS, Python 3.12, ray 2.56.1 with the two changed files
applied,
pyiceberg 0.11.1, pyarrow 25.0.0. `ruff check` and `black --check` are
clean on
both changed files.

The 10 pre-fix failures are exactly the 10 new tests targeting these
bugs, and the
other 6 new tests pass in both runs — including the UDF-filter control
and the
partition-filter metadata case, so the fix is pinned as not having
achieved its
result by disabling pushdown or by abandoning the free count. No
pre-existing
test changes behaviour either way.

### Implementation notes

- **Overlap with #65042.** That PR rewrites `size_bytes` in the same
`BlockMetadata(...)` construction where this PR rewrites `num_rows`, so
whichever merges second hits a textual conflict. The changes are
independent —
  the resolution is to keep both. #65042 also derives its estimate from
`projected_field_ids`, which this PR changes for the empty-projection
case (one
sentinel column rather than none); that is the correct input, since the
sentinel is genuinely all the read fetches, but worth being aware of.
#64811
and #64813 touch nearby lines in `get_read_tasks` / `_get_read_task` and
may
  conflict textually too.
- **The exactness test matches PyIceberg's own.** `DataScan.count()`
decides the
same way — `task.residual == AlwaysTrue() and not task.delete_files`
means take
`record_count`, otherwise read the file — so this reuses the library's
own
  notion of when a manifest count still holds rather than inventing one.
- **Equality deletes are not a third instance of this bug**, despite the
`record_count - position_delete_count` arithmetic ignoring them:
PyIceberg
raises `NotImplementedError` on equality deletes before a miscount could
  occur.

<details>
<summary>Repro script — no cluster or cloud access needed, exits
non-zero on failure</summary>

```python
"""Reproduce three ways ``Dataset.count()`` returns a wrong row count on an
Iceberg dataset.

    pip install "ray[data]" pyiceberg sqlalchemy
    python repro_iceberg_count.py
"""

import logging
import pathlib
import tempfile
import warnings

import pyarrow as pa
from pyiceberg.catalog.sql import SqlCatalog
from pyiceberg.expressions import LessThan
from pyiceberg.schema import Schema
from pyiceberg.types import LongType, NestedField, StringType

warnings.filterwarnings("ignore")

N_ROWS = 100
THRESHOLD = 10  # number of rows with id < THRESHOLD


def make_table():
    """Create a temporary Iceberg table with N_ROWS rows; return its catalog kwargs."""
    tmp = tempfile.mkdtemp()
    warehouse = pathlib.Path(tmp) / "wh"
    warehouse.mkdir()
    catalog = SqlCatalog(
        "local", uri=f"sqlite:///{tmp}/c.db", warehouse=f"file://{warehouse}"
    )
    catalog.create_namespace("db")
    table = catalog.create_table(
        "db.t",
        schema=Schema(
            NestedField(1, "id", LongType(), required=False),
            NestedField(2, "country", StringType(), required=False),
        ),
    )
    table.append(
        pa.table(
            {
                "id": pa.array(range(N_ROWS), pa.int64()),
                "country": pa.array(["US"] * N_ROWS, pa.string()),
            }
        )
    )
    return {
        "name": "local",
        "uri": f"sqlite:///{tmp}/c.db",
        "warehouse": f"file://{warehouse}",
    }


def main():
    catalog_kwargs = make_table()

    import pyiceberg
    import ray
    from ray.data.expressions import col

    ray.init(
        num_cpus=4, include_dashboard=False, log_to_driver=False, logging_level="error"
    )
    logging.getLogger("ray").setLevel(logging.ERROR)
    logging.getLogger("ray.data").setLevel(logging.ERROR)
    ray.data.DataContext.get_current().enable_progress_bars = False

    print(
        f"ray {ray.__version__}   pyiceberg {pyiceberg.__version__}   "
        f"pyarrow {pa.__version__}"
    )
    print(f"\ntable has {N_ROWS} rows; {THRESHOLD} of them have id < {THRESHOLD}\n")

    def base():
        return ray.data.read_iceberg(
            table_identifier="db.t", catalog_kwargs=dict(catalog_kwargs)
        )

    def read_with_row_filter():
        return ray.data.read_iceberg(
            table_identifier="db.t",
            catalog_kwargs=dict(catalog_kwargs),
            row_filter=LessThan("id", THRESHOLD),
        )

    cases = [
        ("read_iceberg().count()", base, N_ROWS),
        (
            "select_columns(['country']).count()",
            lambda: base().select_columns(["country"]),
            N_ROWS,
        ),
        (
            "filter(col('id') < 10).count()",
            lambda: base().filter(expr=col("id") < THRESHOLD),
            THRESHOLD,
        ),
        (
            "filter(lambda r: r['id'] < 10).count()",
            lambda: base().filter(lambda r: r["id"] < THRESHOLD),
            THRESHOLD,
        ),
        (
            "filter(col('id')<10).select_columns(['country']).count()",
            lambda: base()
            .filter(expr=col("id") < THRESHOLD)
            .select_columns(["country"]),
            THRESHOLD,
        ),
        ("read_iceberg(row_filter=id<10).count()", read_with_row_filter, THRESHOLD),
        (
            "select_columns(['country']).materialize().count()",
            lambda: base().select_columns(["country"]).materialize(),
            N_ROWS,
        ),
    ]

    print(f"{'query':56s} {'count()':>8s} {'truth':>6s}  verdict")
    print("-" * 88)
    failures = 0
    for label, make_ds, truth in cases:
        reported = make_ds().count()
        actual_rows = len(make_ds().take_all())  # independent ground truth
        if reported == truth:
            verdict = "ok"
        else:
            verdict = f"WRONG (take_all() yields {actual_rows})"
            failures += 1
        print(f"{label:56s} {reported:8d} {truth:6d}  {verdict}")

    print(f"\n{failures} of {len(cases)} queries report a wrong count.")
    return 1 if failures else 0


if __name__ == "__main__":
    raise SystemExit(main())
```

</details>

AI assistance was used for this change.

---------

Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…oject#65175)

## Description

`Dataset.count()` returns a wrong row count for three common Iceberg
queries, in
both directions — too low and too high. On a local Iceberg table of 100
rows, 10
of which have `id < 10` (full repro script under Additional
information):

```
ray 2.56.1   pyiceberg 0.11.1   pyarrow 25.0.0

table has 100 rows; 10 of them have id < 10

query                                                     count()  truth  verdict
----------------------------------------------------------------------------------------
read_iceberg().count()                                        100    100  ok
select_columns(['country']).count()                           100    100  ok
filter(col('id') < 10).count()                                  0     10  WRONG (take_all() yields 10)
filter(lambda r: r['id'] < 10).count()                         10     10  ok
filter(col('id')<10).select_columns(['country']).count()        0     10  WRONG (take_all() yields 10)
read_iceberg(row_filter=id<10).count()                        100     10  WRONG (take_all() yields 10)
select_columns(['country']).materialize().count()             100    100  ok

3 of 7 queries report a wrong count.
```

Note row four: the *same* filter written as a UDF returns the correct
10. The bug
is not in filtering, it is in what happens when a filter is pushed down
into the
Iceberg read. And `count()` fails silently — nothing raises, nothing
warns, the
number is simply wrong.

Both directions of failure are the same class of defect: **the
datasource claims
a row count it does not deliver.** Two causes, plus an unrelated
dict-mutation
bug in the same constructor:

1. **An empty column projection loses every row.** `count()` projects
zero
columns — it needs a row count, not values. PyIceberg builds its output
by
   *reconstructing* a table against the projected schema, and a table
reconstructed from zero columns reports zero rows however many the scan
   matched. Fixed by reading one cheap column and slicing it away.
2. **Read-task metadata ignores pushed-down filters.** `num_rows` came
from the
manifests' `record_count`, written when the data was written and
therefore
filter-blind. Fixed by reporting the count only when it is provably
exact.
3. **`read_iceberg` mutated caller-owned dicts** — `catalog_kwargs` was
stored by
reference then `pop("name")`-ed, so a second read with the same dict
raised
   `NoSuchTableError`. Fixed by copying.

After this change the repro reports `0 of 7 queries report a wrong
count.`

```
$ pytest python/ray/data/tests/datasource/test_iceberg.py
before:  10 failed, 60 passed
after:   70 passed
```

## Related issues

Fixes ray-project#63913.

**The symptom reported in that issue no longer reproduces on master, but
the
defect does.** `read_iceberg(...).select_columns([...]).count()` is
correct today
because `Project.can_modify_num_rows` is `False`, so `num_rows`
propagates
through the projection and `count()` takes the metadata shortcut without
ever
asking the reader for an empty projection. That masked the reported
symptom; it
did not fix the reader. Add anything that erases the metadata — any
filter — and
the defect resurfaces, as the three failing rows above show. The repro
under
Additional information covers the forms that are still live.

Not a duplicate: no open PR addresses this issue (`gh pr list --search
"63913
in:body"` returns nothing), and the other open Iceberg PRs (ray-project#64811,
ray-project#64813,
ray-project#65042, ray-project#64485) address unrelated concerns — read-task state
deduplication,
read-task memory bounds, decoded-size estimation, and incremental reads.

## Additional information

### Cause 1 — an empty column projection loses every row

`count()` has a fast path that projects zero columns, which is safe as
long as an
empty projection preserves the row count. It does not for PyIceberg,
because
PyIceberg rebuilds rather than slices:

```python
>>> pa.RecordBatch.from_arrays([], schema=pa.schema([])).num_rows
0                                    # rebuilding: count lost
>>> pa.table({"x": range(101)}).select([]).num_rows
101                                  # slicing: count preserved
```

So the read returns nothing and `count()` reports 0.

Reaching this needs two optimizer passes, which is why it only appears
alongside
a filter: `PredicatePushdown` deletes the `Filter` node, and *that* is
what
leaves the `Project` directly above the read for `ProjectionPushdown` to
fold in
on the next pass.

**Fix:** when the pushed-down projection is empty, ask Iceberg for a
single
optional field that exists in no schema version, named after Ray's
existing
`__bsp_stub` placeholder. Iceberg fills a missing optional field with
nulls — the
same rule that lets it read a file written before a column was added —
so the row
count arrives in a column carrying no data. The read task then passes
the block
through Ray's zero-column projection helper
(`BlockAccessor.select([])`), which
retypes the stub to `null`, making the block byte-identical to what the
Parquet
readers produce for an empty projection.

This makes the Iceberg reader satisfy the same empty-projection contract
as
`parquet_datasource.py` and `datasource_v2/readers/file_reader.py`
rather than
adding a second convention, and it needs no knowledge of the table's
schema —
nothing is chosen, so a `snapshot_id` pinned to a snapshot missing a
column
cannot break it.

### Cause 2 — read-task metadata ignores pushed-down filters

`get_read_tasks()` reported `num_rows` from the Iceberg manifests'
`record_count`. That value is filter-blind, so a selective filter still
reported
every row in every surviving file. With a read-time `row_filter` there
is no
`Filter` node in the plan at all, so `count()` trusts the metadata
directly and
returns 100 instead of 10.

**Fix:** report the count only when it is provably exact. PyIceberg
exposes what
is left of a filter after partition pruning as `FileScanTask.residual`;
`AlwaysTrue` means pruning resolved the filter completely — e.g. a
filter on a
partition column that dropped whole files — so the manifest counts still
hold.
Anything else needs row-by-row evaluation, and we report `None`
(unknown), which
makes `count()` do the read.

This deliberately keeps the free count for partition-column filters
rather than
abandoning the optimization wholesale, and
`test_reported_num_rows_matches_rows_read` pins both sides of that
boundary so a
later change can't quietly turn a free count into a full scan.

A `scan_kwargs` `limit` also suppresses the count: the read stops early,
so no
manifest arithmetic describes what comes back. Note that `limit` is
handed to
each read task rather than applied across the scan, so the rows returned
depend
on how files were chunked — another reason not to try to predict it.
That
per-task behaviour looks like a separate pre-existing bug and is left
alone
here; reporting an unknown count keeps `count()` faithful to whatever
the read
actually delivers.

Ordering note: cause 1 has to be fixed first. Fixing cause 2 alone
routes
`count()` off the metadata shortcut and into the empty-projection path,
turning a
wrong 100 into a wrong 0.

**Pushdown clones must re-plan.** `residual` is only meaningful if the
plan files
were planned *with* the predicate. `apply_predicate` and
`apply_projection`
shallow-copy the datasource, so a clone inherits `_plan_files` — and if
that cache
was populated first (`estimate_inmemory_data_size()` reads it, which is
how Ray
autodetects parallelism), every residual in it is `AlwaysTrue`, because
nothing
was filtered at plan time. `counts_are_exact` would then report the
unfiltered
manifest total: the same overcount, via a different route. Both methods
are now
overridden to drop the clone's inherited cache, and
`test_pushdown_does_not_inherit_stale_plan_files` covers it. Not
reachable
through the `Dataset` API today — each pushdown rule clones before
anything warms
the cache — but `IcebergDatasource` is a `@DeveloperAPI`, and it is
reachable
directly, so it is fixed rather than documented.

While there: `plan_files` now caches `list(data_scan.plan_files())`.
PyIceberg
returns a list today, but the method is annotated
`Iterable[FileScanTask]` and
this cache is read more than once, so materializing removes the
dependence on an
unspecified return type. (Existing code already relied on it —
`get_read_tasks`
called `len(list(plan_files))` twice — so a generator would have
silently yielded
zero read tasks.)

### The dict mutation

```
caller's dict before: ['name', 'uri', 'warehouse']
first  read_iceberg  -> count() 100
caller's dict after : ['uri', 'warehouse']        <-- 'name' is gone
second read_iceberg  -> NoSuchTableError: Table does not exist: db.t
```

The same call works once and fails the second time. `scan_kwargs` fails
silently
instead — a reused dict has `snapshot_id` written into it, pinning later
reads to
a stale snapshot with no error at all. Corroboration that this already
bites
people: the existing test file works around it with
`_CATALOG_KWARGS.copy()` at
35 call sites.

### Tests

The Iceberg suite had no `count()` or `num_rows` assertions at all,
which is how
both bugs survived. This adds 16, asserting an **invariant** rather than
hardcoded numbers — the row count the datasource claims must equal the
rows it
produces — so pushdowns added later are covered by the same tests:

- `test_count_matches_rows_actually_produced` (7 cases) — `count()` vs
`take_all()` at the user level. Includes a UDF-filter control case, so
the bug
  cannot be "fixed" by disabling predicate pushdown.
- `test_empty_projection_preserves_row_count` — cause 1 at the
datasource level,
  with Ray's execution engine out of the picture.
- `test_reported_num_rows_matches_rows_read` (3 cases) — claimed
metadata vs rows
actually read, pinning both that partition-only filters keep their exact
count
  and that row-level filters report unknown.
- `test_pushdown_does_not_inherit_stale_plan_files` (2 cases) — that a
pushdown
  clone re-plans its scan instead of inheriting a cache built before the
  predicate existed, and that the cache survives being read twice.
- `test_reported_num_rows_is_unknown_when_scan_stops_early` — that a
`limit`
suppresses the count, with no row filter present so the limit is the
only
  reason it cannot be trusted.
- `test_empty_projection_respects_pinned_snapshot_schema` — evolves the
schema,
  then reads an empty projection pinned to the pre-evolution snapshot.
- `test_read_iceberg_does_not_mutate_caller_kwargs` — the dict mutation,
plus
  that a second identical read still succeeds.

Each new test was confirmed to reproduce the bug before the fix and to
pass
after it. Run against the unfixed datasource, the 10 that target these
bugs all
fail; with the fix, all 70 pass:

```
$ pytest python/ray/data/tests/datasource/test_iceberg.py     # WITHOUT the fix
FAILED test_count_matches_rows_actually_produced[expr_filter]              <- cause 1
FAILED test_count_matches_rows_actually_produced[expr_filter_then_select]  <- cause 1
FAILED test_count_matches_rows_actually_produced[read_time_row_filter]     <- cause 2
FAILED test_empty_projection_preserves_row_count                           <- cause 1
FAILED test_reported_num_rows_matches_rows_read[row_level_filter]          <- cause 2
FAILED test_pushdown_does_not_inherit_stale_plan_files[predicate]           <- cause 2
FAILED test_pushdown_does_not_inherit_stale_plan_files[predicate_then_...]  <- cause 2
FAILED test_reported_num_rows_is_unknown_when_scan_stops_early              <- cause 2
FAILED test_empty_projection_respects_pinned_snapshot_schema                <- cause 1
FAILED test_read_iceberg_does_not_mutate_caller_kwargs                     <- dict mutation
10 failed, 60 passed

$ pytest python/ray/data/tests/datasource/test_iceberg.py     # WITH the fix
70 passed
```

Environment: macOS, Python 3.12, ray 2.56.1 with the two changed files
applied,
pyiceberg 0.11.1, pyarrow 25.0.0. `ruff check` and `black --check` are
clean on
both changed files.

The 10 pre-fix failures are exactly the 10 new tests targeting these
bugs, and the
other 6 new tests pass in both runs — including the UDF-filter control
and the
partition-filter metadata case, so the fix is pinned as not having
achieved its
result by disabling pushdown or by abandoning the free count. No
pre-existing
test changes behaviour either way.

### Implementation notes

- **Overlap with ray-project#65042.** That PR rewrites `size_bytes` in the same
`BlockMetadata(...)` construction where this PR rewrites `num_rows`, so
whichever merges second hits a textual conflict. The changes are
independent —
  the resolution is to keep both. ray-project#65042 also derives its estimate from
`projected_field_ids`, which this PR changes for the empty-projection
case (one
sentinel column rather than none); that is the correct input, since the
sentinel is genuinely all the read fetches, but worth being aware of.
ray-project#64811
and ray-project#64813 touch nearby lines in `get_read_tasks` / `_get_read_task` and
may
  conflict textually too.
- **The exactness test matches PyIceberg's own.** `DataScan.count()`
decides the
same way — `task.residual == AlwaysTrue() and not task.delete_files`
means take
`record_count`, otherwise read the file — so this reuses the library's
own
  notion of when a manifest count still holds rather than inventing one.
- **Equality deletes are not a third instance of this bug**, despite the
`record_count - position_delete_count` arithmetic ignoring them:
PyIceberg
raises `NotImplementedError` on equality deletes before a miscount could
  occur.

<details>
<summary>Repro script — no cluster or cloud access needed, exits
non-zero on failure</summary>

```python
"""Reproduce three ways ``Dataset.count()`` returns a wrong row count on an
Iceberg dataset.

    pip install "ray[data]" pyiceberg sqlalchemy
    python repro_iceberg_count.py
"""

import logging
import pathlib
import tempfile
import warnings

import pyarrow as pa
from pyiceberg.catalog.sql import SqlCatalog
from pyiceberg.expressions import LessThan
from pyiceberg.schema import Schema
from pyiceberg.types import LongType, NestedField, StringType

warnings.filterwarnings("ignore")

N_ROWS = 100
THRESHOLD = 10  # number of rows with id < THRESHOLD

def make_table():
    """Create a temporary Iceberg table with N_ROWS rows; return its catalog kwargs."""
    tmp = tempfile.mkdtemp()
    warehouse = pathlib.Path(tmp) / "wh"
    warehouse.mkdir()
    catalog = SqlCatalog(
        "local", uri=f"sqlite:///{tmp}/c.db", warehouse=f"file://{warehouse}"
    )
    catalog.create_namespace("db")
    table = catalog.create_table(
        "db.t",
        schema=Schema(
            NestedField(1, "id", LongType(), required=False),
            NestedField(2, "country", StringType(), required=False),
        ),
    )
    table.append(
        pa.table(
            {
                "id": pa.array(range(N_ROWS), pa.int64()),
                "country": pa.array(["US"] * N_ROWS, pa.string()),
            }
        )
    )
    return {
        "name": "local",
        "uri": f"sqlite:///{tmp}/c.db",
        "warehouse": f"file://{warehouse}",
    }

def main():
    catalog_kwargs = make_table()

    import pyiceberg
    import ray
    from ray.data.expressions import col

    ray.init(
        num_cpus=4, include_dashboard=False, log_to_driver=False, logging_level="error"
    )
    logging.getLogger("ray").setLevel(logging.ERROR)
    logging.getLogger("ray.data").setLevel(logging.ERROR)
    ray.data.DataContext.get_current().enable_progress_bars = False

    print(
        f"ray {ray.__version__}   pyiceberg {pyiceberg.__version__}   "
        f"pyarrow {pa.__version__}"
    )
    print(f"\ntable has {N_ROWS} rows; {THRESHOLD} of them have id < {THRESHOLD}\n")

    def base():
        return ray.data.read_iceberg(
            table_identifier="db.t", catalog_kwargs=dict(catalog_kwargs)
        )

    def read_with_row_filter():
        return ray.data.read_iceberg(
            table_identifier="db.t",
            catalog_kwargs=dict(catalog_kwargs),
            row_filter=LessThan("id", THRESHOLD),
        )

    cases = [
        ("read_iceberg().count()", base, N_ROWS),
        (
            "select_columns(['country']).count()",
            lambda: base().select_columns(["country"]),
            N_ROWS,
        ),
        (
            "filter(col('id') < 10).count()",
            lambda: base().filter(expr=col("id") < THRESHOLD),
            THRESHOLD,
        ),
        (
            "filter(lambda r: r['id'] < 10).count()",
            lambda: base().filter(lambda r: r["id"] < THRESHOLD),
            THRESHOLD,
        ),
        (
            "filter(col('id')<10).select_columns(['country']).count()",
            lambda: base()
            .filter(expr=col("id") < THRESHOLD)
            .select_columns(["country"]),
            THRESHOLD,
        ),
        ("read_iceberg(row_filter=id<10).count()", read_with_row_filter, THRESHOLD),
        (
            "select_columns(['country']).materialize().count()",
            lambda: base().select_columns(["country"]).materialize(),
            N_ROWS,
        ),
    ]

    print(f"{'query':56s} {'count()':>8s} {'truth':>6s}  verdict")
    print("-" * 88)
    failures = 0
    for label, make_ds, truth in cases:
        reported = make_ds().count()
        actual_rows = len(make_ds().take_all())  # independent ground truth
        if reported == truth:
            verdict = "ok"
        else:
            verdict = f"WRONG (take_all() yields {actual_rows})"
            failures += 1
        print(f"{label:56s} {reported:8d} {truth:6d}  {verdict}")

    print(f"\n{failures} of {len(cases)} queries report a wrong count.")
    return 1 if failures else 0

if __name__ == "__main__":
    raise SystemExit(main())
```

</details>

AI assistance was used for this change.

---------

Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: 400Ping <[email protected]>
Signed-off-by: Aaron Niskode-Dossett <[email protected]>
Signed-off-by: Aaron Niskode-Dossett <[email protected]>
@dossett
dossett force-pushed the iceberg-read-memory branch from 64849b2 to ec9bb6c Compare August 18, 2026 17:52
@abhishekverma-ray

Copy link
Copy Markdown
Contributor

Thanks @dossett — the opt-out addresses my concern about cross-file parallelism and shared delete-file rereads.

On the Arrow schema question, I’m okay with using deterministic large_string/large_list types here.

The old to_table() result was data-dependent, while the streaming path needs a stable schema across yielded blocks; casting down would also be unsafe once 32-bit offsets are exceeded. The PR description now calls out the behavior change, and disabling read_file_tasks_sequentially restores the legacy path.

One clarification: this should consistently be described as a file-level memory bound, since PyIceberg materializes all batches for each file before yielding them.
The current Buildkite failures appear to be unrelated PyPI HTTP 502s. Please rerun them; once they are green, this is LGTM.

@abhishekverma-ray abhishekverma-ray 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.

LGTM

Signed-off-by: Aaron Niskode-Dossett <[email protected]>
@dossett
dossett force-pushed the iceberg-read-memory branch from 8776eb9 to 8756b33 Compare August 19, 2026 14:26
@richardliaw
richardliaw enabled auto-merge (squash) August 19, 2026 20:51
@richardliaw
richardliaw merged commit 34190b6 into ray-project:master Aug 19, 2026
7 checks passed
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…oject#65175)

## Description

`Dataset.count()` returns a wrong row count for three common Iceberg
queries, in
both directions — too low and too high. On a local Iceberg table of 100
rows, 10
of which have `id < 10` (full repro script under Additional
information):

```
ray 2.56.1   pyiceberg 0.11.1   pyarrow 25.0.0

table has 100 rows; 10 of them have id < 10

query                                                     count()  truth  verdict
----------------------------------------------------------------------------------------
read_iceberg().count()                                        100    100  ok
select_columns(['country']).count()                           100    100  ok
filter(col('id') < 10).count()                                  0     10  WRONG (take_all() yields 10)
filter(lambda r: r['id'] < 10).count()                         10     10  ok
filter(col('id')<10).select_columns(['country']).count()        0     10  WRONG (take_all() yields 10)
read_iceberg(row_filter=id<10).count()                        100     10  WRONG (take_all() yields 10)
select_columns(['country']).materialize().count()             100    100  ok

3 of 7 queries report a wrong count.
```

Note row four: the *same* filter written as a UDF returns the correct
10. The bug
is not in filtering, it is in what happens when a filter is pushed down
into the
Iceberg read. And `count()` fails silently — nothing raises, nothing
warns, the
number is simply wrong.

Both directions of failure are the same class of defect: **the
datasource claims
a row count it does not deliver.** Two causes, plus an unrelated
dict-mutation
bug in the same constructor:

1. **An empty column projection loses every row.** `count()` projects
zero
columns — it needs a row count, not values. PyIceberg builds its output
by
   *reconstructing* a table against the projected schema, and a table
reconstructed from zero columns reports zero rows however many the scan
   matched. Fixed by reading one cheap column and slicing it away.
2. **Read-task metadata ignores pushed-down filters.** `num_rows` came
from the
manifests' `record_count`, written when the data was written and
therefore
filter-blind. Fixed by reporting the count only when it is provably
exact.
3. **`read_iceberg` mutated caller-owned dicts** — `catalog_kwargs` was
stored by
reference then `pop("name")`-ed, so a second read with the same dict
raised
   `NoSuchTableError`. Fixed by copying.

After this change the repro reports `0 of 7 queries report a wrong
count.`

```
$ pytest python/ray/data/tests/datasource/test_iceberg.py
before:  10 failed, 60 passed
after:   70 passed
```

## Related issues

Fixes ray-project#63913.

**The symptom reported in that issue no longer reproduces on master, but
the
defect does.** `read_iceberg(...).select_columns([...]).count()` is
correct today
because `Project.can_modify_num_rows` is `False`, so `num_rows`
propagates
through the projection and `count()` takes the metadata shortcut without
ever
asking the reader for an empty projection. That masked the reported
symptom; it
did not fix the reader. Add anything that erases the metadata — any
filter — and
the defect resurfaces, as the three failing rows above show. The repro
under
Additional information covers the forms that are still live.

Not a duplicate: no open PR addresses this issue (`gh pr list --search
"63913
in:body"` returns nothing), and the other open Iceberg PRs (ray-project#64811,
ray-project#64813,
ray-project#65042, ray-project#64485) address unrelated concerns — read-task state
deduplication,
read-task memory bounds, decoded-size estimation, and incremental reads.

## Additional information

### Cause 1 — an empty column projection loses every row

`count()` has a fast path that projects zero columns, which is safe as
long as an
empty projection preserves the row count. It does not for PyIceberg,
because
PyIceberg rebuilds rather than slices:

```python
>>> pa.RecordBatch.from_arrays([], schema=pa.schema([])).num_rows
0                                    # rebuilding: count lost
>>> pa.table({"x": range(101)}).select([]).num_rows
101                                  # slicing: count preserved
```

So the read returns nothing and `count()` reports 0.

Reaching this needs two optimizer passes, which is why it only appears
alongside
a filter: `PredicatePushdown` deletes the `Filter` node, and *that* is
what
leaves the `Project` directly above the read for `ProjectionPushdown` to
fold in
on the next pass.

**Fix:** when the pushed-down projection is empty, ask Iceberg for a
single
optional field that exists in no schema version, named after Ray's
existing
`__bsp_stub` placeholder. Iceberg fills a missing optional field with
nulls — the
same rule that lets it read a file written before a column was added —
so the row
count arrives in a column carrying no data. The read task then passes
the block
through Ray's zero-column projection helper
(`BlockAccessor.select([])`), which
retypes the stub to `null`, making the block byte-identical to what the
Parquet
readers produce for an empty projection.

This makes the Iceberg reader satisfy the same empty-projection contract
as
`parquet_datasource.py` and `datasource_v2/readers/file_reader.py`
rather than
adding a second convention, and it needs no knowledge of the table's
schema —
nothing is chosen, so a `snapshot_id` pinned to a snapshot missing a
column
cannot break it.

### Cause 2 — read-task metadata ignores pushed-down filters

`get_read_tasks()` reported `num_rows` from the Iceberg manifests'
`record_count`. That value is filter-blind, so a selective filter still
reported
every row in every surviving file. With a read-time `row_filter` there
is no
`Filter` node in the plan at all, so `count()` trusts the metadata
directly and
returns 100 instead of 10.

**Fix:** report the count only when it is provably exact. PyIceberg
exposes what
is left of a filter after partition pruning as `FileScanTask.residual`;
`AlwaysTrue` means pruning resolved the filter completely — e.g. a
filter on a
partition column that dropped whole files — so the manifest counts still
hold.
Anything else needs row-by-row evaluation, and we report `None`
(unknown), which
makes `count()` do the read.

This deliberately keeps the free count for partition-column filters
rather than
abandoning the optimization wholesale, and
`test_reported_num_rows_matches_rows_read` pins both sides of that
boundary so a
later change can't quietly turn a free count into a full scan.

A `scan_kwargs` `limit` also suppresses the count: the read stops early,
so no
manifest arithmetic describes what comes back. Note that `limit` is
handed to
each read task rather than applied across the scan, so the rows returned
depend
on how files were chunked — another reason not to try to predict it.
That
per-task behaviour looks like a separate pre-existing bug and is left
alone
here; reporting an unknown count keeps `count()` faithful to whatever
the read
actually delivers.

Ordering note: cause 1 has to be fixed first. Fixing cause 2 alone
routes
`count()` off the metadata shortcut and into the empty-projection path,
turning a
wrong 100 into a wrong 0.

**Pushdown clones must re-plan.** `residual` is only meaningful if the
plan files
were planned *with* the predicate. `apply_predicate` and
`apply_projection`
shallow-copy the datasource, so a clone inherits `_plan_files` — and if
that cache
was populated first (`estimate_inmemory_data_size()` reads it, which is
how Ray
autodetects parallelism), every residual in it is `AlwaysTrue`, because
nothing
was filtered at plan time. `counts_are_exact` would then report the
unfiltered
manifest total: the same overcount, via a different route. Both methods
are now
overridden to drop the clone's inherited cache, and
`test_pushdown_does_not_inherit_stale_plan_files` covers it. Not
reachable
through the `Dataset` API today — each pushdown rule clones before
anything warms
the cache — but `IcebergDatasource` is a `@DeveloperAPI`, and it is
reachable
directly, so it is fixed rather than documented.

While there: `plan_files` now caches `list(data_scan.plan_files())`.
PyIceberg
returns a list today, but the method is annotated
`Iterable[FileScanTask]` and
this cache is read more than once, so materializing removes the
dependence on an
unspecified return type. (Existing code already relied on it —
`get_read_tasks`
called `len(list(plan_files))` twice — so a generator would have
silently yielded
zero read tasks.)

### The dict mutation

```
caller's dict before: ['name', 'uri', 'warehouse']
first  read_iceberg  -> count() 100
caller's dict after : ['uri', 'warehouse']        <-- 'name' is gone
second read_iceberg  -> NoSuchTableError: Table does not exist: db.t
```

The same call works once and fails the second time. `scan_kwargs` fails
silently
instead — a reused dict has `snapshot_id` written into it, pinning later
reads to
a stale snapshot with no error at all. Corroboration that this already
bites
people: the existing test file works around it with
`_CATALOG_KWARGS.copy()` at
35 call sites.

### Tests

The Iceberg suite had no `count()` or `num_rows` assertions at all,
which is how
both bugs survived. This adds 16, asserting an **invariant** rather than
hardcoded numbers — the row count the datasource claims must equal the
rows it
produces — so pushdowns added later are covered by the same tests:

- `test_count_matches_rows_actually_produced` (7 cases) — `count()` vs
`take_all()` at the user level. Includes a UDF-filter control case, so
the bug
  cannot be "fixed" by disabling predicate pushdown.
- `test_empty_projection_preserves_row_count` — cause 1 at the
datasource level,
  with Ray's execution engine out of the picture.
- `test_reported_num_rows_matches_rows_read` (3 cases) — claimed
metadata vs rows
actually read, pinning both that partition-only filters keep their exact
count
  and that row-level filters report unknown.
- `test_pushdown_does_not_inherit_stale_plan_files` (2 cases) — that a
pushdown
  clone re-plans its scan instead of inheriting a cache built before the
  predicate existed, and that the cache survives being read twice.
- `test_reported_num_rows_is_unknown_when_scan_stops_early` — that a
`limit`
suppresses the count, with no row filter present so the limit is the
only
  reason it cannot be trusted.
- `test_empty_projection_respects_pinned_snapshot_schema` — evolves the
schema,
  then reads an empty projection pinned to the pre-evolution snapshot.
- `test_read_iceberg_does_not_mutate_caller_kwargs` — the dict mutation,
plus
  that a second identical read still succeeds.

Each new test was confirmed to reproduce the bug before the fix and to
pass
after it. Run against the unfixed datasource, the 10 that target these
bugs all
fail; with the fix, all 70 pass:

```
$ pytest python/ray/data/tests/datasource/test_iceberg.py     # WITHOUT the fix
FAILED test_count_matches_rows_actually_produced[expr_filter]              <- cause 1
FAILED test_count_matches_rows_actually_produced[expr_filter_then_select]  <- cause 1
FAILED test_count_matches_rows_actually_produced[read_time_row_filter]     <- cause 2
FAILED test_empty_projection_preserves_row_count                           <- cause 1
FAILED test_reported_num_rows_matches_rows_read[row_level_filter]          <- cause 2
FAILED test_pushdown_does_not_inherit_stale_plan_files[predicate]           <- cause 2
FAILED test_pushdown_does_not_inherit_stale_plan_files[predicate_then_...]  <- cause 2
FAILED test_reported_num_rows_is_unknown_when_scan_stops_early              <- cause 2
FAILED test_empty_projection_respects_pinned_snapshot_schema                <- cause 1
FAILED test_read_iceberg_does_not_mutate_caller_kwargs                     <- dict mutation
10 failed, 60 passed

$ pytest python/ray/data/tests/datasource/test_iceberg.py     # WITH the fix
70 passed
```

Environment: macOS, Python 3.12, ray 2.56.1 with the two changed files
applied,
pyiceberg 0.11.1, pyarrow 25.0.0. `ruff check` and `black --check` are
clean on
both changed files.

The 10 pre-fix failures are exactly the 10 new tests targeting these
bugs, and the
other 6 new tests pass in both runs — including the UDF-filter control
and the
partition-filter metadata case, so the fix is pinned as not having
achieved its
result by disabling pushdown or by abandoning the free count. No
pre-existing
test changes behaviour either way.

### Implementation notes

- **Overlap with ray-project#65042.** That PR rewrites `size_bytes` in the same
`BlockMetadata(...)` construction where this PR rewrites `num_rows`, so
whichever merges second hits a textual conflict. The changes are
independent —
  the resolution is to keep both. ray-project#65042 also derives its estimate from
`projected_field_ids`, which this PR changes for the empty-projection
case (one
sentinel column rather than none); that is the correct input, since the
sentinel is genuinely all the read fetches, but worth being aware of.
ray-project#64811
and ray-project#64813 touch nearby lines in `get_read_tasks` / `_get_read_task` and
may
  conflict textually too.
- **The exactness test matches PyIceberg's own.** `DataScan.count()`
decides the
same way — `task.residual == AlwaysTrue() and not task.delete_files`
means take
`record_count`, otherwise read the file — so this reuses the library's
own
  notion of when a manifest count still holds rather than inventing one.
- **Equality deletes are not a third instance of this bug**, despite the
`record_count - position_delete_count` arithmetic ignoring them:
PyIceberg
raises `NotImplementedError` on equality deletes before a miscount could
  occur.

<details>
<summary>Repro script — no cluster or cloud access needed, exits
non-zero on failure</summary>

```python
"""Reproduce three ways ``Dataset.count()`` returns a wrong row count on an
Iceberg dataset.

    pip install "ray[data]" pyiceberg sqlalchemy
    python repro_iceberg_count.py
"""

import logging
import pathlib
import tempfile
import warnings

import pyarrow as pa
from pyiceberg.catalog.sql import SqlCatalog
from pyiceberg.expressions import LessThan
from pyiceberg.schema import Schema
from pyiceberg.types import LongType, NestedField, StringType

warnings.filterwarnings("ignore")

N_ROWS = 100
THRESHOLD = 10  # number of rows with id < THRESHOLD


def make_table():
    """Create a temporary Iceberg table with N_ROWS rows; return its catalog kwargs."""
    tmp = tempfile.mkdtemp()
    warehouse = pathlib.Path(tmp) / "wh"
    warehouse.mkdir()
    catalog = SqlCatalog(
        "local", uri=f"sqlite:///{tmp}/c.db", warehouse=f"file://{warehouse}"
    )
    catalog.create_namespace("db")
    table = catalog.create_table(
        "db.t",
        schema=Schema(
            NestedField(1, "id", LongType(), required=False),
            NestedField(2, "country", StringType(), required=False),
        ),
    )
    table.append(
        pa.table(
            {
                "id": pa.array(range(N_ROWS), pa.int64()),
                "country": pa.array(["US"] * N_ROWS, pa.string()),
            }
        )
    )
    return {
        "name": "local",
        "uri": f"sqlite:///{tmp}/c.db",
        "warehouse": f"file://{warehouse}",
    }


def main():
    catalog_kwargs = make_table()

    import pyiceberg
    import ray
    from ray.data.expressions import col

    ray.init(
        num_cpus=4, include_dashboard=False, log_to_driver=False, logging_level="error"
    )
    logging.getLogger("ray").setLevel(logging.ERROR)
    logging.getLogger("ray.data").setLevel(logging.ERROR)
    ray.data.DataContext.get_current().enable_progress_bars = False

    print(
        f"ray {ray.__version__}   pyiceberg {pyiceberg.__version__}   "
        f"pyarrow {pa.__version__}"
    )
    print(f"\ntable has {N_ROWS} rows; {THRESHOLD} of them have id < {THRESHOLD}\n")

    def base():
        return ray.data.read_iceberg(
            table_identifier="db.t", catalog_kwargs=dict(catalog_kwargs)
        )

    def read_with_row_filter():
        return ray.data.read_iceberg(
            table_identifier="db.t",
            catalog_kwargs=dict(catalog_kwargs),
            row_filter=LessThan("id", THRESHOLD),
        )

    cases = [
        ("read_iceberg().count()", base, N_ROWS),
        (
            "select_columns(['country']).count()",
            lambda: base().select_columns(["country"]),
            N_ROWS,
        ),
        (
            "filter(col('id') < 10).count()",
            lambda: base().filter(expr=col("id") < THRESHOLD),
            THRESHOLD,
        ),
        (
            "filter(lambda r: r['id'] < 10).count()",
            lambda: base().filter(lambda r: r["id"] < THRESHOLD),
            THRESHOLD,
        ),
        (
            "filter(col('id')<10).select_columns(['country']).count()",
            lambda: base()
            .filter(expr=col("id") < THRESHOLD)
            .select_columns(["country"]),
            THRESHOLD,
        ),
        ("read_iceberg(row_filter=id<10).count()", read_with_row_filter, THRESHOLD),
        (
            "select_columns(['country']).materialize().count()",
            lambda: base().select_columns(["country"]).materialize(),
            N_ROWS,
        ),
    ]

    print(f"{'query':56s} {'count()':>8s} {'truth':>6s}  verdict")
    print("-" * 88)
    failures = 0
    for label, make_ds, truth in cases:
        reported = make_ds().count()
        actual_rows = len(make_ds().take_all())  # independent ground truth
        if reported == truth:
            verdict = "ok"
        else:
            verdict = f"WRONG (take_all() yields {actual_rows})"
            failures += 1
        print(f"{label:56s} {reported:8d} {truth:6d}  {verdict}")

    print(f"\n{failures} of {len(cases)} queries report a wrong count.")
    return 1 if failures else 0


if __name__ == "__main__":
    raise SystemExit(main())
```

</details>

AI assistance was used for this change.

---------

Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
*I used CODEX to analyze this problem and create this PR. I've reviewed
the code and tests and stand by them. This summary is written completely
by a human (me) other than very light copy editing by an LLM.*

Currently `_generate_tables()` scans all files associated with the
`FileScanTask`s to produce one Arrow table and then yields the results
in batches. The implication is that the memory consumption is what's
needed to process all FileScanTasks at once.

This change processes one `FileScanTask` at a time and yields the result
in batches. This reduces the memory consumption to a function of the
largest requirement for any single FileScanTask.

This can be a meaningful benefit at scale when multiple files are
processed per Ray task.

UPDATE: @abhishekverma-ray points out in a comment that this subtly
changes the PyArrow field data type, with respect to width of offsets.
Before, the use `to_table()` allowed for promotion to `large_string /
large_list` when needed. But with this PR's use of `to_record_batches()`
that needs to always happen. An alternative idea would be to keep using
`to_table` but yield back results at the file level. That reduces the
memory footprint relative to the current behavior, which processes all
files at once, but take more memory than the current approach in this PR
which is to yield back at the batch level.

I will defer to the guidance of the project maintainers on what the best
tradeoff is here between the memory and the breaking(?) change of the
returned types.

CODEX generated summary follows:
-----
Ray's Iceberg reader passes every `FileScanTask` assigned to a Ray read
task into one PyIceberg `ArrowScan`. PyIceberg materializes the files in
its executor before Ray can consume the resulting batches, so transient
worker memory scales with the number and size of files assigned to that
task. In our production-shaped workload, workers OOMed before downstream
processing made meaningful progress.

By default, this change calls PyIceberg's public `to_record_batches()`
API separately for each `FileScanTask`. That bounds the Ray task's
high-water mark to one file, preserves the task-wide row limit, and
casts every result to the projected Iceberg schema so blocks do not
alternate between small- and large-offset Arrow types. PyIceberg still
materializes a complete file before Ray receives its batches, so this is
a file-level—not batch-level—memory bound.

`DataContext.iceberg_config.read_file_tasks_sequentially` defaults to
`True` for that bounded behavior. Setting it to `False` restores the
prior `to_table(tasks=tasks)` path, including PyIceberg's within-task
cross-file parallelism and shared delete-file reuse. Disable it when a
task has many small files, their combined input comfortably fits in
memory, and throughput matters more than the memory bound.

## Results

A local six-file Iceberg benchmark scanned 12 million rows: two million
rows per file with eight random `int64` columns. Peak process memory
fell from 1.855 GiB to approximately 650 MiB, a 65% reduction (2.85x
lower), with the same output rows and no measurable hot-cache slowdown.

As an end-to-end validation, the original reader OOMed after roughly 242
completed read tasks. The bounded reader, combined with an explicit 5
GiB Ray task-memory reservation, reached 2,343 completed reads with zero
failures; peak worker-node memory was 102.5/160 GiB. The local benchmark
isolates this code change; the cluster result validates the reader
together with separate scheduling configuration.

## Testing

- `/Users/aniskodedossett/development/ray/.venv/bin/pytest -q
python/ray/data/tests/datasource/test_iceberg.py -k 'get_read_task or
read_basic'` — 5 passed, 52 deselected
- `pre-commit run --files
python/ray/data/_internal/datasource/iceberg_datasource.py
python/ray/data/context.py
python/ray/data/tests/datasource/test_iceberg.py` — passed
- `git diff --check` — passed

I searched open `ray-project/ray` pull requests for Iceberg memory,
`read_iceberg` memory, and `ArrowScan` Iceberg changes and found no
active duplicate.

AI assistance was used to investigate, implement, test, benchmark, and
draft this PR. The submitter must review every changed line and validate
the results before requesting upstream review.

---------

Signed-off-by: Aaron Niskode-Dossett <[email protected]>
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 go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants