Part 9 · Query execution · Chapter 31
The vectorized Parquet reader and columnar batches
How Spark 4.0 reads Parquet a batch at a time into ColumnVectors: the read loop, decoding definition levels and RLE dictionary ids run by run, lazy dictionary decoding, the on-heap vector layout, how codegen turns batches back into rows, and the Arrow format Spark uses to exchange columnar data.
After this chapter you should be able to:
- Say when a Parquet scan is vectorized, and what a batch is.
- Trace how Spark's column reader consumes definition levels and dictionary ids, run by run.
- Explain lazy dictionary decoding and the eager decode when a writer fell back to PLAIN.
- Compare Spark's ColumnVector layout with Arrow's, and name where Spark uses Arrow.
Chapter 30 ended with a list of read tasks. This chapter is what one of those tasks does with a Parquet file: how pages become in-memory columns. Chapters 5 and 6 covered the bytes (pages, definition levels, the RLE/bit-packing hybrid and dictionary encoding). Here the subject is Spark’s reader of those bytes, and the Arrow format Spark uses when columnar data leaves the JVM.
The simulator in src/sim/spark/vectorized.ts writes a small optional string column with the encoders of chapter 6. It then reads it back with a port of Spark’s read loop, run by run, and lays the same values out in Arrow’s format.
Row by row versus a batch at a time
Spark has two Parquet readers. The row reader is parquet-java’s ParquetRecordReader with Spark’s ParquetReadSupport, which assembles one InternalRow per record through converters. The vectorized reader is Spark’s own VectorizedParquetRecordReader. It fills one column vector per column, for thousands of rows per call. ParquetFileFormat uses the vectorized reader when ParquetUtils.isBatchReadSupportedForSchema holds. That requires spark.sql.parquet.enableVectorizedReader (default true), and every column must be atomic, or nested with spark.sql.parquet.enableNestedColumnVectorizedReader (default true).[Spark ParquetUtils.isBatchReadSupported][Spark SQLConf]
Using the vectorized reader and outputting batches are separate decisions. FileSourceScanExec.supportsColumnar also requires whole-stage codegen and a schema no wider than spark.sql.codegen.maxFields (100), “Only output columnar if there is WSCG to read it.”[Spark FileSourceScanExec.supportsColumnar] When it holds, EXPLAIN shows Batched: true on the scan. When it does not, the vectorized reader still decodes a batch at a time, but hands rows out one by one through columnarBatch.getRow.
Batching pays because the per-value work is a tight loop over primitive arrays. It costs no virtual call per value, no row object and no boxing. A run of 300 nulls is one putNulls call.
Q1. What must hold for a Parquet FileScan to output columnar batches (Batched: true)? (Select all.) (select all that apply)
The vectorized record reader
initBatch allocates one WritableColumnVector per column of the result schema, OnHeapColumnVector or OffHeapColumnVector with capacity rows. Partition columns get ConstantColumnVectors filled once from the file’s partition values.[Spark VectorizedParquetRecordReader.initBatch] The capacity is spark.sql.parquet.columnarReaderBatchSize, 4096. Off-heap vectors are used when spark.sql.columnVector.offheap.enabled is set, which falls back to spark.memory.offHeap.enabled.[Spark SQLConf offheap] nextBatch resets the vectors and asks each leaf column’s reader for the same number of rows:[Spark nextBatch]
public boolean nextBatch() throws IOException {
for (ParquetColumnVector vector : columnVectors) vector.reset();
columnarBatch.setNumRows(0);
if (rowsReturned >= totalRowCount) return false;
checkEndOfRowGroup(); // load the next row group's pages if needed
int num = (int) Math.min(capacity, totalCountLoadedSoFar - rowsReturned);
for (ParquetColumnVector cv : columnVectors) {
for (ParquetColumnVector leafCv : cv.getLeaves()) {
VectorizedColumnReader columnReader = leafCv.getColumnReader();
if (columnReader != null) columnReader.readBatch(num, leafCv.getValueVector(),
leafCv.getRepetitionLevelVector(), leafCv.getDefinitionLevelVector());
}
cv.assemble(); // nested types: build structs/arrays from leaves
}
rowsReturned += num;
columnarBatch.setNumRows(num);
return true;
}
A batch is a count of rows, not a page. Each column’s pages have their own boundaries, so one readBatch call can finish one page and start the next, and different columns cross pages at different rows.
Q1. How many rows does nextBatch() put in a batch?
Decoding a page into a column vector
VectorizedColumnReader.readBatch loops until the batch is full, reading a page whenever the current one is used up. For each page it picks a values reader from the encoding. RLE_DICTIONARY (or the old PLAIN_DICTIONARY) gets a VectorizedRleValuesReader for the ids, which reads the leading bit-width byte. Other encodings get their own reader.[Spark initDataReader][Spark ParquetReadState]
The definition levels drive the loop. They are an RLE/bit-packed hybrid stream with bit width 1 for a flat optional column, and VectorizedRleValuesReader reads them a group at a time.[Spark readNextGroup] An even header is an RLE run of header >>> 1 copies of one value. An odd header is header >>> 1 groups of 8 bit-packed values, unpacked into a buffer. readBatchInternal then consumes the group:[Spark readBatchInternal]
int n = Math.min(leftInBatch, Math.min(leftInPage, this.currentCount));
switch (mode) {
case RLE -> { // n rows with the same level
if (currentValue == state.maxDefinitionLevel) updater.readValues(n, state.valueOffset, values, valueReader);
else nulls.putNulls(state.valueOffset, n);
state.valueOffset += n;
}
case PACKED -> { // one level per row
for (int i = 0; i < n; ++i) {
if (currentBuffer[currentBufferIdx++] == state.maxDefinitionLevel)
updater.readValue(state.valueOffset++, values, valueReader);
else nulls.putNull(state.valueOffset++);
}
}
}
- Read a group of levels Process up to the limit set by the batch, page and current run.
- Consume a stored value Write the decoded value or its dictionary ID into the vector slot.
- Mark the slot null Advance the output position. Leave the encoded value cursor where it is.
The updater is chosen by ParquetVectorUpdaterFactory from the Parquet type and the Spark type. It is where upcasts (INT32 to long), date and timestamp rebasing, and decimal conversions happen.[Spark ParquetVectorUpdaterFactory] For dictionary pages the “values” are ids. readIntegers copies an RLE run of ids with one putInts(rowId, n, value) and a bit-packed run with an array copy.[Spark readIntegers] The encodings themselves are defined in parquet-format’s Encodings.md.[parquet-format Encodings.md]
Q1. The definition levels of a page start with an RLE run "0 × 300" (max definition level 1). What does readBatchInternal do?
Lazy dictionary decoding
For a dictionary-encoded page, readBatch writes ids into a separate integer vector from column.reserveDictionaryIds(total), and nulls into the column itself. Then it decides whether to decode:[Spark VectorizedColumnReader.readBatch]
if (column.hasDictionary() || (startRowId == pageFirstRowIndex &&
isLazyDecodingSupported(typeName, column.dataType()))) {
column.setDictionary(new ParquetDictionary(dictionary, needTransform)); // keep ids
} else {
updater.decodeDictionaryIds(readState.valueOffset - startOffset, startOffset, column,
dictionaryIds, dictionary); // decode now
}
...
// on a page that is not dictionary encoded:
if (column.hasDictionary() && readState.valueOffset != 0) {
// This batch already has dictionary encoded values but this new page is not. The batch
// does not support a mix of dictionary and not so we will decode the dictionary.
updater.decodeDictionaryIds(readState.valueOffset, 0, column, dictionaryIds, dictionary);
}
column.setDictionary(null);
With a dictionary set, every getter decodes on access. getInt(rowId) returns dictionary.decodeToInt(dictionaryIds.getDictId(rowId)).[Spark OnHeapColumnVector.getInt] getUTF8String returns dictionary.decodeToBinary(...).[Spark WritableColumnVector.getUTF8String] A row that a filter rejects is never decoded, and a string column with few distinct values never copies its bytes into the vector. isLazyDecodingSupported turns this off when the value needs work after decoding: an INT32 read as long or double, a date or timestamp that needs rebasing, a decimal whose scale changes, and INT64 TIMESTAMP_MILLIS.[Spark isLazyDecodingSupported]
reset() between batches clears nulls and appended bytes but keeps the dictionary, so lazy decoding carries on across batches over dictionary pages.[Spark WritableColumnVector.reset] The eager path matters when parquet-java’s writer fell back from dictionary to PLAIN partway through a column chunk, after the dictionary grew too large. A batch that reaches the first PLAIN page decodes the ids it already holds, then appends plain values. From then on the column is read without a dictionary.
Q1. A batch reads dictionary-encoded strings. What does the column vector hold afterwards?
Q2. A batch has read 1,000 dictionary ids when the column reader reaches a PLAIN page (the writer fell back). What happens?
ColumnarBatch and ColumnVector
ColumnVector is the read API: isNullAt, getInt, getUTF8String, getArray, getStruct and the rest.[Spark ColumnVector] ColumnarBatch is an array of them plus numRows. It also gives a row view: getRow(rowId) and rowIterator() return ColumnarBatchRows that read through the vectors.[Spark ColumnarBatch] The implementations are:
| Class | Storage |
|---|---|
OnHeapColumnVector | Java arrays: byte[] nulls, one of intData/longData/doubleData/…, and arrayOffsets/arrayLengths for variable-length values[Spark OnHeapColumnVector] |
OffHeapColumnVector | the same layout in unsafe-allocated memory, read with Platform.getInt(null, data + 4L * rowId)[Spark OffHeapColumnVector] |
ConstantColumnVector | one value for every row (partition columns) |
ArrowColumnVector | a read-only wrapper around an Arrow ValueVector[Spark ArrowColumnVector] |
A string or binary column in a writable vector has no per-row object. putByteArray appends the bytes to a child vector (arrayData()) and records the row’s start in arrayOffsets[rowId] and its length in arrayLengths[rowId].[Spark OnHeapColumnVector.putByteArray] Nulls are a byte per row, not a bit. These choices favor simple, branch-free writes over compactness.
Q1. How does OnHeapColumnVector store a non-dictionary string column?
From batches back to rows
Most of Spark’s operators, and whole-stage codegen, work on rows. The transition is ColumnarToRowExec, and its generated code does not build rows. It loops over the batch and hands column accessors to the parent’s generated code:[Spark ColumnarToRowExec.doProduce]
if (batch == null) nextBatch();
while (batch != null) {
int numRows = batch.numRows();
int localEnd = numRows - batchIdx;
for (int localIdx = 0; localIdx < localEnd; localIdx++) {
int rowIdx = batchIdx + localIdx;
// consume(): the parent's code, with inputs like
// boolean isNull = colInstance0.isNullAt(rowIdx); int v = colInstance0.getInt(rowIdx);
if (shouldStop()) { batchIdx = rowIdx + 1; return; }
}
batchIdx = numRows; batch.closeIfFreeable(); batch = null; nextBatch();
}
colInstance0 is declared with the concrete vector class from vectorTypes (for example OnHeapColumnVector), so the JIT can inline the getter.[Spark ParquetFileFormat.vectorTypes] A Filter and a Project above the scan become code inside this loop. The batch is columnar in memory, but processing is still row at a time. Chapter 32 is about engines that keep processing columnar too.
Q1. What does the code generated by ColumnarToRowExec do?
Arrow
Apache Arrow is a language-independent columnar memory format, with libraries that read and write it without conversion. Its layout differs from Spark’s vectors in the details that matter for interchange.[Arrow format: validity bitmaps][Arrow format: variable-size binary]
- Validity bitmap. A bit per slot, 1 meaning valid, numbered from the least significant bit:
is_valid[j] -> bitmap[j / 8] & (1 << (j % 8)). An array with no nulls may omit it. - Offsets. A variable-size binary array has an offsets buffer of
length + 1integers, 32-bit forUtf8/Binaryand 64-bit forLargeUtf8/LargeBinary. Slotjisdata[offsets[j] .. offsets[j + 1]). Offsets must not decrease, even across null slots. - Padding. Buffers are recommended to be aligned and padded to 8 or 64 bytes, and the format prefers 64 so that a loop can process a whole buffer with SIMD registers and no tail check. IPC serialization enforces the alignment.[Arrow format: alignment and padding]
- Dictionary arrays. An integer index array plus a separate dictionary array, the same idea as Parquet’s dictionary pages and Spark’s lazy vectors.[Arrow format: dictionary-encoded layout]
The spec’s example is ['joe', null, null, 'mark']: validity byte 00001001, offsets 0, 3, 3, 3, 7, data joemark. The lab shows the same for each batch next to Spark’s vector.
Q1. Arrow array [null, "a", "b", null]. What is byte 0 of the validity bitmap, written most significant bit first?
Q2. How many offsets does an Arrow Utf8 array of 1,000 slots have?
Where Spark uses Arrow
Spark’s own scan does not produce Arrow. Arrow appears where columnar data crosses a process boundary:
- Python. Pandas UDFs,
mapInPandas,mapInArrowand the grouped variants send Arrow record batches to Python workers.ArrowWritercopiesInternalRows into Arrow vectors field by field, and results come back wrapped inArrowColumnVectors.[Spark ArrowWriter][Spark PythonArrowOutput]spark.sql.execution.arrow.maxRecordsPerBatch(10,000) caps the rows per Arrow batch.[Spark SQLConf]toPandas()andcreateDataFrame(pandas_df)use Arrow whenspark.sql.execution.arrow.pyspark.enabledis true, which defaults to the deprecatedspark.sql.execution.arrow.enabled, false.[Spark SQLConf]spark.sql.execution.arrow.useLargeVarTypesswitches strings to 64-bit offsets.[Spark SQLConf] - Spark Connect. Query results stream to the client as
ArrowBatchmessages inExecutePlanResponse, each a serialized Arrow IPC payload with a row count.[Spark Connect base.proto]
Q1. Where does Spark 4.0 move data as Arrow? (Select all.) (select all that apply)
Try it
The lab writes 24 rows of a nullable city column in pages of 8, with a dictionary of 4 values, and reads them back. Each page shows its rows and the runs in its two hybrid streams. The rows of the selected batch are highlighted. Things to try:
- Batch size 5: batch 0 is five dictionary ids, all 0 from one RLE run. The vector holds no string bytes until
getUTF8Stringdecodes them. - Batch 1 (rows 5 to 9) crosses from page 0 into page 1, whose definition levels are a bit-packed group. Row 9 is the first of two nulls.
- Tick writer fell back to PLAIN at page 2 and set the batch size to 10. Batch 1 reads 6 ids from page 1, then reaches the PLAIN page: the 6 ids are decoded eagerly (red), the dictionary is dropped, and the vector holds bytes with offsets and lengths.
- Compare the Arrow column: one bit per row for validity, and a single offsets array one longer than the batch.
0: Austin1: Boston2: Chicago3: Denver- readPage: page 0 (RLE_DICTIONARY, 8 values)
- definition RLE run of 1 x5: read 5 dictionary ids [rows 0–4]
- setDictionary: values stay as ids (lazy decoding) [rows 0–4]
| rowId | nulls | dictionaryIds | getUTF8String |
|---|---|---|---|
| 0 | 0 | 0 | Austin |
| 1 | 0 | 0 | Austin |
| 2 | 0 | 0 | Austin |
| 3 | 0 | 0 | Austin |
| 4 | 0 | 0 | Austin |
The vector holds ids and a reference to the Parquet dictionary. A string is decoded only when getUTF8String is called. Ids 20 B + nulls 5 B.
- length, null_count
- 5, 0
- validity bitmap (each byte printed with bit 0 on the right)
00011111- offsets (int32, length + 1)
0, 6, 12, 18, 24, 30- data
AustinAustinAustinAustinAustin- buffers padded to 64 B
- 64 + 64 + 64 B
Summary
- The vectorized reader is used when the schema is atomic (or nested with the nested reader on). The scan outputs
ColumnarBatches only when whole-stage codegen can consume them. nextBatchreadsmin(4096, rows left)rows from every column reader into on-heap or off-heap vectors. Batches and pages have independent boundaries.readBatchInternalconsumes definition levels a hybrid group at a time. An RLE run is onereadValues(n)or oneputNulls(n), and a bit-packed group goes row by row.- Dictionary pages fill
dictionaryIds, and the vector keeps the dictionary and decodes on access, unless the type needs a conversion. A batch that reaches a PLAIN page after dictionary pages decodes its ids first. OnHeapColumnVectoruses a null byte per row, typed arrays, and an offset plus a length per row for strings.ColumnarToRowExecloops over a batch inside generated code, without building rows.- Arrow uses a validity bit per slot (LSB first),
length + 1offsets and 64-byte padding. Spark uses it for Python and Spark Connect, not for its own Parquet scan.
Concepts in this chapter
Explained here
Primary sources
Review this chapter
This chapter has 10 quiz questions.