Skip to content

[WIP][POC][Parquet] Add PFOR encoding support - #10977

Draft
prtkgaur wants to merge 8 commits into
apache:mainfrom
prtkgaur:pfor-encoding
Draft

[WIP][POC][Parquet] Add PFOR encoding support#10977
prtkgaur wants to merge 8 commits into
apache:mainfrom
prtkgaur:pfor-encoding

Conversation

@prtkgaur

@prtkgaur prtkgaur commented Sep 3, 2026

Copy link
Copy Markdown

Which issue does this PR close?

  • Closes #NNN.

Rationale for this change

What changes are included in this PR?

Are these changes tested?

Are there any user-facing changes?

PFOR stores integers as a per-vector frame of reference plus bit-packed
residuals, with the values that do not fit the chosen width carried
separately and patched back after unpacking. A vector may also be
differenced first, which the encoder decides per vector.

The wire format is the one in parquet-format#579, so this is a second
reader and writer of one format rather than a second design:

* a page header giving the packing mode, the vector size, the value byte
  width and the element count, then a uint32 offset per vector;
* per vector, an info block holding the frame of reference, a width byte
  and a uint16 exception count, then the packed residuals, then the
  exception positions and their full-width values;
* bit 7 of the width byte is the differencing flag, leaving seven bits
  of width so that 64 is expressible; when it is set, a full-width start
  value sits between the info block and the residuals, which is what
  makes each differenced vector decodable on its own.

Three things are worth a reviewer's attention. The frame of reference is
searched rather than taken as the minimum, so a cluster with outliers
below it can be patched from both sides; the search is bucketed and
costs a fixed amount of work per vector, and it is seeded with the
minimum's exact cost so it cannot regress against it. The differencing
decision is gated by a sampled estimate, so a vector the mode cannot
help does not pay for it. And the decoder validates the whole offset
chain before any of it steers a read, so a page whose offsets overlap or
run backwards is rejected rather than decoded part-way.

Encoding::PFOR is 11; 10 is left for the separately proposed ALP
encoding. That hole is load-bearing: EncodingMask::ALLOWED_MASK has to
carve out bit 10, or a file claiming encoding 10 passes try_new and then
panics in i32_to_encoding.

get_encoder gains a private::GetEncoder trait specialised per value
type, mirroring the private::GetDecoder that decoding.rs already has,
because a flat match cannot express an encoding that exists only for
INT32 and INT64.
Add PFOR to the arrow_writer round-trip matrix for the integer types, and
cover two things the matrix cannot: that PFOR is the encoding that actually
lands in the column chunk metadata, and that a column of an unsupported
physical type is refused.
The corpus is the one the C++ implementation is measured on: 33 integer
columns from ClickBench, TPC-H, TPC-DS and the NYC taxi data, plus four
sorted or near-sorted shapes that separate the delta schemes from each
other. Each column is measured on encode and decode under both encodings,
and the sizes are printed once before the timings.

The generators draw from a different engine than the C++ ones, so the
values are not identical -- the distribution and the seed of each column
are what carry over.

An i64 leg covers the wide paths, over four of the same shapes scaled
until neither the values nor the frame of reference fit in 32 bits.
@github-actions github-actions Bot added the parquet Changes to the parquet crate label Sep 3, 2026
The benchmark compared PFOR with DELTA_BINARY_PACKED only, which answers what
PFOR costs against the other delta scheme but not what it costs against the two
ways an integer column is usually made smaller today: bit packing, and a general
purpose compressor over plain values.

Six arms now, on the same columns: the RLE/bit-packed hybrid at the column's own
bit width, DELTA_BINARY_PACKED, PFOR with differencing forbidden, PFOR with
differencing allowed, and plain values through lz4 and through zstd. Splitting
PFOR in two separates what the frame-of-reference search buys from what the
differencing mode buys, which the single arm could not show.

