Skip to content

[Data] Deduplicate Iceberg read task state - #64811

Merged
richardliaw merged 2 commits into
ray-project:masterfrom
dossett:iceberg-shared-read-state
Aug 20, 2026
Merged

richardliaw merged 2 commits into
ray-project:masterfrom
dossett:iceberg-shared-read-state

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.

The problem I ran into was that with 50000 Iceberg read tasks the driver was serializing 50000 copies of the same information as it serialized the tasks into its object store. This PR replaces those copies with an ObjectRef to the same information in Ray's distributed object store and the workers fetch that data when needed.

This ended up being a meaningful performance gain in driver-side task construction and serialization at scale, see the benchmarking section below. In my production use case it reduced the Iceberg read-task construction and serialization from over an hour to less than one minute.

CODEX generated summary follows:

Large Iceberg scans currently serialize the same PyIceberg scan state into every Ray ReadTask. On a production-shaped scan with 50,000 read tasks, that repeated metadata prevented Ray from finishing task construction, delayed autoscaling indefinitely, and projected far beyond the head node's object-store capacity.

This change stores the immutable scan state once in Ray's object store. Each read task now carries only its file chunk and the shared ObjectRef; the worker resolves that reference before calling the existing Iceberg read implementation. Read semantics, planning, projection, filtering, and delete handling are unchanged.

Why this is not duplicate work

ray-project/ray#49054 fixed ray-project/ray#49107 by removing the datasource's self reference from each read closure. The replacement partial still captures table IO, full table metadata, the row filter, and the projected schema in every task. Searches of open PRs for that issue, IcebergDatasource.get_read_tasks, Iceberg ObjectRef, table_metadata, serialized Iceberg reads, and Iceberg object-store usage found no PR addressing that residual duplication. ray-project/ray#61753 touches this datasource for unrelated checkpoint filtering.

Benchmark

A controlled single-node benchmark isolated the driver-side work changed by this PR. It created a real local Iceberg table with 1,028 fields, projected 290 fields, and replicated a planned FileScanTask to produce different task counts. For each count, the benchmark constructed the ReadTasks and stored each with ray.put, matching plan_read_op.py. Object sizes were measured through get_local_object_locations.

The patched totals include both the serialized ReadTasks and the single shared-state object.

Read tasks Base object-store bytes Patched object-store bytes Reduction
100 30.45 MB 12.35 MB 59.5%
1,000 304.54 MB 122.40 MB 59.8%
5,000 1.523 GB 611.52 MB 59.8%

At 1,000 tasks, median task construction and serialization time across three runs fell from 2.55 seconds to 0.46 seconds, a 5.5x improvement.

The local fixture’s shared state was 117 KB, substantially smaller than the production workload’s metadata. It therefore demonstrates the scaling behavior without reproducing the production-sized state.

On the production-shaped scan, the serialized size of one read task fell from approximately 1.63 MiB to 106 KiB. The patched implementation constructed all 50,000 tasks in 50.10 seconds, submitted the reads, and allowed autoscaling to begin. The stock implementation did not finish task construction or submit a read. Iceberg planning remained approximately 100 seconds in both cases, as expected; this change targets task serialization and construction rather than file planning.

Tests

.venv/bin/pytest -q python/ray/data/tests/datasource/test_iceberg.py --tb=short
# 55 passed

PATH="$PWD/.venv/bin:/opt/homebrew/bin:/usr/bin:/bin" bazel test //python/ray/data:test_iceberg \
  --test_output=errors --nocache_test_results --action_env=PATH \
  --test_env=VIRTUAL_ENV="$PWD/.venv"
# PASSED

pre-commit run --files \
  python/ray/data/_internal/datasource/iceberg_datasource.py \
  python/ray/data/tests/datasource/test_iceberg.py
# All applicable hooks passed

AI assistance was used to investigate the bottleneck, prototype the change, implement the patch, and draft tests and this description. This PR is a draft pending the human submitter's line-by-line review before review is requested.

@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 optimizes the Iceberg datasource by storing shared read task state (such as table metadata and projected schema) once in the Ray object store via ray.put, rather than duplicating it across every individual read task. This prevents high overhead and potential spilling during large Iceberg scans. A new unit test has also been added to verify this sharing behavior. I have no feedback to provide.

@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]>
@dossett
dossett force-pushed the iceberg-shared-read-state branch from b9edad2 to 28e6bc5 Compare August 18, 2026 17:52
@abhishekverma-ray

Copy link
Copy Markdown
Contributor

Thanks @dossett —the new regression test addresses my concern. It now verifies both the serialized-size reduction using a real ReadTask and successful execution after resolving the shared state from the object store. The implementation looks sound to me.

