MoonFrame is built on an Apache Arrow-style columnar layout. This page
records the complexity of each operation and the storage design behind it.
These are analytical notes on complexity and layout; for measured throughput a
moon bench suite lives alongside the tests (see Benchmarks).
- Column-oriented. A
DataFrameis an array of typedSeriescolumns. Row-oriented work reads each column in bulk rather than cell-by-cell: the JSON / CSV / NDJSON record emitters take one whole-frameto_scalar_matrix()read, while table rendering (to_markdown/to_html) scalarises only the visible row window, per column. - Validity bitmap. Nulls live in a byte-packed bitmap (1 bit per row,
1 = valid) kept separate from the data buffer — Arrow's representation. O(1)column lookup. Aname → indexmap backs every name resolution — the schema's map, read byget_columnand byindex_of/field/select/rename— so a wide frame never scans a name array, whether the question reaches it through the columns or through the schema.
An Int / Float column carrying no nulls can be stored as a
NumericColumn, which has no validity bitmap:
- construction allocates no bitmap
Bytes; - reductions (
sum/mean/min/max) skip the per-slot validity check — thenull_count == 0fast path; countneeds no scan at all: with no bitmap there is nothing to count.
Content decides which columns land there, never the caller. Which paths ask the question is the classification below — the one place it is enumerated, so a comment beside an operation says why it is in its class rather than restating the membership.
| Class | Paths | Backend of the result |
|---|---|---|
| Canonicalise | from_ints / from_floats; every row rebuild (gather, and the filter / sort / unique / join / drop_nulls that route through one); the expression engine's computed columns, map_batches results included |
Numeric when the produced cells carry no null and the column's dtype is numeric (the registry's numeric flag — a Date column is also 64-bit-typed and null-free after pruning, yet stays Builtin: the fast path is dtype-less and cannot carry the date identity), Builtin otherwise — a function of the content and the dtype, never of the source |
| Identity short-circuit | a verb above with no work to do, which returns self rather than rebuilding an equal frame: a filter keeping every row, a keyless sort, a unique dropping nothing, a drop_nulls over null-free gating columns, with_columns([]) |
the source's, verbatim — so an all-valid Builtin column stays Builtin |
| Preserve | slice / head / tail (which share the parent's validity bitmap); fill_null (built on Builtin, then re-converged to its source's backend) |
the source's |
Always Builtin |
the nullable constructors (from_*_options, even when every cell is Some); cast |
Builtin, whatever the source held |
So an all-valid numeric column is not necessarily a Numeric one, and reaching
the fast path is not a latch a column can never leave. The two middle classes
are why: a verb that canonicalises when it rebuilds rows does not rebuild them
when it has no work, and returning self is worth more than the convergence.
None of that is observable through the supported API: the fast path is a
representation optimization, never a correctness fork — values, dtypes and
equality are identical either way. The moment a null enters, the column
materializes back onto the general Builtin backend.
slice / head / tail (and DataFrame::slice) copy the sliced row data
into a fresh buffer but share the parent's validity bitmap as a zero-copy
view, advancing the bitmap offset instead of repacking it (a Numeric
column carries no bitmap, so only its data is copied, and an all-valid
Numeric sub-range stays Numeric). So the validity is zero-copy, not the
column: a slice's row data is a fresh buffer except a String column's
immutable UTF-8 value bytes, which the slice view shares while it rebuilds
only the offsets window. Equality is logical: a slice
compares equal to a freshly built column with the same cells, regardless of the
shared bitmap's offset.
For a frame of n rows and c columns. Two costs are easy to conflate, so
they are separated below: deciding which rows come out (evaluating a
predicate, ordering keys, hashing) and materialising them. Any verb that
rebuilds rows pays the second across every column it carries — k output rows
cost O(k · c), whatever the first column cost. A verb driven by expressions
scales with the whole of what it is given, so E below is the total node
count across that verb's expressions: evaluating one expression walks its tree
node by node, one vectorized pass each, and a verb handed several walks all of
them. (A map / map_batches node then calls a caller's closure — once per row
or once per column — and that cost is the closure's own, not counted in E.)
Each row reuses the symbols in its own line — k is the surviving rows of a
filter, q the key count of a sort / join.
| Operation | Decide | Materialise | Notes |
|---|---|---|---|
get_column / name lookup |
O(1) |
— | name → index map |
filter |
O(n · E) predicate eval |
O(k · c) |
k = surviving rows; the gather rebuilds every column |
select / with_columns |
O(n · E) over the expressions given |
O(n) per output column |
vectorized, whole-column: one pass per node, never per cell |
sort |
O(n · E) to evaluate the q keys into columns, then O(n log n · q) comparisons — a tie on one key falls through to the next |
O(n · c) |
stable, multi-key |
group_by(keys).agg(aggs) |
O(n · E) for the key and aggregate expressions, O(n · q) to build the composite key cells, and O(n · a) for the folds |
O(g · (q + a)) |
g = groups, a = aggregates; each reduction folds a group over its own indices, and the groups partition the n rows, so all a of them together walk each row once |
join |
evaluating the key expressions over both frames — O(n · E) and O(m · E) — then O((n + m) · q) to build and probe the composite keys |
O(r · c) |
r = output rows: matched pairs, plus the unmatched rows Left / Right / Outer keep. A many-to-many match makes it exceed both inputs, and the probe builds a row plan of length r before any column is touched |
unique |
O(n · c) to build a row key from every column (O(n · s) for a subset of s) |
O(k · c) |
hash on the composite row key |
pivot |
O(n · (q + v)) to build the index and on-key cells, then O(n · v) to bucket the value cells |
O(g · k · v) |
g = distinct index combinations, k = distinct on-values — the buckets are keyed sparsely (a group × card pair no row hits owns no array), but the output is still the dense g × k grid, so materialisation costs every slot's cell |
rolling_* |
min / max are O(n) — a monotonic deque, each cell entering and leaving once. The others are O(n · w) per column — each output cell rescans its whole window (w = the window width, n · w even when the window slides one row at a time); median adds an O(w log w) sort per cell |
O(n) |
the sum family's rescan is deliberate: a running total changes the per-window summation order the kernel's floats depend on, so exactness is bought with the rescan |
unpivot |
O(n · k) over the k on-columns (O(n · (k + i)) with i index columns) |
O(n · k · (i + 2)) |
the output holds n · k rows before any column is touched |
sum / mean / min / max |
O(n) per column |
O(c) |
single pass; Numeric skips validity |
count |
O(1) on Numeric, O(n) bits on Builtin |
O(c) |
non-null count: a Numeric column has none, a Builtin one scans its packed bitmap (n / 8 bytes) |
format_* (JSON / CSV / NDJSON) |
— | O(n · c) |
one whole-frame to_scalar_matrix read |
to_markdown / to_html |
— | O(shown · c) |
scalarises only the rows shown — a row cap touches shown, not n |
to_latex |
— | O(n · c) |
every row rendered — an export, not a preview |
collect() runs the optimizer's rewrite pipeline before executing — unless
the plan is a DAG (one
LazyFrame value shared across both sides of a join), which skips it and
executes as built; LazyFrame::collect's docstring states that carve-out,
and frame/optimize.mbt's pass tables are the pipeline's inventory. A
plan that succeeds
produces what the eager pipeline produces — same schema, same
cells, which is what DataFrame's Eq compares and what the differential
suite asserts. Not a claim about physical layout: the backend a column lands
on is an internal representation, and two equal frames may hold their cells
differently.
Execution is batch-wise: a tree-shaped plan becomes a source of batches
(a scan's cursor — one batch per parquet row group, one per IPC record
batch, one per textual source, 4096 rows of a SQL answer —
an in-memory frame, or a join's merged output, every source capped at a
morsel row bound so that a coarse source answers in bounded windows) plus
a spine of spans. A
flow span rides its row-local verbs on each batch as it passes (a filter,
a row-stable selection, renames and drops); a stateful flow rides its
positional verbs the same way, each carrying its place across the batch
boundaries and flushing its tail at the drain (a forward head / slice,
a trailing window that never holds more than its own n rows, a stride,
a row numbering) — so a plan whose verbs all ride flows answers
without holding the whole result; a block span materialises what reaches
it, runs its row-global verbs once (a sort, an aggregation, a join), and
re-emits the frame as a single batch. A
DAG-shaped plan keeps the node-by-node interpreter instead — its memo runs
each shared subplan exactly once, where a pipeline would re-execute it per
occurrence. LazyFrame::collect_batches is the streaming face of the same
plan: each batch answers as it is ready, and a consumer that stops asking
stops the read; sink_parquet / sink_csv / sink_ipc / sink_json /
sink_ndjson are the same
stream with an
encoder for a consumer, the encoded bytes landing in one write — or, under
a PartitionBy, one encoder a file: a file of max_rows_per_file rows
is written as soon as it is full and another row comes, and a
directory's one file when the plan has answered, so the open files'
encoded bytes are what the sink holds, a row's directory found in one
pass over the batch's key cells. The batch
boundaries carry no size promise beyond the cap; the memory promise is
bounded — a blocking verb holds its whole
input (there is no spilling), and everything below the first blocking verb
flows.
A plan that fails still fails, and a plan with a single broken stage reports the eager error. Two things can change which error you see, or whether a particular one happens at all: a plan with several independently broken stages may surface a different one of its own errors once a filter sinks past a broken stage (which one surfaced was an artifact of stage order to begin with), and a file source's push-down can prune the data an error was hiding in — see below.
- Slice pushdown sinks each row-window node (
head/tail/slice/first/last) toward the scan, fusing neighbouring windows into their composite — the fused window keeps exactly the eager chain's rows, and pairs whose composite is not provably that (a negative bound, offsets whose sum leavesInt32) are left un-fused. - Predicate pushdown sinks each
filtertoward the scan, so rows drop as early as the operator provably commutes with the predicate. - Projection pushdown narrows each scan to the columns its consumers
actually read. For a file source (
scan_csv/scan_ndjson/scan_json/scan_parquet/scan_ipc/scan_orc) the column set is pushed into the reader, so a column no stage reads is never parsed —scan_csv("sales.csv").select([col("region"), col("revenue")]).collect()parses only those two columns. Forscan_sqlthe set names the columns each batch builds, with the pushed predicate's own beside them. - The SQL source is the one source that stops a read without knowing
the row count: a sunk
head, and asliceby forward bounds, pulls no row past the window's end, while atail, and a window counted from the answer's end, reads the answer whole first to learn its row count. Each column's dtype is settled by its first batch and every later batch is held to it — a cell that would widen the column refuses — where the eagerread_sqlreads the whole answer before typing a column. - The rewrite rules fold column-free expression subtrees to their
literal values and merge adjacent
with_columnsstages that commute — plan shape only, never a cell's value.
Because a pruned column is never parsed, a parse error confined to it — or to a
row a pushed-down predicate drops, in a column the predicate does not read — is
what an optimized plan will not surface that a full eager read would. That is
the deliberate one, and it applies to every file source (scan_csv /
scan_ndjson / scan_json / scan_parquet / scan_ipc / scan_orc);
LazyFrame::collect's
docstring states both cases as the plan-level contract.
See the operator docstrings (collected in the generated reference) for the
per-operation semantics and
comparison.md for how the semantics line up with Polars.
read_fwf holds the text in memory and cuts each line by the layout
once: a file of r rows and c fields costs O(r × c) cell cuts
beyond the layout, each a walk over the line's code units up to the
field's end — so a line is walked once per field it holds, and a
file with no named layout first reads its first infer_nrows lines
a second time to infer one. Each column is then typed in one pass,
as the CSV reader types its columns.
read_excel parses the whole workbook into memory — the workbook
library's reader has no streaming face — and then lays the chosen
sheet's values out by row and by column, from the sheet's first row
carrying a value to its last and through its last column: a sheet whose
values span r rows and c columns costs O(r × c) beyond the parse,
empty cells included, so one value far down a sheet is a million rows of
layout. Each column is then read in one pass for its dtype and one for
its cells. write_excel writes its cells one by one into a workbook the
library holds in memory and serialises whole at the end: O(r × c)
cells, in memory until the file's one write.
The other two layouts read_excel opens are taken into memory whole as
well. An OpenDocument spreadsheet's content.xml is inflated and walked
once as events — O(n) in the document's bytes — holding the cells that
carry a value, of every table, until the walk ends; a cell a count
repeats costs the cells it stands for, under a budget of 65 536 + 8 ×
the package's bytes and never more than 2^25 to a sheet, so a count
spelling millions of empty cells is refused instead of laid out. An
Excel 97–2003 workbook's stream is gathered from the compound file's
sectors and read once — O(n) in its bytes — holding the shared strings
and the chosen sheet's cells. Both are then laid out into the frame by
the O(r × c) above.
read_avro takes the whole file into memory — the format has no footer
a reader could start from — and then decodes it block by block: a block
under deflate, snappy, or zstandard inflates into memory under a bound
(the most a block may inflate to), and is held only as long as its
records are decoded. Each record's kept fields are decoded cell by cell,
and a field the projection leaves out is stepped over by its own framing,
never built into a cell. A file of r rows and c kept columns costs
O(r × c) cell decodings, plus one walk of every byte the file holds.
The items of every collection in a file count against one budget, so a
file cannot ask for a walk out of proportion to its size. write_avro
encodes every cell into one buffer and writes it once: O(r × c)
encodings, in memory until the file's one write, in blocks of ten
thousand rows.
read_stata takes the whole file into memory and walks its header once;
each kept variable's cells are then read in one pass from the data block,
which the format lays out row by row — so a file of r rows and c kept
columns costs O(r × c) cell reads, and a variable the projection leaves
out is never read into a cell. A long-string column resolves each of its
cells through the table the file carries. write_stata plans every
column in one pass — its cells encoded, a long-string column's records
collected — and then lays the file out into one buffer and writes it
once: O(r × c) cells, in memory until the file's one write.
read_xml holds the whole document in memory — the event reader keeps a
second copy of it as characters — and pulls one event at a time, keeping
only the elements still open: a document of r rows and c columns costs
O(r × c) cells beyond the parse, and a row's cells are typed in one more
pass each. The reader bounds what a document can make it do — entity
references are counted against one budget — but checks an element's
attributes against each other pairwise, so one element with tens of
thousands of attributes costs time quadratic in their number.
format_xml writes every cell into one buffer, once: O(r × c), in memory
until the file's one write.
read_html holds the page in memory and its tokenizer walks it once,
code unit by code unit, over a stack of the tables still open: the walk
costs O(n) in the page's length, and nothing an element says makes it
revisit what it passed. A run of text is copied once, into the cells it
sits in; a table of r rows and c columns then lays its cells out over
a grid in O(r × c), and each column is typed in one pass. A cell's spans
say how far it reaches, and the grid they lay out is bounded — a table
whose spans would carry its grid past some thirty-three million positions
refuses — so a document cannot ask for memory out of proportion to what
it holds.
A transport file is taken whole into memory by read_sas, which walks its header records
once, and then reads each variable's cells in one pass straight out of
the row-major observations: a file of r rows and c columns costs
O(r × c) cell readings, each an IBM-to-IEEE conversion in constant
time. The format has no index, so a read touches every observation once
per column. write_sas plans every column in one pass — a character
column's cells encoded, each numeric cell converted — and lays the file
out into one buffer, once: O(r × c), in memory until the file's one
write. A data set is walked twice: once over its pages for the metadata —
every subheader, the names, the formats and the text blocks — and once
for the cells, each page's rows decompressed into a buffer no longer than
a page and read column by column, O(r × c) beyond the walk, with the
file and the frame both in memory.
read_spss takes the whole file into memory and reads its dictionary
once — every record, with the variables' names, formats and declared
missing values — and then the data record once: a zlib-compressed file
inflates each block into memory under a bound (what the block declares,
and about a thousand times its compressed size), and the cases then read
from the file's bytes or from the inflated ones, each column's cells in
one pass. A file of r rows and c columns costs O(r × c) cell reads
beyond that, with the file, the inflated data and the frame all in
memory. Nothing is written.
read_orc takes the whole file into memory and reads its tail first — the
PostScript, the Footer and the type tree — then opens each stripe in turn:
its footer located, every stream's range checked against the stripe, and
only the streams of the kept columns inflated, block by block, each
block's inflated length bounded by the file's compression block size. Each
kept column's cells are then decoded in one pass over its stripe, so a
file of r rows and c kept columns costs O(r × c) cell decodings
beyond that, with the file and the frame in memory, and a column the
projection leaves out costs nothing beyond locating its streams. A stripe
that declares more rows than its streams can spell — denser than the
format's densest encoding, 520 values to a byte — is refused before a cell
is built for them, so a small file cannot ask for a large allocation.
scan_orc walks a file without holding more than a stripe: one batch a
stripe, the stripes outside a sunk window never decoded, each kept
column's cells cut to the window's overlap. Nothing is written.
read_iceberg reads the table's metadata file, the snapshot's manifest
list and each manifest whole — a table's own files, kilobytes each — and
then every live data file, each a Parquet file read as read_parquet
reads one: taken into memory, decoded whole. A snapshot of f data files
costs the sum of the Parquet reads plus O(r) a row to join the files'
rows into one frame, r the snapshot's rows, with every file in turn and
then the frame in memory. No file is skipped: the column metrics and
partition bounds a manifest entry carries are not consulted, so a table
read for a few rows still reads every file. A position-delete file is
read when it is met, and the positions it strikes cost one more pass
over its data files' rows.
read_delta reads the commit files whole — a table's own text, kilobytes
each — and replays them once; then every live data file, a Parquet file
read as read_parquet reads one, with the same cost per file as the
Iceberg reading above and O(r) to join the files' rows, r the
snapshot's rows. No file is skipped: the statistics an add action
carries are not consulted. A deletion vector is decoded when its file is
read, and the rows it marks cost one more pass over that file's rows.
read_hdf takes the whole file into memory — the superblock, the object
headers and the group B-trees are read in place — then opens the table
dataset it was asked for: every chunk of that dataset is inflated (deflate
undone, the shuffle unshuffled, the checksum verified where present) and
each block's cells are decoded from it in one pass. A file of f bytes
holding a table of r rows and c columns costs O(f) to take in and
O(r × c) cell decodings, with the file, the inflated chunks and the
frame all in memory. hdf_keys reads the headers of every object a walk
meets and no dataset's data, so it costs O(f) over the file's metadata
alone. A chunk index, a filter pipeline or a link and attribute storage
outside what the reader carries is refused by name before a cell is
built, and there is no chunked or iterated read: a file reads whole, as
the format's own readers open one. Nothing is written.
read_lance takes the whole dataset directory into memory — every file
under it, _versions/, data/, _deletions/ and the rest, the bytes the
manifest and the data files are found in — so a directory of f bytes
costs O(f) to take in before a cell is built. The manifests are read
once; then every live data file the snapshot names is decoded page by
page, each page's buffers inflated (FSST expanded, run lengths un-packed,
a general LZ4 or zstandard block decompressed) and its cells assembled,
O(r × c) for r rows and c columns, with the directory's bytes, the
inflated buffers and the frame all in memory. A deletion file is decoded
when its fragment is read, and the rows it marks cost one more pass over
that fragment. A projection keeps only the top-level fields it names and
a field it leaves out is never decoded, but every data file is still
opened — which columns it holds is in its footer — and no file is skipped
by statistics. A format
2.0 or 2.3 file, an encoding or a deletion-file kind outside what the
reader carries, and a feature flag that changes what the manifest means
refuse by name before a cell is built. There is no chunked or iterated
read; a dataset reads whole. Nothing is written.
write_sql sends a frame in INSERT statements of at most 999 bound
values each — the narrowest per-statement bound among the dialects — so a
frame of r rows and c columns is ⌈r / ⌊999 / c⌋⌉ statements, each one
round trip, inside one transaction where the dialect has one. A frame of
no row is the CREATE TABLE alone. The table's text and types are spelled
once, before the first statement, so a dtype no SQL type holds refuses
before anything is sent.
Beyond the complexity notes above, a moon bench micro-benchmark suite measures
real throughput. Run it from the repo root with moon bench.
The three packages that own a bench_test.mbt file are series, frame,
and io; the packages that only define values or build trees (types,
expr, internal/ir) have nothing to time. The rest do
real work and are measured through a caller instead, which is what that caller
actually pays: internal/kernel (the vectorized column passes) and
internal/column (the two storage backends and the validity bitmap) through the
frame expression benchmarks, internal/order (the stable index sort, the row
clamp) through frame's sort and series' head / tail, and
internal/text / internal/numeric (per-cell parsing, ordering, and exact
mixed-numeric comparison) through the io reader benchmarks and the series
reductions. A regression isolated to one of them would want its own
micro-benchmark added here. Because the benches are
ordinary test blocks, moon check compiles them and moon bench executes
them — and CI runs both, so a benchmark that stops compiling or running fails
the build. There is deliberately no performance threshold, since timings
are machine-dependent and a pass/fail bar would be flaky. The suite covers, at
1K / 100K / 1M rows where scaling is informative:
series— construction, and reductions (sum/mean/min/max/count) contrasting theNumericfast path against the generalBuiltinbackend, plusgather/slice— including a nullableBuiltinslice whose validity view starts off byte alignment, the inputcount's byte-at-a-time scan has to handle.frame—filter,with_columns,unique, innerjoin,sort, andgroup_by(...).agg(...); plus the samefilter+group_by+sumpipeline run eagerly and through the lazy optimizer.io—parse_csv_strandparse_ndjson_strthroughput.
The headline result confirms the design intent: on all-valid numeric columns the
Numeric backend reduces several times faster than Builtin, the widest gap
being sum at 1M rows, while count on Numeric is O(1) — it has no
validity bitmap to scan, where a Builtin column reads about n / 8 bytes of
packed bitmap, as the table above says.
No ratio is quoted here on
purpose — the repo pins no reference hardware and stores no baseline output, so
any number printed in prose would drift with the implementation and the
toolchain. Run moon bench for figures on your own machine.