Understanding Lance (3): Intra-Page Layout

Overview #

In the previous article we took a detailed look at the design of Lance data files, but did not yet explain the layout of the data within a page. In Lance, one page = a set of buffers + a PageLayout description. Buffers are just bytes; the layout tells the reader how to interpret this pile of buffers.

Recall that ColumnMetadata stores the metadata of a column, and its pages field holds the per-page information:

ColumnMetadata
└─ pages: [
     Page {
       buffer_offsets: [u64, u64, ...]      ← absolute file offset of each buffer
       buffer_sizes:   [u64, u64, ...]      ← length of each buffer
       length:         u64                  ← number of top-level rows in this page
       encoding:       PageLayout           ← ★ intra-page layout
       priority:       u64                  ← row number of the first row in this page
     }
   ]

As you can see, the number and meaning of the buffers are not fixed; they are entirely determined by the encoding. So “intra-page layout” essentially answers two questions:

  1. How many buffers does this page have?
  2. What is the i-th buffer?

PageLayout here is a oneof with five variants:

message PageLayout {
  oneof layout {
    MiniBlockLayout mini_block_layout = 1;
    ConstantLayout  constant_layout   = 2;
    FullZipLayout   full_zip_layout   = 3;
    BlobLayout      blob_layout       = 4;
    SparseLayout    sparse_layout     = 5;   // 2.3+
  }
}

In the previous article on the Parquet file structure, we mentioned its drawback: multiple columns belonging to the same row group are forcibly bound to the same number of rows. Imagine a row group with two columns: one is fixed-width narrow data such as int32, the other is potentially very long wide data such as string. A row group is split by a byte budget, but the number of rows it covers is determined by the width of an entire row, and all columns share this single row count — so the row count is bound by the widest column in the row group. This creates two problems:

  • small row group → few rows, and an entire chunk of a narrow column ends up at tens of KB or even a few KB; splitting it further into pages produces runt pages;
  • large row group → to accumulate enough bytes for narrow columns, the row count must grow, while the chunks of wide columns inflate multiplicatively, and the write side has to buffer the whole group.

In addition to removing the row group, Lance’s design provides adaptive intra-page layouts for different types of columns. Specifically:

  • all values constant or all null: Constant
  • max single-value length < 256 bytes: MiniBlock
  • otherwise (large values): FullZip
  • huge binary (written to an out-of-line region): Blob (with another Layout nested inside)
  • 2.3+ and the structural budget is tight: Sparse (can also be requested explicitly)

MiniBlock #

The page structure of MiniBlock is roughly:

Page (a logical container; it does not correspond to a contiguous run of bytes)
├─ Buffer 0: chunk metadata (pure index, 2 or 4 bytes per chunk)
├─ Buffer 1: chunk data region (a flat run of bytes with all chunks back to back)
│   ├─ chunk 0 (mini-block, an independent compression/decoding unit)
│   │   ├─ header (num_levels, optional rep/def sizes, sizes of each value buffer)
│   │   ├─ rep buffer              optional, only present when num_levels > 0
│   │   ├─ def buffer              optional
│   │   └─ value buffers 0..N      num_buffers of them, excluding rep/def
│   ├─ chunk 1
│   └─ ...
├─ Buffer 2: dictionary            optional
└─ Buffer 2 or 3: repetition index optional, always the last buffer

metadata index table #

The index table is fixed at buffer 0 of a MiniBlock page.

Page buffer 0 (metadata)

┌──────────────┬──────────────┬─────┬──────────────┐
│ word[0]      │ word[1]      │ ... │ word[N-1]    │
│ 2B/4B LE     │              │     │              │
└──────────────┴──────────────┴─────┴──────────────┘
    chunk 0        chunk 1             chunk N-1
  • Word width: 2 bytes in v2.1, 4 bytes in v2.2/v2.3; words are stored little-endian.
  • The chunk count N = Page.buffer_sizes[0] / word_size; the count is not stored separately.
  • This buffer contains no internal padding; buffer_sizes[0] is exactly N × word_size.
Lance 2.1 (u16, 2 bytes)
      15                                     4 3                0
     ┌────────────────────────────────────────┬──────────────────┐
     │      chunk_bytes / 8 - 1 (12 bit)      │ log2(num_values) │
     └────────────────────────────────────────┴──────────────────┘

