Skip to content

[Data] Better estimate decoded Iceberg read size - #65042

Merged
richardliaw merged 1 commit into
ray-project:masterfrom
dossett:iceberg-read-size-estimate
Aug 19, 2026
Merged

richardliaw merged 1 commit into
ray-project:masterfrom
dossett:iceberg-read-size-estimate

Conversation

@dossett

@dossett dossett commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

I used CODEX to create this PR, and I stand by it. This summary is mine.

Previously, Iceberg read planning used the raw total file size as its in-memory size estimate. For Parquet data, this change estimates decoded in-memory size using Ray's standard 5× encoding ratio. When complete projected-column metrics are available in the Iceberg manifest, it applies that ratio only to the projected columns; otherwise it uses a 5× whole-file estimate. Consequently, unprojected Parquet reads now estimate 5× the encoded file size rather than 1×.

Since this data is present in the Iceberg manifests there are no additional file operations required for this, such as opening file footers. So planning accuracy improves with no material cost.

Codex summary follows:

Summary

  • Use complete Iceberg column_sizes metrics for projected top-level Parquet fields.
  • Apply Ray's existing Parquet decode-ratio estimate to the selected encoded bytes.
  • Fall back to a 5× whole-file estimate when projected metrics are incomplete or unavailable.
  • Preserve non-Parquet behavior and report an empty projection as zero bytes.
  • Use the same estimate for datasource sizing and ReadTask metadata.

Testing

  • bazel test //python/ray/data:test_iceberg — passed.
  • Focused estimator tests in test_iceberg.py — 8 passed, 54 deselected.
  • File-scoped pre-commit hooks — passed.
  • git diff --check origin/master...HEAD — passed.

AI assistance was used for investigation, implementation, testing, and drafting this description. This upstream PR is a draft for human line-by-line review before requesting review.

Duplicate-work check

No open ray-project/ray issue or PR was found for projection-aware Iceberg decoded-size estimation. Searches for Iceberg decoded-size estimation, column_sizes, and Iceberg memory estimation returned no overlapping work.

@dossett dossett changed the title [Data] Estimate decoded Iceberg read size [Data] Better estimate decoded Iceberg read size Jul 27, 2026
@dossett
dossett marked this pull request as ready for review July 27, 2026 17:11
@dossett
dossett requested a review from a team as a code owner July 27, 2026 17:11

@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 improves the in-memory data size estimation for Iceberg tables by using projected column sizes and applying Ray's default Parquet decoding ratio. It also adds comprehensive unit tests to verify the size estimation logic under various scenarios. The review feedback suggests improving the robustness of the file format matching by handling case sensitivity and adding defensive null checks for column sizes to prevent potential runtime errors.

else:
on_disk_size = data_file.file_size_in_bytes

return int(on_disk_size * PARQUET_ENCODING_RATIO_ESTIMATE_DEFAULT)

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.

Thanks for this — the core idea is a genuinely good one.

However, hardcoding the ratio bypasses DataContext.decoding_size_estimation
With your changes, toggling decoding_size_estimation would silently affect Parquet and Delta but not Iceberg.

PARQUET_ENCODING_RATIO_ESTIMATE_DEFAULT is the fallback in _estimate_files_encoding_ratio — it's only returned when decoding_size_estimation is off.

That flag defaults to True, so the Parquet path (and therefore read_delta) normally samples 2–10 files, decodes ~1024 rows from each, and derives the actual ratio.

The gap between the two can be large. For example, on a string-heavy table I get:

INFO parquet_datasource.py -- Estimated parquet encoding ratio is 36.505.

vs. the assumed 5 — a ~7× under-estimate, in the OOM direction. Conversely, compact numeric data often lands nearer 1.5×, where 5 over-reserves.

Would you consider routing through the same helper so the ratio is measured and the flag keeps one meaning across formats? Iceberg is actually in the best position for this: with per-column sizes from the manifest and a measured ratio you'd get both halves right, where Parquet/Delta today gets only the ratio.

Worth saying explicitly: on projection awareness this PR puts Iceberg ahead of the Parquet/Delta path, which still does sum(file_size) * ratio. That's a good direction — I'd just like the two to converge rather than diverge on the ratio.

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.

