From ade241e2c0a91307d079289dea4bf67e4d557a74 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:07:09 -0800 Subject: [PATCH] perf(operators): GroupBy and Batch carry token lists as recipes (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/operators/batch.py | 29 +- src/orcapod/core/operators/filters.py | 22 +- src/orcapod/core/operators/group_by.py | 36 ++- src/orcapod/core/operators/rejoin.py | 8 +- .../core/operators/static_output_pod.py | 5 +- .../core/streams/arrow_table_stream.py | 41 ++- src/orcapod/core/streams/base.py | 17 +- src/orcapod/utils/arrow_utils.py | 35 +- src/orcapod/utils/source_tokens.py | 305 +++++++++++++++--- tests/test_core/streams/test_source_tokens.py | 269 ++++++++++++++- 10 files changed, 664 insertions(+), 103 deletions(-) diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index e7a1969f8..6d6a541e7 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 @@ -150,7 +150,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 = stream.as_carried_table(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 +168,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 491fa79b9..8fc269a7b 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -82,8 +82,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). @@ -106,11 +115,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..e268679fe 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 @@ -448,7 +448,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 = stream.as_carried_table(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 +518,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 +543,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 +559,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 a80921d0e..ba65070e5 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 845a7d6a7..7d46a1136 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -580,8 +580,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 09f1b1d4e..c4dc42682 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 ) @@ -491,13 +519,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 833a17347..3dfdad15d 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: ``"