diff --git a/docs/dev/specs/itl-1464-tokens.md b/docs/dev/specs/itl-1464-tokens.md index d14ceadf4..f7bbc7336 100644 --- a/docs/dev/specs/itl-1464-tokens.md +++ b/docs/dev/specs/itl-1464-tokens.md @@ -1,7 +1,7 @@ # Source-info tokens carried as a recipe (ITL-1464, track TOKENS) Status: direction approved November 25, 2026. Step 1 (sources and row-wise operators) -implemented with this document; step 2 (joins) is stacked on it. +implemented with this document; step 2 (joins) and step 3 (aggregations) are stacked on it. ## The cost @@ -64,7 +64,7 @@ every database's `add_records` refuse a derived column by name (`refuse_derived` | A function pod's outputs (`data_function.py`) | text: an output's token names the computation, not a source row | | `Pick` (`with_source_info`) | text: the token is extended | | `Index` | per row, text (the element's token) | -| `Batch`, `GroupBy` | text lists, one element per member | +| `Batch`, `GroupBy` | derived lists, one element per member (step 3) | | `Join`, `MergeJoin` merged or colliding columns | text | ## Consumers @@ -79,7 +79,7 @@ every database's `add_records` refuse a derived column by name (`refuse_derived` | `Rejoin`: a shared data-tag | equality of the tokens | one recipe in every input: equal wherever the system tags are, so not compared; otherwise text (step 2) | | `Join`: a shared data-tag | both tokens, folded (`join_v1`) | a fold recipe (`FoldRecipe`), the same fold run when the text is made; text when a member is text (step 2) | | `MergeJoin`: a colliding column | both tokens, in a list | text of that column | -| `GroupBy`, `Batch` | the members' tokens, in a list | text (below) | +| `GroupBy`, `Batch` | the members' tokens, in a list | derived lists (step 3, below) | | `iter_data` (rows: function pods, side effects, async rows) | one string per column of each row | built for 8,192 rows at a time | | `F` (`_row_built_form`, `row_built_provenance`) | types and null flags | passes a derived column through (a token is one string and never null) | | Job nodes (`core/nodes/*`) | the stored text; the kept table | text until the transport calls `carried_table` | @@ -96,15 +96,34 @@ every database's `add_records` refuse a derived column by name (`refuse_derived` | semi join | yes, all left columns | | join, rejoin | yes: each input's columns through its renamed system tags; a shared data-tag through a fold of two recipes. Not for inputs of one pipeline hash in `Join`, whose system-tag values are sorted per row | | merge join | yes for columns only one input has; a colliding column is a list of two tokens | -| group by, batch | no: the system tags are folded to one digest, the members' ids are gone. The lists must be text (or carry the members' ids, a later step) | +| group by, batch | not from the system tags, which are folded to one digest: a list column carries its members' ids | | function pod | an output: no. Inputs' tokens are not in its output | -## Aggregations - -`GroupBy` and `Batch` keep one token per member and column, so their output needs the -members' record ids: text lists are about 300 bytes per member and column. A derived list -(the members' record ids once, in one hidden list column, and recipes over it) is possible -but adds a column operators would have to carry; it is not done here. +## Aggregations (step 3) + +`GroupBy` and `Batch` fold the members' system tags into one digest, so a list of tokens +cannot be derived from the table's own system tags. A list column of `MemberTokenType` +holds its members' ids itself: its storage is `large_list>`, the two ids as dictionaries over the input's columns (a member is an index; the +ids' text is held once, the few source ids once each), the guard a struct with no field, +so Parquet refuses it. Every token column of one aggregation that reads the same system +tags shares one array of ids, so a further column costs nothing. + +- The text is made by the same `materialize`, 65,536 members at a time, and has the type + the aggregation gave it (F retypes it as it does text). +- A data-tag key's fold, and the system tags' folds, read the members' text a part at a + time, and the fold digests its canonical JSON a part at a time (the same bytes). +- A list of tokens that is aggregated again, and a token that is text, are aggregated as + 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. ## Measured @@ -118,4 +137,6 @@ A synthetic time series table, about 2.2 million rows, 13 columns, about 250 MiB | `drop_nulls` | 19.7 GiB | 2.4 GiB | 18.6 GiB | 1.7 GiB | | `polars_filter` | 16.6 GiB | 2.5 GiB | 9.3 GiB | 0.75 GiB | | `join` (8 and 14 columns) | above 24 GiB | 3.6 GiB (step 2) | | 2.6 GiB | -| `group_by` | 20.9 GiB | 20.7 GiB (its lists are text) | 15.9 GiB | 15.9 GiB | +| `group_by` | 20.9 GiB | 3.3 GiB (step 3) | 15.9 GiB | 1.6 GiB | +| `drop_nulls`, `group_by`, `map_data` | above 24 GiB | 3.9 GiB (step 3) | | 1.8 GiB | +| the same, then a function pod | above 24 GiB | 5.5 GiB (step 3) | | 2.2 GiB | diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index e7a1969f8..4f9fd8828 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -26,7 +26,7 @@ from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens from orcapod.types import Schema @@ -57,6 +57,8 @@ class Batch(UnaryOperator): drop_partial_batch: Drop a last batch with fewer than ``batch_size`` rows. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). PROVISIONAL: ClassVar[bool] = True @@ -150,7 +152,13 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: Returns: A stream with one row per batch. """ - table = stream.as_table(columns={"source": True, "system_tags": True}) + table = self._input_table(stream, columns={"source": True, "system_tags": True}) + # A list of tokens is aggregated as text (ITL-1464). + table = source_tokens.materialize( + table, + set(source_tokens.derived_columns(table.schema)) + - set(source_tokens.recipe_columns(table.schema)), + ) tag_columns, _ = stream.keys() @@ -162,25 +170,36 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: ), ) kept = table.slice(0, int(offsets[-1].as_py())) - bounds = cast(list[int], offsets.to_pylist()) # Every stream has a data context; StreamProtocol does not declare it. type_converter = stream.data_context.type_converter # pyright: ignore[reportAttributeAccessIssue] + # The source-info lists of tokens carried as recipes (ITL-1464). + recipes = source_tokens.recipe_columns(table.schema) + order = pa.array(np.arange(kept.num_rows), pa.int64()) + token_lists = source_tokens.MemberTokens(kept, order, offsets) + fields: list[pa.Field[Any]] = [] arrays: list[pa.Array[Any]] = [] for field in table.schema: + if field.name in recipes: + tokens = token_lists.column( + recipes[field.name], pa.large_list(pa.large_string()) + ) + fields.append(pa.field(field.name, tokens.type, nullable=False)) + arrays.append(tokens) + continue column = kept.column(field.name) if field.name.startswith(constants.SYSTEM_TAG_PREFIX): # Text values, folded per batch; text loses nothing in Python. - values = cast(list[Any], column.to_pylist()) + members = source_tokens.member_texts(kept, field.name, order, offsets) fields.append(field) arrays.append( pa.array( [ arrow_utils.fold_system_tag_values( - values[start:end], label=BATCH_FOLD_LABEL + values, label=BATCH_FOLD_LABEL ) - for start, end in zip(bounds[:-1], bounds[1:]) + for values in members ], field.type, ) diff --git a/src/orcapod/core/operators/filters.py b/src/orcapod/core/operators/filters.py index e0de9aad8..fc89e1699 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -84,8 +84,17 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: if derived and not self._reads_only(others): whole, derived = source_tokens.materialize(whole), () table = whole.drop_columns(list(derived)) + recipes = source_tokens.recipe_columns(whole.schema) + # A list of tokens holds its members' ids, so its kept rows are taken by number. + lists = [name for name in derived if name not in recipes] + row = arrow_utils.unused_column_name(whole, "__row") df = pl.DataFrame(table) + if lists: + df = df.with_columns(pl.int_range(pl.len()).alias(row)) filtered_table = df.filter(*self.predicates, **self.constraints).to_arrow() + kept = filtered_table.column(row) if lists else None + if lists: + filtered_table = filtered_table.drop_columns([row]) # A filter passes every column through, so each one takes the # large-normalized form of its input Arrow type (string -> # large_string, list -> large_list, recursively; hash-identical). @@ -108,11 +117,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: ) for name in derived: field = whole.schema.field(name) - recipe = source_tokens.derived_recipe(field.type) - assert recipe is not None - filtered_table = filtered_table.append_column( - field, source_tokens.derived_array(recipe, filtered_table.num_rows) - ) + if name in recipes: + column = source_tokens.derived_array( + recipes[name], filtered_table.num_rows + ) + else: + assert kept is not None + column = whole.column(name).take(kept) + filtered_table = filtered_table.append_column(field, column) filtered_table = filtered_table.select(whole.column_names) return ArrowTableStream( diff --git a/src/orcapod/core/operators/group_by.py b/src/orcapod/core/operators/group_by.py index acce7333c..7cb8a095a 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -24,7 +24,7 @@ from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens from orcapod.utils.schema_utils import column_names # GroupBy decides which rows form a group, and in what order, with Polars, and builds @@ -312,6 +312,8 @@ class GroupBy(UnaryOperator): NotImplementedError: If ``member_order`` is a function. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). PROVISIONAL: ClassVar[bool] = True @@ -448,7 +450,13 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: InputValidationError: If a key is a list of any kind, or a user tag's type has no order (``arrow_keys.part_without_rule``). """ - table = stream.as_table(columns={"source": True, "system_tags": True}) + table = self._input_table(stream, columns={"source": True, "system_tags": True}) + # A list of tokens is aggregated as text (ITL-1464). + table = source_tokens.materialize( + table, + set(source_tokens.derived_columns(table.schema)) + - set(source_tokens.recipe_columns(table.schema)), + ) tag_columns, _ = stream.keys() # The async path reaches here without ``validate_unary_input``. _refuse_unorderable_tags( @@ -512,21 +520,23 @@ def emitted(c: str) -> pa.Array[Any]: return table.column(c).take(rows).combine_chunks() def folded(c: str) -> pa.Array[Any]: - """The fold of system-tag column ``c`` per group, over the members in order.""" + """The fold of text column ``c`` per group, over the members in order.""" # The members' text values in member order, folded per group; text loses # nothing in Python. - values = cast(list[Any], table.column(c).take(order).to_pylist()) - bounds = cast(list[int], offsets.to_pylist()) return pa.array( [ arrow_utils.fold_system_tag_values( - values[start:end], label=GROUP_BY_FOLD_LABEL + members, label=GROUP_BY_FOLD_LABEL ) - for start, end in zip(bounds[:-1], bounds[1:]) + for members in source_tokens.member_texts(table, c, order, offsets) ], - table.schema.field(c).type, + pa.large_string(), ) + # The source-info lists of tokens carried as recipes (ITL-1464). + recipes = source_tokens.recipe_columns(table.schema) + token_lists = source_tokens.MemberTokens(table, order, offsets) + # Every stream has a data context; StreamProtocol does not declare it. type_converter = stream.data_context.type_converter # pyright: ignore[reportAttributeAccessIssue] fields: list[pa.Field[Any]] = [] @@ -535,7 +545,12 @@ def folded(c: str) -> pa.Array[Any]: # folded column keep their field, a member column becomes a list. for field in table.drop_columns(list(dropped_columns)).schema: c = field.name - if c in member_columns: + if c in member_columns and c in recipes: + list_type = pa.large_list(pa.large_string()) + column = token_lists.column(recipes[c], list_type) + fields.append(pa.field(c, column.type, nullable=False)) + arrays.append(column) + elif c in member_columns: list_type = arrow_utils.aggregated_list_type( field.type, type_converter, column=c ) @@ -546,7 +561,10 @@ def folded(c: str) -> pa.Array[Any]: ) ) else: - fields.append(field) + # A key's source info is one fold, text whatever its members were. + fields.append( + field.with_type(pa.large_string()) if c in recipes else field + ) arrays.append(emitted(c) if c in self.by else folded(c)) grouped_table = pa.Table.from_arrays(arrays, schema=pa.schema(fields)) diff --git a/src/orcapod/core/operators/rejoin.py b/src/orcapod/core/operators/rejoin.py index 13e7e9b03..6ea63db12 100644 --- a/src/orcapod/core/operators/rejoin.py +++ b/src/orcapod/core/operators/rejoin.py @@ -87,8 +87,12 @@ def _with_comparable_tokens(tables: Sequence["pa.Table"]) -> "list[pa.Table]": differing = { name for name, kinds in types.items() - if any(source_tokens.derived_recipe(kind) is not None for kind in kinds) - and any(kind != kinds[0] for kind in kinds) + if len(kinds) > 1 + and any(source_tokens.is_derived(kind) for kind in kinds) + and not all( + source_tokens.derived_recipe(kind) is not None and kind == kinds[0] + for kind in kinds + ) } return [source_tokens.materialize(table, differing) for table in tables] diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index c17ec38ad..0e5352aea 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -607,8 +607,9 @@ def _type_source_info_by_values(table: pa.Table) -> pa.Table: continue if pa.types.is_large_string(field.type): continue - if source_tokens.derived_recipe(field.type) is not None: - # Every token of a derived column is one string. + if source_tokens.is_derived(field.type): + # A token is one string, and a list of them is never empty: the type + # the column declares is the one its tokens give. continue values = table.column(index).to_pylist() kinds = {arrow_utils.source_info_arrow_type(value) for value in values} diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 4860839f1..e656e98cd 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -28,6 +28,30 @@ """The rows whose source-info text ``iter_data`` builds at once (ITL-1464).""" +def _parts(rows: "pa.Table") -> Iterator[tuple[int, int]]: + """The row ranges ``iter_data`` builds at once: all rows, or bounded ones (ITL-1464). + + A table with derived tokens is cut so that a part holds at most ``ROWS_PER_PART`` + rows and, beyond one row, at most eight times as many tokens in a column of lists. + """ + if not rows.num_rows: + return + if not source_tokens.derived_columns(rows.schema): + yield 0, rows.num_rows + return + members = source_tokens.members_per_row(rows) + ends = None if members is None else members.cumsum() + start = 0 + while start < rows.num_rows: + end = min(start + ROWS_PER_PART, rows.num_rows) + if ends is not None: + before = int(ends[start - 1]) if start else 0 + fit = int(ends.searchsorted(before + 8 * ROWS_PER_PART, side="right")) + end = min(end, max(fit, start + 1)) + yield start, end + start = end + + class ArrowTableStream(StreamBase): """ An immutable stream based on a PyArrow Table. @@ -93,14 +117,18 @@ def __init__( # Dictionary-encoded columns are not currently supported (ITL-1264, # ITL-1277): every source and operator result becomes a stream here, so this # refuses them all, tags and data alike. - if found := schema_utils.dictionary_columns(table.schema): + # A derived token column is no column of these types: it is text to every reader. + shown = pa.schema( + [f for f in table.schema if not source_tokens.is_derived(f.type)] + ) + if found := schema_utils.dictionary_columns(shown): raise schema_utils.dictionary_columns_error( found, tag_columns, data_tags, system_tag_columns ) # Nor are columns of a type the schema hash rejects (a union, a list view, a # run-end-encoded type; developer, November 21, 2026, ITL-640): a stream's # identity is its Arrow schema hash, which cannot hold them. - if found := schema_utils.schema_hash_rejected_columns(table.schema): + if found := schema_utils.schema_hash_rejected_columns(shown): raise schema_utils.schema_hash_rejected_columns_error( found, tag_columns, data_tags, system_tag_columns ) @@ -488,13 +516,8 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, Data]]: ) # Derived tokens become text a part of the rows at a time (ITL-1464); a # table with none is one part. - size = ( - ROWS_PER_PART - if source_tokens.derived_columns(rows.schema) - else max(rows.num_rows, 1) - ) - for start in range(0, rows.num_rows, size): - part = source_tokens.materialize(rows.slice(start, size)) + for start, end in _parts(rows): + part = source_tokens.materialize(rows.slice(start, end - start)) # The part is prepared once for all of its rows (ITL-1348): building # ``Tag(row)`` and ``Data(row)`` from one-row slices normalized every # row three times and split its columns again. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index eeaa7a16f..59d3e4591 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -341,12 +341,17 @@ def row_built_provenance(table: pa.Table) -> pa.Table: for field, column in zip(table.schema, table.columns, strict=True): if field.name.startswith(constants.SOURCE_PREFIX): # A derived token column stays derived: its text is what the rows give. - kind = ( - field.type - if source_tokens.derived_recipe(field.type) is not None - else _source_info_value_type(field.type) - ) - if kind != field.type: + if isinstance(field.type, source_tokens.MemberTokenType): + kind = field.type.with_list_type( + _source_info_value_type(field.type.list_type) + ) + if kind != field.type: + column = source_tokens.retyped(column, kind) + elif source_tokens.is_derived(field.type): + kind = field.type + else: + kind = _source_info_value_type(field.type) + if kind != column.type: column = column.cast(kind) new_field = pa.field(field.name, kind, nullable=field.nullable) elif field.name.startswith(constants.SYSTEM_TAG_PREFIX): diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index e51519cbd..f017b3190 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -1,9 +1,17 @@ from __future__ import annotations import hashlib +import itertools import json from collections import defaultdict -from collections.abc import Callable, Iterator, Mapping, Collection, Sequence +from collections.abc import ( + Callable, + Collection, + Iterable, + Iterator, + Mapping, + Sequence, +) from typing import Any, TYPE_CHECKING, cast import pyarrow as pa @@ -1471,7 +1479,11 @@ def append_to_system_tags(table: "pa.Table", value: str) -> "pa.Table": ) -def fold_system_tag_values(values: Sequence[Any], *, label: str) -> str: +_FOLD_PART = 4096 +"""How many members ``fold_system_tag_values`` digests at once.""" + + +def fold_system_tag_values(values: Iterable[Any], *, label: str) -> str: """Fold a group's system-tag values into one scalar: ``"