Skip to content

Allow for serialization of Parquet Page Index via custom PageIndexProvider - #11031

Merged
etseidl merged 12 commits into
apache:mainfrom
etseidl:page_index_serialization
Sep 24, 2026
Merged

etseidl merged 12 commits into
apache:mainfrom
etseidl:page_index_serialization

Conversation

@etseidl

@etseidl etseidl commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

See issue, but allow for serialization of the page indexes through the PageIndexProvider API.

What changes are included in this PR?

Changes ThriftMetadataWriter to operate through the PageIndexProvider API rather than using individual column and offset index vectors. Removes some now unnecessary pub(crate) functions.

Are these changes tested?

Yes

Are there any user-facing changes?

All page indexes will now serialize, but no changes to the public API

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

@etseidl this is an AI assisted review, I spent time coaching the agent on what to look for and discussing some of the findings, but the final text is largely AI generated. Let me know if you think it's not useful and I will change strategies.

Reviewed at 60e4b4cb. A complete custom provider now round-trips through ParquetMetaDataWriter (verified; the same test fails on main). Two items need a decision before merge: a partial provider writes metadata that cannot be read back (A1), and SerializedFileWriter now copies the full page index each time it closes a file (A2).

id severity summary where
A1 Bug Chunks that the provider does not return keep their index offsets from the source file. The output fails to read back with the page index. inline metadata/writer.rs L101, L145
A2 Perf write_*_indexes clone every index into a new dense copy. For SerializedFileWriter this is a regression: on main the vectors were moved. inline metadata/writer.rs L76
A3 Test gap The guard in ParquetMetaDataWriter::finish has no effect, but a || → && mutant there survives all tests. inline metadata/writer.rs L473
A4 Test gap No test writes a custom provider with ParquetMetaDataWriter. That is the feature of this PR. body
A5 Docs The PR removes the warning, but adds no statement that custom providers are now serialized. inline metadata/writer.rs L351
A6 Nit is_empty() || all(..): the is_empty() check is redundant. inline file/writer.rs L382
P4 Bug (pre-existing) A1 also occurs when a full structure is absent. The A1 fix does not cover this case. body

A1 / P4: where the stale offsets come from

flowchart LR
  S["source file<br/>page index at 3184..3394"] --> R["ParquetMetaData<br/>offsets into source file"]
  R --> P["provider:<br/>column 0 only"]
  P --> W["ParquetMetaDataWriter"]
  W --> O["890 B buffer<br/>col 0: new offsets<br/>col 1, 2: 3207.. (stale)"]
  O --> X["read with page index:<br/>EOF, range 0..3394 > 890 B"]
Loading

P4 (pre-existing, same output on main). With the A1 suggestion applied, the writer still copies the offsets of a structure that is absent from the provider:

input metadata written read back with page index
reader: column index Required, offset index Skip column index only EOF: Range 0..3394 is beyond file bounds 959
reader: no page index nothing EOF: Range 3184..3394 is beyond file bounds 824

These offsets are correct only when the output is appended to the source file (footer rewrite). Please decide: clear them also, or document that the writer copies them unchanged.

A4: tests to add

Both tests pass on this PR. On main, the first test fails with EOF("Parquet file too small. Page index range 82..115 overlaps with file metadata 0..357"). The second test kills the A3 mutant. They go next to test_metadata_read_write_roundtrip_page_index in parquet/src/arrow/mod.rs and use its helpers.

