diff --git a/docs/dev/specs/itl-1464-tokens.md b/docs/dev/specs/itl-1464-tokens.md index f7bbc7336..41207b34d 100644 --- a/docs/dev/specs/itl-1464-tokens.md +++ b/docs/dev/specs/itl-1464-tokens.md @@ -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 diff --git a/src/orcapod/core/operators/group_by.py b/src/orcapod/core/operators/group_by.py index d4cc34abc..8069b6cd3 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -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 ( @@ -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. @@ -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). @@ -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, @@ -645,11 +692,17 @@ 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]) @@ -657,22 +710,37 @@ def _member_layout( 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")) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 65b22424b..782b4ad50 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -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, @@ -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. @@ -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() @@ -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 @@ -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 @@ -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``. @@ -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: diff --git a/src/orcapod/core/row_spool.py b/src/orcapod/core/row_spool.py index d7dd5b260..18fa0be22 100644 --- a/src/orcapod/core/row_spool.py +++ b/src/orcapod/core/row_spool.py @@ -8,7 +8,9 @@ Arrow IPC file of one record batch, uncompressed, read memory-mapped. A mapped page is the operating system's to drop: it counts in a process's resident size while it is there, but it is no memory of Arrow's or of this process's own. An extension column is written as its -storage and wrapped again when read, so reading needs no registered type. +storage and wrapped again when read, so reading needs no registered type. Derived +source-info tokens (``utils/source_tokens.py``) are written as ``source_tokens.Shelf`` +says: the ids of a list's members once a file, and only those the file's rows read. Lifetime: a segment is deleted once every row of it is discarded; a spool's files are removed by ``close`` (a spool is a context manager: normal end, exception and @@ -47,6 +49,8 @@ import numpy.typing as npt import pyarrow as pa +from orcapod.utils import source_tokens + try: import fcntl except ImportError: # no such module on Windows @@ -183,7 +187,9 @@ def __init__(self, start: int, table: pa.Table) -> None: self.rows: int = table.num_rows self.live: int = table.num_rows self.table: pa.Table | None = table + self.bytes: int = held_bytes(table) self.path: str | None = None + self.shelf: source_tokens.Shelf = source_tokens.Shelf(()) def drop(self) -> None: """Let the rows go, and delete their file.""" @@ -259,7 +265,7 @@ def append(self, table: pa.Table) -> None: self._segments.remove(added) self._starts = None if added.table is not None: - self._in_memory -= added.table.nbytes + self._in_memory -= added.bytes self._schema, self.size = schema, size raise @@ -294,7 +300,7 @@ def _add(self, segment: _Segment) -> None: self._segments.append(segment) self._starts = None if segment.table is not None: - self._in_memory += segment.table.nbytes + self._in_memory += segment.bytes def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: """The rows with these numbers, in this order, as one chunk per column. @@ -337,7 +343,7 @@ def _take_from(self, segment: _Segment, local: pa.Array[Any]) -> pa.Table: # py if segment.table is not None: return segment.table.take(local) assert segment.path is not None and self._schema is not None - return _wrapped(self._stored(segment).take(local), self._schema) + return _wrapped(self._stored(segment).take(local), segment.shelf, self._schema) @staticmethod def _stored(segment: _Segment) -> pa.Table: @@ -399,7 +405,7 @@ def slice(self, start: int, length: int) -> pa.Table: if segment.table is not None: part = segment.table else: - part = _wrapped(self._stored(segment), self._schema) + part = _wrapped(self._stored(segment), segment.shelf, self._schema) parts.append(part.slice(first - segment.start, last - first)) return pa.concat_tables(parts) if parts else self._schema.empty_table() @@ -432,7 +438,7 @@ def discard(self, rows: npt.NDArray[np.int64]) -> None: segment.live -= int(counts[index]) if not segment.live: if segment.table is not None: - self._in_memory -= segment.table.nbytes + self._in_memory -= segment.bytes segment.drop() emptied = True if emptied: @@ -452,8 +458,12 @@ def _spill(self) -> None: runs.append([segment]) for run in runs: tables = [s.table for s in run if s.table is not None] - table = pa.concat_tables(tables).combine_chunks() - merged = _Segment(run[0].start, table) + # The derived columns first: put together, every one of them would have + # the ids of all the members of its own (ITL-1464). + shelf = source_tokens.Shelf.of(tables) + table = pa.concat_tables([_as_storage(t, shelf) for t in tables]) + merged = _Segment(run[0].start, table.combine_chunks()) + merged.shelf = shelf merged.live = sum(s.live for s in run) merged.path = self._write(merged) merged.table = None @@ -461,7 +471,7 @@ def _spill(self) -> None: position = self._segments.index(run[0]) self._segments = [s for s in self._segments if id(s) not in replaced] self._segments.insert(position, merged) - self._in_memory -= sum(t.nbytes for t in tables) + self._in_memory -= sum(s.bytes for s in run) self._starts = None def _write(self, segment: _Segment) -> str: @@ -474,7 +484,7 @@ def _write(self, segment: _Segment) -> str: self, _remove_directory, self._directory, os.getpid() ) path = os.path.join(self._directory, f"{segment.start}.arrow") - table = _as_storage(segment.table) + table = segment.table try: with ( pa.OSFile(path, "wb") as sink, @@ -510,34 +520,66 @@ def __exit__(self, *exc: object) -> None: self.close() -def _owned(table: pa.Table) -> pa.Table: - """``table`` as one chunk over buffers of its own size, copied only if needed.""" - table = table.combine_chunks() - if table.get_total_buffer_size() > 2 * table.nbytes: - table = table.take(pa.array(np.arange(table.num_rows), pa.int64())) - return table +def held_bytes(table: pa.Table) -> int: + """The bytes ``table`` holds, what its derived lists share counted once.""" + lists = [ + name + for name in source_tokens.derived_columns(table.schema) + if isinstance(table.schema.field(name).type, source_tokens.MemberTokenType) + ] + shared = table.select(lists).get_total_buffer_size() if lists else 0 + return table.drop_columns(lists).nbytes + shared + +def _owned(table: pa.Table) -> pa.Table: + """``table`` as one chunk over buffers of its own size, copied only if needed. -def _as_storage(table: pa.Table) -> pa.Table: + Derived lists of tokens keep only the ids their rows read, shared by the lists that + have the same. + """ + table = table.combine_chunks() + derived = source_tokens.derived_columns(table.schema) + plain = table.drop_columns(list(derived)) + if plain.get_total_buffer_size() > 2 * plain.nbytes: + plain = plain.take(pa.array(np.arange(table.num_rows), pa.int64())) + if not derived: + return plain + shelf = source_tokens.Shelf.of([table]) + shelved = shelf.shelve(table) + for index, name in enumerate(plain.column_names): + position = shelved.schema.get_field_index(name) + shelved = shelved.set_column(position, plain.field(index), plain.column(index)) + return shelf.restore(shelved.combine_chunks(), table.schema) + + +def _as_storage(table: pa.Table, shelf: source_tokens.Shelf) -> pa.Table: """``table`` with each extension column as its storage, no field metadata. - Flags are dropped too: a field declared non-nullable may hold a null (a column not - settled yet), and ``_wrapped`` puts the schema back. + Derived token columns are written as ``shelf`` says. Flags are dropped too: a field + declared non-nullable may hold a null (a column not settled yet), and ``_wrapped`` + puts the schema back. """ columns: list[Any] = [] # pyright: ignore[reportExplicitAny] # any column - for column in table.combine_chunks().columns: + table = shelf.shelve(table.combine_chunks()).combine_chunks() + for column in table.columns: array: Any = column.chunk(0) # pyright: ignore[reportExplicitAny] # any column is_extension = isinstance(column.type, pa.BaseExtensionType) columns.append(array.storage if is_extension else array) return pa.Table.from_arrays(columns, names=table.column_names) -def _wrapped(table: pa.Table, schema: pa.Schema) -> pa.Table: +def _wrapped( + table: pa.Table, shelf: source_tokens.Shelf, schema: pa.Schema +) -> pa.Table: """Undo ``_as_storage``: the columns of ``table``, one chunk each, under ``schema``.""" columns: list[Any] = [] # pyright: ignore[reportExplicitAny] # any column - for column, field in zip(table.combine_chunks().columns, schema): + table = table.combine_chunks() + for name, column in zip(table.column_names, table.columns, strict=True): array = column.chunk(0) - if isinstance(field.type, pa.BaseExtensionType): - array = pa.ExtensionArray.from_storage(field.type, array) + index = schema.get_field_index(name) + kind = schema.field(index).type if index >= 0 else column.type + if isinstance(kind, pa.BaseExtensionType): + array = pa.ExtensionArray.from_storage(kind, array) columns.append(array) - return pa.Table.from_arrays(columns, schema=schema) + wrapped = pa.Table.from_arrays(columns, names=table.column_names) + return shelf.restore(wrapped, schema) diff --git a/src/orcapod/utils/source_tokens.py b/src/orcapod/utils/source_tokens.py index 6d21ac592..d46945fae 100644 --- a/src/orcapod/utils/source_tokens.py +++ b/src/orcapod/utils/source_tokens.py @@ -30,6 +30,36 @@ _TEXT = pa.large_string() + +def _refused_storage() -> pa.DataType: + """The storage of a derived column: no byte a row, and a type Arrow will not hand on. + + Lists of no element, of structs nested deeper than Arrow IPC (64) and the C data + interface write, whose innermost has no field, which Parquet refuses. No element + exists, so the depth costs nothing per row. + """ + kind: pa.DataType = pa.struct([]) + for _ in range(66): + kind = pa.struct([pa.field("", kind)]) + return pa.list_(pa.field("", kind), 0) + + +_STORAGE = _refused_storage() + + +def _empty_lists(rows: int) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array + """``rows`` values of ``_STORAGE``, none of them null, with no byte.""" + + def none_of(kind: Any) -> Any: # pyright: ignore[reportExplicitAny, reportAny] # a struct type + children = [none_of(child.type) for child in kind] + return pa.Array.from_buffers(kind, 0, cast(Any, [None]), 0, 0, children) + + storage: Any = _STORAGE + return pa.Array.from_buffers( + _STORAGE, rows, cast(Any, [None]), 0, 0, [none_of(storage.value_type)] + ) + + ROWS_PER_CHUNK = 65_536 """The most rows whose token text is built in one step.""" @@ -174,6 +204,14 @@ def __arrow_ext_serialize__(self) -> bytes: def __arrow_ext_scalar_class__(self) -> type[pa.ExtensionScalar]: return _DerivedTokenScalar + def to_pandas_dtype(self) -> NoReturn: # pyright: ignore[reportIncompatibleMethodOverride] # refuses + """Refuse to become a data frame's column, which would hold the storage. + + Raises: + TypeError: Always. + """ + raise TypeError("a derived source-info token column has no pandas form") + def __reduce__(self) -> NoReturn: """Refuse to be pickled: a table another process reads holds the text. @@ -202,7 +240,7 @@ class DerivedTokenType(_DerivedType): """The Arrow type of a derived token column: no bytes, and the recipe.""" def __init__(self, recipe: Recipe) -> None: - super().__init__(recipe, pa.struct([]), "orcapod.internal.derived_token") + super().__init__(recipe, _STORAGE, "orcapod.internal.derived_token") @classmethod def __arrow_ext_deserialize__( @@ -217,7 +255,7 @@ class MemberTokenType(_DerivedType): An aggregation folds its members' system tags into one digest, so a list column holds the members' own ids: its storage is a list of structs of the system-tag values the recipe reads (dictionaries over the input's columns, so a member is a few - bytes and its id's text is held once), and an empty struct, which Parquet refuses. + bytes and its id's text is held once), and a guard no writer accepts. Attributes: recipe: How a member's token is made from its ids. @@ -262,6 +300,12 @@ def text(self, storage: Any) -> pa.Array[Any]: # pyright: ignore[reportExplicit ) +def _members(names: Sequence[str], ids: Sequence[Any]) -> pa.StructArray: # pyright: ignore[reportExplicitAny] # Arrow arrays + """The members of derived lists: their ids, and the guard that refuses a write.""" + guard = _empty_lists(len(ids[0])) + return pa.StructArray.from_arrays([*ids, guard], names=[*names, ""]) + + class MemberTokens: """Builds the derived list columns of one aggregation; they share the members' ids. @@ -293,10 +337,7 @@ def column(self, recipe: Recipe, list_type: pa.DataType) -> pa.Array[Any]: # py if read not in self._lists: names = sorted(read) ids = [self._ids(name) for name in names] - guard = pa.Array.from_buffers( - pa.struct([]), len(self._order), cast(Any, [None]), 0, 0 - ) - members = pa.StructArray.from_arrays([*ids, guard], names=[*names, ""]) + members = _members(names, ids) self._lists[read] = pa.LargeListArray.from_arrays(self._offsets, members) storage = self._lists[read] return pa.ExtensionArray.from_storage( @@ -308,20 +349,29 @@ def _ids(self, name: str) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny column = self._table.column(name) if name.startswith(constants.SYSTEM_TAG_SOURCE_ID_PREFIX): # A few values repeated over every row. - encoded: Any = column.combine_chunks().dictionary_encode() + encoded: Any = one_chunk(column).dictionary_encode() return encoded.take(self._order) return pa.DictionaryArray.from_arrays( - self._order.cast(pa.int64()), column.combine_chunks() + self._order.cast(pa.int64()), one_chunk(column) ) def derived_array(recipe: Recipe, rows: int) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array """A derived token column of ``rows`` rows: no row has a byte.""" - # No validity bitmap: no row is null. (The stubs do not allow the absent buffer.) - storage = pa.Array.from_buffers(pa.struct([]), rows, cast(Any, [None]), 0, 0) + storage = _empty_lists(rows) return pa.ExtensionArray.from_storage(DerivedTokenType(recipe), storage) +def one_chunk(column: pa.ChunkedArray[Any]) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow column + """``column`` as one array, copied only when it has several chunks. + + ``combine_chunks`` copies a column of one chunk too. + """ + if column.num_chunks == 1: + return cast(Any, column).chunk(0) + return cast(Any, column).combine_chunks() + + def is_derived(kind: pa.DataType) -> bool: """Whether a column of type ``kind`` is derived: one token a row, or a list.""" return isinstance(kind, _DerivedType) @@ -422,13 +472,26 @@ def with_recipe(table: pa.Table, name: str, recipe: Recipe) -> pa.Table: return table.set_column(table.schema.get_field_index(name), field, tokens) +def _holds_derived(kind: pa.DataType) -> bool: + """Whether ``kind`` is a derived type or has one inside it, at any depth.""" + if is_derived(kind): + return True + if isinstance(kind, pa.BaseExtensionType): + return _holds_derived(kind.storage_type) + if pa.types.is_dictionary(kind): + return _holds_derived(kind.value_type) + return any( + _holds_derived(kind.field(index).type) for index in range(kind.num_fields) + ) + + def refuse_derived(schema: pa.Schema) -> None: - """Raise if a column of ``schema`` is derived: hashes and stores take text only. + """Raise if a column of ``schema`` is, or contains, a derived one: hashes and stores take text only. Raises: TypeError: Naming the derived columns. """ - if derived := derived_columns(schema): + if derived := [f.name for f in schema if _holds_derived(f.type)]: raise TypeError( f"columns {list(derived)} are derived source-info tokens: their text must " + "be built first (source_tokens.materialize)" @@ -507,3 +570,152 @@ def rename_read_columns(table: pa.Table, names: Mapping[str, str]) -> pa.Table: if renamed != recipe: table = with_recipe(table, name, renamed) return table + + +# --------------------------------------------------------------------------- +# A table's derived columns on local disk (the row spool) +# --------------------------------------------------------------------------- + +_SHELF = "__member_ids_" + + +@dataclass(frozen=True) +class Shelf: + """How the derived columns of tables of one schema are written (``shelve``). + + A column of one token a row is not written: its type says it all. The lists of + tokens whose members' ids are equal are written once, as one column of ids without + the guard, whose dictionaries hold only the ids the rows read. + + Attributes: + groups: For each ids column written, the list columns that have those ids. + """ + + groups: tuple[tuple[str, ...], ...] + + @classmethod + def of(cls, tables: Sequence[pa.Table]) -> Shelf: + """The fewest ids columns that hold the lists of all of ``tables``.""" + groups: list[list[str]] = [] + schema = tables[0].schema + for field in schema: + if not isinstance(field.type, MemberTokenType): + continue + for group in groups: + if all( + _same_ids(t.column(group[0]), t.column(field.name)) for t in tables + ): + group.append(field.name) + break + else: + groups.append([field.name]) + return cls(tuple(tuple(group) for group in groups)) + + def shelve(self, table: pa.Table) -> pa.Table: + """``table`` without its derived columns, and with the ids of its lists. + + The ids are copied: nothing of the result refers to the table's dictionaries. + + Args: + table: The rows, each derived column in one chunk. + """ + shelved = table.drop_columns(list(derived_columns(table.schema))) + for number, group in enumerate(self.groups): + shelved = shelved.append_column( + f"{_SHELF}{number}", + _trimmed_ids(cast(Any, table.column(group[0])).chunk(0)), + ) + if not shelved.num_columns: + # Only derived columns: the number of rows must still be written. + shelved = pa.table({_SHELF: pa.nulls(table.num_rows)}) + return shelved + + def restore(self, shelved: pa.Table, schema: pa.Schema) -> pa.Table: + """The table ``shelve`` was given, of schema ``schema``, over ``shelved``'s buffers. + + Args: + shelved: Rows ``shelve`` made, each column in one chunk. + schema: The table's schema. + """ + rows = shelved.num_rows + shelf = {name: n for n, group in enumerate(self.groups) for name in group} + lists: dict[int, Any] = {} + columns: list[Any] = [] + for field in schema: + kind = field.type + if isinstance(kind, MemberTokenType): + number = shelf[field.name] + if number not in lists: + lists[number] = _with_guard( + shelved.column(f"{_SHELF}{number}").chunk(0) + ) + columns.append(pa.ExtensionArray.from_storage(kind, lists[number])) + elif isinstance(kind, DerivedTokenType): + columns.append(derived_array(kind.recipe, rows)) + else: + columns.append(shelved.column(field.name)) + return pa.Table.from_arrays(columns, schema=schema) + + +def _same_ids(left: pa.ChunkedArray[Any], right: pa.ChunkedArray[Any]) -> bool: # pyright: ignore[reportExplicitAny] # Arrow columns + """Whether two derived list columns, of one chunk each, have equal members' ids.""" + one, two = (cast(Any, column.chunk(0)).storage for column in (left, right)) + if one.type != two.type: + return False + if [b and b.address for b in one.buffers()] == [ + b and b.address for b in two.buffers() + ] and one.offset == two.offset: + # One array: the dictionaries are not among its buffers, the indices are. + return all( + a.dictionary.equals(b.dictionary) + for a, b in zip(_id_columns(one), _id_columns(two), strict=True) + ) + return bool(one.equals(two)) + + +def _id_columns(storage: Any) -> list[Any]: # pyright: ignore[reportExplicitAny, reportAny] # Arrow arrays + """The dictionary columns of the members of ``storage``'s lists.""" + members = storage.flatten() + return members.flatten()[:-1] + + +def _trimmed_ids(array: pa.Array[Any]) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array + """A derived list chunk's ids, no guard, over dictionaries of the ids read only.""" + storage = cast(Any, array).storage + members = storage.flatten() + names = [field.name for field in members.type][:-1] + ids: list[Any] = [] + for column in members.flatten()[:-1]: + indices = column.indices.to_numpy() + texts = column.dictionary + if len(indices) * 8 < len(texts): + used, renumbered = np.unique(indices, return_inverse=True) + else: + read = np.zeros(len(texts), dtype=bool) + read[indices] = True + used = np.flatnonzero(read) + numbers = np.cumsum(read, dtype=np.int64) - 1 + renumbered = numbers[indices] + ids.append( + pa.DictionaryArray.from_arrays( + pa.array(renumbered, column.type.index_type), + texts.take(pa.array(used, pa.int64())), + ) + ) + offsets = pc.subtract(storage.offsets, storage.offsets[0]) + return pa.LargeListArray.from_arrays( + cast("pa.Int64Array", offsets), pa.StructArray.from_arrays(ids, names=names) + ) + + +def _with_guard(ids: Any) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny, reportAny] # Arrow arrays + """``_trimmed_ids``'s array as a derived list's storage, over the same buffers.""" + members = ids.values + columns = [ + members.field(n).slice(members.offset, len(members)) + if len(members.field(n)) != len(members) + else members.field(n) + for n in range(members.type.num_fields) + ] + names = [field.name for field in members.type] + return pa.LargeListArray.from_arrays(ids.offsets, _members(names, columns)) diff --git a/tests/test_core/operators/test_group_by.py b/tests/test_core/operators/test_group_by.py index 72aeb9d1a..7b651070b 100644 --- a/tests/test_core/operators/test_group_by.py +++ b/tests/test_core/operators/test_group_by.py @@ -2,6 +2,7 @@ from __future__ import annotations +from decimal import Decimal from pathlib import Path from typing import Any, get_origin @@ -16,6 +17,7 @@ from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants +from tests.test_core.operators.test_row_built_form import assert_same_values @pytest.fixture @@ -612,3 +614,154 @@ def test_batch_preserves_path_element_type(self): f"expected a list extension type, got {field.type}" ) assert field.type.storage_type == pa.large_list(pa.large_string()) + + +@pytest.mark.parametrize("ties", [False, True]) +@pytest.mark.parametrize("kind", ["float", "null", "list"]) +def test_members_that_tie_on_every_tag_are_ordered_by_record_id( + kind: str, ties: bool +) -> None: + """The record id decides where the tags tie, as Polars orders them: 0.0 with -0.0, + every NaN with every NaN, null with null. Without a tie it decides nothing, whether + or not it is sorted by (ITL-1464).""" + rows = 40 + nan = float("nan") + values: dict[str, list[Any]] = { + "float": [(0.0, -0.0, nan, -nan)[i % 4] for i in range(rows)], + "null": [(None, "a")[i % 2] for i in range(rows)], + "list": [([1, None], [1, 2])[i % 2] for i in range(rows)], + } + table = pa.table( + { + "g": pa.array([f"g{i // 20}" for i in range(rows)]), + "t": pa.array(values[kind]), + "n": pa.array([0 if ties else (i * 7) % rows for i in range(rows)]), + # The record ids, in another order than the rows. + "id": pa.array([f"r{(i * 11) % rows:02}" for i in range(rows)]), + "v": pa.array(range(rows)), + } + ) + source = ArrowTableSource( + table, + tag_columns=["g", "t", "n"], + tag_only_columns=True, + record_id_columns=["id"], + ) + + def rank(value: Any) -> tuple[int, Any]: + if value is None: + return (3, "") + if isinstance(value, list): + return (0, [(v is None, v or 0) for v in value]) + if value != value: + return (2, "") + return (1, value) + + got = source.group_by(["g"]).as_table() + # Other tags in name order ("n", then "t"), then the record id. + for group, members in zip(got["g"].to_pylist(), got["v"].to_pylist(), strict=True): + wanted = [r for r in table.to_pylist() if r["g"] == group] + wanted.sort(key=lambda r: (r["n"], rank(r["t"]), r["id"])) + assert members == [r["v"] for r in wanted] + + +_TEXTS = [ + "", + "a", + "B", + "b", + "a\u0301", + "\u00e1", + "z", + "\U0001f600", + "\ue000", + "aa", + "a\x00", +] + + +def _random_table(seed: int, rows: int) -> pa.Table: + """Keys and tags of several types, with ties, nulls, NaN, signed zeros and text.""" + import random + + pick = random.Random(seed) + few = pick.choice([1, 3, len(_TEXTS)]) + + def column(values: list[Any]) -> list[Any]: + return [pick.choice(values) for _ in range(rows)] + + return pa.table( + { + "s": pa.array(column([*_TEXTS[-few:], None]), pa.string()), + "t": pa.array(column(_TEXTS)), + "f": pa.array( + column([0.0, -0.0, float("nan"), None, 1.5, float("-inf")]), + pa.float64(), + ), + "d": pa.array( + column([Decimal("1.5"), None, Decimal("-2")]), pa.decimal256(40, 2) + ), + "p": pa.array(column([1, None, 2]), pa.timestamp("us", tz="UTC")), + "l": pa.array( + column([["b"], ["b", None], [], None, ["a"]]), pa.list_(pa.string()) + ), + "u": pa.array([f"u{pick.random()}" for _ in range(rows)]), + "v": pa.array(range(rows)), + } + ) + + +@pytest.mark.parametrize("seed", range(40)) +def test_groups_and_members_are_those_of_the_whole_sort( + seed: int, monkeypatch: pytest.MonkeyPatch +) -> None: + """Ranks for text and leaving the system tags out change no group, member order, + fold or hash: the oracle sorts by every column as it is (ITL-1464).""" + import random + + import orcapod.core.operators.group_by as group_by_module + + pick = random.Random(seed) + table = _random_table(seed, pick.choice([1, 2, 30, 200])) + tags = ["s", "t", "f", "d", "p", "l", "u"] + names = pick.sample(tags, pick.randint(2, len(tags))) + by = [c for c in names if c != "l"][: pick.randint(1, 2)] + order = [c for c in names if c not in by][: pick.randint(0, 2)] + operator = GroupBy(by=by, member_order=order or "name") + + def grouped() -> pa.Table: + source = ArrowTableSource( + table, + tag_columns=names, + tag_only_columns=bool(seed % 2), + record_id_columns=["v"] if seed % 3 else (), + ) + return operator(source).as_table(all_info=True) + + got = grouped() + monkeypatch.setattr(group_by_module, "_ranked", lambda array: array) + # The whole sort: as if rows always tied on the tags. + monkeypatch.setattr(group_by_module, "_all_distinct", lambda frame, names: False) + expected = grouped() + assert got.schema.equals(expected.schema, check_metadata=True) + assert_same_values(got, expected) + + +@pytest.mark.parametrize("repeat", [1, 9]) +def test_ranks_order_text_as_its_bytes(repeat: int) -> None: + from orcapod.core.operators.group_by import ( + _ranked, # pyright: ignore[reportPrivateUsage] # under test + ) + + values = [*_TEXTS, None] * repeat + array = pa.array(values, pa.large_string()) + ranked = _ranked(array) + assert (ranked is array) == (repeat == 1) + ranks: list[Any] = ranked.to_pylist() + for one, left in zip(values, ranks, strict=True): + for two, right in zip(values, ranks, strict=True): + if one is None or two is None: + assert (left is None) == (one is None) + continue + assert (left < right) == (one.encode() < two.encode()) + assert (left == right) == (one == two) diff --git a/tests/test_core/streams/test_source_tokens.py b/tests/test_core/streams/test_source_tokens.py index 157c3a5e3..27bfe98d8 100644 --- a/tests/test_core/streams/test_source_tokens.py +++ b/tests/test_core/streams/test_source_tokens.py @@ -12,11 +12,13 @@ import pickle from collections.abc import Callable from pathlib import Path -from typing import Any +from typing import Any, cast +import numpy as np import polars as pl import pyarrow as pa import pyarrow.compute as pc +import pyarrow.feather as feather import pyarrow.parquet as pq import pytest @@ -25,6 +27,7 @@ from orcapod.core.operators.base import UnaryOperator from orcapod.core.operators.join import JOIN_FOLD_LABEL from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.row_spool import RowSpool from orcapod.core.streams import ArrowTableStream from orcapod.core.streams.carried import carried_table from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS @@ -357,7 +360,7 @@ def test_a_recipe_survives_its_json() -> None: for recipe in (leaf, fold): kind = source_tokens.DerivedTokenType(recipe) again = source_tokens.DerivedTokenType.__arrow_ext_deserialize__( - pa.struct([]), kind.__arrow_ext_serialize__() + kind.storage_type, kind.__arrow_ext_serialize__() ) assert again == kind and again.recipe == recipe @@ -523,6 +526,35 @@ def make() -> list[pa.Table]: assert table.schema.equals(expected.schema, check_metadata=True) +def _ipc_writes(table: pa.Table) -> dict[str, Callable[[], Any]]: + def new(make: Any) -> None: + with make(pa.BufferOutputStream(), table.schema) as writer: + writer.write_table(table) + + return { + "file": lambda: new(pa.ipc.new_file), + "stream": lambda: new(pa.ipc.new_stream), + "batch": lambda: table.combine_chunks().to_batches()[0].serialize(), + "feather": lambda: feather.write_feather( + table, cast(Any, pa.BufferOutputStream()) + ), + "c_stream": lambda: pa.RecordBatchReader.from_stream(cast(Any, table)), + } + + +@pytest.mark.parametrize("write", ["file", "stream", "batch", "feather", "c_stream"]) +@pytest.mark.parametrize("grouped", [False, True]) +def test_arrow_ipc_refuses_a_derived_column(write: str, grouped: bool) -> None: + """No path out of the process, or into another library, gives a recipe's storage.""" + stream: Any = _keyed(20, 3).group_by(["g"]) if grouped else _keyed(20, 3) + carried = carried_table(stream, {"source": True, "system_tags": True}) + with pytest.raises(pa.ArrowInvalid, match="[Rr]ecursion"): + _ipc_writes(carried)[write]() + with pytest.raises(TypeError, match="no pandas form"): + _ = carried.to_pandas() + _ipc_writes(source_tokens.materialize(carried))[write]() + + def test_a_grouped_stream_refuses_to_leak() -> None: carried = carried_table( _keyed(10, 4).group_by(["g"]), {"source": True, "system_tags": True} @@ -782,6 +814,42 @@ def test_a_store_refuses_a_derived_column( database.add_records(("t",), records, record_id_column="rid", flush=True) +@pytest.mark.parametrize("grouped", [False, True]) +@pytest.mark.parametrize("nested", ["struct", "list", "deep", "dictionary"]) +def test_a_nested_derived_column_is_refused(nested: str, grouped: bool) -> None: + """Review of PR 563, round 2: a recipe put inside another value is refused too.""" + stream: Any = _keyed(9, 3).group_by(["g"]) if grouped else _source() + tokens: Any = carried_table(stream, CARRIED).column("_source_x").combine_chunks() + count = len(tokens) + struct = pa.StructArray.from_arrays([tokens, pa.array(range(count))], ["a", "b"]) + arrow: Any = pa + made: dict[str, Callable[[], Any]] = { + "struct": lambda: struct, + "list": lambda: arrow.LargeListArray.from_arrays([0, count], tokens), + "deep": lambda: arrow.ListArray.from_arrays( + [0, count], pa.StructArray.from_arrays([struct], ["s"]) + ), + "dictionary": lambda: arrow.DictionaryArray.from_arrays( + pa.array([0] * count), struct + ), + } + column = made[nested]() + table = arrow.table({"v": column}) + hasher = contexts.get_default_context().arrow_hasher + records = table.append_column( + "rid", pa.array([str(i).encode() for i in range(len(table))], pa.large_binary()) + ) + for use in ( + lambda: hasher.hash_table(table), + lambda: hasher.hash_schema(table.schema), + lambda: InMemoryArrowDatabase().add_records( + ("t",), records, record_id_column="rid", flush=True + ), + ): + with pytest.raises(TypeError, match="derived"): + _ = use() + + def test_the_carried_read_is_no_part_of_a_stream() -> None: """Review of PR 563: no public name gives a derived column.""" for stream in (_source(), ROW_WISE["chain"]()): @@ -789,36 +857,124 @@ def test_the_carried_read_is_no_part_of_a_stream() -> None: assert "carried" not in " ".join(dir(StreamProtocol)) -@pytest.mark.parametrize("grouped", [False, True]) -def test_a_spilled_table_keeps_its_recipes(grouped: bool) -> None: - """As the row spool writes it: an extension column's storage, wrapped when read.""" - stream = _keyed(50, 12) - made: Any = stream.group_by(["g"]) if grouped else stream - carried: Any = carried_table(made, CARRIED).combine_chunks() - arrow: Any = pa - batch: Any = carried.to_batches()[0] - storage = arrow.RecordBatch.from_arrays( - [getattr(c, "storage", c) for c in batch.columns], names=batch.schema.names +SPILLED: dict[str, Callable[[], Any]] = { + "source": lambda: _keyed(500, 12), + "grouped": lambda: _keyed(500, 12).group_by(["g"]), + "one_row_groups": lambda: _keyed(50, 3).group_by(["t"]), + "batch": lambda: Batch(batch_size=7)(_keyed(500, 12)), + # Two inputs, so two kinds of ids; and lists beside tokens of one a row. + "joined": lambda: Join()( + _other("a").group_by(["j"]), _other("b").group_by(["j"]).map_data({"k": "k2"}) + ), + # Lists of one source read by two groupings: equal names, other members. + "two_groupings": lambda: Join()( + _keyed(60, 4).group_by(["g"]).select_data_columns(["x", "g"]), + _keyed(60, 4) + .polars_filter(pl.col("x") > 30) + .group_by(["g"]) + .select_data_columns(["y", "g"]), + ), +} + + +def _own_chunks(table: pa.Table, sizes: list[int]) -> list[pa.Table]: + """``table`` cut into slices of ``sizes`` rows, in turn.""" + parts: list[pa.Table] = [] + start = 0 + while start < table.num_rows: + size = sizes[len(parts) % len(sizes)] + parts.append(table.slice(start, size)) + start += size + return parts + + +@pytest.mark.parametrize("limit", [0, 4096, 1 << 30]) +@pytest.mark.parametrize("sizes", [[1], [5, 2, 9], [1000]]) +@pytest.mark.parametrize("name", SPILLED) +def test_a_spooled_table_keeps_its_recipes( + name: str, sizes: list[int], limit: int, tmp_path: Path +) -> None: + """The row spool: every row back, by number and whole, lists and tokens derived.""" + carried = carried_table(SPILLED[name](), CARRIED) + text = source_tokens.materialize(carried) + assert _derived(carried) + with RowSpool(memory_bytes=limit, root=str(tmp_path)) as spool: + for part in _own_chunks(carried, sizes): + spool.append(part) + whole = spool.table() + rows = np.arange(carried.num_rows, dtype=np.int64) + for order in (rows, rows[::-1], rows[::3], rows[-1:]): + taken = spool.take(order) + assert taken.schema.equals(carried.schema, check_metadata=True) + assert_same_values( + source_tokens.materialize(taken), text.take(cast(Any, pa.array(order))) + ) + part = spool.slice(1, 3) + assert_same_values(source_tokens.materialize(part), text.slice(1, 3)) + # Also once the files are gone. + assert whole.schema.equals(carried.schema, check_metadata=True) + assert_same_values(source_tokens.materialize(whole), text) + + +def test_a_table_of_derived_columns_only_is_spooled(tmp_path: Path) -> None: + carried = carried_table(_keyed(20, 4), CARRIED) + tokens = carried.select(list(_derived(carried))) + with RowSpool(memory_bytes=0, root=str(tmp_path)) as spool: + spool.append(tokens) + taken = spool.take(np.array([3, 1], np.int64)) + assert taken.num_rows == 2 and taken.schema.equals(tokens.schema) + + +def test_a_spool_writes_a_groups_own_ids_once(tmp_path: Path) -> None: + """Two of many groups write their members' ids, not every group's, and once for all + the token columns.""" + wide = pa.table( + { + "t": pa.array(range(6000)), + "g": pa.array([f"g{i % 100}" for i in range(6000)]), + **{f"v{n}": pa.array([1.0] * 6000) for n in range(12)}, + } ) - sink = pa.BufferOutputStream() - with pa.ipc.new_file(sink, storage.schema) as writer: - writer.write_batch(storage) - read = pa.ipc.open_file(sink.getvalue()).get_batch(0) - wrapped = arrow.Table.from_arrays( - [ - arrow.ExtensionArray.from_storage(f.type, c) - if isinstance(f.type, pa.BaseExtensionType) - else c - for f, c in zip(carried.schema, read.columns, strict=True) - ], - schema=carried.schema, + stream = ArrowTableSource( + wide, tag_columns=["t", "g"], record_id_columns=["t"], source_id="s" * 40 + ).group_by(["g"]) + carried = carried_table(stream, {"source": True, "system_tags": True}) + lists = [n for n in _derived(carried) if n != "_source_g"] + assert len(lists) == 13 + ids = 120 * (len('{"t":1234}') + 8 + 8) # 120 members: text, two numbers + with RowSpool(memory_bytes=0, root=str(tmp_path)) as spool: + spool.append(carried.select(lists).slice(0, 2)) + (written,) = tmp_path.rglob("*.arrow") + assert written.stat().st_size < 4 * ids + with RowSpool(root=str(tmp_path)) as held: + held.append(carried.select(lists).slice(0, 2)) + assert held.memory_bytes < 8 * ids + + +def test_discarded_lists_are_counted_as_they_were_held() -> None: + """What a spool says it holds comes back to nothing.""" + carried = carried_table( + _keyed(500, 20).group_by(["g"]), {"source": True, "system_tags": True} ) - order = pa.array([7, 2, 2, 9]) - assert _derived(wrapped) == _derived(carried) - assert_same_values( - source_tokens.materialize(wrapped.take(order)), - source_tokens.materialize(carried).take(order), + with RowSpool() as spool: + for part in _own_chunks(carried, [3, 5]): + spool.append(part) + assert spool.memory_bytes > 0 + for start in range(0, spool.size, 4): + spool.discard(np.arange(start, min(start + 4, spool.size), dtype=np.int64)) + assert spool.memory_bytes == 0 + + +def test_a_spilled_list_pins_nothing_of_the_tables_ids() -> None: + """Rows kept in memory hold their own ids, not the dictionary of every row.""" + carried = carried_table( + _keyed(5000, 100).group_by(["g"]), {"source": True, "system_tags": True} ) + with RowSpool() as spool: + spool.append(carried.slice(0, 1)) + chunk: Any = spool.table().column("_source_x").chunk(0) + members = chunk.storage.flatten() + assert len(members.field(0).dictionary) == len(members) < 200 def test_grouped_tables_of_two_reads_are_put_together() -> None: @@ -843,7 +999,8 @@ def test_a_carried_column_has_no_bytes_and_is_not_null() -> None: taken = carried.take(pa.array([1, 5])).filter(pc.field("k") > 1) for table in (carried, taken, pa.concat_tables([carried, taken]).combine_chunks()): for name in _derived(table): - assert table.column(name).nbytes == 0 + # At most a validity bitmap. + assert table.column(name).nbytes <= table.num_rows // 8 + 1 assert table.column(name).null_count == 0 assert not table.schema.field(name).nullable