Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions docs/dev/specs/itl-1464-tokens.md
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -74,9 +74,10 @@ every database's `add_records` refuse a derived column by name (`refuse_derived`
| 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 |
Expand Down Expand Up @@ -116,5 +117,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 |
40 changes: 37 additions & 3 deletions src/orcapod/core/operators/join.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ``__``.
Expand Down Expand Up @@ -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):
Expand All @@ -189,6 +203,8 @@ def _fold_pending(value: Any) -> Any:


class Join(NonZeroInputOperator):
CARRIES_TOKENS: ClassVar[bool] = True

# Data-tags (ITL-1023): handled.
DATA_TAGS_ISSUE: ClassVar[str | None] = None

Expand Down Expand Up @@ -464,7 +480,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
self._input_table(stream, 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
Expand All @@ -477,7 +494,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}),
self._input_table(
next_stream, columns={"source": True, "system_tags": True}
),
next_tag_keys,
)
next_table = arrow_utils.append_to_system_tags(
Expand Down Expand Up @@ -580,6 +599,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(
[
Expand All @@ -606,6 +636,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()],
Expand Down
20 changes: 17 additions & 3 deletions src/orcapod/core/operators/merge_join.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -156,6 +156,8 @@ class MergeJoin(BinaryOperator):
merged into a list in argument order, as for plain inputs.
"""

CARRIES_TOKENS: ClassVar[bool] = True

# Provisional: its identity is not frozen with data context v1 (ITL-1279).
PROVISIONAL: ClassVar[bool] = True

Expand Down Expand Up @@ -397,11 +399,15 @@ 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}),
self._input_table(
left_stream, 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}),
self._input_table(
right_stream, columns={"source": True, "system_tags": True}
),
self._system_tag_suffix(right_stream, 1),
)

Expand Down Expand Up @@ -429,6 +435,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

Expand Down Expand Up @@ -496,6 +508,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
Expand Down
48 changes: 43 additions & 5 deletions src/orcapod/core/operators/rejoin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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",
Expand Down Expand Up @@ -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]] = {}
Expand Down Expand Up @@ -328,6 +360,8 @@ class Rejoin(Join):
release.
"""

CARRIES_TOKENS: ClassVar[bool] = True

PROVISIONAL: ClassVar[bool] = True

def validate_nonzero_inputs(self, *streams: StreamProtocol) -> None:
Expand Down Expand Up @@ -421,12 +455,14 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol:
tag_keys, _ = stream.keys()
tables.append(
without_meta_columns(
stream.as_table(
columns={"source": True, "system_tags": True, "context": True}
self._input_table(
stream,
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)}
Expand Down Expand Up @@ -572,7 +608,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(
Expand Down
6 changes: 4 additions & 2 deletions src/orcapod/core/operators/semijoin.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ class SemiJoin(BinaryOperator):
(a null key matches nothing) and keeps the left input's type (ITL-829).
"""

CARRIES_TOKENS: ClassVar[bool] = True

CONSTRAINING_INPUTS: ClassVar[tuple[int, ...]] = (1,)
CONSTRAINT_MATCHES_SHARED_TAGS: ClassVar[bool] = True

Expand Down Expand Up @@ -224,8 +226,8 @@ def binary_static_process(
if not common_keys:
return left_stream

left_table = left_stream.as_table(
columns={"source": True, "system_tags": True, "context": True}
left_table = self._input_table(
left_stream, columns={"source": True, "system_tags": True, "context": True}
)
# Only the right side's keys are read, never its data columns.
right_table = right_stream.as_table().select(list(common_keys))
Expand Down
Loading
Loading