Skip to content
Merged
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
59 changes: 47 additions & 12 deletions src/orcapod/core/operators/join.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from collections.abc import Callable, Collection, Mapping, Sequence
from typing import Any, ClassVar

import polars as pl
import pyarrow as pa

from orcapod.core.operators.meta_columns import (
Expand Down Expand Up @@ -63,6 +64,44 @@
_PENDING_MEMBERS = "\x00join-pending-members\x00"


# The constant key every join adds to both sides' keys (``_with_common_key``): with it,
# inputs that share no tag give every pair, and Polars applies its multi-key rule, under
# which a row whose key holds a top-level null matches nothing (a null list, struct or
# ``decimal256`` key too, which a single-key Polars join would match with another null).
_COMMON_JOIN_KEY = "_common"


def _with_common_key(table: "pa.Table") -> "pa.Table":
"""Return ``table`` with the constant join key ``_COMMON_JOIN_KEY`` as its first column.

``int8`` explicitly, so a zero-row table gets no ``null``-typed column, which Polars
refuses in a join.
"""
return table.add_column(
0, _COMMON_JOIN_KEY, pa.array([0] * len(table), type=pa.int8())
)


def _matched_pairs(
left: "pl.DataFrame", right: "pl.DataFrame", keys: Sequence[str]
) -> "pl.DataFrame":
"""The pairs of rows a join matches: Polars' inner join of two key frames.

The one statement of which rows a join pairs, for the sync join (``_inner_join``)
and the streaming kernels. ``keys`` holds ``_COMMON_JOIN_KEY`` and both frames hold
it (``_with_common_key``); the frames are ``arrow_keys.polars_key_frame``'s.

Args:
left: The left key frame, with its row-number column.
right: The right key frame, with its row-number column.
keys: The key columns, ``_COMMON_JOIN_KEY`` among them.

Returns:
One row per matched pair, holding both row-number columns.
"""
return left.join(right, on=list(keys), how="inner")


def _inner_join(left: "pa.Table", right: "pa.Table", keys: list[str]) -> "pa.Table":
"""Inner-join two tables on their key columns, every value taken from the tables.

Expand All @@ -84,8 +123,10 @@ def _inner_join(left: "pa.Table", right: "pa.Table", keys: list[str]) -> "pa.Tab
The joined table. Its fields carry no flags of the inputs (every field
nullable); the caller restores them.
"""
pairs = polars_key_frame(left, keys, _LEFT_ROW).join(
polars_key_frame(right, keys, _RIGHT_ROW), on=keys, how="inner"
pairs = _matched_pairs(
polars_key_frame(left, keys, _LEFT_ROW),
polars_key_frame(right, keys, _RIGHT_ROW),
keys,
)
left_rows = pairs.get_column(_LEFT_ROW).to_arrow()
right_rows = pairs.get_column(_RIGHT_ROW).to_arrow()
Expand Down Expand Up @@ -413,8 +454,6 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol:
# data column (meta columns are dropped, so they never collide).
tag_schema, data_schema = self._joined_user_schemas(*streams)

COMMON_JOIN_KEY = "_common"

n_char = self.orcapod_config.hashing.system_tag_n_char

stream = ordered_streams[0]
Expand All @@ -428,9 +467,7 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol:
)
# 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
table = table.add_column(
0, COMMON_JOIN_KEY, pa.array([0] * len(table), type=pa.int8())
)
table = _with_common_key(table)
table = arrow_utils.append_to_system_tags(
table,
f"{stream.pipeline_hash().to_hex(n_char)}:0",
Expand All @@ -448,9 +485,7 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol:
)
# trick to ensure that there will always be at least one shared key
# this ensure that no overlap in keys lead to full caretesian product
next_table = next_table.add_column(
0, COMMON_JOIN_KEY, pa.array([0] * len(next_table), type=pa.int8())
)
next_table = _with_common_key(next_table)

common_tag_keys = tag_keys.intersection(next_tag_keys)
next_data_tags = set(stream_data_tags(next_stream))
Expand Down Expand Up @@ -482,7 +517,7 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol:
arrow_utils.column_arrow_type(next_table.schema, key),
)
require_matchable_key("Join", key, key_type)
common_tag_keys.add(COMMON_JOIN_KEY)
common_tag_keys.add(_COMMON_JOIN_KEY)