Test code (rustfmt clean)
    #[test]
    fn test_metadata_read_write_roundtrip_custom_page_index() {
        use crate::file::metadata::page_index::PageIndexProvider;
        use crate::file::page_index::{
            column_index::ColumnIndexMetaData, offset_index::OffsetIndexMetaData,
        };

        /// A custom provider that forwards to another provider
        #[derive(Debug)]
        struct Forward(Arc<dyn PageIndexProvider>);
        impl PageIndexProvider for Forward {
            fn has_offset_indexes(&self) -> bool {
                self.0.has_offset_indexes()
            }
            fn has_column_indexes(&self) -> bool {
                self.0.has_column_indexes()
            }
            fn column_index(&self, rg: usize, col: usize) -> Option<&ColumnIndexMetaData> {
                self.0.column_index(rg, col)
            }
            fn offset_index(&self, rg: usize, col: usize) -> Option<&OffsetIndexMetaData> {
                self.0.offset_index(rg, col)
            }
            fn as_any(&self) -> &dyn std::any::Any {
                self
            }
        }

        let read = |bytes: &Bytes| {
            let options = ParquetMetaDataOptions::new().with_encoding_stats_as_mask(false);
            ParquetMetaDataReader::new()
                .with_metadata_options(Some(options))
                .with_page_index_policy(PageIndexPolicy::Required)
                .parse_and_finish(bytes)
                .unwrap()
        };
        let original = read(&create_parquet_file());
        let provider = Forward(original.page_index().unwrap().clone());
        let custom = original
            .clone()
            .into_builder()
            .set_page_index(Some(Arc::new(provider)))
            .build();
        let roundtrip = read(&metadata_to_bytes(&custom));
        assert_eq!(
            normalize_locations(original),
            normalize_locations(roundtrip)
        );
    }

    #[test]
    fn test_metadata_read_write_roundtrip_offset_index_only() {
        // `Chunk` statistics: the file has an offset index, but no column index
        let array: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
        let batch = RecordBatch::try_from_iter(vec![("id", array)]).unwrap();
        let props = WriterProperties::builder()
            .set_statistics_enabled(EnabledStatistics::Chunk)
            .build();
        let mut buf = vec![];
        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), Some(props)).unwrap();
        writer.write(&batch).unwrap();
        writer.close().unwrap();

        let read = |bytes: &Bytes| {
            let options = ParquetMetaDataOptions::new().with_encoding_stats_as_mask(false);
            ParquetMetaDataReader::new()
                .with_metadata_options(Some(options))
                .with_page_index_policy(PageIndexPolicy::Optional)
                .parse_and_finish(bytes)
                .unwrap()
        };
        let original = read(&Bytes::from(buf));
        let page_index = original.page_index().unwrap();
        assert!(!page_index.has_column_indexes() && page_index.has_offset_indexes());
        let roundtrip = read(&metadata_to_bytes(&original));
        assert_eq!(
            normalize_locations(original),
            normalize_locations(roundtrip)
        );
    }

A partial provider variant of the first test fails today with the A1 error. It passes with the A1 suggestion.

Pre-allocation

No growth issue. PageIndexBuilder::empty_index allocates exactly row groups × columns, and SerializedRowGroupWriter uses Vec::with_capacity(num_columns). The cost is the copy itself (A2).

How this was checked

Scratch tests on 60e4b4cb and on the merge base e3a21bf4 (the three changed files are the same on main). The --lib, arrow_reader, arrow_writer and encryption tests pass with the inline suggestions applied. They also pass with the A2 sketch plus the A1 change.

Comment thread parquet/src/file/metadata/writer.rs Resolved
Comment thread parquet/src/file/metadata/writer.rs Outdated
Comment on lines 101 to 102
offidx_vec[row_group_idx][column_idx] = Some(offset_index.clone());
}

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.

Bug (A1). If the provider has no offset index for a chunk, the chunk keeps offset_index_offset/length from the input metadata. These offsets point into the source file, not into the new buffer. A partial provider (for example Example 2 in examples/custom_page_index.rs) writes metadata that fails to read back:

source file 4386 B; provider returns column 0 only (custom provider or PageIndexBuilder)
written metadata: 890 bytes
  rg0 col0: column_index_range=Some(0..23)      offset_index_range=Some(46..58)
  rg0 col1: column_index_range=Some(3207..3230) offset_index_range=Some(3334..3346)  <- source file
read back with page index: Err(EOF: Parquet file too small. Range 0..3394 is beyond file bounds 890)

With this suggestion (and the same change at L145), col 1 and col 2 have no index ranges and the read back is Ok. On main, a partial PageIndex fails the same way, so this is not a regression. But custom providers are usually partial, so this PR is the right place to fix it.

Trade-off: clearing removes offsets that are still correct only when the output is appended to the source file. If that use matters, return an error instead.