The current Buildkite premerge run is still failing, so please rerun or confirm that failure is unrelated before merge.

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

Looks fine.

@dossett
dossett force-pushed the iceberg-shared-read-state branch 2 times, most recently from 200ef85 to 5b1c552 Compare August 19, 2026 22:10
Signed-off-by: Aaron Niskode-Dossett <[email protected]>
Signed-off-by: Aaron Niskode-Dossett <[email protected]>
@dossett
dossett force-pushed the iceberg-shared-read-state branch from 5b1c552 to 895ccb2 Compare August 19, 2026 23:21
@richardliaw
richardliaw merged commit 6e5aeb9 into ray-project:master Aug 20, 2026
6 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.*

The problem I ran into was that with 50000 Iceberg read tasks the driver
was serializing 50000 copies of the same information as it serialized
the tasks into its object store. This PR replaces those copies with an
`ObjectRef` to the same information in Ray's distributed object store
and the workers fetch that data when needed.

This ended up being a meaningful performance gain in driver-side task
construction and serialization at scale, see the benchmarking section
below. In my production use case it reduced the Iceberg read-task
construction and serialization from over an hour to less than one
minute.


CODEX generated summary follows:
-----
Large Iceberg scans currently serialize the same PyIceberg scan state
into every Ray `ReadTask`. On a production-shaped scan with 50,000 read
tasks, that repeated metadata prevented Ray from finishing task
construction, delayed autoscaling indefinitely, and projected far beyond
the head node's object-store capacity.

This change stores the immutable scan state once in Ray's object store.
Each read task now carries only its file chunk and the shared
`ObjectRef`; the worker resolves that reference before calling the
existing Iceberg read implementation. Read semantics, planning,
projection, filtering, and delete handling are unchanged.

## Why this is not duplicate work

[ray-project#49054](ray-project#49054)
fixed
[ray-project#49107](ray-project#49107)
by removing the datasource's `self` reference from each read closure.
The replacement partial still captures table IO, full table metadata,
the row filter, and the projected schema in every task. Searches of open
PRs for that issue, `IcebergDatasource.get_read_tasks`, Iceberg
`ObjectRef`, `table_metadata`, serialized Iceberg reads, and Iceberg
object-store usage found no PR addressing that residual duplication.
[ray-project#61753](ray-project#61753)
touches this datasource for unrelated checkpoint filtering.

## Benchmark
A controlled single-node benchmark isolated the driver-side work changed
by this PR. It created a real local Iceberg table with 1,028 fields,
projected 290 fields, and replicated a planned FileScanTask to produce
different task counts. For each count, the benchmark constructed the
ReadTasks and stored each with ray.put, matching plan_read_op.py. Object
sizes were measured through get_local_object_locations.

The patched totals include both the serialized ReadTasks and the single
shared-state object.

| Read tasks | Base object-store bytes | Patched object-store bytes |
Reduction |
| ---: | ---: | ---: | ---: |
| 100 | 30.45 MB | 12.35 MB | 59.5% |
| 1,000 | 304.54 MB | 122.40 MB | 59.8% |
| 5,000 | 1.523 GB | 611.52 MB | 59.8% |

At 1,000 tasks, median task construction and serialization time across
three runs fell from 2.55 seconds to 0.46 seconds, a 5.5x improvement.

The local fixture’s shared state was 117 KB, substantially smaller than
the production workload’s metadata. It therefore demonstrates the
scaling behavior without reproducing the production-sized state.

On the production-shaped scan, the serialized size of one read task fell
from approximately 1.63 MiB to 106 KiB. The patched implementation
constructed all 50,000 tasks in 50.10 seconds, submitted the reads, and
allowed autoscaling to begin. The stock implementation did not finish
task construction or submit a read. Iceberg planning remained
approximately 100 seconds in both cases, as expected; this change
targets task serialization and construction rather than file planning.

## Tests

```text
.venv/bin/pytest -q python/ray/data/tests/datasource/test_iceberg.py --tb=short
# 55 passed

PATH="$PWD/.venv/bin:/opt/homebrew/bin:/usr/bin:/bin" bazel test //python/ray/data:test_iceberg \
  --test_output=errors --nocache_test_results --action_env=PATH \
  --test_env=VIRTUAL_ENV="$PWD/.venv"
# PASSED

pre-commit run --files \
  python/ray/data/_internal/datasource/iceberg_datasource.py \
  python/ray/data/tests/datasource/test_iceberg.py
# All applicable hooks passed
```

AI assistance was used to investigate the bottleneck, prototype the
change, implement the patch, and draft tests and this description. This
PR is a draft pending the human submitter's line-by-line review before
review is requested.

---------

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.

[Data] iceberg data source performance degradation when reading large table

3 participants