From 9176ee76d8744bd481d6779f020404b6acda2f03 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:49:28 -0800 Subject: [PATCH] perf(operators): joins carry source-info tokens as recipes (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-tokens.md | 11 +- src/orcapod/core/operators/join.py | 38 +++- src/orcapod/core/operators/merge_join.py | 16 +- src/orcapod/core/operators/rejoin.py | 43 ++++- src/orcapod/core/operators/semijoin.py | 2 +- src/orcapod/utils/source_tokens.py | 111 +++++++++--- tests/test_core/streams/test_source_tokens.py | 168 ++++++++++++++++++ 7 files changed, 347 insertions(+), 42 deletions(-) diff --git a/docs/dev/specs/itl-1464-tokens.md b/docs/dev/specs/itl-1464-tokens.md index 7473d3954..77000c2f8 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 a separate pull request. +implemented with this document; step 2 (joins) is stacked on it. ## The cost @@ -65,9 +65,10 @@ the system tags gives text (the recipe would have nothing to read). | Column selections, `MapData`, `MapTags`, `MapColumns`, `TagBy`, `AddTags`, `DropNulls`, `Filter` | none of the values | derived in, derived out | | `PolarsFilter` | none, unless a predicate reads a token | the columns stay out of the Polars frame and are put back for the kept rows; a predicate that could read one (a selector, a regular expression, a non-expression, a name that is no column) gets text, as before | | `without_input_meta` | names only | derived | -| `SemiJoin` (left input) | none | step 2 | -| `Join`, `Rejoin`, `MergeJoin`: columns of one input | none | step 2 | -| `Join`: a shared data-tag | both tokens, folded (`join_v1`) | step 2: a fold recipe; until then text | +| `SemiJoin` (left input) | none | derived (step 2) | +| `Join`, `Rejoin`, `MergeJoin`: columns of one input | none | derived (step 2) | +| `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) | | `iter_data` (rows: function pods, side effects, async rows) | one string per column of each row | built for 8,192 rows at a time | @@ -107,5 +108,5 @@ A synthetic time series table, about 2.2 million rows, 13 columns, about 250 MiB | `map_data` | 10.8 GiB | 2.0 GiB | 9.3 GiB | 0.75 GiB | | `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 | above 24 GiB (step 2) | | | +| `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 | diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 430957232..8ccfc80ce 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -45,7 +45,7 @@ ) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, DataValue, Schema -from orcapod.utils import arrow_utils, schema_utils +from orcapod.utils import arrow_utils, schema_utils, source_tokens # The row-number columns of the frames Polars joins (``_inner_join``); a tag, so a # key, never starts with the meta prefix ``__``. @@ -179,6 +179,20 @@ def _fold_members(tokens: Sequence[str | None]) -> str: return arrow_utils.fold_system_tag_values(ordered, label=JOIN_FOLD_LABEL) +# The two steps of the merge, for tokens carried as recipes (``source_tokens``, ITL-1464): +# the members met so far, and the fold the join ends with. +_PENDING_FOLD = "join pending" +source_tokens.register_fold(_PENDING_FOLD, _pending) +source_tokens.register_fold(JOIN_FOLD_LABEL, _fold_members) + + +def _pending_members(recipe: source_tokens.Recipe) -> tuple[source_tokens.Recipe, ...]: + """The member recipes a merged column holds so far (itself, if not pending).""" + if isinstance(recipe, source_tokens.FoldRecipe) and recipe.fold == _PENDING_FOLD: + return recipe.members + return (recipe,) + + def _fold_pending(value: Any) -> Any: """Replace every pending token position of ``value`` by its merged token.""" if isinstance(value, list): @@ -464,7 +478,8 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: # Source-info columns of merged data-tag columns, folded once at the end. merged_source: set[str] = set() table = without_meta_columns( - stream.as_table(columns={"source": True, "system_tags": True}), tag_keys + stream.as_carried_table(columns={"source": True, "system_tags": True}), + tag_keys, ) # trick to get cartesian product; use int8 explicitly so that zero-row # tables don't produce a null-typed column that Polars rejects on join @@ -477,7 +492,9 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: for idx, next_stream in enumerate(ordered_streams[1:], start=1): next_tag_keys, _ = next_stream.keys() next_table = without_meta_columns( - next_stream.as_table(columns={"source": True, "system_tags": True}), + next_stream.as_carried_table( + columns={"source": True, "system_tags": True} + ), next_tag_keys, ) next_table = arrow_utils.append_to_system_tags( @@ -580,6 +597,17 @@ def _merge_source_columns( The table with ``left_name`` holding both sides' members, pending until the join folds them (``_fold_source_column``). """ + left_recipe, right_recipe = ( + source_tokens.derived_recipe(table.schema.field(name).type) + for name in (left_name, right_name) + ) + if left_recipe is not None and right_recipe is not None: + members = (*_pending_members(left_recipe), *_pending_members(right_recipe)) + recipe = source_tokens.FoldRecipe(_PENDING_FOLD, members) + return source_tokens.with_recipe(table, left_name, recipe).drop_columns( + [right_name] + ) + table = source_tokens.materialize(table, (left_name, right_name)) field = table.schema.field(left_name) merged = pa.array( [ @@ -606,6 +634,10 @@ def _fold_source_column(table: "pa.Table", name: str) -> "pa.Table": Returns: The table with one merged token at every token position of ``name``. """ + recipe = source_tokens.derived_recipe(table.schema.field(name).type) + if recipe is not None: + fold = source_tokens.FoldRecipe(JOIN_FOLD_LABEL, _pending_members(recipe)) + return source_tokens.with_recipe(table, name, fold) field = table.schema.field(name) folded = pa.array( [_fold_pending(value) for value in table.column(name).to_pylist()], diff --git a/src/orcapod/core/operators/merge_join.py b/src/orcapod/core/operators/merge_join.py index 88abafc5a..f3729bb3e 100644 --- a/src/orcapod/core/operators/merge_join.py +++ b/src/orcapod/core/operators/merge_join.py @@ -32,7 +32,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, schema_utils +from orcapod.utils import arrow_utils, schema_utils, source_tokens def _output_types( @@ -397,11 +397,13 @@ def binary_static_process( # Tables with source info and system tags, each input's system-tag # column names extended with its pipeline hash and argument index. left_table = arrow_utils.append_to_system_tags( - left_stream.as_table(columns={"source": True, "system_tags": True}), + left_stream.as_carried_table(columns={"source": True, "system_tags": True}), self._system_tag_suffix(left_stream, 0), ) right_table = arrow_utils.append_to_system_tags( - right_stream.as_table(columns={"source": True, "system_tags": True}), + right_stream.as_carried_table( + columns={"source": True, "system_tags": True} + ), self._system_tag_suffix(right_stream, 1), ) @@ -429,6 +431,12 @@ def binary_static_process( [right_source.get(c, c) for c in right_table.column_names] ) + # A source-info column both inputs have becomes a list of both tokens: text + # (ITL-1464). Any other is carried as it is. + both = set(left_table.column_names) & set(right_table.column_names) + left_table = source_tokens.materialize(left_table, both) + right_table = source_tokens.materialize(right_table, both) + # Find colliding data columns (a merged data-tag column is not one) colliding_keys = (set(left_data_keys) & set(right_data_keys)) - merged @@ -496,6 +504,8 @@ def binary_static_process( for left_name, right_name in right_source.items(): joined = Join._merge_source_columns(joined, left_name, right_name) # pyright: ignore[reportPrivateUsage] # Join's one rule joined = Join._fold_source_column(joined, left_name) # pyright: ignore[reportPrivateUsage] # Join's one rule + # A merge of derived tokens has a recipe, so a type, of its own (ITL-1464). + output_types[left_name] = joined.schema.field(left_name).type # Use the left stream's type converter — not the default context — so that a # MergeJoin over streams built with a non-default DataContext reconstructs the diff --git a/src/orcapod/core/operators/rejoin.py b/src/orcapod/core/operators/rejoin.py index d760f5865..a80921d0e 100644 --- a/src/orcapod/core/operators/rejoin.py +++ b/src/orcapod/core/operators/rejoin.py @@ -48,7 +48,7 @@ ) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, Schema -from orcapod.utils import arrow_utils, schema_utils +from orcapod.utils import arrow_utils, schema_utils, source_tokens from orcapod.utils.warning_utils import outside_orcapod_stacklevel # Row-number columns of the frames Polars matches, and the column of a row's occurrence @@ -66,6 +66,38 @@ def _system_tag_names(stream: StreamProtocol) -> list[str]: ) +def _with_comparable_tokens(tables: Sequence["pa.Table"]) -> "list[pa.Table]": + """Give each shared source-info column one form: one recipe, or text (ITL-1464). + + Rejoin compares a shared column's values. When every input that has a token column + derives it by one recipe, it is equal wherever the system tags are, which the rows + already match on, so it stays derived and is not compared (``_agrees_by_recipe``). + Otherwise its text is built in every input. + + Args: + tables: The inputs' rows. + + Returns: + The same tables; a derived column several of them have has one recipe. + """ + types: dict[str, list[pa.DataType]] = {} + for table in tables: + for field in table.schema: + types.setdefault(field.name, []).append(field.type) + 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) + } + return [source_tokens.materialize(table, differing) for table in tables] + + +def _agrees_by_recipe(table: "pa.Table", name: str) -> bool: + """Whether column ``name`` is derived, so rows with equal system tags agree on it.""" + return source_tokens.derived_recipe(table.schema.field(name).type) is not None + + def _agreeing( pairs: "pl.DataFrame", left: "pa.Table", @@ -207,7 +239,7 @@ def _differing_columns(tables: Sequence["pa.Table"], keys: Sequence[str]) -> lis holders: dict[str, list[int]] = {} for index, table in enumerate(tables): for name in table.column_names: - if name not in keys: + if name not in keys and not _agrees_by_recipe(table, name): holders.setdefault(name, []).append(index) # The columns several inputs have, by the inputs that have them. shared: dict[tuple[int, ...], list[str]] = {} @@ -421,12 +453,13 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: tag_keys, _ = stream.keys() tables.append( without_meta_columns( - stream.as_table( + stream.as_carried_table( columns={"source": True, "system_tags": True, "context": True} ), tag_keys, ) ) + tables = _with_comparable_tokens(tables) # The rule on the tables themselves, in call order: an input whose schema # states no system tag (``_require_rejoinable``) is checked here. by_call = {id(stream): table for stream, table in zip(ordered_streams, tables)} @@ -572,7 +605,9 @@ def _rejoin_pair( others = [ name for name in right.column_names - if name in left.column_names and name not in keys + if name in left.column_names + and name not in keys + and not _agrees_by_recipe(left, name) ] for name in sorted(others): shared_type = require_shared_arrow_type( diff --git a/src/orcapod/core/operators/semijoin.py b/src/orcapod/core/operators/semijoin.py index d2a379f50..1d59f8a91 100644 --- a/src/orcapod/core/operators/semijoin.py +++ b/src/orcapod/core/operators/semijoin.py @@ -224,7 +224,7 @@ def binary_static_process( if not common_keys: return left_stream - left_table = left_stream.as_table( + left_table = left_stream.as_carried_table( columns={"source": True, "system_tags": True, "context": True} ) # Only the right side's keys are read, never its data columns. diff --git a/src/orcapod/utils/source_tokens.py b/src/orcapod/utils/source_tokens.py index 0fd59bcfc..c68537e77 100644 --- a/src/orcapod/utils/source_tokens.py +++ b/src/orcapod/utils/source_tokens.py @@ -18,9 +18,9 @@ from __future__ import annotations import json -from collections.abc import Collection, Mapping +from collections.abc import Callable, Collection, Mapping, Sequence from dataclasses import dataclass -from typing import Any, NoReturn, cast +from typing import Any, NoReturn, TypeAlias, cast import pyarrow as pa import pyarrow.compute as pc @@ -33,6 +33,20 @@ """The most rows whose token text is built in one step.""" +_folds: dict[str, Callable[[Sequence[str | None]], str]] = {} + + +def register_fold(name: str, fold: Callable[[Sequence[str | None]], str]) -> None: + """Say how a ``FoldRecipe`` named ``name`` makes one token of several. + + Args: + name: The fold's name; for a fold with an algorithm label, the label. + fold: One token from the members' tokens. Called once per row, with the members + in the recipe's order. + """ + _folds[name] = fold + + @dataclass(frozen=True) class TokenRecipe: """How the token of each row is made from the row's system tags. @@ -48,14 +62,14 @@ class TokenRecipe: record_id: str column: str - def to_json(self) -> str: - """The recipe as text: what two equal recipes share.""" - return json.dumps([self.source_id, self.record_id, self.column]) + def to_json(self) -> Any: # pyright: ignore[reportExplicitAny] # JSON + """The recipe as a JSON value: what two equal recipes share.""" + return [self.source_id, self.record_id, self.column] - @classmethod - def from_json(cls, text: str) -> TokenRecipe: - """The recipe ``to_json`` wrote.""" - return cls(*json.loads(text)) + @property + def read_columns(self) -> frozenset[str]: + """The system-tag columns the recipe reads.""" + return frozenset((self.source_id, self.record_id)) def renamed(self, names: Mapping[str, str]) -> TokenRecipe: """The recipe over system-tag columns renamed by ``names``.""" @@ -65,10 +79,6 @@ def renamed(self, names: Mapping[str, str]) -> TokenRecipe: self.column, ) - def reads(self, columns: Collection[str]) -> bool: - """Whether the recipe reads one of ``columns``.""" - return self.source_id in columns or self.record_id in columns - def text(self, batch: pa.RecordBatch) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array """The tokens of ``batch``'s rows, as ``large_string``.""" return pc.binary_join_element_wise( # pyright: ignore[reportCallIssue, reportUnknownVariableType] # the stubs leave out scalar arguments @@ -79,6 +89,52 @@ def text(self, batch: pa.RecordBatch) -> pa.Array[Any]: # pyright: ignore[repor ) +@dataclass(frozen=True) +class FoldRecipe: + """How one token is made of the tokens of several merged columns, row by row. + + Attributes: + fold: The registered fold (``register_fold``). + members: The merged columns' recipes, in the order they were met. + """ + + fold: str + members: tuple[Recipe, ...] + + def to_json(self) -> Any: # pyright: ignore[reportExplicitAny] # JSON + """The recipe as a JSON value: what two equal recipes share.""" + return {"fold": self.fold, "members": [m.to_json() for m in self.members]} + + @property + def read_columns(self) -> frozenset[str]: + """The system-tag columns the members read.""" + return frozenset[str]().union(*(m.read_columns for m in self.members)) + + def renamed(self, names: Mapping[str, str]) -> FoldRecipe: + """The recipe over system-tag columns renamed by ``names``.""" + return FoldRecipe(self.fold, tuple(m.renamed(names) for m in self.members)) + + def text(self, batch: pa.RecordBatch) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array + """The tokens of ``batch``'s rows, as ``large_string``.""" + fold = _folds[self.fold] + members = [member.text(batch).to_pylist() for member in self.members] + return pa.array( + [fold(tokens) for tokens in zip(*members, strict=True)], type=_TEXT + ) + + +Recipe: TypeAlias = TokenRecipe | FoldRecipe + + +def recipe_from_json(value: Any) -> Recipe: # pyright: ignore[reportExplicitAny, reportAny] # JSON + """The recipe whose ``to_json`` is ``value``.""" + if isinstance(value, dict): + return FoldRecipe( + value["fold"], tuple(recipe_from_json(m) for m in value["members"]) + ) + return TokenRecipe(*value) + + class _DerivedTokenScalar(pa.ExtensionScalar): """A value of a derived column: it has none to read.""" @@ -102,18 +158,18 @@ class DerivedTokenType(pa.ExtensionType): wrapped in its type again. Two derived columns have one type only with one recipe. """ - def __init__(self, recipe: TokenRecipe) -> None: + def __init__(self, recipe: Recipe) -> None: self.recipe = recipe super().__init__(pa.struct([]), "orcapod.internal.derived_token") def __arrow_ext_serialize__(self) -> bytes: - return self.recipe.to_json().encode() + return json.dumps(self.recipe.to_json()).encode() @classmethod def __arrow_ext_deserialize__( cls, storage_type: pa.DataType, serialized: bytes ) -> DerivedTokenType: - return cls(TokenRecipe.from_json(serialized.decode())) + return cls(recipe_from_json(json.loads(serialized))) def __arrow_ext_scalar_class__(self) -> type[pa.ExtensionScalar]: return _DerivedTokenScalar @@ -137,14 +193,14 @@ def __hash__(self) -> int: return hash(self.recipe) -def derived_array(recipe: TokenRecipe, rows: int) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array +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) return pa.ExtensionArray.from_storage(DerivedTokenType(recipe), storage) -def derived_recipe(kind: pa.DataType) -> TokenRecipe | None: +def derived_recipe(kind: pa.DataType) -> Recipe | None: """The recipe of a column of type ``kind``; ``None`` when it is not derived.""" return kind.recipe if isinstance(kind, DerivedTokenType) else None @@ -154,6 +210,13 @@ def derived_columns(schema: pa.Schema) -> tuple[str, ...]: return tuple(f.name for f in schema if derived_recipe(f.type) is not None) +def with_recipe(table: pa.Table, name: str, recipe: Recipe) -> pa.Table: + """``table`` with its token column ``name`` derived by ``recipe``, its field kept.""" + tokens = derived_array(recipe, table.num_rows) + field = table.schema.field(name).with_type(tokens.type) + return table.set_column(table.schema.get_field_index(name), field, tokens) + + def materialize(table: pa.Table, names: Collection[str] | None = None) -> pa.Table: """Return ``table`` with its derived token columns as text. @@ -171,12 +234,12 @@ def materialize(table: pa.Table, names: Collection[str] | None = None) -> pa.Tab if not wanted: return table schema = table.schema - recipes: dict[str, TokenRecipe] = {} + recipes: dict[str, Recipe] = {} for name in wanted: recipe = derived_recipe(schema.field(name).type) assert recipe is not None recipes[name] = recipe - read = {c for r in recipes.values() for c in (r.source_id, r.record_id)} + read = {c for recipe in recipes.values() for c in recipe.read_columns} tags = table.select([c for c in table.column_names if c in read]) chunks: dict[str, list[pa.Array[Any]]] = {name: [] for name in wanted} # pyright: ignore[reportExplicitAny] # Arrow arrays for batch in tags.to_batches(max_chunksize=ROWS_PER_CHUNK): @@ -204,7 +267,7 @@ def materialize_reading(table: pa.Table, columns: Collection[str]) -> pa.Table: name for name in derived_columns(table.schema) if (recipe := derived_recipe(table.schema.field(name).type)) is not None - and recipe.reads(columns) + and not recipe.read_columns.isdisjoint(columns) ], ) @@ -226,9 +289,5 @@ def rename_read_columns(table: pa.Table, names: Mapping[str, str]) -> pa.Table: renamed = recipe.renamed(names) if renamed == recipe: continue - table = table.set_column( - table.schema.get_field_index(name), - field.with_type(DerivedTokenType(renamed)), - derived_array(renamed, table.num_rows), - ) + table = with_recipe(table, name, renamed) return table diff --git a/tests/test_core/streams/test_source_tokens.py b/tests/test_core/streams/test_source_tokens.py index 40eb740ea..0480d5744 100644 --- a/tests/test_core/streams/test_source_tokens.py +++ b/tests/test_core/streams/test_source_tokens.py @@ -20,6 +20,7 @@ from orcapod import contexts from orcapod.core.data_tags import stream_data_tags 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.streams import ArrowTableStream from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS @@ -29,10 +30,13 @@ DropColumns, DropNulls, DropTagColumns, + Join, MapColumns, MapData, MapTags, + MergeJoin, PolarsFilter, + Rejoin, SelectDataColumns, TagBy, ) @@ -178,6 +182,170 @@ def test_every_operator_gives_what_text_sources_give( assert_same_values(table, expected) +def _other(name: str, **kwargs: Any) -> ArrowTableSource: + """A source sharing the data-tags ``k`` and ``j``, of its own schema (``name``).""" + table = pa.table( + { + f"{name}1": pa.array([float(i) for i in range(12)]), + "j": pa.array([f"j{i % 3}" for i in range(12)]), + "k": pa.array(reversed(range(12)), pa.int32()), + f"{name}2": pa.array([f"v{i}" for i in range(12)]), + } + ) + return ArrowTableSource(table, tag_columns=["j", "k"], **kwargs) + + +def _text_other(name: str) -> ArrowTableStream: + """``_other`` as a raw stream whose tokens are text already.""" + source = _other(name) + return ArrowTableStream( + source.as_table(columns={"source": True, "system_tags": True}), + tag_columns=["j", "k"], + data_tags=["j", "k"], + ) + + +MATCHES: dict[str, tuple[Callable[[], Any], set[str]]] = { + # The columns whose tokens may be text after it, by name; every other is derived. + "join_2": (lambda: _other("a").join(_other("b")), set()), + "join_2_swapped": (lambda: _other("b").join(_other("a")), set()), + "join_3": (lambda: Join()(_other("c"), _other("a"), _other("b")), set()), + "join_chain": (lambda: _other("a").join(_other("b")).join(_other("c")), set()), + "join_then_row_wise": ( + lambda: ( + _other("a") + .join(_other("b")) + .map_data({"a1": "x", "b2": "y"}) + .drop_nulls() + .polars_filter(pl.col("x") > 3) + ), + set(), + ), + "join_tag_only": ( + lambda: _source().join(_other("a", tag_only_columns=["j"])), + set(), + ), + "join_text_member": ( + lambda: Join()(_other("a"), _text_other("b"), _other("c")), + {"j", "k", "b1", "b2"}, + ), + "join_one_schema": ( + lambda: ( + _other("a", source_id="s2") + .map_data({"a1": "p", "a2": "q"}) + .join(_other("a", source_id="s1").map_data({"a1": "p2", "a2": "q2"})) + ), + set(), + ), + "semi_join": (lambda: _source().semi_join(_plain_source()), set()), + "merge_join": ( + lambda: MergeJoin()( + _other("a").map_data({"a2": "same"}), _other("b").map_data({"b2": "same"}) + ), + {"same"}, + ), + "rejoin": ( + lambda: Rejoin()( + _other("a").select_data_columns(["a1", "j", "k"]), + _other("a").select_data_columns(["a2", "j", "k"]), + ), + set(), + ), + "rejoin_filtered": ( + lambda: Rejoin()( + _other("a").select_data_columns(["a1", "j", "k"]), + _other("a").polars_filter(pl.col("a1") > 3).drop_data_columns(["a1"]), + ), + set(), + ), +} + + +@pytest.mark.parametrize("name", MATCHES) +def test_a_match_carries_the_tokens_and_gives_the_same_rows( + name: str, text_sources: Callable[[], None] +) -> None: + make, text = MATCHES[name] + result = make() + carried = result.as_carried_table(columns={"source": True, "system_tags": True}) + tokens = { + c.removeprefix("_source_") + for c in carried.column_names + if c.startswith(constants.SOURCE_PREFIX) + } + derived = {c.removeprefix("_source_") for c in _derived(carried)} + assert tokens - derived == text & tokens + table = result.as_table(all_info=True) + rows = [(t.as_dict(all_info=True), d.as_dict(all_info=True)) for t, d in result] + assert table.num_rows > 0 + text_sources() + oracle = make() + expected = oracle.as_table(all_info=True) + assert table.schema.equals(expected.schema, check_metadata=True) + assert_same_values(table, expected) + assert rows == [ + (t.as_dict(all_info=True), d.as_dict(all_info=True)) for t, d in oracle + ] + + +@pytest.mark.parametrize("order", [("s1", "s2"), ("s2", "s1")]) +def test_inputs_of_one_pipeline_hash_keep_their_own_tokens( + order: tuple[str, str], text_sources: Callable[[], None] +) -> None: + """Two sources of one schema, every column a data-tag: the join sorts their + system-tag values per row, so the tokens that read them are text first.""" + + def make() -> Any: + streams = [ + ArrowTableSource( + _table().select(["k", "j"]).slice(i), + tag_columns=["k", "j"], + source_id=s, + ) + for i, s in enumerate(order) + ] + assert streams[0].pipeline_hash() == streams[1].pipeline_hash() + return streams[0].join(streams[1]) + + result = make() + assert not _derived(result.as_carried_table(columns=CARRIED)) + table = result.as_table(all_info=True) + text_sources() + expected = make().as_table(all_info=True) + assert table.num_rows == 9 + assert table.schema.equals(expected.schema, check_metadata=True) + assert_same_values(table, expected) + + +def test_a_join_fold_is_the_fold_of_its_members() -> None: + """The merged token is ``join_v1`` of the inputs' own tokens, whatever the order.""" + a, b = _other("a"), _other("b") + table = a.join(b).as_table(columns={"source": True}) + own = [ + dict(zip(t["k"].to_pylist(), t["_source_k"].to_pylist(), strict=True)) + for t in (s.as_table(columns={"source": True}) for s in (a, b)) + ] + for key, token in zip( + table["k"].to_pylist(), table["_source_k"].to_pylist(), strict=True + ): + assert token == arrow_utils.fold_system_tag_values( + sorted(tokens[key] for tokens in own), label=JOIN_FOLD_LABEL + ) + + +def test_a_recipe_survives_its_json() -> None: + leaf = source_tokens.TokenRecipe("s", "r", "c") + fold = source_tokens.FoldRecipe( + JOIN_FOLD_LABEL, (leaf, source_tokens.FoldRecipe(JOIN_FOLD_LABEL, (leaf, leaf))) + ) + for recipe in (leaf, fold): + kind = source_tokens.DerivedTokenType(recipe) + again = source_tokens.DerivedTokenType.__arrow_ext_deserialize__( + pa.struct([]), kind.__arrow_ext_serialize__() + ) + assert again == kind and again.recipe == recipe + + def _column_configs() -> list[dict[str, bool]]: groups = ("source", "system_tags", "context", "content_hash", "sort_by_tags") return [