The compressor arms time the codec alone over a buffer already in memory, which
is what the C++ benchmark times, so their decode figure is bytes to bytes and
does not include producing values. The RLE arm is handed its bit width out of
band because the hybrid does not carry one, which is also how the C++ arm is set
up. Neither is an encoding a writer could choose for an integer column; they are
reference points.

The size table is now one row per column and one ratio per arm, with the arm that
produced the fewest bytes named at the end of the row.
Two CI gates fail on the sources added here, and neither shows up in the usual
local commands.

`cargo fmt -p parquet` never reaches these files. The `encodings` module is
declared inside the `experimental!` macro, and rustfmt cannot descend into a
module declaration produced by a macro, so every file under it is invisible to a
plain format run. CI formats the crate by naming each file with
`skip_children=true`, which does reach them; that is the command that flagged the
twenty sites reflowed here.

The docs job builds with `--document-private-items` and `-Dwarnings`, which makes
a link from public documentation to a private item an error rather than a
warning. `PforDecoder`'s type-level comment linked to its own private buffer
field, so the sentence now names the buffer in prose instead.
Four comments buried their subject behind "there is" or "there are", and one
opened with a bare "This". Each now names the thing it is about.
Drop `bits_required`, which duplicated `bit_util::num_required_bits` --
a function six other places in this crate already import -- along with a
test that duplicated bit_util's own, assertion for assertion.

Confine `encodings::pfor` to the crate, leaving public only the one
trait a benchmark names, and replace the two glob imports of it with
explicit lists. Both changes are about being told things: a glob hides
where a name comes from, and a `pub` item inside a `doc(hidden)` module
is still public, so `dead_code` could not report one going unused.

Split `decode_vector` into the phases the format lays out. A
`VectorLayout` now reads the info block and checks every wire-derived
size once, where the offset arithmetic used to be recomputed further
down; `unpack_residuals`, `patch_exceptions`, `accumulate` and `step_by`
take slices rather than `&mut self`, which is what kept the phases in
one 151-line body. Six new tests call them directly, two of which cover
rejections that previously needed a hand-built malformed page.
Paired per column against the C++ implementation of this format, the Rust
decoder runs at 0.37x of it on 29 shared int32 columns, while this crate's
DELTA_BINARY_PACKED runs at 1.55x of the same C++ benchmark, which places the
gap in the unpack loop rather than the harness. Record the two candidate causes
next to the loop.
CurtHagenlocher added a commit to clast-project/engineered-wood that referenced this pull request Sep 5, 2026
FSST's proposal asks for encoding 10 and does not get it. ALP claimed 10
too, shipped here first, and has since been merged into parquet.thrift on
parquet-format main -- so 10 is settled and not FSST's. FSST took 11 here,
which is what the arrow-rs proof-of-concept predicted would happen once ALP
landed.

11 is no longer free either. apache/parquet-format#617 proposes PFOR
(Patched Frame of Reference) as encoding 11, and unlike the FSST proposal it
arrives with two implementations behind it: apache/parquet-java#3775 and
apache/arrow-rs#10977, both of which write 11.

So FSST moves to 12 and 11 is reserved. The collision is not one a reader
can detect and report: a decoder reads the encoding byte, believes it, and
misreads the page body -- there is no magic or length that disagrees. That
makes it worth vacating the slot now rather than after files exist.

The number lives only on the enum member; every other site goes through
Encoding.Fsst, so this is a one-line format change plus its documentation.
Breaking for anyone who has persisted the numeric value, which the
[Experimental] attribute on the member has always warned about.

Adds EncodingWireNumberTests to pin all of the numbers, including that
nothing answers to 11. Round-trip tests cannot see a renumber: this library
would write and read its own files happily either way and only disagree
with other implementations, which is exactly the failure mode that produced
the move.

Also corrects a stale README claim that FSST_16 is unimplemented and
rejected; both symbol table widths have shipped since 2026-08-13.


