Skip to content

[Data] Iceberg DSv2 [3/15]: Answer count() from Iceberg's own per-file row counts - #68437

Draft
AarryaSaraf wants to merge 2 commits into
iceberg-dsv2-parity-4-wirefrom
iceberg-dsv2-parity-5-count
Draft

AarryaSaraf wants to merge 2 commits into
iceberg-dsv2-parity-4-wirefrom
iceberg-dsv2-parity-5-count

Conversation

@AarryaSaraf

@AarryaSaraf AarryaSaraf commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Under the V2 reader, count() takes each file's row count from Iceberg's manifests (record_count) instead of decoding the file. It decodes only the files where that count could be wrong. 3 of 15 in the stack moving read_iceberg onto Datasource V2 (#66181), on top of [2/15]. V1 already counts from record_count, so this restores parity.

Before

With [2/15]'s V2 reader, count() decodes every data file it lists.

After

  1. The reader reports per-file row counts. Files: _internal/datasource_v2/formats/iceberg/iceberg_file_reader.py.
    • IcebergFileReader implements SupportsMetadata.read_metadata. A file reports its record_count when it has no delete files and its residual is AlwaysTrue. The residual is the part of the filter the file's partition values don't already satisfy.
    • Any other file is decoded and counted, as PyIceberg's own count() does. A pushed limit turns the whole path off.
    • A residual is trusted only when every operator in the filter treats null the same way in Iceberg and in PyArrow. Example: on a table partitioned by c with rows c = [3, null, 4], c != 3 reads 1 row. Iceberg still gives the null partition's file an AlwaysTrue residual, so trusting it would count 2.
  2. The scanner says when the count is exact. Files: iceberg_scanner.py. metadata_row_count_is_exact is true unless a limit is pushed.
  3. The indexer serves the count path as it is. Files: iceberg_file_indexer.py. as_whole_file_indexer returns self, because Ray's count rule needs one row per file and no per-file IO while listing, and Iceberg's listing already does both.

V1 has the same record_count shortcut without the null check (_internal/datasource/iceberg_datasource.py), so it likely overcounts the example above. That isn't measured, and it's a separate fix.

flowchart TD
    subgraph Before
        subgraph BS["Subsystem: IO (formats/iceberg/)"]
            B1["count()"] --> B2["IcebergFileReader.read<br/>decode every file"]
        end
    end
    subgraph After
        subgraph AS["Subsystem: IO (formats/iceberg/)"]
            A1["count()"] --> A2{"IcebergFileReader.read_metadata<br/>no deletes, AlwaysTrue residual,<br/>null-safe filter?"}
            A2 -->|yes| A3["record_count from the manifest"]
            A2 -->|no| A4["decode the file"]
        end
    end
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    class A2,A3 added
Loading

Subsystems

IO (formats/iceberg/: reader, scanner, indexer).

Testing

pytest python/ray/data/tests/datasource/test_iceberg.py: 154 passed, 6 skipped at this PR's head (pyarrow 24.0.0, PyIceberg 0.11.1). New tests cover:

  • the count is answered from metadata;
  • a limit turns the metadata count off;
  • the null-partition case above agrees with the read;
  • deleted rows are subtracted.

ruff 0.8.4 (default and --select I), black 22.10.0, pydoclint 0.9.1 and pyrefly 0.51.0 (CI's environment) are clean.

Not a duplicate: apart from this stack, no open PR moves read_iceberg to Datasource V2. I searched open PRs with "iceberg" in the title on 2026-11-21; the only other one, #68252, fixes Iceberg writes on actor pools.

AI assistance (Claude Code) was used. I have reviewed every changed line and ran the tests above locally.

Signed-off-by: Aarrya [email protected]

🤖 Generated with Claude Code

@AarryaSaraf
AarryaSaraf added this pull request to stack #68450 November 21, 2026 23:17
… row counts

Iceberg writes each data file's record_count into its own manifests, and the
Iceberg listing task already carries that number through to the read tasks, so
Dataset.count() can be answered without decoding anything. This wires the
Iceberg reader into the existing PushdownCountFiles rule, which until now
declined on this source because both of its hooks default to "no".

Three overrides, one per hook the rule asks about:

- IcebergFileIndexer.as_whole_file_indexer() returns self. An Iceberg scan task
  names a whole file and is never split, so one file is always one manifest
  row, and planning reads table metadata only -- no per-file IO. The Parquet
  footer indexer has to return a different, plainer indexer because it emits
  one row per row-group run.

- IcebergScanner.metadata_row_count_is_exact() returns True unless a limit has
  been pushed in. A row filter is fine: Iceberg plans a residual per file --
  the part of the filter the file's partition values do not already satisfy --
  and the reader checks it per file. A limit is applied while reading and
  nothing in the metadata says where it stops.

- IcebergFileReader now mixes in SupportsMetadata. read_metadata() yields one
  BlockMetadata per file, taking num_rows straight from the manifest when the
  file's residual is AlwaysTrue and it has no delete files, and otherwise
  decoding the file to count it -- the same thing PyIceberg's own count() does,
  and necessary because record_count includes rows a delete file removes.

Net effect: an unfiltered count() reads no data at all. A Ray filter stays
above the read in this stack, so a filtered count() reads; read_iceberg's
row_filter still reaches Iceberg, and the reader checks each file's residual.

Tests: count() is answered without a ReadFiles and returns the delete-aware
answer; a limit still forces a read; read_metadata subtracts positionally
deleted rows while the manifest keeps the pre-delete count; and the reader
declines metadata under a limit independently of the scanner. The filtered
count() test waits for filter pushdown in the next stack.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@AarryaSaraf
AarryaSaraf force-pushed the iceberg-dsv2-parity-5-count branch from b8ad65f to 74d7f4d Compare November 24, 2026 01:24
@AarryaSaraf AarryaSaraf changed the title [Data] Iceberg DSv2 [2/14]: Answer count() from Iceberg's own per-file row counts [Data] Iceberg DSv2 [3/15]: Answer count() from Iceberg's own per-file row counts Nov 24, 2026
@AarryaSaraf
AarryaSaraf removed this pull request from stack #68450 November 24, 2026 01:50
@AarryaSaraf
AarryaSaraf added this pull request to stack #68499 November 24, 2026 01:51
for task in scan_tasks_from_manifest(manifest=file_manifest):
if (
trust_residuals
and isinstance(task.residual, AlwaysTrue)

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.

count() returns too many rows when the REST catalog plans the scan (#68498).

The REST spec makes a task's residual-filter optional: "If the residual is not present, the client must produce the residual or use the original filter." PyIceberg 0.11 sets a missing residual to AlwaysTrue instead (FileScanTask.from_rest_response). So this check takes record_count for files whose rows the filter still has to check.

I ran it with the fake REST catalog from #68498, which sends no residual, and row_filter=GreaterThanOrEqual("col_a", <median of the planned file>):

RowMatchCheck.every_row_matches later in the stack has the same problem, and [10/15] uses it to stop listing early for limit().

Suggested fix: when the listing planned on the server, replace an AlwaysTrue residual with the scan's row_filter (unless row_filter is itself AlwaysTrue) before writing the manifest. Test: the fake-server read with that filter, asserting count() == len(take_all()).

V1 has the same bug (counts_are_exact in iceberg_datasource.py). The same run gave 6 rows read and count() = 11 on V1.

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.

Fixed. When the REST catalog plans the scan, the listing now works out each file's residual from its partition values, as local planning does, instead of PyIceberg's AlwaysTrue. The spec sends dates and timestamps as strings, so those are converted first, and anything that can't be evaluated falls back to the whole filter. Added your count() == len(take_all()) test through the fake server, plus a day(ts) residual test. V1 is unchanged.

The number of rows the task yields after filters and deletes.
"""
return sum(
batch.num_rows for batch in self._scan(None).to_record_batches([task])

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.

count() returns 0 for data files that don't store their identity-partition column. These are Hive tables migrated with Spark migrate, snapshot or add_files, which the Iceberg spec allows.

Counting by reading projects only the stub field. PyIceberg fills a missing partition column from the partition value only for fields in the projected schema, so a filter on that column sees null and drops every row. PyIceberg's own DataScan.count() projects the scan's schema and gets it right.

Repro: a table partitioned by identity col_c, with one file holding only col_a/col_b, partition col_c=2, col_a=[1,2,3].

  • row_filter=And(EqualTo("col_c", 2), GreaterThan("col_a", 1)): take_all = 2, count() = 0 (V1 also 0), PyIceberg count() = 2.
  • EqualTo("col_c", 2) plus a position-delete file on that data file: take_all = 2, V1 count() = 2, V2 count() = 0. It's already 0 at [Data] Iceberg DSv2 [2/15]: Route read_iceberg through Datasource V2 #68436, which counts through the same stub projection.

Suggested fix: when counting by reading, project the fields the row filter uses (or the scan's projection), not just the stub.

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.

Fixed.

# bin-packed read unit. The Parquet reader batches to bound how many
# footers one task fetches; here the counts are in the manifest, so
# there is no per-file IO to spread out.
return None

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.

When count() has to decode files, it runs one task per listing block (up to 1024 files) instead of in parallel. PushdownCountFiles drops the partitioner, so MapBatches(count_rows) gets the raw listing blocks. With None here, each block is one task that decodes its files one after another. That covers every file with delete files and every file under a filter on a data column, != or NOT IN.

Repro: 8 files, row_filter=col_a >= 0, RAY_DATA_ICEBERG_BIN_PACKING_BYTES=1000. take_all() runs 8 ReadFilesIcebergV2 tasks; count() runs 1 MapBatches(count_rows) task. At #68436 the same count() ran 8 read tasks.

Could this return a small batch size, or pack the files that need decoding?

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.

Fixed.

@abhishekverma-ray abhishekverma-ray self-assigned this Nov 24, 2026
…ts partition values

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants