Skip to content
47 changes: 40 additions & 7 deletions docs/dev/specs/itl-1464-tokens.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,46 @@ tags shares one array of ids, so a further column costs nothing.
text. Matching operators carry a list column of one input; a shared one becomes text.
- `iter_data` builds at most 8,192 rows and, beyond one row, 65,536 members at once.

Sharing on a spill: Arrow IPC writes a dictionary per column, so the sharing between
columns is lost, and a segment holds the whole dictionary of every column whatever rows it
holds. Measured with 200,000 members in 300 groups and 9 token columns: 70 MiB held in
memory (the whole table, its ids included), 112 MiB written for the token columns whole
(125 MiB as text), and 96 MiB for a segment of 2 groups (0.8 MiB as text). A spool that
splits a grouped table into segments should therefore write its token lists as text, or
take each segment's ids out of the dictionaries first.
On a spill (`RowSpool`, `source_tokens.Shelf`): a column of one token a row is not written
(its type says it all), and lists whose members' ids are equal share one ids column in a
file, whose dictionaries hold only the ids that file's rows read. Rows a spool keeps in
memory are trimmed the same way, so a slice never pins the ids of the whole table. Read
back, the columns share the mapped ids again. `kept_table` cuts by bytes, what is shared
counted once. Measured with 200,000 members in 300 groups and 9 token columns: 16.1 MiB in
one file and 16.4 MiB in 150 files of 2 groups (0.11 MiB a file; it was 96 MiB), against
125.5 MiB as text.

Refusing to leave the process: the storage of a recipe column is a list of no element of
structs nested deeper than Arrow IPC and the C data interface write (the depth costs
nothing per row, since no element exists), and a list's storage holds the same as a guard.
IPC files, streams and messages, Feather, the C stream and pandas refuse a table with rows.
A table with no rows can be written: it has no value. The hash and store guards look inside
structs, lists, dictionaries and extension storages (`refuse_derived`).

## Grouping millions of rows

`GroupBy` reads its keys and system tags in one chunk each (a `take` from many chunks puts
them together every time), and sorts by the record ids, the largest columns, only when rows
tie on every tag before them. Text with few distinct values is sorted by its rank (four bytes
a row). Measured outside a job with a synthetic event table of about
8 million rows, 8 columns, 100 groups of about 80,000 members (footprint: the memory the
system charges the process; the source's own read is 3.5 GiB of every line):

| Step | Seconds before | after | Peak footprint before | after |
|---|---|---|---|---|
| read, recipes carried | | 64 | | 3.5 GiB |
| `group_by` | 411 | 143 | 10.5 GiB | 4.9 GiB |
| `group_by`, a function per group | | 155 | | 5.3 GiB |

The values of the grouped table are 0.09 GiB: they do not dominate. What it holds is 1.7
GiB, the members' record ids (about 190 bytes each, the canonical JSON of the key). Of the
143 seconds, about 70 are the folds of the eight system-tag and key columns, whose digests
read every member's text, as they always did.

In a job, on the integration branch's head with this: 4.4 GiB on sync and 5.8 GiB on async
for `group_by` (3.0 GiB on async at half the rows); with a function per group 10.9 GiB on sync and 6.1 GiB on async. The
difference on sync is the function node, which holds every input row as objects before it
computes: 100 rows of 80,000 members, values and token text.

## Measured

Expand Down
114 changes: 91 additions & 23 deletions src/orcapod/core/operators/group_by.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import numpy as np
import polars as pl
import pyarrow as pa
import pyarrow.compute as pc

from orcapod.core.unique_keys import UniqueKeys, certificate
from orcapod.core.operators.arrow_keys import (
Expand Down Expand Up @@ -204,6 +205,46 @@ def _member_order_names(
return names


def _all_distinct(frame: "pl.DataFrame", names: Sequence[str]) -> bool:
"""Whether no two rows of a sorted frame tie on ``names``.

Nested values order by other expressions than they compare by, so with one of them
the answer is always no.
"""
if any(frame.schema[name].is_nested() for name in names):
return False
if frame.height < 2:
return True
runs = cast(int, frame.select(pl.struct(names).rle_id().max()).item()) + 1
return runs == frame.height


_RANK_SAMPLE = 65_536
"""How many values of a text column decide whether it is worth ranking (``_ranked``)."""


def _ranked(array: "pa.Array[Any]") -> "pa.Array[Any]":
"""``array``, or the ranks of its values when it is text with few distinct values.

The sort frame then holds four bytes a row in place of the text (ITL-1464). Ranks
order and compare as the text does: the rank is the value's place among the distinct
values in byte order, which is Polars' order of text, and a null stays null.

Args:
array: A prepared key column (``polars_ready``).
"""
if not (pa.types.is_large_string(array.type) or pa.types.is_string(array.type)):
return array
sample = array.slice(0, _RANK_SAMPLE)
if pc.count_distinct(sample).as_py() * 2 > len(sample):
return array # a text of its own in most rows: ranking would cost a copy of it
encoded: Any = array.dictionary_encode()
by_bytes = pc.sort_indices(encoded.dictionary.cast(pa.large_binary())).to_numpy()
ranks = np.empty(len(by_bytes), dtype=np.uint32)
ranks[by_bytes] = np.arange(len(by_bytes), dtype=np.uint32)
return pa.array(ranks).take(encoded.indices)


class GroupBy(UnaryOperator):
"""Reduce rows sharing a key into one row with list-valued data members.

Expand Down Expand Up @@ -472,13 +513,18 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol:
system_tag_columns = tuple(
c for c in table.column_names if c.startswith(constants.SYSTEM_TAG_PREFIX)
)
# One chunk each: they are taken by row number a part at a time, and a take from
# many chunks of text puts all of them together every time (ITL-1464).
for c in system_tag_columns:
at = table.schema.get_field_index(c)
# The folds, the sort and the members' ids read these again and again, by row
# number: each in one chunk (a ``take`` from many puts them together every time).
for name in (*self.by, *system_tag_columns):
index = table.schema.get_field_index(name)
table = table.set_column(
at, table.schema.field(c), table.column(c).combine_chunks()
index,
table.schema.field(index),
source_tokens.one_chunk(table.column(index)),
)
# The chunks let go are several GiB at millions of rows, and the pool would
# keep them beside what follows.
pa.default_memory_pool().release_unused()
# The source info of a data-tag key: the key's value is the merge of its
# members' equal values, so its source info is one token, the fold of the
# members' tokens in member order, as the system tags fold (ITL-1017).
Expand Down Expand Up @@ -626,6 +672,7 @@ def _member_layout(
"""
named = self.member_order or ()
sort_columns = named + tuple(sorted(c for c in non_key_tags if c not in named))
tags = len(sort_columns)
for prefix in (
constants.SYSTEM_TAG_RECORD_ID_PREFIX,
constants.SYSTEM_TAG_SOURCE_ID_PREFIX,
Expand All @@ -645,34 +692,55 @@ def _member_layout(
key_names = [f"key{i}" for i in range(len(self.by))]
order_names = [f"order{i}" for i in range(len(sort_columns))]
for name, c in zip(
[*key_names, *order_names], [*self.by, *sort_columns], strict=True
[*key_names, *order_names[:tags]],
[*self.by, *sort_columns[:tags]],
strict=True,
):
frame_columns[name] = polars_ready(table.column(c).combine_chunks())
frame_columns[name] = _ranked(
polars_ready(source_tokens.one_chunk(table.column(c)))
)
# The bits of each float key, to emit the member value with the smallest.
key_storage = {c: values_of(table.column(c).combine_chunks()) for c in self.by}
key_storage = {
c: values_of(source_tokens.one_chunk(table.column(c))) for c in self.by
}
bit_names: dict[str, str] = {}
for i, c in enumerate(self.by):
bits = _float_bits(key_storage[c])
if bits is not None:
bit_names[c] = f"bits{i}"
frame_columns[f"bits{i}"] = bits

frame = cast(
"pl.DataFrame",
pl.from_arrow(
pa.Table.from_arrays(
list(frame_columns.values()), names=list(frame_columns)
def in_order(names: Sequence[str]) -> pl.DataFrame:
"""The frame sorted by the keys and the columns that order the members."""
frame = cast(
"pl.DataFrame",
pl.from_arrow(
pa.Table.from_arrays(
list(frame_columns.values()), names=list(frame_columns)
)
),
)
# Keys first, so the groups come out in key order: a NaN key after every
# number and before null, null last (``nulls_last``); rows that tie on every
# column keep the input's order.
return frame.sort(
[_sort_key(name, frame.schema[name]) for name in names],
nulls_last=True,
maintain_order=True,
)

# The system tags are the last tiebreakers, and their texts are by far the
# largest columns: they are sorted only when rows tie on everything before them
# (ITL-1464). Nested values order by other expressions than they compare by, so
# with one of them they always are.
names = [*key_names, *order_names[:tags]]
frame = in_order(names)
if not _all_distinct(frame, names):
for name, c in zip(order_names[tags:], sort_columns[tags:], strict=True):
frame_columns[name] = polars_ready(
source_tokens.one_chunk(table.column(c))
)
),
)
# Keys first, so the groups come out in key order: a NaN key after every
# number and before null, null last (``nulls_last``); rows that tie on every
# column keep the input's order.
frame = frame.sort(
[_sort_key(name, frame.schema[name]) for name in key_names + order_names],
nulls_last=True,
maintain_order=True,
)
frame = in_order([*key_names, *order_names])
# Group boundaries by Polars' own equality: every NaN equals every NaN and
# 0.0 equals -0.0, as the joins match keys (ITL-1234, ITL-1251).
frame = frame.with_columns(pl.struct(key_names).rle_id().alias("group"))
Expand Down
46 changes: 13 additions & 33 deletions src/orcapod/core/operators/static_output_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
stream_data_tags,
)
from orcapod.core.function_pod import FunctionPodStream
from orcapod.core.row_spool import SPOOL_MEMORY_BYTES, RowSpool
from orcapod.core.row_spool import SPOOL_MEMORY_BYTES, RowSpool, held_bytes
from orcapod.core.operators.provisional import (
provisional_operator_name,
warn_provisional_operator,
Expand Down Expand Up @@ -1578,9 +1578,7 @@ def rows_once(
def kept_table(table: pa.Table) -> pa.Table:
"""Return ``table`` as a node keeps it: on local disk when it is large (ITL-1464).

A table of at most ``KEPT_ROWS_MEMORY_BYTES`` is returned as it is, and so is one
with derived token lists: they share the ids of all their members, which every file
would hold once per column. A larger one
A table of at most ``KEPT_ROWS_MEMORY_BYTES`` is returned as it is. A larger one
is written to a ``RowSpool`` and returned read back memory-mapped: the same
schema and values (only the arrays' chunking differs), not process memory. The
mapping lives as long as a table that refers to it.
Expand All @@ -1591,12 +1589,15 @@ def kept_table(table: pa.Table) -> pa.Table:
Returns:
The table to keep.
"""
lists = any(isinstance(f.type, source_tokens.MemberTokenType) for f in table.schema)
if lists or table.nbytes <= KEPT_ROWS_MEMORY_BYTES or not table.num_rows:
held = held_bytes(table)
if held <= KEPT_ROWS_MEMORY_BYTES or not table.num_rows:
return table
with RowSpool(memory_bytes=KEPT_ROWS_MEMORY_BYTES) as spool:
for start in range(0, table.num_rows, SPILL_SLICE_ROWS):
spool.append(table.slice(start, SPILL_SLICE_ROWS))
# A row of lists can be megabytes: a slice is bounded in bytes too (ITL-1464).
fit = int(KEPT_ROWS_MEMORY_BYTES * table.num_rows / held)
size = max(1, min(SPILL_SLICE_ROWS, fit))
for start in range(0, table.num_rows, size):
spool.append(table.slice(start, size))
return spool.table()


Expand Down Expand Up @@ -1729,9 +1730,6 @@ class BatchSpool:

def __init__(self) -> None:
self._spool: RowSpool = RowSpool(memory_bytes=KEPT_ROWS_MEMORY_BYTES)
# Rows with derived token lists, which share the ids of all their members: each
# file of a spool would hold them once per column (``itl-1464-tokens.md``).
self._in_memory: list[pa.Table] = []
self._schema: pa.Schema | None = None
self._token_types: dict[str, pa.DataType] = {}
self._error: Exception | None = None
Expand All @@ -1755,17 +1753,7 @@ def _add(self, batch: pa.RecordBatch) -> None:
self._schema = table.schema
elif not table.schema.equals(self._schema, check_metadata=True):
table = self._in_one_form(table)
self._keep(table)

def _keep(self, table: pa.Table) -> None:
"""Hold ``table``, whose schema is the one of the rows held."""
lists = any(
isinstance(f.type, source_tokens.MemberTokenType) for f in table.schema
)
if lists or self._in_memory:
self._in_memory.append(table)
else:
self._spool.append(table)
self._spool.append(table)

def _in_one_form(self, table: pa.Table) -> pa.Table:
"""``table`` under the held rows' schema; where only one of the two derives a
Expand All @@ -1784,25 +1772,18 @@ def _in_one_form(self, table: pa.Table) -> pa.Table:
if f.name in derived and f.type != self._schema.field(f.name).type
}
if names & {*source_tokens.derived_columns(self._schema)}:
held = self._held()
held = self._spool.table()
self._schema = source_tokens.materialize(
self._schema.empty_table(), names
).schema
self._spool.close()
self._spool = RowSpool(memory_bytes=KEPT_ROWS_MEMORY_BYTES)
self._in_memory = []
for start in range(0, held.num_rows, SPILL_SLICE_ROWS):
part = held.slice(start, SPILL_SLICE_ROWS)
self._keep(source_tokens.materialize(part, names))
self._spool.append(source_tokens.materialize(part, names))
table = source_tokens.materialize(table, names)
return pa.concat_tables([self._schema.empty_table(), table])

def _held(self) -> pa.Table:
"""Every row held, in order."""
if not self._in_memory:
return self._spool.table()
return pa.concat_tables(self._in_memory)

def table(self) -> pa.Table | None:
"""Every row added, in order; ``None`` for no row. It stays valid after ``close``.

Expand All @@ -1811,12 +1792,11 @@ def table(self) -> pa.Table | None:
"""
if self._error is not None:
raise self._error
return self._held() if self.num_rows else None
return self._spool.table() if self.num_rows else None

def close(self) -> None:
"""Let the rows go and delete their files."""
self._spool.close()
self._in_memory = []


async def stream_of_channel(channel: RecordBatchInput) -> StreamProtocol:
Expand Down
Loading
Loading