Lance 2.2+ (u32, 4 bytes)
      31                                     4 3                0
     ┌────────────────────────────────────────┬──────────────────┐
     │      chunk_bytes / 8 - 1 (28 bit)      │ log2(num_values) │
     └────────────────────────────────────────┴──────────────────┘

Parsing formula:

chunk_bytes = ((word >> 4) + 1) * 8
log         =  word & 0x0F
  • chunk_bytes is the byte size of the entire chunk, including the header, padding, and the rep/def/value payload.
  • Because every section is 8B-aligned, this is stored as “number of 8B words - 1”; the -1 lets 12 bits represent 32 KiB (4096 8B words).
  • log is log2(num_values); in non-final chunks the value count is 1 « log; the final chunk has log = 0, and its value count is derived from num_items minus the sum of the preceding chunks.

Formula:

word = ((chunk_bytes / 8 - 1) << 4) | log2(num_values)

Offsets are not stored in the metadata; the reader reconstructs each chunk’s byte size from buffer 0, then uses a prefix sum to compute each chunk’s relative position in buffer 1:

chunk_start[0]   = 0
chunk_start[k+1] = chunk_start[k] + chunk_bytes[k]

absolute file offset of a chunk = start of buffer 1 + chunk_start[k]

The prefix sum is computed once at initialization; afterwards, fetching a start by k is O(1), and finding k by row number is a binary search, O(log N). The whole process only depends on buffer 0 — buffer 1 does not need to be read.

Data region #

Here is the full layout of a chunk in the data region:

chunk start (8B aligned)
┌──────────────────────────────────────────────────┐
├────────────── header  fixed fields ──────────────┤
│  u16 num_levels                                  │
│  u16 rep_size             [optional]             │
│  u16 def_size             [optional]             │
│  u16/u32 value_size[0..N-1]                      │
├───────────────── padding to 8B ──────────────────┤
│                                                  │
├─────────────── payload  raw bytes ───────────────┤
│  rep buffer               [rep_size bytes]       │
│  padding to 8B                                   │
│  def buffer               [def_size bytes]       │
│  padding to 8B                                   │
│  value buffer 0           [value_size[0] bytes]  │
│  padding to 8B                                   │
│  value buffer 1           [value_size[1] bytes]  │
│  padding to 8B                                   │
│  ...                                             │
└──────────────────────────────────────────────────┘

The structure of each part is described below:

Field Width When present Meaning
num_levels u16, always always the number of rep/def entries in this chunk (not the number of buffers, nor the “number of levels”)
rep_size u16 layout.rep_compression present compressed byte size of the rep buffer
def_size u16 layout.def_compression present compressed byte size of the def buffer
value_size[i] u16 / u32 always, layout.num_buffers of them byte size of the i-th value buffer

Notes:

  • num_levels = 0 means there is no rep/def;
  • num_levels is the number of rep/def entries: without nesting it happens to equal the item count; with lists the entry count ≥ item count (an empty list occupies one entry in the level stream but produces no item);
  • the real item count is in MiniBlockLayout.num_items, and the row count in Page.length; the three need not be equal;
  • rep_size / def_size are always u16, even when v2.2 uses u32 value sizes;
  • num_buffers is not written in the chunk; it comes from MiniBlockLayout.

Example #

Suppose a column has a page with 2524 int32 values, split into 3 chunks. Its actual form in the file looks like this:

file bytes
        │
65536 ──┼──┐
        │  │ buffer 0 (6 bytes)
        │  │ ┌────────┬────────┬────────┐
        │  │ │ u16    │ u16    │ u16    │
        │  │ │ 0x200A │ 0x200A │ 0x0EE0 │
        │  │ └────────┴────────┴────────┘
65542 ──┼──┘
        │      ← 58 bytes of gap here (alignment padding, belongs to no buffer)
65600 ──┼──┐
        │  │ buffer 1 (10120 bytes)
        │  │
        │  │ ┌────────────────────────────┐
        │  │ │ chunk 0  [65600, 69704)    │   4104 B
        │  │ ├────────────────────────────┤
        │  │ │ chunk 1  [69704, 73808)    │   4104 B
        │  │ ├────────────────────────────┤
        │  │ │ chunk 2  [73808, 75720)    │   1912 B
        │  │ └────────────────────────────┘
75720 ──┼──┘
        │

To read the 1500th value (its relative position within the page), the flow is:

1. consult buffer 0 (already in memory)
     0x200A → chunk 0 has 1024 values
     0x200A → chunk 1 has 1024 values
     cumulative 2048 > 1500, so the target is in chunk 1
2. compute the file offset of chunk 1: 65600 + 4104 = 69704
3. read the file at [69704, 73808) — the only disk I/O in the whole flow
4. decode chunk 1's header to get the value buffer start (after the 8-byte header + padding)
5. decompress the value buffer and take value #(1500 - 1024) = 476

The responsibilities of the three layers are clear at a glance:

  • buffer 0: holds the metadata, telling you “which chunk to go to”
  • buffer 1: carries the bytes of all chunks
  • chunk: tells you “how to decode these 4 KiB”

Note that to keep the description simple, the case where a rep index exists is omitted here; it will be covered in the FullZip section.

FullZip #

MiniBlock’s chunk headers, metadata index words, and 8B alignment are a great deal for narrow values; but for wide values (vectors, long strings, large binaries), each chunk can hold only a few values, and the per-chunk overhead ratio is too high.

FullZip = interleave the control words, lengths, and values of the whole page by item into one contiguous data buffer, plus an optional rep index to locate rows. The difference between the two:

  • MiniBlock: page index + per-chunk headers + rep/def/value separated within each chunk
  • FullZip : one control word per item, with the value immediately following

The choice between MiniBlock and FullZip is an adaptive heuristic:

max single-value length < 256B  → prefer MiniBlock
otherwise                       → FullZip

Overall layout #

A FullZip-encoded page looks like this:

FullZip page
├─ buffer 0   data         the zipped stream of the whole page
└─ buffer 1   rep index    starting offset of each row (optional)

Notes:

  • Page buffers are 64B-aligned (PAGE_BUFFER_ALIGNMENT).
  • No padding inside the data buffer; items are packed byte after byte.
  • rep index entries are packed tightly at 1/2/4/8B.
  • The file positions/lengths of the two buffers come from ColumnMetadata.Page.buffer_offsets / buffer_sizes; they are not written in FullZipLayout.

When does a rep index exist:

value type rep index
fixed-width flat, no list none
fixed-width flat, nullable none (but control words exist)
fixed-width with list yes
variable-width always

Item-by-item layout of the data buffer #

As shown below, each item in the data buffer consists of three parts:

  • control word: 0 / 1 / 2 / 4 B wide, storing rep and def
  • length: the byte length of this value
  • value: the data part
          item 0                    item 1
┌────────┬────────┬───────┬────────┬────────┬───────┐
│ ctrl   │ len?   │ value │ ctrl   │ len?   │ value │
└────────┴────────┴───────┴────────┴────────┴───────┘

The detailed rules for the control word:

bits_rep = log2_ceil(max_rep)
bits_def = log2_ceil(max_def)
total    = bits_rep + bits_def

The bit fields of the control word:

both rep and def present:

  ┌────────────────┬────────────────┐
  │ rep (bits_rep) │ def (bits_def) │
  └────────────────┴────────────────┘
  word = (rep << bits_def) | def

rep only:

  ┌────────────────┐
  │      rep       │
  └────────────────┘
  word = rep

def only:

  ┌────────────────┐
  │      def       │
  └────────────────┘
  word = def

neither:

  no control word is written

rep index #

The layout of the rep index:

[offset_0, offset_1, ..., offset_{rows-1}, offset_rows]

Notes:

  • There are rows + 1 entries in total.
  • The k-th entry = the byte offset, within the data buffer, of the first level entry (control word) of row k.
  • The last one is the end offset of the whole page’s data buffer.
  • Width 1 / 2 / 4 / 8 bytes, little-endian.
  • The smallest width that fits the maximum offset is chosen; only byte packing, no general compression.

Summary #

Compared with MiniBlock, FullZip removes chunk grouping and puts all items of a page into a single stream:

  • sequential scan → read one contiguous buffer with almost no chunk-level overhead
  • random access → requires the rep index to jump to a row

Write flow #

write_full_zip(level_entries, values):
    buf = []
    rep_index = []
    offset = 0

    for (rep, def) in level_entries:
        append control_word(rep, def) to buf

        if is_new_row(rep):
            rep_index.append(offset)      # record the start of this row

        if is_visible(def):
            if fixed:
                append value_slot to buf          # written even for null
            else if is_valid(def):
                append length to buf
                append value bytes to buf
            # variable + null: no length/data written

        offset = len(buf)

    rep_index.append(len(buf))            # end of the whole page

Read strategies #

whole-page read:
  read the entire data buffer directly
  1 IOP in the data phase
  no rep index needed

partial-row read, rep index not cached:
  1. read rep_index[row_start] and rep_index[row_end]
  2. read data[a .. b]
  → 2 IOPs

partial-row read, rep index cached:
  compute a..b directly, read data
  → 1 IOP

Example #

Schema and data #

tags: list<item: string>     -- the list itself is non-null but may be empty; items are nullable
row 0: ["aaa", "bb"]
row 1: []
row 2: ["ccc", null]
row 3: ["dddd"]

rep/def layers #

leaf-first:

layers = [NullableItem, EmptyableList]
max_rep = 1
max_def = 2
max_visible_def = 1

So:

bits_rep = log2_ceil(1) = 1
bits_def = log2_ceil(2) = 2
control word is 1 byte wide
word = (rep << 2) | def

level entries #

entry rep def word meaning written
row0 item0 1 0 0x04 new row, valid value ctrl + len + "aaa"
row0 item1 0 0 0x00 same row, valid value ctrl + len + "bb"
row1 1 2 0x06 new row, empty list ctrl only
row2 item0 1 0 0x04 new row, valid value ctrl + len + "ccc"
row2 item1 0 1 0x01 same row, null ctrl only
row3 item0 1 0 0x04 new row, valid value ctrl + len + "dddd"
num_items         = 6
num_visible_items = 5

data buffer #

length uses 4 bytes:

off  bytes            meaning
0    04               ctrl: rep=1 def=0
1    03 00 00 00      len=3
5    61 61 61         "aaa"
8    00               ctrl: rep=0 def=0
9    02 00 00 00      len=2
13   62 62            "bb"
15   06               ctrl: rep=1 def=2 (empty list)
16   04               ctrl: rep=1 def=0
17   03 00 00 00      len=3
21   63 63 63         "ccc"
24   01               ctrl: rep=0 def=1 (null)
25   04               ctrl: rep=1 def=0
26   04 00 00 00      len=4
30   64 64 64 64      "dddd"
34   (end)
data buffer total length = 34 bytes

rep index #

[0, 15, 16, 25, 34]

The maximum is 34 < 256, so each entry is 1 byte:

00 0F 10 19 22

Random read #

To read the row range [2, 3) (i.e., only row 2), the flow is:

a = rep_index[2] = 16
b = rep_index[3] = 25
read data[16 .. 25] = 04 03 00 00 00 63 63 63 01

Decoding:

04 → rep=1 def=0 → new row, valid → len=3, "ccc"
01 → rep=0 def=1 → same row, null → no length/data

Protobuf #

The proto definition of the FullZip layout is:

message FullZipLayout {
  uint32 bits_rep = 1;
  uint32 bits_def = 2;

  oneof details {
    uint32 bits_per_value = 3;   // fixed-width
    uint32 bits_per_offset = 4;  // variable-width, 32 or 64
  }

  uint32 num_items = 5;
  uint32 num_visible_items = 6;
  CompressiveEncoding value_compression = 7;
  repeated RepDefLayer layers = 8;
}

Based on this proto definition, the corresponding data in this example is:

bits_rep            = 1
bits_def            = 2
details             = bits_per_offset(32)
num_items           = 6
num_visible_items   = 5
value_compression   = variable
layers              = [NullableItem, EmptyableList]

Constant #

When all visible values of a page are identical, or all null, the Constant layout is used. It has two storage forms:

  • ≤ 32 bytes → inlined into the inline_value field of PageLayout, occupying no buffer
  • > 32 bytes → a dedicated scalar value buffer

The combinations of buffer count and inline_value are fixed; all other combinations are considered illegal:

inline_value present, no rep/def   → 0 buffers
inline_value present, with rep/def → 2 buffers (rep, def)
inline_value absent,  no rep/def   → 1 buffer (scalar value)
inline_value absent,  with rep/def → 3 buffers (scalar value, rep, def)

These four combinations cover all legal cases, so the buffer count can only be 0, 1, 2, or 3.

All-null pages are further divided into two branches:

SimpleAllNull    only a NullableItem layer; no rep/def stream needed
ComplexAllNull   structural nesting such as lists exists; rep/def must be stored to distinguish "null" from "empty list"

Blob #

When values grow so large that “one page can only hold a few rows”, they should no longer stay in the page. The Blob layout writes the actual bytes to a separate region outside the page, leaving only descriptors inside:

buffer 0   descriptor array, described by inner_layout
           usually packed struct<position: u64, size: u64>

BlobLayout embeds a complete PageLayout (inner_layout), so this is a recursive structure: the descriptors themselves can be stored with MiniBlock, enjoying the random access brought by chunk indexing.

Reading is a two-step process:

1. decode the descriptor → (position, size)
2. do one range read against the out-of-line region at (position, size)

Sparse #

Introduced in Lance 2.3. The previous layouts all encode structure (list nesting, nulls) as rep/def streams; Sparse takes a different approach: record the slot mapping directly, without decoding rep/def.

Overall layout #

Sparse page
├─ buffer 0   value chunk  metadata (8 bytes per chunk)
├─ buffer 1   value chunks mini-block compressed
└─ buffer 2+  structure    one buffer per layer

Each entry of buffer 0 is two u32s, rather than packing the information into a single 16/32-bit word as MiniBlock does:

u32  chunk_size / 8 - 1
u32  number of visible values in this chunk

The chunk size must be a multiple of 8, and each chunk holds at most 32768 visible values. has_large_chunk determines whether the length fields of value buffers inside a chunk use u16 or u32.

Structure layers described by “domains” #

domain 0 (top-level rows) → domain 1 → ... → domain N (leaf value slots)

Each layer is one of three kinds:

layer type what it records
SparseValidityLayer validity of the slots at this layer (stores either null positions or valid positions, one of the two)
SparseListLayer the set of non-empty parent slots + the child count of each parent slot; unlisted parent slots are empty lists
SparseFixedSizeListLayer a fixed dimension; child domain size = slot count × dimension

Difference from MiniBlock #

MiniBlock: structure → rep/def stream → random access requires decoding the stream first to locate
Sparse   : structure → independent layer buffers → locate by projecting layers

At initialization, buffer 0 and all structure buffers are loaded and normalized into a cached page plan; the value payload (buffer 1) is not loaded. After projecting the target row range, only the value chunks intersecting the leaf range are read; if there is no leaf range at all, offsets and validity are rebuilt purely from the structure plan, without touching buffer 1.

The cost is larger metadata (8 bytes/chunk vs 2~4 bytes/chunk), in exchange for not having to decode rep/def first under nested structures.

Comparison of the five layouts #

layout buffer count random access granularity compression freedom suitable for
MiniBlock 2 + dictionary + rep index one chunk (~4 KiB) chunk-level, any compression most types
FullZip 1 + rep index one value / one row per-value transparent compression only large values, embeddings
Constant 0 / 1 / 2 / 3 no extra I/O needed none constant columns, all null
Blob 1 (descriptors) descriptors + one out-of-line read any images, videos, large binaries
Sparse 2 + structure layers one value chunk chunk-level complex nesting in 2.3+

The boundaries of the five layouts are drawn along the dimension of “value size”:

< 256 bytes         chunk it; cheap chunk index, fine granularity      → MiniBlock
256 B ~ tens of KB  no chunking, per-value positioning                 → FullZip
huge binary         moved out of the page; 16-byte descriptor in-page  → Blob
constant            nothing needs to be stored                         → Constant

If only one layout were kept, you would have to choose between “chunk header overhead” and “positioning granularity”:

MiniBlock only: embeddings pay one chunk header per 4096 values
FullZip only  : narrow columns pay a positioning cost for every value read, and lose compression freedom

The point of adaptive layouts is to let the write side pick the cost that matches the shape of the data, instead of forcing every column to pay the same price.