Suggested change
offidx_vec[row_group_idx][column_idx] = Some(offset_index.clone());
}
offidx_vec[row_group_idx][column_idx] = Some(offset_index.clone());
} else {
// no offset index for this chunk: do not keep an offset into the source file
column_metadata.offset_index_offset = None;
column_metadata.offset_index_length = None;
}

Comment thread parquet/src/file/metadata/writer.rs Outdated
Comment on lines 145 to 146
colidx_vec[row_group_idx][column_idx] = Some(column_index.clone());
}

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.

Bug (A1, continued). Same change for the column index.

Suggested change
colidx_vec[row_group_idx][column_idx] = Some(column_index.clone());
}
colidx_vec[row_group_idx][column_idx] = Some(column_index.clone());
} else {
// no column index for this chunk: do not keep an offset into the source file
column_metadata.column_index_offset = None;
column_metadata.column_index_length = None;
}

Comment thread parquet/src/file/metadata/writer.rs Resolved
Comment thread parquet/src/file/metadata/writer.rs Resolved
Comment thread parquet/src/file/writer.rs Resolved
@etseidl

etseidl commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @adriangb. It's taken me awhile to wrap my head around some of the points, but I largely agree with the findings. I think for P4 we should probably just loop through the cloned row group metadata and clear all offset/length pairs.

@etseidl

etseidl commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

@adriangb I think I've addressed everything, including the P4 case (which I added a test for).

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

Amazing, thank you!

I don't have rights in this repo so this is a token approval, but LGTM!

@etseidl

etseidl commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

Uh oh. @adriangb I just remembered something. When we added the ParquetMetaDataWriter, I believe one use case was to externalize the footer metadata so it could be saved locally, while the original file lived elsewhere (in object store for instance). We wanted to keep the page index locations intact so they could be fetched from the original file. But the changes we just made clear them now. I think that's a behavior change we want to think through. Perhaps add a boolean to the writer to optionally clear them?

WDYT?

@adriangb

adriangb commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

It looks like we at least don't use the footer-only path. The arrow-rs example and the original caching use case both load the page index before writing, and as far as I can tell no one else requested it, and #6464 reports the leftover offsets as a bug.

I suggest that we keep the current behavior (always clear the locations that the writer did not write), add the breaking change label, and close #6464. Then we document two points on ParquetMetaDataWriter: to include the page index, load it before you write; to cache the footer only, store the raw footer bytes, which already contain the original offsets. This is simpler than a boolean, and the output is always self-consistent. If someone needs the old behavior later, we can add the option then. If needed we can break that out into a cleanup PR. Thoughts?

@etseidl

etseidl commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

suggest that we keep the current behavior (always clear the locations that the writer did not write), add the breaking change label, and close #6464. Then we document two points on ParquetMetaDataWriter: to include the page index, load it before you write; to cache the footer only, store the raw footer bytes, which already contain the original offsets. This is simpler than a boolean, and the output is always self-consistent. If someone needs the old behavior later, we can add the option then. If needed we can break that out into a cleanup PR. Thoughts?

Well, I've got too much work stacked on this PR to wait for the breaking API window to open again 😅. I think what I have now works; it keeps the current behavior, but allows for clearing the index info if desired. We can change the default behavior to clearing the indexes later. I think even as is, we might be able to close #6464. @alamb any thoughts on that score?

Comment thread parquet/src/arrow/mod.rs
}

#[test]
fn test_metadata_read_write_roundtrip_missing_page_index() {

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.

This reproduces the #6464 test above, but uses the new option to clear page index locations

@adriangb

Copy link
Copy Markdown
Contributor

suggest that we keep the current behavior (always clear the locations that the writer did not write), add the breaking change label, and close #6464. Then we document two points on ParquetMetaDataWriter: to include the page index, load it before you write; to cache the footer only, store the raw footer bytes, which already contain the original offsets. This is simpler than a boolean, and the output is always self-consistent. If someone needs the old behavior later, we can add the option then. If needed we can break that out into a cleanup PR. Thoughts?

Well, I've got too much work stacked on this PR to wait for the breaking API window to open again 😅. I think what I have now works; it keeps the current behavior, but allows for clearing the index info if desired. We can change the default behavior to clearing the indexes later. I think even as is, we might be able to close #6464. @alamb any thoughts on that score?

Sounds good to me!

@alamb

alamb commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

suggest that we keep the current behavior (always clear the locations that the writer did not write), add the breaking change label, and close #6464. Then we document two points on ParquetMetaDataWriter: to include the page index, load it before you write; to cache the footer only, store the raw footer bytes, which already contain the original offsets. This is simpler than a boolean, and the output is always self-consistent. If someone needs the old behavior later, we can add the option then. If needed we can break that out into a cleanup PR. Thoughts?

Well, I've got too much work stacked on this PR to wait for the breaking API window to open again 😅. I think what I have now works; it keeps the current behavior, but allows for clearing the index info if desired. We can change the default behavior to clearing the indexes later. I think even as is, we might be able to close #6464. @alamb any thoughts on that score?

As long as the repro in #6464 works now i think we can close it fr sure

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

Makes sense to me -- thank you @etseidl and @adriangb

Comment thread parquet/src/arrow/mod.rs
let custom = original
.clone()
.into_builder()
.set_page_index(Some(Arc::new(provider)))

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.

nice!

row_groups: Vec<RowGroupMetaData>,
column_indexes: Option<Vec<Vec<Option<ColumnIndexMetaData>>>>,
offset_indexes: Option<Vec<Vec<Option<OffsetIndexMetaData>>>>,
page_index: Option<Arc<dyn PageIndexProvider>>,

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.

👍

Comment thread parquet/src/file/metadata/writer.rs Outdated
offset_indexes: Vec<Vec<Option<OffsetIndexMetaData>>>,
) -> Self {
self.offset_indexes = Some(offset_indexes);
pub fn with_page_index(mut self, page_index: Arc<dyn PageIndexProvider>) -> Self {

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.

I always find the pub use in this crate confusing -- i think this is pub(crate) effectively -- could we mark it like that explicitly too?

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.

Will do. I found a similarly confusing pub in #11157. I'll have to do some issue hunting, but did we bring up adding lints to flag unnecessary pub visibility?

Comment thread parquet/src/file/metadata/writer.rs Outdated
}

/// Set whether or not to preserve the page index location metadata in the Thrift
/// `ColumnMetaData`.

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.

Suggested change
/// `ColumnMetaData`.
/// `ColumnMetaData` (defaults to `true`).

/// page indexes are not duplicated (for instance if the provided `ParquetMetaData`
/// returns no `PageIndexProvider`). As such, this defaults to `true`.
///
/// Set this to `false` to reset the location metadata if no page indexes are

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.

it took me a while to understand this but it makes sense now

The more we deal with PageIndexes the more I feel like it is strange that BloomFilters are not handled in a unified way (they aren't part of the ParquetMetadataReader API, etc)

That can be a probelm for another day though

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.

I agree, and that's next on my list once we're done fiddling with the page indexes 😄

to avoid confusion.
Also apply suggested fix to docs.
@etseidl

etseidl commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @adriangb and @alamb!

@etseidl

etseidl commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

I'm going to merge this as is and leave closing #6464 for another day. Perhaps when 61.0.0 approaches, we can flip the behavior to clearing the index locations by default, and make preserving them opt-in. Thanks again for the reviews!

@etseidl
etseidl merged commit 34060c4 into apache:main Sep 24, 2026
31 checks passed
@etseidl
etseidl deleted the page_index_serialization branch September 24, 2026 20:28
@Jefffrey Jefffrey added the enhancement New feature/addition label Sep 25, 2026
haohuaijin pushed a commit to haohuaijin/arrow-rs that referenced this pull request Sep 25, 2026
…ovider` (apache#11031)

# Which issue does this PR close?

- Closes apache#11030.

# Rationale for this change

See issue, but allow for serialization of the page indexes through the
`PageIndexProvider` API.

# What changes are included in this PR?

Changes `ThriftMetadataWriter` to operate through the
`PageIndexProvider` API rather than using individual column and offset
index vectors. Removes some now unnecessary `pub(crate)` functions.

# Are these changes tested?

Yes

# Are there any user-facing changes?

All page indexes will now serialize, but no changes to the public API
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature/addition parquet parquet crate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ParquetMetaDataWriter silently omits page indexes from custom PageIndexProviders

4 participants