table_ref_schema = table.schema
table = _inner_join(table, next_table, list(common_tag_keys))
Expand All @@ -501,7 +536,7 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol:

# reorder columns to bring tag columns to the front
# TODO: come up with a better algorithm
table = table.drop(COMMON_JOIN_KEY)
table = table.drop(_COMMON_JOIN_KEY)
for name in sorted(merged_source):
table = self._fold_source_column(table, name)

Expand Down
21 changes: 9 additions & 12 deletions src/orcapod/core/operators/merge_join.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
from orcapod.core.operators.join import (
_MERGED_SOURCE_PREFIX, # pyright: ignore[reportPrivateUsage] # one definition, shared with Join
_inner_join, # pyright: ignore[reportPrivateUsage] # one definition, shared with Join
_COMMON_JOIN_KEY, # pyright: ignore[reportPrivateUsage] # one definition, shared with Join
_with_common_key, # pyright: ignore[reportPrivateUsage] # one definition, shared with Join
Join,
)
from orcapod.core.operators.key_nullability import (
Expand Down Expand Up @@ -476,24 +478,19 @@ def binary_static_process(
# Inner join on the shared tag keys. A constant key makes the join a
# cartesian product when the inputs share no tag; int8 explicitly, so a
# zero-row table doesn't produce a null-typed column (same as Join).
COMMON_JOIN_KEY = "_common"
output_nullable.pop(COMMON_JOIN_KEY, None)
left_table = left_table.add_column(
0, COMMON_JOIN_KEY, pa.array([0] * len(left_table), type=pa.int8())
)
right_table = right_table.add_column(
0, COMMON_JOIN_KEY, pa.array([0] * len(right_table), type=pa.int8())
)
join_keys = sorted(shared_tag_keys | {COMMON_JOIN_KEY})
output_nullable.pop(_COMMON_JOIN_KEY, None)
left_table = _with_common_key(left_table)
right_table = _with_common_key(right_table)
join_keys = sorted(shared_tag_keys | {_COMMON_JOIN_KEY})

# The right-table columns the join suffixes with ``_right``: those the
# left table also has, other than the keys.
left_col_set = set(left_table.column_names) - {COMMON_JOIN_KEY}
right_col_set = set(right_table.column_names) - {COMMON_JOIN_KEY}
left_col_set = set(left_table.column_names) - {_COMMON_JOIN_KEY}
right_col_set = set(right_table.column_names) - {_COMMON_JOIN_KEY}
suffixed_bases = (right_col_set & left_col_set) - set(join_keys)

joined = _inner_join(left_table, right_table, join_keys)
joined = joined.drop(COMMON_JOIN_KEY)
joined = joined.drop(_COMMON_JOIN_KEY)
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
Expand Down
28 changes: 24 additions & 4 deletions src/orcapod/core/operators/semijoin.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,29 @@
_LEFT_ROW = "__semi_join_left_row"


def _has_whole_key(
table: "pa.Table", keys: Sequence[str]
) -> "pa.ChunkedArray[Any] | pa.BooleanArray":
"""Whether each row's key holds no top-level null, as a boolean mask.

A row whose key holds a top-level null matches nothing in a semi-join: Polars
already applies that to scalar keys but treats a null struct or list as equal to
another, so such rows are dropped before the match (the sync path and the
streaming kernel alike).

Args:
table: The rows.
keys: The key columns, at least one.

Returns:
One boolean per row.
"""
valid = table.column(keys[0]).is_valid()
for name in keys[1:]:
valid = pc.and_(valid, table.column(name).is_valid())
return valid


class SemiJoin(BinaryOperator):
"""
Binary operator that performs a semi-join between two streams.
Expand Down Expand Up @@ -218,10 +241,7 @@ def binary_static_process(
# Polars already applies that to scalar keys but treats a null struct or
# list as equal to another, so drop right rows with a null key.
right_keys = right_table.select(list(common_keys))
valid = right_keys.column(0).is_valid()
for index in range(1, right_keys.num_columns):
valid = pc.and_(valid, right_keys.column(index).is_valid())
right_keys = right_keys.filter(valid)
right_keys = right_keys.filter(_has_whole_key(right_keys, common_keys))

# Polars, unlike Arrow's hash join, accepts nested (list, struct) keys.
# It decides which left rows match from the prepared keys and the left
Expand Down
Loading
Loading