Claude-Session: https://claude.ai/code/session_01UX8ZZxcXf5q4EqqwhDntNA

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
CurtHagenlocher added a commit to clast-project/engineered-wood that referenced this pull request Sep 5, 2026
…239)

* fix(parquet)!: move FSST off encoding 11, which PFOR now claims

FSST's proposal asks for encoding 10 and does not get it. ALP claimed 10
too, shipped here first, and has since been merged into parquet.thrift on
parquet-format main -- so 10 is settled and not FSST's. FSST took 11 here,
which is what the arrow-rs proof-of-concept predicted would happen once ALP
landed.

11 is no longer free either. apache/parquet-format#617 proposes PFOR
(Patched Frame of Reference) as encoding 11, and unlike the FSST proposal it
arrives with two implementations behind it: apache/parquet-java#3775 and
apache/arrow-rs#10977, both of which write 11.

So FSST moves to 12 and 11 is reserved. The collision is not one a reader
can detect and report: a decoder reads the encoding byte, believes it, and
misreads the page body -- there is no magic or length that disagrees. That
makes it worth vacating the slot now rather than after files exist.

The number lives only on the enum member; every other site goes through
Encoding.Fsst, so this is a one-line format change plus its documentation.
Breaking for anyone who has persisted the numeric value, which the
[Experimental] attribute on the member has always warned about.

Adds EncodingWireNumberTests to pin all of the numbers, including that
nothing answers to 11. Round-trip tests cannot see a renumber: this library
would write and read its own files happily either way and only disagree
with other implementations, which is exactly the failure mode that produced
the move.

Also corrects a stale README claim that FSST_16 is unimplemented and
rejected; both symbol table widths have shipped since 2026-08-13.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UX8ZZxcXf5q4EqqwhDntNA

* feat(parquet): PFOR encoding, plain and delta, behind EWPARQUET0005

Implements PFOR (Patched Frame of Reference) for INT32 and INT64 as
proposed in apache/parquet-format#617, reader and writer, both modes.

Frame of reference plus bit-packing, with the values that do not fit the
chosen width stored separately as exceptions -- so one outlier stops
widening the packing for everyone. Each 1024-value vector independently
chooses whether to pack values or the differences between them, which is
the difference from DELTA_BINARY_PACKED: a column sorted only in stretches
gets the delta treatment on those stretches and frame-of-reference on the
rest. The writer measures the result and falls back to PLAIN per page, so
enabling the setting cannot make a file bigger.

The page layout is close enough to ALP's that PforDecoder is shaped like
AlpDecoder and the two read together: a 7-byte header, an offset array whose
offsets are measured from its own start, then self-describing vectors. What
PFOR adds is the delta flag in bit 7 of the width byte, a per-vector start
value, and a prefix sum -- which must run AFTER the exceptions are patched,
since an exception in a delta vector is a difference like any other.

TWO PLACES WHERE THE SPEC CONTRADICTS ITSELF, both found by measuring.

First, the frame. PforEncoding.md says it is the column's minimum. On the
shape PFOR exists for -- a tight cluster with a low sentinel -- that is the
wrong answer by a wide margin: the sentinel takes the frame, every ordinary
value sits tens of thousands above it, and the width is set by the gap
rather than the cluster. The spec's own Example 3 is that column and quotes
a width only a frame ABOVE the minimum can produce. So the minimum is a
candidate here, not the rule: the encoder buckets the range, slides a window
over the bucket counts per candidate width, lowers the winner onto the
smallest value it covers, and costs that frame exactly. The minimum is
always among the candidates and the only one costed from a real histogram,
so the search cannot do worse than the naive rule. arrow-rs does the same;
parquet-java does not. MEASURED, on 200k INT64 date keys with a null
sentinel: 0.65x against DELTA_BINARY_PACKED with the naive frame, 5.31x
with the search.