Check the avg_value_size_in_bytes hint mentioned in the spec

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@abhishekverma-ray Funny you should mention that! I originally did implement this with _estimate_files_encoding_ratio but as I reviewed the parquet implementation more I saw that ParquetDatasourceV2 chose to just go with the single ratio in lieu of any more detailed sampling (see also description of #62182).

I would much prefer that since my production data is quite different that 5x. If I misunderstood the ParquetDatasourceV2 direction, I'm happy to change my approach.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@abhishekverma-ray avg_value_size_in_bytes is part of the Iceberg v4 spec as I understand it, which is not yet released. When v4 is available stats like that will be great to use.

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.

Thanks @dossett — I rechecked the current direction, and you’re right that my comment was based on the legacy Parquet datasource. use_datasource_v2 now defaults to true, and the V2 estimator intentionally uses the fixed 5× ratio to avoid sampling overhead. I’m therefore fine treating configurable/measured ratios as a broader follow-up rather than blocking this PR.

You’re also right about avg_value_size_in_bytes: it is part of the still-unadopted V4 content-stats work, so it isn’t usable here today.

Two things before approval:

Could you correct the PR description? The previous Iceberg implementation did not multiply the complete file size by 5×; it returned raw file bytes. This PR therefore also changes unprojected Parquet estimates from 1× to 5×, which should be called out explicitly.

Both microcheck and premerge are currently failing. Could you fix them and get them green?

Once the description and CI are addressed, this looks good to me.

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-read-size-estimate branch from 63ba775 to b2e4636 Compare August 18, 2026 17:52
@richardliaw richardliaw added the go add ONLY when ready to merge, run all tests label Aug 18, 2026

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

@dossett
dossett force-pushed the iceberg-read-size-estimate branch from 25aa062 to c9dfa4a Compare August 19, 2026 14:06

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Fix All in Cursor

Reviewed by Cursor Bugbot for commit c9dfa4a. Configure here.

@richardliaw
richardliaw enabled auto-merge (squash) August 19, 2026 20:51
Signed-off-by: Aaron Niskode-Dossett <[email protected]>
auto-merge was automatically disabled August 19, 2026 22:13

Head branch was pushed to by a user without write access

@dossett
dossett force-pushed the iceberg-read-size-estimate branch from fcdfec1 to e81f1a5 Compare August 19, 2026 22:13
@richardliaw
richardliaw merged commit 106674b into ray-project:master Aug 19, 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 create this PR, and I stand by it. This summary is
mine._

Previously, Iceberg read planning used the raw total file size as its
in-memory size estimate. For Parquet data, this change estimates decoded
in-memory size using Ray's standard 5× encoding ratio. When complete
projected-column metrics are available in the Iceberg manifest, it
applies that ratio only to the projected columns; otherwise it uses a 5×
whole-file estimate. Consequently, unprojected Parquet reads now
estimate 5× the encoded file size rather than 1×.

Since this data is present in the Iceberg manifests there are no
additional file operations required for this, such as opening file
footers. So planning accuracy improves with no material cost.


Codex summary follows:
-----
### Summary

- Use complete Iceberg `column_sizes` metrics for projected top-level
Parquet fields.
- Apply Ray's existing Parquet decode-ratio estimate to the selected
encoded bytes.
- Fall back to a 5× whole-file estimate when projected metrics are
incomplete or unavailable.
- Preserve non-Parquet behavior and report an empty projection as zero
bytes.
- Use the same estimate for datasource sizing and `ReadTask` metadata.

### Testing

- `bazel test //python/ray/data:test_iceberg` — passed.
- Focused estimator tests in `test_iceberg.py` — 8 passed, 54
deselected.
- File-scoped pre-commit hooks — passed.
- `git diff --check origin/master...HEAD` — passed.

AI assistance was used for investigation, implementation, testing, and
drafting this description. This upstream PR is a draft for human
line-by-line review before requesting review.

### Duplicate-work check

No open `ray-project/ray` issue or PR was found for projection-aware
Iceberg decoded-size estimation. Searches for Iceberg decoded-size
estimation, `column_sizes`, and Iceberg memory estimation returned no
overlapping work.

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