Second, width 0 in the delta mode. The spec says a reader may fill with the
start value and "get the same answer for any frame". It does not: fill and
the general path agree only when the frame is 0. No conforming writer can
emit anything else, so it is unreachable from real data -- but arrow-rs
takes the fill path and its own test pins an answer the general path
disagrees with. This decodes by the general path, which is what the numbered
decode steps say, and pins that.

Compression, 200k INT64 per shape, uncompressed, vs DELTA_BINARY_PACKED:
date keys + sentinel 5.31x, sorted in stretches 3.11x, tight cluster 1.74x,
sorted ids 1.20x, timestamps 1.20x, sequence with gaps 1.06x, random 1.03x.
With zstd the picture reverses everywhere except the outlier shapes, because
DBP's output on clean sequential data is far more compressible than PFOR's
tightly packed output. doc/parquet-pfor.md carries both tables and says so
plainly rather than quoting only the flattering half.

Tests sweep EVERY bit width, 0 to 32 and 0 to 64, at a vector length that is
a multiple of eight and one that is not, rather than sampling: this is the
class of bug that shipped once already in the RLE decoder (#236), and it is
invisible at every width but the broken one. Three byte-for-byte golden
vectors from arrow-rs's tests are the only assertions that could catch us
writing a self-consistent page nobody else can read.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UX8ZZxcXf5q4EqqwhDntNA

* fix(parquet): strip the UTF-8 BOMs the PFOR commit introduced

Three files were rewritten through a utf-8-sig encoder, which prepends a
BOM. CI's "Check for UTF-8 BOMs" step is exactly there to catch it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UX8ZZxcXf5q4EqqwhDntNA

* fix(parquet): bound a PFOR vector by the next offset, and reuse encoder scratch

Both from Copilot's review of #239.

A vector was sliced from its own offset to the END OF THE PAGE rather than
to the next vector's offset. Every per-vector truncation check then measured
against the wrong extent: a vector shorter than its own header claims read
on into the following vectors' bytes, satisfied every length check, and
returned their contents as data. Non-monotonic offsets were not checked at
all, so a decreasing offset silently decoded overlapping vectors.

Neither is a memory-safety problem -- the reads stay inside the page -- but
both are silent. The value count comes from the page header, so the output
is the right shape and the wrong data, with nothing raised to say so. The
two new tests fail on the old code with "No exception was thrown", which is
the whole point.

The first attempt at the truncation test did not discriminate: shifting the
next offset backwards also breaks the FOLLOWING vector, which threw for an
unrelated reason and made the test pass against the bug. It now widens the
first vector's declared bit width instead, leaving every offset alone, and
asserts the precondition that makes it a regression test -- short measured
against the next offset, long enough measured against the end of the page.

Also makes the encoder's per-page scratch thread-static. Encoding a page
allocated differences, residuals, exception positions, a histogram and the
frame-search buckets every time, about eleven kilobytes of garbage per page
of every integer column. Thread-static rather than pooled because column
chunks encode in parallel and each thread encodes one page at a time, which
is why ColumnChunkWriter.t_valuesBuffer is thread-static too.

Not taken: the reviewer also suggested writing vectors into one contiguous
page buffer instead of a byte[] per vector. That is a real cost, but the
byte[]-per-vector shape is AlpEncoder's as well, and changing it in one
encoder leaves the two inconsistent. Worth doing across both with a
benchmark behind it, not blind in this PR.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UX8ZZxcXf5q4EqqwhDntNA

* fix(parquet): drop the "11 is reserved" comment now that PFOR occupies 11

Merge fallout. #238 left a comment above the FSST member reserving 11 for
PFOR; this branch replaced it with the member itself, and merging main back
in reinstated the comment alongside the member it describes. "Reserved
rather than reused" now sits directly above Pfor = 11.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UX8ZZxcXf5q4EqqwhDntNA

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: CurtHagenlocher <904803+CurtHagenlocher@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

parquet Changes to the parquet crate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants