From 2818eba7a199658838fdb7c580036f4b8a051c15 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:20:41 -0800 Subject: [PATCH 01/26] feat(core): row spool, rows fetched by number from memory and local disk (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/row_spool.py | 359 ++++++++++++++++++++++++++++++ tests/test_core/test_row_spool.py | 238 ++++++++++++++++++++ 2 files changed, 597 insertions(+) create mode 100644 src/orcapod/core/row_spool.py create mode 100644 tests/test_core/test_row_spool.py diff --git a/src/orcapod/core/row_spool.py b/src/orcapod/core/row_spool.py new file mode 100644 index 000000000..e56b5c8d7 --- /dev/null +++ b/src/orcapod/core/row_spool.py @@ -0,0 +1,359 @@ +"""Rows held for a later fetch by row number: some in memory, the rest on local disk. + +A join on the async path keeps its inputs' join keys in memory and the rows behind them +here (ITL-1464). ``RowSpool.append`` numbers rows in the order they come; ``take`` fetches +rows by those numbers; ``discard`` says that rows are never fetched again. + +Format: rows wait in memory until they exceed a byte limit, then become one segment: an +Arrow IPC file of one record batch, uncompressed, read memory-mapped (a mapped page is +the operating system's to drop, not memory this process holds). An extension column is +written as its storage and wrapped again when read, so reading needs no registered type. + +Lifetime: a segment is deleted once every row of it is discarded; a spool's files are +removed by ``close`` (a spool is a context manager: normal end, exception and +cancellation alike) and when it is collected. A process keeps its spools in one directory +of its own, removed at interpreter exit. A killed process leaves its directory behind; the +next process to spill there removes it: every directory holds a lock file its process +keeps locked, so a directory whose lock is free has no owner. (Without ``fcntl``, as on +Windows, nothing is swept.) A spool is not a store: nothing in it outlives the run, is +found by a later process as rows, or enters a hash. +""" + +from __future__ import annotations + +import atexit +import os +import shutil +import tempfile +import threading +import weakref +from typing import IO, Any, Self + +import numpy as np +import numpy.typing as npt +import pyarrow as pa + +try: + import fcntl +except ImportError: # no such module on Windows + fcntl = None + +SPOOL_MEMORY_BYTES = 64 * 1024 * 1024 +"""How many bytes of rows a spool keeps in memory before they become a segment.""" + +_PREFIX = "orcapod-spool-" +_LOCK_NAME = "lock" + + +class _ProcessDirectories: + """The directory of this process under each root, made and swept on first use.""" + + def __init__(self) -> None: + self._guard = threading.Lock() + self._pid: int = os.getpid() + self._held: dict[str, tuple[str, IO[str]]] = {} + + def get(self, root: str) -> str: + """This process's directory under ``root``.""" + with self._guard: + if self._pid != os.getpid(): + # A forked child: the directories held are its parent's. + self._pid, self._held = os.getpid(), {} + if root not in self._held or not os.path.isdir(self._held[root][0]): + self._held[root] = _make_process_directory(root) + return self._held[root][0] + + def remove(self) -> None: + """Remove this process's directories (at exit).""" + if self._pid != os.getpid(): + return # a forked child holds none of its own + for directory, lock in self._held.values(): + shutil.rmtree(directory, ignore_errors=True) + lock.close() + self._held = {} + + +def _make_process_directory(root: str) -> tuple[str, IO[str]]: + """Make this process's directory under ``root``, locked, and sweep abandoned ones. + + Both happen under one lock of the root, so a sweep never sees a directory that is + made but not yet locked. + """ + os.makedirs(root, exist_ok=True) + if fcntl is None: + directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) + return directory, open(os.path.join(directory, _LOCK_NAME), "w") + name = os.path.join(root, f".{_PREFIX}{os.getuid()}.lock") + flags = os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC + with os.fdopen(os.open(name, flags, 0o600), "w") as root_lock: + fcntl.flock(root_lock, fcntl.LOCK_EX) + _sweep(root) + directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) + lock = open(os.path.join(directory, _LOCK_NAME), "w") + fcntl.flock(lock, fcntl.LOCK_EX) + return directory, lock + + +def _sweep(root: str) -> None: + """Remove this user's spool directories under ``root`` that no process holds.""" + assert fcntl is not None + with os.scandir(root) as entries: + candidates = [ + entry.path + for entry in entries + if entry.name.startswith(_PREFIX) and entry.is_dir(follow_symlinks=False) + ] + for directory in candidates: + try: + if os.stat(directory).st_uid != os.getuid(): + continue + with open(os.path.join(directory, _LOCK_NAME)) as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + shutil.rmtree(directory, ignore_errors=True) + except OSError: + continue # held by a live process, being removed, or not a spool's + + +_directories = _ProcessDirectories() +_ = atexit.register(_directories.remove) + + +def _remove_directory(directory: str, owner: int) -> None: + """Remove a spool's directory, in the process that made it only.""" + if os.getpid() == owner: + shutil.rmtree(directory, ignore_errors=True) + + +class _Segment: + """Rows of one run of row numbers, in memory (``table``) or in a file (``path``).""" + + def __init__(self, start: int, table: pa.Table) -> None: + self.start: int = start + self.rows: int = table.num_rows + self.live: int = table.num_rows + self.table: pa.Table | None = table + self.path: str | None = None + + def drop(self) -> None: + """Let the rows go, and delete their file.""" + self.table = None + if self.path is not None: + os.unlink(self.path) + self.path = None + + +class RowSpool: + """Rows numbered from 0 in the order appended, fetched by number. + + Args: + memory_bytes: How many bytes of rows stay in memory; beyond that the rows in + memory are written to a file. + root: The directory to keep files under; by default the system's temporary + directory. Nothing is made there until rows are written. + """ + + def __init__( + self, memory_bytes: int = SPOOL_MEMORY_BYTES, root: str | None = None + ) -> None: + self._memory_bytes: int = memory_bytes + self._root: str | None = root + self._closed: bool = False + self._schema: pa.Schema | None = None + self._segments: list[_Segment] = [] + self._starts: npt.NDArray[np.int64] | None = None + self._in_memory: int = 0 + self._directory: str | None = None + self._cleanup: weakref.finalize[..., Any] | None = None # pyright: ignore[reportExplicitAny] # any finalizer + self.size: int = 0 + """How many rows were appended: the next row's number.""" + + @property + def memory_bytes(self) -> int: + """How many bytes of rows are in memory now.""" + return self._in_memory + + def append(self, table: pa.Table) -> None: + """Hold ``table``'s rows, numbered from ``size`` on. + + Args: + table: The rows; every table appended has one schema. + + Raises: + ValueError: If the spool is closed. + OSError: If the rows in memory cannot be written to the local disk. + """ + if self._closed: + raise ValueError("the row spool is closed") + if not table.num_rows: + return + if self._schema is None: + self._schema = table.schema + # One chunk that owns its rows: a slice would keep its whole parent alive. + self._add(_Segment(self.size, _owned(table))) + self.size += table.num_rows + if self._in_memory > self._memory_bytes: + self._spill() + + def _add(self, segment: _Segment) -> None: + self._segments.append(segment) + self._starts = None + if segment.table is not None: + self._in_memory += segment.table.nbytes + + def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: + """The rows with these numbers, in this order, as one chunk per column. + + Only the segments that hold a wanted row are read, each once. + + Args: + rows: Row numbers, at least one, none of them discarded. + """ + if self._starts is None: + self._starts = np.fromiter( + (s.start for s in self._segments), np.int64, len(self._segments) + ) + held_in = np.searchsorted(self._starts, rows, side="right") - 1 + order = np.argsort(held_in, kind="stable") + sorted_rows, sorted_in = rows[order], held_in[order] + edges = np.flatnonzero(np.diff(sorted_in)) + 1 + parts: list[pa.Table] = [] + for group in np.split(np.arange(len(rows)), edges): + segment = self._segments[int(sorted_in[group[0]])] + local = pa.array(sorted_rows[group] - segment.start, pa.int64()) + parts.append(self._take_from(segment, local)) + if len(parts) == 1: + # One segment: the stable sort changed nothing. + return parts[0].combine_chunks() + taken = pa.concat_tables(parts).combine_chunks() + back = np.empty(len(order), np.int64) + back[order] = np.arange(len(order)) + return taken.take(pa.array(back, pa.int64())).combine_chunks() + + def _take_from(self, segment: _Segment, local: pa.Array[Any]) -> pa.Table: # pyright: ignore[reportExplicitAny] # row numbers + """Rows of one segment, by their numbers in it.""" + if segment.table is not None: + return segment.table.take(local) + assert segment.path is not None and self._schema is not None + with pa.memory_map(segment.path) as mapped: + stored = pa.ipc.open_file(mapped).read_all() + return _wrapped(stored.take(local), self._schema) + + def discard(self, rows: npt.NDArray[np.int64]) -> None: + """Say that these rows are never fetched again. + + A segment whose rows are all discarded is let go, and its file deleted. + + Args: + rows: Row numbers, each discarded once only. + """ + if not len(rows): + return + starts = np.fromiter( + (s.start for s in self._segments), np.int64, len(self._segments) + ) + held_in = np.searchsorted(starts, rows, side="right") - 1 + counts = np.bincount(held_in, minlength=len(self._segments)) + emptied = False + for index in np.flatnonzero(counts): + segment = self._segments[int(index)] + segment.live -= int(counts[index]) + if not segment.live: + if segment.table is not None: + self._in_memory -= segment.table.nbytes + segment.drop() + emptied = True + if emptied: + self._segments = [s for s in self._segments if s.live] + self._starts = None + + def _spill(self) -> None: + """Write the segments in memory to one file, as one segment.""" + waiting = [s for s in self._segments if s.table is not None] + assert self._schema is not None + # Neighbours only: a segment's rows have consecutive numbers. + runs: list[list[_Segment]] = [] + for segment in waiting: + if runs and runs[-1][-1].start + runs[-1][-1].rows == segment.start: + runs[-1].append(segment) + else: + runs.append([segment]) + for run in runs: + tables = [s.table for s in run if s.table is not None] + table = pa.concat_tables(tables).combine_chunks() + merged = _Segment(run[0].start, table) + merged.live = sum(s.live for s in run) + merged.path = self._write(merged) + merged.table = None + replaced = set(map(id, run)) + position = self._segments.index(run[0]) + self._segments = [s for s in self._segments if id(s) not in replaced] + self._segments.insert(position, merged) + self._in_memory -= sum(t.nbytes for t in tables) + self._starts = None + + def _write(self, segment: _Segment) -> str: + """Write a segment's rows to a file of their own; return its path.""" + assert segment.table is not None + if self._directory is None: + process_directory = _directories.get(self._root or tempfile.gettempdir()) + self._directory = tempfile.mkdtemp(dir=process_directory) + self._cleanup = weakref.finalize( + self, _remove_directory, self._directory, os.getpid() + ) + path = os.path.join(self._directory, f"{segment.start}.arrow") + table = _as_storage(segment.table) + with ( + pa.OSFile(path, "wb") as sink, + pa.ipc.new_file(sink, table.schema) as writer, + ): + writer.write_table(table) + return path + + def close(self) -> None: + """Let every row go and remove the files. Calling it again does nothing.""" + self._closed = True + self._segments = [] + self._starts = None + self._in_memory = 0 + if self._cleanup is not None: + _ = self._cleanup() + self._directory = self._cleanup = None + + def __enter__(self) -> Self: + return self + + def __exit__(self, *exc: object) -> None: + self.close() + + +def _owned(table: pa.Table) -> pa.Table: + """``table`` as one chunk over buffers of its own size, copied only if needed.""" + table = table.combine_chunks() + if table.get_total_buffer_size() > 2 * table.nbytes: + table = table.take(pa.array(np.arange(table.num_rows), pa.int64())) + return table + + +def _as_storage(table: pa.Table) -> pa.Table: + """``table`` with each extension column as its storage, no field metadata. + + Flags are dropped too: a field declared non-nullable may hold a null (a column not + settled yet), and ``_wrapped`` puts the schema back. + """ + columns: list[Any] = [] # pyright: ignore[reportExplicitAny] # any column + for column in table.combine_chunks().columns: + array: Any = column.chunk(0) # pyright: ignore[reportExplicitAny] # any column + is_extension = isinstance(column.type, pa.BaseExtensionType) + columns.append(array.storage if is_extension else array) + return pa.Table.from_arrays(columns, names=table.column_names) + + +def _wrapped(table: pa.Table, schema: pa.Schema) -> pa.Table: + """Undo ``_as_storage``: the columns of ``table``, one chunk each, under ``schema``.""" + columns: list[Any] = [] # pyright: ignore[reportExplicitAny] # any column + for column, field in zip(table.combine_chunks().columns, schema): + array = column.chunk(0) + if isinstance(field.type, pa.BaseExtensionType): + array = pa.ExtensionArray.from_storage(field.type, array) + columns.append(array) + return pa.Table.from_arrays(columns, schema=schema) diff --git a/tests/test_core/test_row_spool.py b/tests/test_core/test_row_spool.py new file mode 100644 index 000000000..848fcb94a --- /dev/null +++ b/tests/test_core/test_row_spool.py @@ -0,0 +1,238 @@ +"""Rows held by number, in memory and on local disk (``core/row_spool``, ITL-1464).""" + +from __future__ import annotations + +import asyncio +import gc +import os +import subprocess +import sys +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import pyarrow as pa +import pytest + +from orcapod.core import row_spool +from orcapod.core.row_spool import RowSpool + + +def _table(start: int, rows: int) -> pa.Table: + """Rows with two tags and two data columns, a list and an extension among them.""" + numbers = list(range(start, start + rows)) + return pa.table( + { + "session": pa.array([f"s{n % 3}" for n in numbers], pa.large_string()), + "at": pa.array( + [datetime.fromtimestamp(n, timezone.utc) for n in numbers], + pa.timestamp("us", "UTC"), + ), + "values": pa.array( + [None if n % 5 == 0 else [n, None] for n in numbers], + pa.large_list(pa.int64()), + ), + "id": pa.ExtensionArray.from_storage( + pa.uuid(), + pa.array([n.to_bytes(16, "big") for n in numbers], pa.binary(16)), + ), + } + ) + + +def _filled( + root: Path, sizes: list[int], memory_bytes: int +) -> tuple[RowSpool, pa.Table]: + spool = RowSpool(memory_bytes, str(root)) + tables, start = [], 0 + for size in sizes: + tables.append(_table(start, size)) + spool.append(tables[-1]) + start += size + return spool, pa.concat_tables(tables) + + +def _files(root: Path) -> list[Path]: + return sorted(root.rglob("*.arrow")) + + +@pytest.mark.parametrize("memory_bytes", [0, 3_000, 10**9]) +def test_rows_come_back_by_number_in_the_order_asked( + tmp_path: Path, memory_bytes: int +) -> None: + spool, rows = _filled(tmp_path, [1, 50, 0, 7, 120, 3], memory_bytes) + assert spool.size == rows.num_rows + assert bool(_files(tmp_path)) == (memory_bytes < 10**9) + assert spool.memory_bytes <= max(memory_bytes, 0) + rng = np.random.default_rng(0) + for count in (1, 5, 400): # 400: every row several times + wanted = rng.integers(0, rows.num_rows, count) + taken = spool.take(wanted) + assert taken.schema.equals(rows.schema, check_metadata=True) + assert taken.equals(rows.take(pa.array(wanted, pa.int64()))) + spool.close() + + +def test_a_field_flagged_non_nullable_keeps_the_null_it_holds(tmp_path: Path) -> None: + schema = pa.schema([pa.field("a", pa.int64(), nullable=False, metadata={"k": "v"})]) + table = pa.Table.from_arrays([pa.array([1, None])], schema=schema) + with RowSpool(0, str(tmp_path)) as spool: + spool.append(table) + taken = spool.take(np.array([1, 0])) + assert taken.schema.equals(schema, check_metadata=True) + assert taken.column("a").to_pylist() == [None, 1] + + +def test_a_slice_does_not_keep_its_parent(tmp_path: Path) -> None: + spool = RowSpool(10**9, str(tmp_path)) + spool.append(_table(0, 10_000).slice(5, 2)) + held = spool._segments[0].table # pyright: ignore[reportPrivateUsage] # what it keeps alive + assert held is not None and held.get_total_buffer_size() < 2_000 + assert spool.memory_bytes < 1_000 + assert spool.take(np.array([1])).equals(_table(6, 1)) + + +@pytest.mark.parametrize("memory_bytes", [0, 3_000, 10**9]) +def test_discarded_rows_free_their_segment_and_the_rest_stay( + tmp_path: Path, memory_bytes: int +) -> None: + spool, rows = _filled(tmp_path, [40, 40, 40], memory_bytes) + spool.discard(np.arange(0, 120, 2)) + spool.discard(np.array([], dtype=np.int64)) + odd = np.arange(1, 120, 2) + assert spool.take(odd).equals(rows.take(pa.array(odd, pa.int64()))) + spool.append(_table(120, 40)) # numbered after the discarded rows + assert spool.take(np.array([159, 1])).equals( + pa.concat_tables([_table(159, 1), _table(1, 1)]).combine_chunks() + ) + spool.discard(odd) + spool.discard(np.arange(120, 160)) + assert spool.memory_bytes == 0 + assert _files(tmp_path) == [] + + +def test_rows_spilled_after_a_segment_between_them_was_freed(tmp_path: Path) -> None: + spool = RowSpool(1 << 16, str(tmp_path)) + for start in (0, 10, 20): + spool.append(_table(start, 10)) + spool.discard(np.arange(10, 20)) + spool.append(_table(30, 5_000)) # past the limit: what is in memory is written + assert spool.memory_bytes == 0 + wanted = np.array([0, 25, 30, 5_029, 9]) + expected = pa.concat_tables([_table(0, 30), _table(30, 5_000)]) + assert spool.take(wanted).equals(expected.take(pa.array(wanted, pa.int64()))) + spool.close() + + +def test_nothing_is_written_below_the_limit(tmp_path: Path) -> None: + spool, _ = _filled(tmp_path, [10, 10], 10**9) + assert list(tmp_path.iterdir()) == [] + spool.close() + + +def _spool_directories(root: Path) -> list[Path]: + return [p for d in root.glob("orcapod-spool-*") for p in d.iterdir() if p.is_dir()] + + +def test_close_removes_the_files_and_refuses_more_rows(tmp_path: Path) -> None: + spool, _ = _filled(tmp_path, [10], 0) + assert _files(tmp_path) + spool.close() + spool.close() + assert _spool_directories(tmp_path) == [] + with pytest.raises(ValueError, match="closed"): + spool.append(_table(0, 1)) + + +def test_an_exception_removes_the_files(tmp_path: Path) -> None: + with pytest.raises(RuntimeError, match="stop"), RowSpool(0, str(tmp_path)) as spool: + spool.append(_table(0, 10)) + raise RuntimeError("stop") + assert _spool_directories(tmp_path) == [] + + +@pytest.mark.asyncio +async def test_a_cancellation_removes_the_files(tmp_path: Path) -> None: + async def hold() -> None: + with RowSpool(0, str(tmp_path)) as spool: + spool.append(_table(0, 10)) + await asyncio.Event().wait() + + task = asyncio.create_task(hold()) + await asyncio.sleep(0) + assert _files(tmp_path) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert _spool_directories(tmp_path) == [] + + +def test_a_collected_spool_removes_its_files(tmp_path: Path) -> None: + spool, _ = _filled(tmp_path, [10], 0) + assert _files(tmp_path) + del spool + gc.collect() + assert _spool_directories(tmp_path) == [] + + +_CHILD = """ +import os, sys +import pyarrow as pa +from orcapod.core.row_spool import RowSpool +spool = RowSpool(0, sys.argv[1]) +spool.append(pa.table({"a": [1]})) +print("ready", flush=True) +if sys.argv[2] == "kill": + os.kill(os.getpid(), 9) +if sys.argv[2] == "wait": + sys.stdin.read() +""" + + +def _child(root: Path, end: str) -> subprocess.Popen[str]: + return subprocess.Popen( + [sys.executable, "-c", _CHILD, str(root), end], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True, + ) + + +def test_a_process_that_ends_normally_leaves_nothing(tmp_path: Path) -> None: + child = _child(tmp_path, "exit") + _ = child.communicate() + assert child.returncode == 0 + assert list(tmp_path.glob("orcapod-spool-*")) == [] + + +@pytest.mark.skipif(sys.platform == "win32", reason="swept through fcntl locks") +def test_a_killed_process_is_swept_and_a_live_one_is_not(tmp_path: Path) -> None: + killed = _child(tmp_path, "kill") + _ = killed.communicate() + (left,) = tmp_path.glob("orcapod-spool-*") + assert _files(left) + live = _child(tmp_path, "wait") + assert live.stdout is not None + assert live.stdout.readline() == "ready\n" + try: + assert not left.exists() # the second process swept it + (held,) = tmp_path.glob("orcapod-spool-*") + other = tmp_path / "orcapod-spool-not-ours" # no lock file: left alone + other.mkdir() + spool, _ = _filled(tmp_path, [10], 0) + assert held.exists() and _files(held) + assert other.exists() + spool.close() + finally: + _ = live.communicate() + assert not held.exists() + + +def test_a_forked_child_never_removes_its_parents_files(tmp_path: Path) -> None: + # A child inherits its parent's finalizers; the owner check is what stops them. + directory = tmp_path / "spool" + directory.mkdir() + row_spool._remove_directory(str(directory), os.getpid() + 1) # pyright: ignore[reportPrivateUsage] # the owner check itself + assert directory.exists() + row_spool._remove_directory(str(directory), os.getpid()) # pyright: ignore[reportPrivateUsage] # the owner check itself + assert not directory.exists() From aa339d2e57fd54f2428c5798aa1b6ede039e658d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:23:57 -0800 Subject: [PATCH 02/26] feat(operators): streaming join kernels hold join keys and spooled rows, with bounded output batches (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/operators/streaming_joins.py | 426 ++++++++++++------ 1 file changed, 281 insertions(+), 145 deletions(-) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 8089f0715..39586747c 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -78,10 +78,11 @@ from __future__ import annotations from abc import ABC, abstractmethod -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from typing import Any, ClassVar import numpy as np +import numpy.typing as npt import polars as pl import pyarrow as pa import pyarrow.compute as pc @@ -116,6 +117,7 @@ settle_token_types, tokens_as, ) +from orcapod.core.row_spool import RowSpool from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants @@ -129,6 +131,15 @@ # (keys are tag columns, and a tag never starts with the meta prefix ``__``). _ROW = ("__streaming_left_row", "__streaming_right_row") +# How many rows an output batch holds at most: a row with its source-info tokens is +# several KiB, so a batch is some tens of MiB. +PAIRS_PER_BATCH = 8_192 + +# The pair-count column of a many-to-many match, and how many removed rows a side's key +# frame holds before it is compacted. +_COUNT = "__streaming_count" +_COMPACT_ROWS = 65_536 + def _settled_by_values(schema: pa.Schema) -> pa.Schema: """``schema`` with every system-tag and source-info field nullable. @@ -191,111 +202,180 @@ def _key_frame(table: pa.Table, keys: Sequence[str], row: str) -> pl.DataFrame: ) -def _match( - arriving: pl.DataFrame, held: pl.DataFrame, keys: Sequence[str] -) -> pl.DataFrame: - """Join two key frames by the sync join's rule (``join._matched_pairs``). +def _bounded_pairs( + arriving: pl.DataFrame, + held: pl.DataFrame, + keys: Sequence[str], + *, + at_most_one: bool, + row: str, +) -> Iterator[pl.DataFrame]: + """Join two key frames by the sync join's rule, in pieces of a bounded size. - Both frames hold the constant join key, so inputs that share no tag give every pair - and a top-level null key matches nothing, as on the sync path. + The rule is ``join._matched_pairs``. Both frames hold the constant join key, so + inputs that share no tag give every pair and a top-level null key matches nothing, + as on the sync path. A piece holds at most ``PAIRS_PER_BATCH`` pairs, or the pairs of + one arriving row when it has more: those are at most the rows held. Args: arriving: The arriving batch's key frame. held: The other side's accumulated key frame. keys: The shared tag columns. + at_most_one: Whether an arriving row matches at most one held row (the held + side is unique on the keys), so the pairs need not be counted first. + row: The arriving frame's row-number column. - Returns: - One row per matched pair, holding both row-number columns. + Yields: + One row per matched pair, holding both row-number columns; never empty. """ - return _matched_pairs(arriving, held, [*keys, _COMMON_JOIN_KEY]) + on = [*keys, _COMMON_JOIN_KEY] + if at_most_one: + pieces = [arriving] + else: + # Only the held rows that match, then how many each arriving row has. + held = held.join(arriving, on=on, how="semi") + if not held.height: + return + counts = held.group_by(on).len(name=_COUNT) + counted = arriving.join(counts, on=on, how="inner").sort(row) + pieces = [arriving] + if int(counted.get_column(_COUNT).sum()) > PAIRS_PER_BATCH: + pieces = _pieces(counted) + for piece in pieces: + pairs = _matched_pairs(piece, held, on) + for start in range(0, pairs.height, PAIRS_PER_BATCH): + yield pairs.slice(start, PAIRS_PER_BATCH) -def _joined_by_rows( - left: pa.Table, - right: pa.Table, - keys: Sequence[str], - left_rows: pa.Array[Any], - right_rows: pa.Array[Any], -) -> pa.Table: - """Take matched pairs from two tables, in the layout of ``join._inner_join``. +def _pieces(counted: pl.DataFrame) -> Iterator[pl.DataFrame]: + """Cut arriving rows into runs whose pair counts add up to ``PAIRS_PER_BATCH``. + + Args: + counted: The arriving rows that match, each with its number of pairs. + + Yields: + The runs, without the counts; a row with more pairs is a run of its own. + """ + ends = np.cumsum(counted.get_column(_COUNT).to_numpy().astype(np.int64)) + rows = counted.drop(_COUNT) + start = 0 + while start < rows.height: + before = int(ends[start - 1]) if start else 0 + end = int(np.searchsorted(ends, before + PAIRS_PER_BATCH, side="right")) + end = max(end, start + 1) + yield rows.slice(start, end - start) + start = end + + +def _side_by_side(left: pa.Table, right: pa.Table, keys: Sequence[str]) -> pa.Table: + """Put matched rows of two tables side by side, in the layout of ``join._inner_join``. The left columns (one of each key, the left row's value), then the right columns that are not keys, a name the left table also has taking the suffix ``_right``. Args: - left: The left table. - right: The right table. + left: The left row of each pair. + right: The right row of each pair. keys: The key columns. - left_rows: The left row of each pair. - right_rows: The right row of each pair. Returns: The joined table, fields without the inputs' flags (as ``_inner_join``). """ - names: list[str] = [] - arrays: list[Any] = [] - for name in left.column_names: - names.append(name) - arrays.append(left.column(name).take(left_rows)) + names: list[str] = list(left.column_names) + arrays: list[Any] = list(left.columns) for name in right.column_names: if name in keys: continue names.append(f"{name}_right" if name in left.column_names else name) - arrays.append(right.column(name).take(right_rows)) + arrays.append(right.column(name)) return pa.Table.from_arrays(arrays, names=names) class _Side: - """One side of a binary symmetric hash join: the rows it holds and their key frame. + """One side of a symmetric join: its rows' key frame, the rows themselves spooled. Args: keys: The key columns. row: This side's row-number column. + constant_key: Whether the key frame holds the constant join key. """ - def __init__(self, keys: Sequence[str], row: str) -> None: + def __init__( + self, keys: Sequence[str], row: str, *, constant_key: bool = True + ) -> None: self.keys: list[str] = list(keys) self.row: str = row self.closed: bool = False self.schema: pa.Schema | None = None - self._tables: list[pa.Table] = [] - self._frames: list[pl.DataFrame] = [] - self._table: pa.Table | None = None - self._frame: pl.DataFrame | None = None self.rows: int = 0 + self._constant_key: bool = constant_key + self._frames: list[pl.DataFrame] = [] + self._spool: RowSpool = RowSpool() + # Whether each row is still held, by its number (grown by doubling). + self._alive: npt.NDArray[np.bool_] = np.ones(0, dtype=np.bool_) + self._removed_count: int = 0 def key_frame(self, table: pa.Table) -> pl.DataFrame: """The key frame of ``table``, its rows numbered from 0.""" - return _key_frame(table, self.keys, self.row) + if self._constant_key: + return _key_frame(table, self.keys, self.row) + return polars_key_frame(table, self.keys, self.row) def append(self, table: pa.Table, frame: pl.DataFrame) -> None: """Hold ``table``'s rows, with ``frame`` from ``key_frame``.""" - self._tables.append(table) - # Numbered after the rows already held, as ``table()`` holds them. - self._frames.append( - frame.with_columns(pl.col(self.row) + self.rows) if self.rows else frame - ) - self._table = None - self._frame = None + if not table.num_rows: + return + # Numbered after the rows already held, as the spool numbers them. + self._frames.append(frame.with_columns(pl.col(self.row) + self._spool.size)) + self._spool.append(table) self.rows += table.num_rows + if self._spool.size > len(self._alive): + grown = np.ones(2 * self._spool.size, dtype=np.bool_) + grown[: len(self._alive)] = self._alive + self._alive = grown - def table(self) -> pa.Table: - """Every row held, numbered as in ``frame``.""" - if self._table is None: - self._table = pa.concat_tables(self._tables) - return self._table + def held(self, rows: npt.NDArray[np.int64]) -> npt.NDArray[np.int64]: + """Those of ``rows`` that were not removed.""" + return rows[self._alive[rows]] + + def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: + """The held rows with these numbers, in this order.""" + return self._spool.take(rows) def frame(self) -> pl.DataFrame: - """The key frame of every row held.""" - if self._frame is None: - self._frame = pl.concat(self._frames, rechunk=False) - self._frames = [self._frame] - return self._frame + """The key frame of the rows held and, until compacted, of removed ones. + + A caller whose removed rows can match again asks ``held`` which are held. + """ + if len(self._frames) != 1: + self._frames = [pl.concat(self._frames, rechunk=False)] + return self._frames[0] + + def remove(self, rows: npt.NDArray[np.int64]) -> None: + """Let rows go that can never match again: each is held, each given once.""" + if not len(rows): + return + self._spool.discard(rows) + self.rows -= len(rows) + self._alive[rows] = False + self._removed_count += len(rows) + if self._removed_count >= max(self.rows, _COMPACT_ROWS): + self._compact() + + def _compact(self) -> None: + """Drop the removed rows from the key frame.""" + frame = self.frame() + rows = frame.get_column(self.row).to_numpy() + self._frames = [frame.filter(pl.Series(self._alive[rows]))] + self._removed_count = 0 def clear(self) -> None: - """Drop every row held.""" - self._tables, self._frames = [], [] - self._table, self._frame = None, None + """Drop every row held, and their files.""" + self._frames = [] + self._alive = np.ones(0, dtype=np.bool_) + self._removed_count = 0 + self._spool.close() + self._spool = RowSpool() self.rows = 0 @@ -306,13 +386,18 @@ class _BinaryLink: keys: The key columns. finish: Turns the pairs' joined table (``_joined_by_rows`` layout) into the link's output rows; given the two sides' schemas. + unique: Whether each side is certified unique on the keys: no two of its rows + match one row of the other side. A row is let go once it has matched if, and + only if, the other side is unique: it can match nothing else. """ def __init__( self, keys: Sequence[str], finish: Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table], + unique: tuple[bool, bool] = (False, False), ) -> None: + self.unique: tuple[bool, bool] = unique self.keys: list[str] = list(keys) self.sides: tuple[_Side, _Side] = (_Side(keys, _ROW[0]), _Side(keys, _ROW[1])) self._finish: Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table] = finish @@ -340,48 +425,63 @@ def release(self) -> None: side.closed = True side.clear() - def push(self, side: int, table: pa.Table) -> pa.Table | None: + def push(self, side: int, table: pa.Table) -> Iterator[pa.Table]: """Match ``table``'s rows with the other side's, then hold them if still needed. + The rows are held, and the matched ones let go, once the iterator is read to its + end. + Args: side: 0 for the left side, 1 for the right. table: The arriving rows; every table of one side has one schema. - Returns: - The output rows of the new pairs, or ``None`` when there is none. + Yields: + The output rows of the new pairs, in pieces of at most ``PAIRS_PER_BATCH``. """ this, other = self.sides[side], self.sides[1 - side] if this.schema is None: this.schema = table.schema if other.closed and not other.rows: # Nothing can pair with these rows, and none is held: no key to prepare. - return None + return if self.keys: # A row whose key holds a top-level null matches nothing: never held, so a # closed side holding only such rows is exhausted. table = table.filter(_has_whole_key(table, self.keys)) if not table.num_rows: - return None + return frame = this.key_frame(table) - result = None + this_unique, other_unique = self.unique[side], self.unique[1 - side] + matched = np.zeros(table.num_rows, dtype=np.bool_) + gone: list[npt.NDArray[np.int64]] = [] if other.rows: - pairs = _match(frame, other.frame(), self.keys) - if pairs.height: - rows = ( - pairs.get_column(_ROW[0]).to_arrow(), - pairs.get_column(_ROW[1]).to_arrow(), - ) - tables = (table, other.table()) if side == 0 else (other.table(), table) - joined = _joined_by_rows(*tables, self.keys, *rows) + for pairs in _bounded_pairs( + frame, other.frame(), self.keys, at_most_one=other_unique, row=this.row + ): + mine = pairs.get_column(this.row).to_numpy().astype(np.int64) + theirs = pairs.get_column(other.row).to_numpy().astype(np.int64) + if other_unique: + matched[mine] = True + if this_unique: + gone.append(theirs) + taken = (table.take(pa.array(mine, pa.int64())), other.take(theirs)) + left, right = taken if side == 0 else (taken[1], taken[0]) assert self.sides[0].schema is not None assert self.sides[1].schema is not None - result = self._finish( - joined, self.sides[0].schema, self.sides[1].schema + yield self._finish( + _side_by_side(left, right, self.keys), + self.sides[0].schema, + self.sides[1].schema, ) + if gone: + other.remove(np.concatenate(gone)) # A row is held only for rows still to arrive on the other side. if not other.closed: + if matched.any(): + unmatched = ~matched + table = table.filter(pa.array(unmatched)) + frame = this.key_frame(table) this.append(table, frame) - return result def close(self, side: int) -> None: """Note that ``side`` ends: the other side's rows can never match again.""" @@ -454,11 +554,24 @@ def held_rows(self) -> int: def push(self, input_index: int, batch: pa.RecordBatch) -> list[pa.RecordBatch]: """Take one record batch of an input; return the output rows it decides. + ``iter_push`` with its batches collected: for an output known to be small. + """ + return list(self.iter_push(input_index, batch)) + + def iter_push( + self, input_index: int, batch: pa.RecordBatch + ) -> Iterator[pa.RecordBatch]: + """Take one record batch of an input; yield the output rows it decides. + + The iterator must be read to its end before the kernel is used again: the + batch's own rows are held only then. Reading it piece by piece keeps the output + of a many-to-many match out of memory. + Args: input_index: The input, in call order. batch: The batch, holding the input's transport columns. - Returns: + Yields: The output record batches, possibly none. Raises: @@ -470,9 +583,9 @@ def push(self, input_index: int, batch: pa.RecordBatch) -> list[pa.RecordBatch]: self._require_open(input_index) table = self._as_input_table(input_index, batch) if not table.num_rows: - return [] + return self._received[input_index] = True - return self._emitted(self._push(input_index, table)) + yield from self._emitted(self._push(input_index, table)) def close(self, input_index: int) -> list[pa.RecordBatch]: """Note that an input has ended; return the output rows that decides. @@ -491,7 +604,7 @@ def close(self, input_index: int) -> list[pa.RecordBatch]: """ self._require_open(input_index) self._closed[input_index] = True - emitted = self._emitted(self._close(input_index)) + emitted = list(self._emitted(self._close(input_index))) if all(self._closed): self._check_settled_against_empty_inputs() result = self._check_empty_inputs() @@ -539,8 +652,8 @@ def _check_empty_inputs(self) -> StreamProtocol | None: ) @abstractmethod - def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: - """Take an input's rows; return the output tables they decide. + def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: + """Take an input's rows; give the output tables they decide. Args: input_index: The input, in call order. @@ -643,13 +756,12 @@ def _check_settled_token_types( """ del input_index, token_types - def _emitted(self, tables: list[pa.Table]) -> list[pa.RecordBatch]: + def _emitted(self, tables: Iterable[pa.Table]) -> Iterator[pa.RecordBatch]: """The record batches of the output tables, holding ``output_columns``. Every system-tag and source-info field is declared nullable: the complete table's values decide those flags (``StaticOutputOperatorPod._flag_by_values``). """ - batches: list[pa.RecordBatch] = [] for table in tables: if table.num_rows: self._emitted_any = True @@ -657,8 +769,10 @@ def _emitted(self, tables: list[pa.Table]) -> list[pa.RecordBatch]: table = pa.Table.from_arrays( table.columns, schema=_settled_by_values(table.schema) ) - batches.extend(table.to_batches()) - return batches + yield from table.to_batches() + + def release(self) -> None: + """Let every row held go, with its files: the run has ended or failed.""" def _suffix(self, input_index: int, position: int) -> str: """What an input's system-tag column names gain: ``{pipeline hash}:{position}``.""" @@ -753,7 +867,7 @@ def finish( return finish - def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: + def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: """Feed an input's rows into its step and forward what each step emits. The input at canonical position 0 is the first step's left side, the input at @@ -776,13 +890,19 @@ def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: if rename := self._renames.get(input_index): table = table.rename_columns([rename.get(c, c) for c in table.column_names]) step, side = (0, 0) if position == 0 else (position - 1, 1) - result = self._links[step].push(side, table) - while result is not None and step < len(self._links) - 1: - if step in self._sinks: - return [] - step += 1 - result = self._links[step].push(0, result) - return [] if result is None else [result] + return self._through(step, side, table) + + def _through(self, step: int, side: int, table: pa.Table) -> Iterator[pa.Table]: + """Push rows into a step, and what it emits through the steps after it.""" + for result in self._links[step].push(side, table): + if step == len(self._links) - 1: + yield result + elif step not in self._sinks: + yield from self._through(step + 1, 0, result) + + def release(self) -> None: + for link in self._links: + link.release() def _close(self, input_index: int) -> list[pa.Table]: """End an input's side of its step, and every side that can no longer receive. @@ -1001,7 +1121,7 @@ def _finish( schema=schema, ) - def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: + def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: table = arrow_utils.append_to_system_tags( table, self._suffix(input_index, input_index) ) @@ -1009,8 +1129,10 @@ def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: table = table.rename_columns( [self._rename.get(c, c) for c in table.column_names] ) - result = self._link.push(input_index, table) - return [] if result is None else [result] + return self._link.push(input_index, table) + + def release(self) -> None: + self._link.release() def _close(self, input_index: int) -> list[pa.Table]: self._link.close(input_index) @@ -1037,80 +1159,94 @@ def __init__(self, operator: SemiJoin, inputs: Sequence[StreamProtocol]) -> None super().__init__(operator, inputs) left, right = inputs self._keys = list(SemiJoin._match_keys(left.keys()[0], right.keys()[0])) # pyright: ignore[reportPrivateUsage] # SemiJoin's one rule - # The left rows not decided yet, and the right rows' keys. - self._waiting: pa.Table | None = None + # The left rows not decided yet (keys, the rows spooled), and the distinct keys of + # the right rows. + self._waiting = _Side(self._keys, _ROW[0], constant_key=False) self._right_frames: list[pl.DataFrame] = [] - self._right_frame: pl.DataFrame | None = None + # Whether Polars tells key values apart as its joins do (no nested key). + self._distinct: bool = not any( + pa.types.is_nested(self._layouts[1].field(name).type) for name in self._keys + ) @property def held_rows(self) -> int: - waiting = self._waiting.num_rows if self._waiting is not None else 0 - return waiting + sum(frame.height for frame in self._right_frames) + return self._waiting.rows + sum(frame.height for frame in self._right_frames) + + def release(self) -> None: + self._waiting.clear() + self._right_frames = [] def _right_keys(self) -> pl.DataFrame | None: - """The key frame of every right row held, or ``None`` with none.""" + """The key frame of the right rows held, or ``None`` with none.""" if not self._right_frames: return None - if self._right_frame is None: - self._right_frame = pl.concat(self._right_frames, rechunk=False) - self._right_frames = [self._right_frame] - return self._right_frame - - def _kept(self, left: pa.Table, right_keys: pl.DataFrame) -> pa.Array[Any]: - """Whether each left row's key is among ``right_keys``, as a boolean mask.""" - kept = polars_key_frame(left, self._keys, _ROW[0]).join( - right_keys, on=self._keys, how="semi" - ) - mask = np.zeros(left.num_rows, dtype=np.bool_) - mask[kept.get_column(_ROW[0]).to_numpy()] = True - return pa.array(mask) - - def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: + if len(self._right_frames) > 1: + self._right_frames = [pl.concat(self._right_frames, rechunk=False)] + return self._right_frames[0] + + def _matched( + self, left: pl.DataFrame, right_keys: pl.DataFrame + ) -> npt.NDArray[np.int64]: + """The left rows whose key is among ``right_keys``, by number.""" + kept = left.join(right_keys, on=self._keys, how="semi") + return kept.get_column(_ROW[0]).to_numpy().astype(np.int64) + + def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: if not self._keys: return [table] if input_index == 0 else [] if input_index == 0: - right_keys = self._right_keys() - if right_keys is None: - kept = pa.array(np.zeros(table.num_rows, dtype=np.bool_)) - else: - kept = self._kept(table, right_keys) - if not self._closed[1]: - # A left row whose key holds a top-level null never matches. - undecided = table.filter( - pc.and_(pc.invert(kept), _has_whole_key(table, self._keys)) - ) - if undecided.num_rows: - self._waiting = ( - undecided - if self._waiting is None - else pa.concat_tables([self._waiting, undecided]) - ) - return [table.filter(kept)] - # A right batch: only its keys, and only rows whose keys hold no top-level null - # (the sync path drops those: such a key never matches). + return self._push_left(table) + return self._push_right(table) + + def _push_left(self, table: pa.Table) -> Iterator[pa.Table]: + """Emit the left rows a right row matched already; hold the undecided ones.""" + frame = self._waiting.key_frame(table) + kept = np.zeros(table.num_rows, dtype=np.bool_) + if (right_keys := self._right_keys()) is not None: + kept[self._matched(frame, right_keys)] = True + mask = pa.array(kept) + if not self._closed[1]: + # A left row whose key holds a top-level null never matches. + undecided = table.filter( + pc.and_(pc.invert(mask), _has_whole_key(table, self._keys)) + ) + self._waiting.append(undecided, self._waiting.key_frame(undecided)) + yield table.filter(mask) + + def _push_right(self, table: pa.Table) -> Iterator[pa.Table]: + """Hold the right rows' keys; emit the waiting left rows they decide.""" + # Only rows whose keys hold no top-level null (the sync path drops those: such a + # key never matches). keys = table.select(self._keys) keys = keys.filter(_has_whole_key(keys, self._keys)) if not keys.num_rows: - return [] + return frame = polars_key_frame(keys, self._keys) + if self._distinct: + frame = frame.unique() if not self._closed[0]: - self._right_frames.append(frame) - self._right_frame = None - if self._waiting is None: - return [] - kept = self._kept(self._waiting, frame) - decided = self._waiting.filter(kept) - remaining = self._waiting.filter(pc.invert(kept)) - self._waiting = remaining if remaining.num_rows else None - return [decided] + held = self._right_keys() + if held is not None and self._distinct: + new = frame.join(held, on=self._keys, how="anti") + else: + new = frame + if new.height: + self._right_frames.append(new) + if not self._waiting.rows: + return + decided = self._waiting.held(self._matched(self._waiting.frame(), frame)) + for start in range(0, len(decided), PAIRS_PER_BATCH): + rows = decided[start : start + PAIRS_PER_BATCH] + yield self._waiting.take(rows) + self._waiting.remove(rows) def _close(self, input_index: int) -> list[pa.Table]: if input_index == 0: # No left row will arrive: the right keys can match nothing new. - self._right_frames, self._right_frame = [], None + self._right_frames = [] else: # No right row will arrive: the undecided left rows never match. - self._waiting = None + self._waiting.clear() return [] From b6796d15d08c87bf6e821851fd5467e9fc5f5832 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:24:09 -0800 Subject: [PATCH 03/26] perf(core): carry source-info tokens as a recipe until their text is needed (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/operators/add_tags.py | 2 +- .../core/operators/column_selection.py | 10 +- src/orcapod/core/operators/drop_nulls.py | 2 +- src/orcapod/core/operators/filter.py | 2 +- src/orcapod/core/operators/filters.py | 37 ++- src/orcapod/core/operators/mappers.py | 6 +- src/orcapod/core/operators/meta_columns.py | 2 +- .../core/operators/static_output_pod.py | 10 + src/orcapod/core/operators/tag_by.py | 2 +- src/orcapod/core/sources/base.py | 12 + src/orcapod/core/sources/derived_source.py | 6 + .../core/sources/spiraldb_table_source.py | 37 ++- src/orcapod/core/sources/stream_builder.py | 15 +- .../core/streams/arrow_table_stream.py | 59 +++-- src/orcapod/core/streams/base.py | 12 + .../protocols/core_protocols/streams.py | 11 + src/orcapod/utils/arrow_utils.py | 72 +++--- src/orcapod/utils/source_tokens.py | 234 ++++++++++++++++++ .../unit/test_arrow_data_utils.py | 24 -- tests/test_utils/test_arrow_utils.py | 94 +++---- 20 files changed, 472 insertions(+), 177 deletions(-) create mode 100644 src/orcapod/utils/source_tokens.py diff --git a/src/orcapod/core/operators/add_tags.py b/src/orcapod/core/operators/add_tags.py index 9af218e81..efedd2592 100644 --- a/src/orcapod/core/operators/add_tags.py +++ b/src/orcapod/core/operators/add_tags.py @@ -322,7 +322,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ tag_keys, _ = stream.keys() data_context = stream.data_context # pyright: ignore[reportAttributeAccessIssue] # StreamProtocol omits data_context, which every concrete stream provides (ITL-844) - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index cbc6570b8..9cfd73cbd 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -90,7 +90,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("All tag columns are selected. Returning stream unaltered.") return stream - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -229,7 +229,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("All data columns are selected. Returning stream unaltered.") return stream - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -388,7 +388,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("No tag columns to drop. Returning stream unaltered.") return stream - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -534,7 +534,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: associated_source_columns = [ f"{constants.SOURCE_PREFIX}{c}" for c in columns_to_drop ] - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -774,7 +774,7 @@ def validate_unary_input(self, stream: StreamProtocol) -> None: def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: tag_columns, data_columns = self._user_columns(stream) tags_removed, data_removed = self._removals(tag_columns, data_columns) - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/operators/drop_nulls.py b/src/orcapod/core/operators/drop_nulls.py index 1e7840935..028bcfa8c 100644 --- a/src/orcapod/core/operators/drop_nulls.py +++ b/src/orcapod/core/operators/drop_nulls.py @@ -316,7 +316,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: A stream over the surviving rows, in input order, with the named columns non-nullable. A result with no rows has the same schema. """ - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/operators/filter.py b/src/orcapod/core/operators/filter.py index e5a4fa1a8..b8e3621e1 100644 --- a/src/orcapod/core/operators/filter.py +++ b/src/orcapod/core/operators/filter.py @@ -243,7 +243,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ # Every system column passes through: source info, system tags and each row's # data context (a raw stream may hold several). - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/operators/filters.py b/src/orcapod/core/operators/filters.py index ce01c02b5..2a84592f5 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -10,7 +10,7 @@ from orcapod.core.streams import ArrowTableStream from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import ColumnConfig, Schema -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens if TYPE_CHECKING: import numpy as np @@ -71,9 +71,17 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: return stream # TODO: improve efficiency here... - table = stream.as_table( + whole = stream.as_carried_table( columns={"source": True, "system_tags": True, "sort_by_tags": False} ) + # Polars reads no derived token column: one is left out, and put back for the + # rows kept (its recipe reads the system tags kept with them, ITL-1464), unless + # a predicate could read it. + derived = source_tokens.derived_columns(whole.schema) + others = {c for c in whole.column_names if c not in derived} + if derived and not self._reads_only(others): + whole, derived = source_tokens.materialize(whole), () + table = whole.drop_columns(list(derived)) df = pl.DataFrame(table) filtered_table = df.filter(*self.predicates, **self.constraints).to_arrow() # A filter passes every column through, so each one takes the @@ -96,6 +104,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: filtered_table = arrow_utils.restore_schema_nullability( filtered_table, pa.schema(input_fields) ) + 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) + ) + filtered_table = filtered_table.select(whole.column_names) return ArrowTableStream( filtered_table, @@ -103,6 +119,23 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: data_tags=stream_data_tags(stream), ) + def _reads_only(self, columns: Collection[str]) -> bool: + """Whether every predicate certainly reads columns of ``columns`` only. + + Certain only for expressions that name each column they read: a selector + (``pl.all()``, a regular expression, a type) can read any column, and a predicate + that is not an expression is not looked into. A name that is no column is not + certain either: Polars' error then lists the columns there are. + """ + if not set(self.constraints) <= set(columns): + return False + return all( + isinstance(predicate, pl.Expr) + and not predicate.meta.has_multiple_outputs() + and set(predicate.meta.root_names()) <= set(columns) + for predicate in self.predicates + ) + def validate_unary_input(self, stream: StreamProtocol) -> None: """ This method should be implemented by subclasses to validate the inputs to the operator. diff --git a/src/orcapod/core/operators/mappers.py b/src/orcapod/core/operators/mappers.py index fa89ec4a5..184f66252 100644 --- a/src/orcapod/core/operators/mappers.py +++ b/src/orcapod/core/operators/mappers.py @@ -179,7 +179,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: # nothing to rename in the data, return stream as is return stream - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -457,7 +457,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: # nothing to rename or drop in the tags, return stream as is return stream - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -799,7 +799,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: tag_renames, data_renames, tags_dropped, data_dropped = self._plan( tag_columns, data_columns ) - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/operators/meta_columns.py b/src/orcapod/core/operators/meta_columns.py index 674d55e46..a2312b830 100644 --- a/src/orcapod/core/operators/meta_columns.py +++ b/src/orcapod/core/operators/meta_columns.py @@ -112,7 +112,7 @@ def without_input_meta( """ if not _carries_meta(stream, inputs): return stream - table = stream.as_table( + table = stream.as_carried_table( columns={"source": True, "system_tags": True, "context": True} ) tag_columns = stream.keys()[0] diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f829d44a5..c8f45d059 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -2045,6 +2045,16 @@ def as_table( ) return self._cached_stream.as_table(columns=columns, all_info=all_info) + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The operator's result, derived token columns as they are (ITL-1464).""" + self._refresh() + assert self._cached_stream is not None, ( + "StreamProtocol has not been updated or is empty." + ) + return self._cached_stream.as_carried_table(columns=columns) + def iter_data( self, ) -> Iterator[tuple[TagProtocol, DataProtocol]]: diff --git a/src/orcapod/core/operators/tag_by.py b/src/orcapod/core/operators/tag_by.py index 911fefc36..a7cbe5f7a 100644 --- a/src/orcapod/core/operators/tag_by.py +++ b/src/orcapod/core/operators/tag_by.py @@ -209,7 +209,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ tag_columns, _ = stream.keys() # The context column too, so each row keeps its own data context key. - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 07221924c..780e1c63a 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -537,6 +537,18 @@ def as_table( """Delegate to the underlying stream's as_table.""" return self._stream.as_table(columns=columns, all_info=all_info) + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The underlying stream's table, derived token columns as they are (ITL-1464). + + A source that reads its rows its own way (a subclass, or an object, with its own + ``as_table``) gives that table. + """ + if type(self).as_table is RootSource.as_table and "as_table" not in vars(self): + return self._stream.as_carried_table(columns=columns) + return super().as_carried_table(columns=columns) + # ------------------------------------------------------------------------- # The start-of-run check (ITL-1102) # ------------------------------------------------------------------------- diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1c4a57228..ab1a585b1 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -812,3 +812,9 @@ def as_table( all_info: bool = False, ) -> "pa.Table": return self._get_stream().as_table(columns=columns, all_info=all_info) + + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The source's table, derived token columns as they are (ITL-1464).""" + return self._get_stream().as_carried_table(columns=columns) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 6312a677f..b1dba51bb 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -62,7 +62,7 @@ row_identifiers, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream -from orcapod.core.streams.base import check_head_size +from orcapod.core.streams.base import StreamBase, check_head_size from orcapod.core.streams.view import ViewStatus, StreamView from orcapod.databases.spiraldb_connector import ( SpiralDBConnector, @@ -959,31 +959,32 @@ def as_table( all_info: bool = False, ) -> "pa.Table": """Scan the table and return its rows as one PyArrow table (all held in memory).""" - return self._whole_table( - self._batch_streams(), columns=columns, all_info=all_info + return self._whole_stream(self._batch_streams()).as_table( + columns=columns, all_info=all_info ) - def _whole_table( - self, - streams: Iterator["ArrowTableStream"], - *, - columns: ColumnConfig | dict[str, Any] | None, - all_info: bool, + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None ) -> "pa.Table": - """Return the rows of ``streams`` (batches of one read) as one table.""" + """Scan the table as ``as_table`` does, building no source-info text (ITL-1464).""" + return self._whole_stream(self._batch_streams()).as_carried_table( + columns=columns + ) + + def _whole_stream(self, streams: Iterator["ArrowTableStream"]) -> StreamBase: + """Return the rows of ``streams`` (batches of one read) as one stream.""" # One stream over all the rows, so that a whole-table option (sorting by # tags) applies across batches. enriched = {"source": True, "system_tags": True} - tables = [stream.as_table(columns=enriched) for stream in streams] + tables = [stream.as_carried_table(columns=enriched) for stream in streams] if not tables: - return self._stream.as_table(columns=columns, all_info=all_info) - whole = ArrowTableStream( + return self._stream + return ArrowTableStream( table=pa.concat_tables(tables), tag_columns=self._tag_columns, system_tag_columns=self._system_tag_columns, data_tags=self._data_tags, ) - return whole.as_table(columns=columns, all_info=all_info) def _head( self, @@ -1013,11 +1014,9 @@ def _head( head_limit = n if limit is None else min(n, limit) asof = self._asof table = self._lookup_table() - rows = self._whole_table( - self._read_batches(table, asof=asof, limit=head_limit, max_rows=None), - columns=columns, - all_info=all_info, - ) + rows = self._whole_stream( + self._read_batches(table, asof=asof, limit=head_limit, max_rows=None) + ).as_table(columns=columns, all_info=all_info) if rows.num_rows < head_limit or head_limit == limit: return _Head(rows, True, rows.num_rows, False) bound, total = self._bounded_count(n, table) diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 5fbb8eb52..67eeb2114 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -25,7 +25,6 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import RowIdentifierError from orcapod.logical_types.identifier import LogicalTypeIdentifierError -from orcapod.system_constants import constants from orcapod.types import ContentHash from orcapod.utils import arrow_utils, schema_utils from orcapod.utils.schema_utils import compute_source_schema_hash @@ -597,7 +596,8 @@ def attach_provenance( key's canonical JSON), and its source id is the source's name: the two system-tag columns. Each source-info value is ``::::`` (for example ``_source_amplitude`` - holds ``::row_3::amplitude``). A row keeps its record id wherever + holds ``::row_3::amplitude``), carried as a recipe over the two system + tags until its text is needed (``source_tokens``). A row keeps its record id wherever and however often it is read, as long as its identifier is the same (ITL-1154). @@ -615,13 +615,12 @@ def attach_provenance( Returns: The stream over the enriched table. """ - source_info = [ - f"{source_id}{constants.BLOCK_SEPARATOR}{identifier}" - for identifier in row_identifiers - ] - table = arrow_utils.add_source_info( + # The tokens say nothing the two system tags below and the column names do not: + # each is carried as that recipe, and its text is built when it is needed + # (``source_tokens``, ITL-1464). + table = arrow_utils.add_source_tokens( table, - source_info, + schema_hash, exclude_columns=[c for c in tag_columns if c not in data_tags], ) table = arrow_utils.add_system_tag_columns( diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index df49eaff6..09f1b1d4e 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -20,10 +20,13 @@ from orcapod.protocols.hashing_protocols import PipelineElementProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema, SourceInfoValue -from orcapod.utils import arrow_utils, schema_utils +from orcapod.utils import arrow_utils, schema_utils, source_tokens logger = logging.getLogger(__name__) +ROWS_PER_PART = 8192 +"""The rows whose source-info text ``iter_data`` builds at once (ITL-1464).""" + class ArrowTableStream(StreamBase): """ @@ -351,6 +354,13 @@ def as_table( columns_config = ColumnConfig.handle_config(columns, all_info=all_info) return self._assemble_table(columns_config, limit=None) + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The table with its derived token columns as they are (ITL-1464).""" + config = ColumnConfig.handle_config(columns) + return self._assemble_table(config, limit=None, carried=config.system_tags) + def head( self, n: int = 10, @@ -384,13 +394,19 @@ def _typed_zero_row_table(self) -> "pa.Table": return self._assemble_table(ZERO_ROW_INPUT_COLUMNS, limit=0) def _assemble_table( - self, columns_config: ColumnConfig, limit: int | None + self, + columns_config: ColumnConfig, + limit: int | None, + *, + carried: bool = False, ) -> "pa.Table": """Return the stream's rows with the column groups of ``columns_config``. Args: columns_config: The column groups to include, and whether to sort by tags. limit: Assemble only the first ``limit`` rows; ``None`` for all of them. + carried: Leave a derived token column derived (``as_carried_table``), which + needs the system tags in the table; ``False`` gives its text. """ output_table = self._table data_context_table = self._data_context_table @@ -408,8 +424,8 @@ def hashes() -> pa.Array[Any]: [str(data.content_hash()) for _, data in rows], type=pa.large_string() ) - def shape(carried: "pa.Table") -> "pa.Table": - table_stack = (carried,) + def shape(rows: "pa.Table") -> "pa.Table": + table_stack = (rows,) if columns_config.context: table_stack += (data_context_table,) if columns_config.source: @@ -423,6 +439,8 @@ def shape(carried: "pa.Table") -> "pa.Table": # the system tags are asked for. The system tags stay in the table # through the sort: they break ties between equal tags. table = arrow_utils.sort_by_tag_columns(table, tuple(self._tag_columns)) + if not carried: + table = source_tokens.materialize(table) if not columns_config.system_tags: table = table.drop_columns(list(self._system_tag_columns)) return table @@ -471,21 +489,30 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, Data]]: self._source_info_table.schema.field(name), self._source_info_table.column(name), ) - # The table 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. - tags = ( - Tag.rows_of(rows.select(tag_columns), self.data_context) - if tag_columns - else None + # 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 data in Data.rows_of(rows.select(data_columns), self.data_context): - # A fresh empty tag per row, so rows never share one object. - tag = next(tags) if tags is not None else Tag({}) + for start in range(0, rows.num_rows, size): + part = source_tokens.materialize(rows.slice(start, size)) + # 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. + tags = ( + Tag.rows_of(part.select(tag_columns), self.data_context) + if tag_columns + else None + ) + for data in Data.rows_of(part.select(data_columns), self.data_context): + # A fresh empty tag per row, so rows never share one object. + tag = next(tags) if tags is not None else Tag({}) - yield tag, data + yield tag, data - cached_elements.append((tag, data)) + cached_elements.append((tag, data)) self._cached_elements = cached_elements else: yield from self._cached_elements diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 9f8b731f7..26fa6713d 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1509,6 +1509,18 @@ def as_table( all_info: bool = False, ) -> "pa.Table": ... + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The table of ``as_table(columns=columns)``, as operators pass it on. + + A source-info column may be derived (``utils/source_tokens.py``): a recipe over + the table's system tags in place of its text, which ``source_tokens.materialize`` + builds. Internal: never stored, hashed or shown (ITL-1464). A stream that holds + none gives ``as_table``. + """ + return self.as_table(columns=columns) + def as_polars_df( self, *, diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index c8c72abd6..b35e38beb 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -255,6 +255,17 @@ def async_iter_data(self) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: """ ... + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The table of ``as_table(columns=columns)``, as operators pass it on. + + A source-info column may be derived (``utils/source_tokens.py``): a recipe over + the table's system tags in place of its text. Internal: never stored, hashed or + shown (ITL-1464). + """ + ... + def as_table( self, *, diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 86ac58283..e51519cbd 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -10,6 +10,7 @@ from orcapod.system_constants import constants from orcapod.types import ColumnConfig, SourceInfoValue +from orcapod.utils import source_tokens if TYPE_CHECKING: from orcapod.logical_types.identifier import LogicalTypeIdentifier @@ -1464,7 +1465,10 @@ def append_to_system_tags(table: "pa.Table", value: str) -> "pa.Table": else c for c in table.column_names } - return table.rename_columns(column_name_map) + # A derived token column keeps reading the columns it read (ITL-1464). + return source_tokens.rename_read_columns( + table.rename_columns(column_name_map), column_name_map + ) def fold_system_tag_values(values: Sequence[Any], *, label: str) -> str: @@ -1712,6 +1716,12 @@ def sort_system_tag_values(table: "pa.Table") -> "pa.Table": if len(positions) <= 1: continue + # The values move between these columns, so a token derived from them is built + # first: it names the row it always named (ITL-1464). + table = source_tokens.materialize_reading( + table, {name for pair in positions.values() for name in pair.values()} + ) + # Sort positions numerically sorted_positions = sorted(positions.keys(), key=int) @@ -1777,50 +1787,38 @@ def sort_system_tag_values(table: "pa.Table") -> "pa.Table": return table -def add_source_info( +def add_source_tokens( table: "pa.Table", - source_info: str | Collection[str] | None, - exclude_prefixes: Collection[str] = ( - constants.META_PREFIX, - constants.DATAGRAM_PREFIX, - ), + schema_hash: str, exclude_columns: Collection[str] = (), ) -> "pa.Table": - """Add source information to an Arrow table.""" - # Create a base list of per-row source tokens; one entry per row. - if source_info is None or isinstance(source_info, str): - base_source = [source_info] * table.num_rows - elif isinstance(source_info, Collection): - if len(source_info) != table.num_rows: - raise ValueError( - "Length of source_info collection must match number of rows in the table." - ) - base_source = list(source_info) - else: - raise TypeError( - f"source_info must be a str, a sized Collection[str], or None; " - f"got {type(source_info).__name__}" - ) + """Add the source-info token column of each data column, as a recipe (ITL-1464). + + Each ``_source_`` column holds no bytes: its type says the token is the row's + source id, its record id and ``col`` (``source_tokens.TokenRecipe``), read from the + two system-tag columns ``add_system_tag_columns`` adds under ``schema_hash``. + + Args: + table: The rows. + schema_hash: The source's schema hash, which names the system-tag columns. + exclude_columns: Columns with no token (the plain tags). Meta and datagram + columns have none either. - # For each data column, build an independent _source_ column from the - # base tokens. We must NOT re-use the array produced for a previous column - # as input for the next one — doing so would accumulate column names - # (e.g. "src::col1::col2" instead of "src::col2"). - for col in table.column_names: - if col.startswith(tuple(exclude_prefixes)) or col in exclude_columns: + Returns: + The table with its token columns, non-nullable: a token is never null. + """ + source_id, record_id = system_tag_column_names(schema_hash) + prefixes = (constants.META_PREFIX, constants.DATAGRAM_PREFIX) + for name in table.column_names: + if name.startswith(prefixes) or name in exclude_columns: continue - col_source = pa.array( - [f"{source_val}::{col}" for source_val in base_source], - type=pa.large_string(), + tokens = source_tokens.derived_array( + source_tokens.TokenRecipe(source_id, record_id, name), table.num_rows ) - # Source info columns are always computed strings, never null. table = table.append_column( - pa.field( - f"{constants.SOURCE_PREFIX}{col}", pa.large_string(), nullable=False - ), - col_source, + pa.field(f"{constants.SOURCE_PREFIX}{name}", tokens.type, nullable=False), + tokens, ) - return table diff --git a/src/orcapod/utils/source_tokens.py b/src/orcapod/utils/source_tokens.py new file mode 100644 index 000000000..9602c5b9f --- /dev/null +++ b/src/orcapod/utils/source_tokens.py @@ -0,0 +1,234 @@ +"""Source-info tokens that are carried as a recipe, not as text (ITL-1464). + +A source row's token is ``::::``: the values of the row's +two system tags and the name the column had at the source. As text it repeats them for +every row and data column, about 35 times the data of a typical table. Inside the library +a token column can instead be **derived**: a column of ``DerivedTokenType`` holds no +bytes, and its type holds the recipe that gives the text from the table's own system-tag +columns. Filtering, taking, slicing, concatenating, selecting and renaming carry such a +column as any other; nothing is computed until the text is needed (``materialize``). + +A derived column is an internal form of a table that operators pass on +(``StreamProtocol.as_carried_table``). It never leaves the library: ``as_table``, rows, +stored tables and everything hashed hold the text. A place that forgets fails loudly: no +value of a derived column can be read, cast to text, hashed, or written to Parquet (its +storage is a struct with no field, which Parquet refuses). +""" + +from __future__ import annotations + +import json +from collections.abc import Collection, Mapping +from dataclasses import dataclass +from typing import Any, NoReturn + +import pyarrow as pa +import pyarrow.compute as pc + +from orcapod.system_constants import constants + +_TEXT = pa.large_string() + +ROWS_PER_CHUNK = 65_536 +"""The most rows whose token text is built in one step.""" + + +@dataclass(frozen=True) +class TokenRecipe: + """How the token of each row is made from the row's system tags. + + Attributes: + source_id: The system-tag column holding the row's source id. + record_id: The system-tag column holding the row's record id. + column: The column name the token ends with: the column's name at the source, + whatever it is called now. + """ + + source_id: str + 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]) + + @classmethod + def from_json(cls, text: str) -> TokenRecipe: + """The recipe ``to_json`` wrote.""" + return cls(*json.loads(text)) + + def renamed(self, names: Mapping[str, str]) -> TokenRecipe: + """The recipe over system-tag columns renamed by ``names``.""" + return TokenRecipe( + names.get(self.source_id, self.source_id), + names.get(self.record_id, self.record_id), + 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( + batch.column(self.source_id).cast(_TEXT), + batch.column(self.record_id).cast(_TEXT), + pa.scalar(self.column, _TEXT), + pa.scalar(constants.BLOCK_SEPARATOR, _TEXT), + ) + + +class _DerivedTokenScalar(pa.ExtensionScalar): + """A value of a derived column: it has none to read.""" + + def as_py(self, *args: Any, **kwargs: Any) -> NoReturn: # pyright: ignore[reportExplicitAny, reportIncompatibleMethodOverride] # pyarrow's own signature varies by version + """Refuse to give a value. + + Raises: + TypeError: Always; the text must be built first (``materialize``). + """ + raise TypeError( + "a derived source-info token has no value: build its text first " + "(source_tokens.materialize)" + ) + + +class DerivedTokenType(pa.ExtensionType): + """The Arrow type of a derived token column: no bytes, and the recipe. + + Internal and never registered, so it is in no stored table and no schema Orcapod + presents or hashes. Two derived columns have one type only with one recipe. + """ + + def __init__(self, recipe: TokenRecipe) -> None: + self.recipe = recipe + super().__init__(pa.struct([]), "orcapod.internal.derived_token") + + def __arrow_ext_serialize__(self) -> bytes: + return 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())) + + def __arrow_ext_scalar_class__(self) -> type[pa.ExtensionScalar]: + return _DerivedTokenScalar + + # pyarrow compares extension types by name and storage only; Arrow asks this. + def __eq__(self, other: object) -> bool: + return isinstance(other, DerivedTokenType) and self.recipe == other.recipe + + def __hash__(self) -> int: + return hash(self.recipe) + + +def derived_array(recipe: TokenRecipe, rows: int) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array + """A derived token column of ``rows`` rows: no row has a byte.""" + storage = pa.Array.from_buffers(pa.struct([]), rows, [None], 0, 0) + return pa.ExtensionArray.from_storage(DerivedTokenType(recipe), storage) + + +def derived_recipe(kind: pa.DataType) -> TokenRecipe | None: + """The recipe of a column of type ``kind``; ``None`` when it is not derived.""" + return kind.recipe if isinstance(kind, DerivedTokenType) else None + + +def derived_columns(schema: pa.Schema) -> tuple[str, ...]: + """The names of the derived token columns of ``schema``.""" + return tuple(f.name for f in schema if derived_recipe(f.type) is not None) + + +def materialize(table: pa.Table, names: Collection[str] | None = None) -> pa.Table: + """Return ``table`` with its derived token columns as text. + + Args: + table: A table holding the system-tag columns its derived columns read. + names: The derived columns to build; ``None`` for all of them. + + Returns: + The table, each such column ``large_string`` with the field's own name and + nullability; ``table`` itself when there is none. + """ + wanted = [ + name for name in derived_columns(table.schema) if names is None or name in names + ] + if not wanted: + return table + schema = table.schema + recipes: dict[str, TokenRecipe] = {} + 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)} + 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): + for name, recipe in recipes.items(): + chunks[name].append(recipe.text(batch)) + for name in wanted: + index = schema.get_field_index(name) + table = table.set_column( + index, + schema.field(name).with_type(_TEXT), + pa.chunked_array(chunks[name], type=_TEXT), + ) + return table + + +def materialize_reading(table: pa.Table, columns: Collection[str]) -> pa.Table: + """Build the text of the derived columns that read one of ``columns``. + + Called before the values of system-tag columns change, so every token keeps naming + the row it named. + """ + return materialize( + 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) + ], + ) + + +def rename_read_columns(table: pa.Table, names: Mapping[str, str]) -> pa.Table: + """Point the derived columns of ``table`` at system-tag columns renamed by ``names``. + + Args: + table: The table, its system-tag columns already renamed. + names: Old to new column name. + + Returns: + The table with each derived column's recipe reading the new names. + """ + for name in derived_columns(table.schema): + field = table.schema.field(name) + recipe = derived_recipe(field.type) + assert recipe is not None + 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), + ) + return table + + +def text_schema(schema: pa.Schema) -> pa.Schema: + """``schema`` with each derived token column as the text it stands for.""" + if not derived_columns(schema): + return schema + return pa.schema( + [ + field.with_type(_TEXT) if derived_recipe(field.type) else field + for field in schema + ], + metadata=schema.metadata, + ) diff --git a/test-specification/unit/test_arrow_data_utils.py b/test-specification/unit/test_arrow_data_utils.py index dfc17c7a2..100adcabe 100644 --- a/test-specification/unit/test_arrow_data_utils.py +++ b/test-specification/unit/test_arrow_data_utils.py @@ -13,7 +13,6 @@ from orcapod.system_constants import constants from orcapod.utils.arrow_utils import ( - add_source_info, add_system_tag_columns, append_to_system_tags, drop_columns_with_prefix, @@ -144,29 +143,6 @@ def test_sorts_system_tag_values(self): assert result.num_rows == table_with_tags.num_rows -# --------------------------------------------------------------------------- -# add_source_info -# --------------------------------------------------------------------------- - - -class TestAddSourceInfo: - """Per design, source info columns are prefixed with _source_ and track - provenance tokens per data column.""" - - def test_adds_source_info_columns(self): - table = pa.table({"id": [1, 2], "value": [10, 20]}) - result = add_source_info(table, source_info="src_token") - source_cols = [ - c for c in result.column_names if c.startswith(constants.SOURCE_PREFIX) - ] - assert len(source_cols) > 0 - - def test_source_info_length_mismatch_raises(self): - table = pa.table({"id": [1, 2], "value": [10, 20]}) - with pytest.raises(ValueError): - add_source_info(table, source_info=["a", "b", "c"]) # Wrong count - - # --------------------------------------------------------------------------- # drop_columns_with_prefix # --------------------------------------------------------------------------- diff --git a/tests/test_utils/test_arrow_utils.py b/tests/test_utils/test_arrow_utils.py index 26bbddda1..234b86c34 100644 --- a/tests/test_utils/test_arrow_utils.py +++ b/tests/test_utils/test_arrow_utils.py @@ -4,8 +4,10 @@ import pytest from orcapod.types import ColumnConfig, SourceInfoValue +from orcapod.utils import source_tokens from orcapod.utils.arrow_utils import ( - add_source_info, + add_source_tokens, + add_system_tag_columns, apply_column_config, column_arrow_type, concat_tables_by_name, @@ -243,65 +245,41 @@ def test_none_schema_metadata_stays_none(self): assert not result.metadata -# --------------------------------------------------------------------------- -# add_source_info -# --------------------------------------------------------------------------- - - -class TestAddSourceInfo: - """add_source_info must produce one _source_ column per data column - whose values are exactly '::' for every row.""" - - def test_single_column_produces_correct_source_token(self): - """_source_ value is '::' for every row.""" - table = pa.table({"x": pa.array([10, 20], type=pa.int64())}) - result = add_source_info(table, "mysrc") - - assert result.column("_source_x").to_pylist() == ["mysrc::x", "mysrc::x"] - - def test_multi_column_each_source_column_uses_its_own_name(self): - """Each _source_ value is '::' — columns are independent.""" - table = pa.table( - { - "x": pa.array([1, 2], type=pa.int64()), - "y": pa.array([3, 4], type=pa.int64()), - "z": pa.array([5, 6], type=pa.int64()), - } - ) - result = add_source_info(table, "base") +class TestAddSourceTokens: + """One ``_source_`` column per data column, whose text is + ``::::`` of the row's own system tags.""" - assert result.column("_source_x").to_pylist() == ["base::x", "base::x"] - assert result.column("_source_y").to_pylist() == ["base::y", "base::y"] - assert result.column("_source_z").to_pylist() == ["base::z", "base::z"] - - def test_per_row_source_tokens_combined_with_column_name(self): - """With a per-row source list, each row's token is '::'.""" - table = pa.table( - { - "a": pa.array([10, 20], type=pa.int64()), - "b": pa.array([30, 40], type=pa.int64()), - } + def test_each_column_gets_its_own_token_of_every_row(self): + table = pa.table({"k": [1, 2], "y": ["p", "q"], "x": [3.0, 4.0]}) + carried = add_system_tag_columns( + add_source_tokens(table, "hash", exclude_columns=["k"]), + "hash", + "src", + ["row_0", "row_1"], ) - result = add_source_info(table, ["src0", "src1"]) - - assert result.column("_source_a").to_pylist() == ["src0::a", "src1::a"] - assert result.column("_source_b").to_pylist() == ["src0::b", "src1::b"] - - def test_correct_number_of_source_columns_added(self): - """Exactly one _source_ column is added per non-excluded data column.""" - table = pa.table( - { - "p": pa.array([1], type=pa.int64()), - "q": pa.array([2], type=pa.int64()), - "r": pa.array([3], type=pa.int64()), - } - ) - result = add_source_info(table, "s") - - assert result.num_columns == 6 # 3 data + 3 source - assert "_source_p" in result.column_names - assert "_source_q" in result.column_names - assert "_source_r" in result.column_names + result = source_tokens.materialize(carried) + assert [c for c in result.column_names if c.startswith("_source_")] == [ + "_source_y", + "_source_x", + ] + assert result.column("_source_y").to_pylist() == [ + "src::row_0::y", + "src::row_1::y", + ] + assert result.column("_source_x").to_pylist() == [ + "src::row_0::x", + "src::row_1::x", + ] + field = result.schema.field("_source_x") + assert (field.type, field.nullable) == (pa.large_string(), False) + + def test_meta_columns_get_none(self): + table = pa.table({"x": [1], "__m": [2]}) + assert add_source_tokens(table, "hash").column_names == [ + "x", + "__m", + "_source_x", + ] class TestSystemTagColumnNames: From 3e0794d87c9279010104d7cc7467080c85616b2a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:29:31 -0800 Subject: [PATCH 04/26] feat(core): uniqueness certificates derived per stream, and Join, MergeJoin and SemiJoin streaming on record-batch channels (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/cached_function_pod.py | 5 + src/orcapod/core/function_pod.py | 10 + src/orcapod/core/nodes/function_node.py | 6 + src/orcapod/core/nodes/operator_node.py | 12 + src/orcapod/core/nodes/source_node.py | 7 + src/orcapod/core/operators/add_tags.py | 5 + .../core/operators/column_selection.py | 25 ++ src/orcapod/core/operators/drop_nulls.py | 5 + src/orcapod/core/operators/filter.py | 5 + src/orcapod/core/operators/filters.py | 5 + src/orcapod/core/operators/group_by.py | 6 + src/orcapod/core/operators/index.py | 5 + src/orcapod/core/operators/join.py | 33 ++ src/orcapod/core/operators/mappers.py | 17 + src/orcapod/core/operators/merge_join.py | 38 +++ src/orcapod/core/operators/pick.py | 5 + src/orcapod/core/operators/rejoin.py | 5 + src/orcapod/core/operators/semijoin.py | 32 ++ .../core/operators/static_output_pod.py | 10 + src/orcapod/core/operators/streaming_joins.py | 148 ++++++++- src/orcapod/core/operators/tag_by.py | 5 + .../core/sources/arrow_table_source.py | 1 + src/orcapod/core/sources/base.py | 23 ++ src/orcapod/core/sources/data_frame_source.py | 1 + src/orcapod/core/sources/dict_source.py | 1 + src/orcapod/core/sources/list_source.py | 1 + .../core/sources/postgresql_table_source.py | 1 + .../core/sources/sqlite_table_source.py | 1 + src/orcapod/core/streams/base.py | 9 + src/orcapod/core/unique_keys.py | 129 ++++++++ .../protocols/core_protocols/streams.py | 9 + src/orcapod/side_effects.py | 15 + tests/test_core/test_unique_keys.py | 301 ++++++++++++++++++ 33 files changed, 879 insertions(+), 2 deletions(-) create mode 100644 src/orcapod/core/unique_keys.py create mode 100644 tests/test_core/test_unique_keys.py diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 5fa41bfdb..23f262ac7 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -8,6 +8,7 @@ from collections.abc import Iterator from typing import TYPE_CHECKING, Any +from orcapod.core.unique_keys import UniqueKeys from orcapod.core.data_function import CachedDataFunction from orcapod.core.datagrams import Datagram from orcapod.core.function_pod import ( @@ -57,6 +58,10 @@ class CachedFunctionPod(WrappedFunctionPod): # Expose RESULT_COMPUTED_FLAG from the shared ResultCache RESULT_COMPUTED_FLAG = ResultCache.RESULT_COMPUTED_FLAG + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys: each row comes from one input row, its tags kept.""" + return stream.unique_keys + def __init__( self, function_pod: FunctionPodProtocol, diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 8a24c3b49..4a4fd51ce 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -12,6 +12,7 @@ import pyarrow as pa from orcapod import contexts +from orcapod.core.unique_keys import UniqueKeys, derived_keys from orcapod.channels import ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase @@ -885,6 +886,10 @@ def output_schema( class FunctionPod(_FunctionPodBase): + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys: each row comes from one input row, its tags kept.""" + return stream.unique_keys + def __init__( self, data_function: DataFunctionProtocol, @@ -1172,6 +1177,11 @@ def __init__( self._reset_generation = 0 self._input_state: tuple[object, ...] | None = None + @property + def unique_keys(self) -> UniqueKeys: + """The tag sets no two rows agree on, derived from the inputs' (``core/unique_keys``).""" + return derived_keys(self.producer, self.upstreams, self) + @property def producer(self) -> PodProtocol: return self._function_pod diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 9a0353053..c2ea7c490 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -33,6 +33,7 @@ import pyarrow as pa from orcapod import contexts +from orcapod.core.unique_keys import UniqueKeys, derived_keys from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.core.function_pod import ( fall_through_tags, @@ -549,6 +550,11 @@ def node_type(self) -> str: """Return ``"side_effect_function"`` when the pod injects ``InvocationContext``, else ``"function"``.""" return self._node_type + @property + def unique_keys(self) -> UniqueKeys: + """The tag sets no two rows agree on, derived from the inputs' (``core/unique_keys``).""" + return derived_keys(self.producer, self.upstreams, self) + @property def producer(self) -> FunctionPodProtocol: return self._function_pod diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index b2134184a..5c6ccd300 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -28,6 +28,7 @@ import pyarrow.compute as pc from orcapod import contexts +from orcapod.core.unique_keys import NO_UNIQUE_KEYS, UniqueKeys, derived_keys from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.core.data_tags import ( mark_data_tags, @@ -298,6 +299,17 @@ def pipeline_hash(self, hasher=None) -> ContentHash: # Stream interface # ------------------------------------------------------------------ + @property + def unique_keys(self) -> UniqueKeys: + """The tag sets no two rows agree on, derived from the inputs' (``core/unique_keys``). + + None in ``REPLAY`` mode: every logged run of the node's key is replayed, so a + tag tuple can occur once per run. + """ + if self.cache_mode == CacheMode.REPLAY: + return NO_UNIQUE_KEYS + return derived_keys(self.producer, self.upstreams, self) + @property def producer(self) -> OperatorPodProtocol: return self._operator diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b6b8bc0f6..e9a80bf98 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -21,6 +21,7 @@ import pyarrow as pa from orcapod import contexts +from orcapod.core.unique_keys import NO_UNIQUE_KEYS, UniqueKeys from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase @@ -908,6 +909,12 @@ def explain(self) -> Explanation: return explain(self) + @property + def unique_keys(self) -> UniqueKeys: + """The bound stream's unique keys (``core/unique_keys``); none when unbound.""" + bound = self._bound_stream() + return NO_UNIQUE_KEYS if bound is None else bound.unique_keys + @property def producer(self) -> None: """Source nodes have no producer pod — they are root nodes. diff --git a/src/orcapod/core/operators/add_tags.py b/src/orcapod/core/operators/add_tags.py index 9af218e81..2f0b2f162 100644 --- a/src/orcapod/core/operators/add_tags.py +++ b/src/orcapod/core/operators/add_tags.py @@ -9,6 +9,7 @@ import pyarrow as pa +from orcapod.core.unique_keys import UniqueKeys from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.data_tags import stream_data_tags from orcapod.core.datagrams import Tag @@ -124,6 +125,10 @@ class AddTags(UnaryOperator): ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): tags are only added.""" + return stream.unique_keys + def __init__(self, tags: Mapping[str, TagConstant], **kwargs: Any): if not tags: raise ValueError("add_tags: no tag given") diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index cbc6570b8..149b6418d 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -3,6 +3,7 @@ from collections.abc import Collection, Sequence from typing import Any, ClassVar +from orcapod.core.unique_keys import UniqueKeys from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.operators.base import UnaryOperator @@ -62,6 +63,10 @@ class SelectTagColumns(UnaryOperator): ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): those whose tags all stay.""" + return stream.unique_keys + def __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): self.columns = _canonical_columns(columns) self.strict = strict @@ -201,6 +206,10 @@ class SelectDataColumns(UnaryOperator): ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): tags are unchanged.""" + return stream.unique_keys + def __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): self.columns = _canonical_columns(columns) self.strict = strict @@ -357,6 +366,10 @@ class DropTagColumns(UnaryOperator): ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): those whose tags all stay.""" + return stream.unique_keys + def __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): self.columns = _canonical_columns(columns) self.strict = strict @@ -501,6 +514,10 @@ class DropDataColumns(UnaryOperator): ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): tags are unchanged.""" + return stream.unique_keys + def __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): self.columns = _canonical_columns(columns) self.strict = strict @@ -883,6 +900,10 @@ class DropColumns(_TagAndDataColumnsOperator): _verb: ClassVar[str] = "drop" + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): those whose tags all stay.""" + return stream.unique_keys + def _removed(self, columns: Collection[str]) -> list[str]: return [c for c in columns if c in self.columns] @@ -907,5 +928,9 @@ class SelectColumns(_TagAndDataColumnsOperator): _verb: ClassVar[str] = "select" + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): those whose tags all stay.""" + return stream.unique_keys + def _removed(self, columns: Collection[str]) -> list[str]: return [c for c in columns if c not in self.columns] diff --git a/src/orcapod/core/operators/drop_nulls.py b/src/orcapod/core/operators/drop_nulls.py index 1e7840935..f9034893e 100644 --- a/src/orcapod/core/operators/drop_nulls.py +++ b/src/orcapod/core/operators/drop_nulls.py @@ -10,6 +10,7 @@ import pyarrow as pa import pyarrow.compute as pc +from orcapod.core.unique_keys import UniqueKeys from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel @@ -95,6 +96,10 @@ class DropNulls(UnaryOperator): ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): rows are only left out.""" + return stream.unique_keys + def __init__( self, columns: str | Collection[str] | None = None, **kwargs: Any ) -> None: diff --git a/src/orcapod/core/operators/filter.py b/src/orcapod/core/operators/filter.py index e5a4fa1a8..0ddd8c9e7 100644 --- a/src/orcapod/core/operators/filter.py +++ b/src/orcapod/core/operators/filter.py @@ -12,6 +12,7 @@ import pyarrow as pa +from orcapod.core.unique_keys import UniqueKeys from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.base import UnaryOperator @@ -86,6 +87,10 @@ class Filter(UnaryOperator): # Its identity is not frozen with data context v1 (ITL-1374). PROVISIONAL: ClassVar[bool] = True + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): rows are only left out.""" + return stream.unique_keys + def __init__( self, condition: Condition | Mapping[str, object], **kwargs: Any ) -> None: diff --git a/src/orcapod/core/operators/filters.py b/src/orcapod/core/operators/filters.py index ce01c02b5..7299af251 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -5,6 +5,7 @@ import polars as pl import pyarrow as pa +from orcapod.core.unique_keys import UniqueKeys from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.base import UnaryOperator from orcapod.core.streams import ArrowTableStream @@ -49,6 +50,10 @@ class PolarsFilter(UnaryOperator): # Its identity is not frozen with data context v1 (ITL-1266, ITL-1247). PROVISIONAL = True + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): rows are only left out.""" + return stream.unique_keys + def __init__( self, predicates: Collection[ diff --git a/src/orcapod/core/operators/group_by.py b/src/orcapod/core/operators/group_by.py index acce7333c..94cfb3256 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -9,6 +9,7 @@ import polars as pl import pyarrow as pa +from orcapod.core.unique_keys import UniqueKeys, certificate from orcapod.core.operators.arrow_keys import ( is_list_kind, part_without_rule, @@ -318,6 +319,11 @@ class GroupBy(UnaryOperator): # Data-tags (ITL-1023): handled. DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The grouping keys: one row per key, under the joins' equality.""" + del stream + return certificate([self.by]) + def __init__( self, by: str | Collection[str], diff --git a/src/orcapod/core/operators/index.py b/src/orcapod/core/operators/index.py index cbb6c2c37..2ee1e90e7 100644 --- a/src/orcapod/core/operators/index.py +++ b/src/orcapod/core/operators/index.py @@ -9,6 +9,7 @@ import pyarrow as pa +from orcapod.core.unique_keys import UniqueKeys from orcapod.types.explanation import plain_repr from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.meta_columns import WithoutMetaWriter @@ -56,6 +57,10 @@ class Index(UnaryOperator): ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): each row comes from one input row.""" + return stream.unique_keys + def __init__( self, column: str, diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 430957232..9ad39005b 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -8,6 +8,8 @@ import polars as pl import pyarrow as pa +from orcapod.protocols.core_protocols.streams import RecordBatchInput, RecordBatchOutput +from orcapod.core.unique_keys import UniqueKeys, joined_keys from orcapod.types.explanation import plain_repr from orcapod.core.operators.meta_columns import ( WithoutMetaWriter, @@ -192,6 +194,16 @@ class Join(NonZeroInputOperator): # Data-tags (ITL-1023): handled. DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, *streams: StreamProtocol) -> UniqueKeys: + """The inputs' unique keys, joined input by input (``joined_keys``).""" + keys = streams[0].unique_keys + tags = set(streams[0].keys()[0]) + for stream in streams[1:]: + names = set(stream.keys()[0]) + keys = joined_keys(keys, stream.unique_keys, tags & names) + tags |= names + return keys + @property def kernel_id(self) -> tuple[str, ...]: """ @@ -695,6 +707,27 @@ def _compute_system_tag_suffixes( suffixes.append(f"{truncated}:{canon_position[orig_idx]}") return suffixes + async def async_execute_batches( + self, inputs: Sequence[RecordBatchInput], output: RecordBatchOutput + ) -> None: + """Run over input channels of Arrow record batches, holding keys only. + + ``streaming_joins.StreamingJoin`` gives the rows of the sync path as a set, in memory + bounded by its inputs' join keys (``docs/dev/specs/itl-1464-joins.md``). + + Args: + inputs: One input channel per input stream, in the operator's order. + output: The channel the result's record batches are sent into. + """ + if type(self) is not Join: + # A subclass may compute other rows: its own sync call over all of its inputs. + await super().async_execute_batches(inputs, output) + return + # The kernels are built on this module's join rules. + from orcapod.core.operators.streaming_joins import StreamingJoin, run_kernel + + await run_kernel(lambda streams: StreamingJoin(self, streams), inputs, output) + async def async_execute( self, inputs: Sequence[ReadableChannel[tuple[TagProtocol, DataProtocol]]], diff --git a/src/orcapod/core/operators/mappers.py b/src/orcapod/core/operators/mappers.py index fa89ec4a5..da036bd29 100644 --- a/src/orcapod/core/operators/mappers.py +++ b/src/orcapod/core/operators/mappers.py @@ -1,6 +1,7 @@ from collections.abc import Collection, Mapping, Sequence from typing import Any, ClassVar +from orcapod.core.unique_keys import UniqueKeys, renamed_keys from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.operators.base import UnaryOperator @@ -96,6 +97,10 @@ class MapData(UnaryOperator): ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): no tag is renamed.""" + return stream.unique_keys + def __init__( self, name_map: Mapping[str, str], @@ -373,6 +378,13 @@ class MapTags(UnaryOperator): ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys, renamed, without those that lose a tag.""" + dropped = set(stream.keys()[0]) - set(self.name_map) + return renamed_keys( + stream.unique_keys, self.name_map, dropped if self.drop_unmapped else () + ) + def __init__( self, name_map: Mapping[str, str], @@ -669,6 +681,11 @@ class MapColumns(UnaryOperator): ROW_BY_ROW: ClassVar[bool] = True PROVISIONAL: ClassVar[bool] = True + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys, renamed, without those that lose a tag.""" + tag_renames, _, dropped, _ = self._plan(*self._user_columns(stream)) + return renamed_keys(stream.unique_keys, tag_renames, dropped) + def __init__( self, name_map: Mapping[str, str], diff --git a/src/orcapod/core/operators/merge_join.py b/src/orcapod/core/operators/merge_join.py index 88abafc5a..4abe330d8 100644 --- a/src/orcapod/core/operators/merge_join.py +++ b/src/orcapod/core/operators/merge_join.py @@ -4,6 +4,8 @@ import numpy as np import pyarrow as pa +from orcapod.protocols.core_protocols.streams import RecordBatchInput, RecordBatchOutput +from orcapod.core.unique_keys import UniqueKeys, joined_keys from orcapod.types.explanation import plain_repr from orcapod.core.operators.base import ( BinaryOperator, @@ -162,6 +164,16 @@ class MergeJoin(BinaryOperator): # Data-tags (ITL-1023) are handled (ITL-1194). DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, *streams: StreamProtocol) -> UniqueKeys: + """The inputs' unique keys, joined input by input (``joined_keys``).""" + keys = streams[0].unique_keys + tags = set(streams[0].keys()[0]) + for stream in streams[1:]: + names = set(stream.keys()[0]) + keys = joined_keys(keys, stream.unique_keys, tags & names) + tags |= names + return keys + @property def kernel_id(self) -> tuple[str, ...]: return (f"{self.__class__.__name__}",) @@ -583,6 +595,32 @@ def binary_static_process( data_tags=data_tag_names(tag_schema, data_schema), ) + async def async_execute_batches( + self, inputs: Sequence[RecordBatchInput], output: RecordBatchOutput + ) -> None: + """Run over input channels of Arrow record batches, holding keys only. + + ``streaming_joins.StreamingMergeJoin`` gives the rows of the sync path as a set, in memory + bounded by its inputs' join keys (``docs/dev/specs/itl-1464-joins.md``). + + Args: + inputs: One input channel per input stream, in the operator's order. + output: The channel the result's record batches are sent into. + """ + if type(self) is not MergeJoin: + # A subclass may compute other rows: its own sync call over all of its inputs. + await super().async_execute_batches(inputs, output) + return + # The kernels are built on this module's join rules. + from orcapod.core.operators.streaming_joins import ( + StreamingMergeJoin, + run_kernel, + ) + + await run_kernel( + lambda streams: StreamingMergeJoin(self, streams), inputs, output + ) + def rows_dropped_text( self, position: int, diff --git a/src/orcapod/core/operators/pick.py b/src/orcapod/core/operators/pick.py index 09824160d..a4353b420 100644 --- a/src/orcapod/core/operators/pick.py +++ b/src/orcapod/core/operators/pick.py @@ -9,6 +9,7 @@ import pyarrow as pa +from orcapod.core.unique_keys import UniqueKeys from orcapod.types.explanation import plain_repr from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.meta_columns import WithoutMetaWriter @@ -58,6 +59,10 @@ class Pick(UnaryOperator): ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): each row comes from one input row.""" + return stream.unique_keys + def __init__( self, column: str, diff --git a/src/orcapod/core/operators/rejoin.py b/src/orcapod/core/operators/rejoin.py index d760f5865..ead09f127 100644 --- a/src/orcapod/core/operators/rejoin.py +++ b/src/orcapod/core/operators/rejoin.py @@ -26,6 +26,7 @@ import polars as pl import pyarrow as pa +from orcapod.core.unique_keys import UniqueKeys, certificate from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.data_tags import data_tag_names, data_tags_first from orcapod.core.operators.arrow_keys import polars_key_frame @@ -330,6 +331,10 @@ class Rejoin(Join): PROVISIONAL: ClassVar[bool] = True + def derive_unique_keys(self, *streams: StreamProtocol) -> UniqueKeys: + """Every input's unique keys: a row of an input is in at most one result row.""" + return certificate(key for stream in streams for key in stream.unique_keys) + def validate_nonzero_inputs(self, *streams: StreamProtocol) -> None: """Check that the inputs can be rejoined: shared system tags, compatible columns. diff --git a/src/orcapod/core/operators/semijoin.py b/src/orcapod/core/operators/semijoin.py index d2a379f50..2ab81df26 100644 --- a/src/orcapod/core/operators/semijoin.py +++ b/src/orcapod/core/operators/semijoin.py @@ -8,6 +8,8 @@ import pyarrow as pa import pyarrow.compute as pc +from orcapod.protocols.core_protocols.streams import RecordBatchInput, RecordBatchOutput +from orcapod.core.unique_keys import UniqueKeys from orcapod.types.explanation import plain_repr from orcapod.channels import ChannelClosed, ReadableChannel, WritableChannel from orcapod.core.operators.meta_columns import WithoutMetaWriter @@ -79,6 +81,13 @@ class SemiJoin(BinaryOperator): CONSTRAINING_INPUTS: ClassVar[tuple[int, ...]] = (1,) CONSTRAINT_MATCHES_SHARED_TAGS: ClassVar[bool] = True + def derive_unique_keys( + self, left: StreamProtocol, right: StreamProtocol + ) -> UniqueKeys: + """The left input's unique keys: left rows are only left out.""" + del right + return left.unique_keys + @staticmethod def _match_keys( left_tag_keys: Collection[str], right_tag_keys: Collection[str] @@ -323,6 +332,29 @@ def _common_keys_from_schema(self) -> tuple[str, ...]: """ return getattr(self, "_validated_common_keys", ()) + async def async_execute_batches( + self, inputs: Sequence[RecordBatchInput], output: RecordBatchOutput + ) -> None: + """Run over input channels of Arrow record batches, holding keys only. + + ``streaming_joins.StreamingSemiJoin`` gives the rows of the sync path as a set, in memory + bounded by its inputs' join keys (``docs/dev/specs/itl-1464-joins.md``). + + Args: + inputs: One input channel per input stream, in the operator's order. + output: The channel the result's record batches are sent into. + """ + if type(self) is not SemiJoin: + # A subclass may compute other rows: its own sync call over all of its inputs. + await super().async_execute_batches(inputs, output) + return + # The kernels are built on this module's join rules. + from orcapod.core.operators.streaming_joins import StreamingSemiJoin, run_kernel + + await run_kernel( + lambda streams: StreamingSemiJoin(self, streams), inputs, output + ) + async def async_execute( self, inputs: Sequence[ReadableChannel[tuple[TagProtocol, DataProtocol]]], diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f829d44a5..335087a82 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -18,6 +18,7 @@ import pyarrow as pa import pyarrow.compute as pc +from orcapod.core.unique_keys import UniqueKeys, derived_keys from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, RecordBatchOutput, @@ -1633,6 +1634,10 @@ def open_channel(self) -> Any: # The members that tell what the output is without reading it: the node's, which # the built stream takes too (``_as_upstream_stream``), or the built stream's once # it is built. A protocol check (``isinstance``) reads them and builds nothing. + @property + def unique_keys(self) -> UniqueKeys: + return self._node.unique_keys + @property def producer(self) -> Any: return self._node.producer @@ -1874,6 +1879,11 @@ def pipeline_identity_structure(self) -> Any: structure += (self._pod.argument_symmetry(self._upstreams),) return structure + @property + def unique_keys(self) -> UniqueKeys: + """The tag sets no two rows agree on, derived from the inputs' (``core/unique_keys``).""" + return derived_keys(self.producer, self.upstreams, self) + @property def producer(self) -> PodProtocol: return self._pod diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 39586747c..2af444484 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -77,6 +77,7 @@ from __future__ import annotations +import asyncio from abc import ABC, abstractmethod from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from typing import Any, ClassVar @@ -114,12 +115,17 @@ from orcapod.core.operators.static_output_pod import ( RowBuiltFormUnavailable, StaticOutputOperatorPod, + close_inputs, + concatenate_batches, + finish_operator, settle_token_types, tokens_as, ) from orcapod.core.row_spool import RowSpool from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.protocols.core_protocols.streams import RecordBatchInput, RecordBatchOutput +from orcapod.core.unique_keys import joined_keys, unique_on from orcapod.system_constants import constants from orcapod.utils import arrow_utils @@ -140,6 +146,10 @@ _COUNT = "__streaming_count" _COMPACT_ROWS = 65_536 +# How many rows of one input are read ahead and pushed at once. A push joins its rows with +# every key held, so rows that have arrived already are pushed together. +PUSH_ROWS = 65_536 + def _settled_by_values(schema: pa.Schema) -> pa.Schema: """``schema`` with every system-tag and source-info field nullable. @@ -815,6 +825,8 @@ def __init__(self, operator: Join, inputs: Sequence[StreamProtocol]) -> None: if len(inputs) == 1: return first = inputs[order[0]] + # The unique keys of the rows joined so far (``core/unique_keys``). + unique_keys = first.unique_keys tag_keys = set(first.keys()[0]) data_tags = set(stream_data_tags(first)) for position, index in enumerate(order[1:], start=1): @@ -833,8 +845,13 @@ def __init__(self, operator: Join, inputs: Sequence[StreamProtocol]) -> None: keys = sorted(tag_keys & next_tags) last = position == len(inputs) - 1 self._links.append( - _BinaryLink(keys, self._link_finish(keys, rename, final=last)) + _BinaryLink( + keys, + self._link_finish(keys, rename, final=last), + (unique_on(unique_keys, keys), unique_on(stream.unique_keys, keys)), + ) ) + unique_keys = joined_keys(unique_keys, stream.unique_keys, keys) self._merges.append(bool(rename)) tag_keys |= next_tags data_tags |= next_data_tags @@ -985,7 +1002,14 @@ def __init__(self, operator: MergeJoin, inputs: Sequence[StreamProtocol]) -> Non self._type_converter = StaticOutputOperatorPod._upstream_context( # pyright: ignore[reportPrivateUsage] # the operators' one rule left ).type_converter - self._link = _BinaryLink(sorted(self._shared_tags), self._finish) + self._link = _BinaryLink( + sorted(self._shared_tags), + self._finish, + ( + unique_on(left.unique_keys, self._shared_tags), + unique_on(right.unique_keys, self._shared_tags), + ), + ) def _check_settled_against_empty_inputs(self) -> None: """Refuse, when every input has closed, a run whose input with rows settled a @@ -1760,3 +1784,123 @@ def _close(self, input_index: int) -> list[pa.Table]: ) ) return [] + + +async def run_kernel( + make_kernel: Callable[[Sequence[StreamProtocol]], StreamingJoinKernel], + inputs: Sequence[RecordBatchInput], + output: RecordBatchOutput, +) -> None: + """Run a join kernel over an operator's channels (``async_execute_batches``). + + Every input is read at once and to its end, whatever the others do: the inputs may + be two readers of one upstream, which a wait would block, and an input's read error + must be met. Each input reads ahead at most ``PUSH_ROWS`` rows and waits, and the + output's batches are sent one at a time, so a slow reader of the output holds the + join back. + + The kernel's rows and files are let go at a normal end, a failure and a + cancellation. Channels end as in ``StaticOutputOperatorPod.async_execute_batches``. + + Args: + make_kernel: Makes the kernel from the input streams (the descriptions). + inputs: The operator's input channels, in order. + output: The channel the result's record batches are sent into. + """ + readers: list[asyncio.Task[None]] = [] + kernel: StreamingJoinKernel | None = None + try: + # An input read already cannot be given whole: refused before anything is read. + claims = [channel.reserve() for channel in inputs] + kernel = make_kernel([channel.stream for channel in inputs]) + changed = asyncio.Event() + ahead = [_ReadAhead(changed) for _ in inputs] + readers = [ + asyncio.create_task(buffer.fill(channel, claim)) + for buffer, channel, claim in zip(ahead, inputs, claims) + ] + open_inputs = set(range(len(inputs))) + while open_inputs: + changed.clear() + progressed = False + for index in sorted(open_inputs): + batches, ended = ahead[index].drain() + for batch in _push_sizes(batches): + progressed = True + for result in kernel.iter_push(index, batch): + await output.send(result) + # The readers get a turn also when nothing was sent. + await asyncio.sleep(0) + if ended: + progressed = True + await readers[index] # raises what ended it, if anything did + open_inputs.discard(index) + for result in kernel.close(index): + await output.send(result) + if not progressed: + _ = await changed.wait() + except BaseException as error: + output.fail(error) + for reader in readers: + _ = reader.cancel() + _ = await asyncio.gather(*readers, return_exceptions=True) + await close_inputs(inputs, error) + raise + finally: + if kernel is not None: + kernel.release() + await finish_operator(inputs, output) + + +class _ReadAhead: + """The record batches one input delivered and the join has not pushed yet. + + Args: + changed: Set when a batch arrives or the input ends. + """ + + def __init__(self, changed: asyncio.Event) -> None: + self._changed: asyncio.Event = changed + self._room: asyncio.Event = asyncio.Event() + self._batches: list[pa.RecordBatch] = [] + self._rows: int = 0 + self._ended: bool = False + + async def fill(self, channel: RecordBatchInput, claim: object) -> None: + """Read ``channel`` to its end, waiting while ``PUSH_ROWS`` rows are unread.""" + try: + _ = channel.reserve(claim) + async for batch in channel: + if not batch.num_rows: + continue + self._batches.append(batch) + self._rows += batch.num_rows + self._changed.set() + while self._rows >= PUSH_ROWS: + self._room.clear() + _ = await self._room.wait() + finally: + self._ended = True + self._changed.set() + + def drain(self) -> tuple[list[pa.RecordBatch], bool]: + """Take the batches read, and whether the input has ended after them.""" + batches, self._batches, self._rows = self._batches, [], 0 + self._room.set() + return batches, self._ended + + +def _push_sizes(batches: Sequence[pa.RecordBatch]) -> Iterator[pa.RecordBatch]: + """``batches`` put under one another and cut to at most ``PUSH_ROWS`` rows. + + Args: + batches: Record batches of one input, in the order they arrived. + """ + if len(batches) == 1: + # As delivered: a batch of its own is what the kernel checks. + table = pa.Table.from_batches(batches) + else: + table = concatenate_batches(batches) + if table is not None: + for start in range(0, table.num_rows, PUSH_ROWS): + yield from table.slice(start, PUSH_ROWS).combine_chunks().to_batches() diff --git a/src/orcapod/core/operators/tag_by.py b/src/orcapod/core/operators/tag_by.py index 911fefc36..bb5007b11 100644 --- a/src/orcapod/core/operators/tag_by.py +++ b/src/orcapod/core/operators/tag_by.py @@ -7,6 +7,7 @@ from typing_extensions import override +from orcapod.core.unique_keys import UniqueKeys from orcapod.core.operators.base import UnaryOperator from orcapod.core.data_tags import require_taggable_type, stream_data_tags from orcapod.core.streams import ArrowTableStream @@ -79,6 +80,10 @@ class TagBy(UnaryOperator): # Data-tags (ITL-1023): handled; this operator makes them. DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): tags are only added.""" + return stream.unique_keys + def __init__(self, columns: str | Iterable[str], **kwargs: Any) -> None: names = _tag_by_names(columns) schema_utils.require_names_not_meta(names) diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index f05485472..f24c80e0d 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -91,6 +91,7 @@ class ArrowTableSource(RootSource): SOURCE_KIND: ClassVar[str] = "arrow_table" # The version of this kind's implementation, in the kind part (ITL-1425). SOURCE_VERSION: ClassVar[int] = 1 + KEY_COLUMNS_CHECKED: ClassVar[bool] = True TABLE_IS_ROWS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 07221924c..b1cc18d68 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Any, ClassVar, TypeVar from orcapod import contexts +from orcapod.core.unique_keys import NO_UNIQUE_KEYS, UniqueKeys, certificate from orcapod.config import OrcapodConfig from orcapod.core.streams.base import ( StreamBase, @@ -389,6 +390,28 @@ def row_limit(self) -> int | None: """The resolved key columns of the record ids, in key order; ``()`` for the position. Every concrete source sets it in ``__init__``.""" + KEY_COLUMNS_CHECKED: ClassVar[bool] = False + """Whether every read of the source refuses a repeated key (ITL-1464). + + Declared ``True`` only by the library source kinds whose rows all pass + ``SourceStreamBuilder``, which names each row by its key columns and refuses a + repeat, each on its own class: read for the exact class only, never inherited. + """ + + @property + def unique_keys(self) -> UniqueKeys: + """The key columns, when they are checked and all are tags (``core/unique_keys``). + + Two rows that agree on the key columns under the joins' equality have one record + id, which is a function of the values (a key is never a float). + """ + if vars(type(self)).get("KEY_COLUMNS_CHECKED") is not True: + return NO_UNIQUE_KEYS + key = frozenset(self._key_columns) + if not key or not key <= set(self.keys()[0]): + return NO_UNIQUE_KEYS + return certificate([key]) + _arrow_schemas_cache: "tuple[pa.Schema, pa.Schema] | None" = None @property diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 6c65bf64d..ae424fdbf 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -46,6 +46,7 @@ class DataFrameSource(RootSource): SOURCE_KIND: ClassVar[str] = "data_frame" # The version of this kind's implementation, in the kind part (ITL-1425). SOURCE_VERSION: ClassVar[int] = 1 + KEY_COLUMNS_CHECKED: ClassVar[bool] = True TABLE_IS_ROWS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index fdf7c1f34..eefb1647a 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -42,6 +42,7 @@ class DictSource(RootSource): SOURCE_KIND: ClassVar[str] = "dict" # The version of this kind's implementation, in the kind part (ITL-1425). SOURCE_VERSION: ClassVar[int] = 1 + KEY_COLUMNS_CHECKED: ClassVar[bool] = True TABLE_IS_ROWS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index f18da3433..c01fc5c54 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -41,6 +41,7 @@ def _default_tag(element: Any, idx: int) -> dict[str, Any]: SOURCE_KIND: ClassVar[str] = "list" # The version of this kind's implementation, in the kind part (ITL-1425). SOURCE_VERSION: ClassVar[int] = 1 + KEY_COLUMNS_CHECKED: ClassVar[bool] = True TABLE_IS_ROWS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index 58acc1f17..2c4900776 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -175,6 +175,7 @@ class PostgreSQLTableSource(DBTableSource): """Config type key and the kind in the source id's kind part (one vocabulary).""" SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" + KEY_COLUMNS_CHECKED: ClassVar[bool] = True TABLE_IS_ROWS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/sqlite_table_source.py b/src/orcapod/core/sources/sqlite_table_source.py index eab59a821..fb6319521 100644 --- a/src/orcapod/core/sources/sqlite_table_source.py +++ b/src/orcapod/core/sources/sqlite_table_source.py @@ -104,6 +104,7 @@ class SQLiteTableSource(DBTableSource): """Config type key and the kind in the source id's kind part (one vocabulary).""" SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" + KEY_COLUMNS_CHECKED: ClassVar[bool] = True TABLE_IS_ROWS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 9f8b731f7..b34dc2565 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -23,6 +23,7 @@ import polars as pl import pyarrow as pa +from orcapod.core.unique_keys import NO_UNIQUE_KEYS, UniqueKeys from orcapod.core.base import TraceableBase from orcapod.core.data_tags import data_tag_names from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel @@ -1386,6 +1387,14 @@ def index( return Index(column, i, out=out, fail_on_miss=fail_on_miss)(self, label=label) + @property + def unique_keys(self) -> UniqueKeys: + """The tag sets no two rows agree on (``core/unique_keys``). + + None by default: a stream that derives or checks them says so itself. + """ + return NO_UNIQUE_KEYS + def arrow_schema(self) -> pa.Schema: """The Arrow schema of the columns this stream passes between job nodes. diff --git a/src/orcapod/core/unique_keys.py b/src/orcapod/core/unique_keys.py new file mode 100644 index 000000000..a55e2191f --- /dev/null +++ b/src/orcapod/core/unique_keys.py @@ -0,0 +1,129 @@ +"""Uniqueness certificates: the tag sets no two rows of a stream agree on (ITL-1464). + +A *unique key* of a stream is a set of its tags such that no two of its rows agree on all +of them, under the joins' equality of values (NaN equals NaN, ``-0.0`` equals ``0.0``). A +stream's certificate is a set of unique keys (``StreamProtocol.unique_keys``); the empty +set certifies nothing. A join uses it to let a row go once it has matched, so a wrong +certificate would lose rows: every rule here certifies only what is certain. + +A source certifies its key columns when it checks them on every read, and they are all +tags. Every other stream derives its certificate from its inputs' by the rule its pod's +class declares, at the time it is asked: nothing is stored on a stream, and nothing here +enters a hash, an identity, a config, a stored row or equality. A rule is read from the +pod's exact class: a subclass, which may change the rows, certifies nothing unless it +declares a rule itself. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping, Sequence +from contextvars import ContextVar +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from orcapod.protocols.core_protocols import StreamProtocol + +UniqueKeys = frozenset[frozenset[str]] + +NO_UNIQUE_KEYS: UniqueKeys = frozenset() + +MAX_UNIQUE_KEYS = 8 +"""How many unique keys a certificate keeps (a join's keys combine pairwise).""" + +_MEMO: ContextVar[dict[int, tuple[object, UniqueKeys]] | None] = ContextVar( + "_UNIQUE_KEYS_MEMO", default=None +) +"""The certificates derived during one outermost call: a graph of diamonds reaches one +stream by many ways.""" + + +def certificate(keys: Iterable[Iterable[str]]) -> UniqueKeys: + """``keys`` as a certificate: no key that holds another one, at most a few. + + Args: + keys: Unique keys. + """ + sets = sorted({frozenset(key) for key in keys}, key=lambda k: (len(k), sorted(k))) + kept: list[frozenset[str]] = [] + for key in sets: + if not any(other <= key for other in kept): + kept.append(key) + return frozenset(kept[:MAX_UNIQUE_KEYS]) + + +def unique_on(keys: UniqueKeys, columns: Iterable[str]) -> bool: + """Whether a stream certified with ``keys`` has no two rows agreeing on ``columns``.""" + names = frozenset(columns) + return any(key <= names for key in keys) + + +def renamed_keys( + keys: UniqueKeys, renames: Mapping[str, str], dropped: Iterable[str] = () +) -> UniqueKeys: + """``keys`` after tags are renamed, all at once, and some dropped. + + Args: + keys: Unique keys. + renames: The new name of each renamed tag. + dropped: The tags that are gone; a name in it may also be another tag's new one. + """ + gone = frozenset(dropped) + return certificate( + {renames.get(name, name) for name in key} for key in keys if not key & gone + ) + + +def joined_keys( + left: UniqueKeys, right: UniqueKeys, shared: Iterable[str] +) -> UniqueKeys: + """The certificate of an inner join on ``shared`` tags. + + A joined row is named by a key of each side. When one side is unique on the shared + tags, a row of the other side is in at most one joined row, so that side's keys stay. + + Args: + left: The left side's unique keys. + right: The right side's unique keys. + shared: The tags matched on. + """ + names = frozenset(shared) + keys: set[frozenset[str]] = {a | b for a in left for b in right} + if unique_on(right, names): + keys |= left + if unique_on(left, names): + keys |= right + return certificate(keys) + + +def derived_keys( + pod: object, upstreams: Sequence[StreamProtocol], stream: StreamProtocol +) -> UniqueKeys: + """The certificate of ``stream``, the result of ``pod`` over ``upstreams``. + + The pod's class declares its rule as a method ``derive_unique_keys(*upstreams)``; + without one on the exact class, nothing is certified. + + Args: + pod: The producing pod. + upstreams: Its inputs. + stream: Its result, whose tags the keys must be among. + """ + rule = vars(type(pod)).get("derive_unique_keys") + if rule is None: + return NO_UNIQUE_KEYS + memo = _MEMO.get() + token = None + if memo is None: + memo = {} + token = _MEMO.set(memo) + try: + found = memo.get(id(stream)) + if found is None: + tags = frozenset(stream.keys()[0]) + keys = certificate(k for k in rule(pod, *upstreams) if k <= tags) + # The stream is kept beside its keys: an id is its own only while it lives. + found = memo[id(stream)] = (stream, keys) + return found[1] + finally: + if token is not None: + _MEMO.reset(token) diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index c8c72abd6..f83b2ea88 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -217,6 +217,15 @@ def arrow_types_declared(self) -> bool: """ ... + @property + def unique_keys(self) -> frozenset[frozenset[str]]: + """The tag sets no two rows of the stream agree on; empty certifies nothing. + + Derived from the inputs when asked, never stored; in no hash, identity, config, + stored row or equality (``orcapod.core.unique_keys``, ITL-1464). + """ + ... + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """ Generates explicit iterator over (tag, data) pairs in the stream. diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 071aa82ac..4280eefe0 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -18,6 +18,7 @@ import pyarrow as pa from typing_extensions import override +from orcapod.core.unique_keys import UniqueKeys, derived_keys from orcapod.core.base import TraceableBase from orcapod.core.nodes.staleness import RunHoldingNode from orcapod.core.nodes.function_node import ( @@ -139,6 +140,11 @@ def __init__( self._input_stream = input_stream super().__init__(**kwargs) + @property + def unique_keys(self) -> UniqueKeys: + """The tag sets no two rows agree on, derived from the inputs' (``core/unique_keys``).""" + return derived_keys(self.producer, self.upstreams, self) + @property def producer(self) -> SideEffectPod: # type: ignore[override] return self._pod @@ -620,6 +626,10 @@ class SideEffectPod(TraceableBase): data_context: Optional data context override. """ + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys: each row comes from one input row, its tags kept.""" + return stream.unique_keys + def __init__( self, fn: Callable, @@ -924,6 +934,11 @@ def __init__( # StreamBase interface # ------------------------------------------------------------------ + @property + def unique_keys(self) -> UniqueKeys: + """The tag sets no two rows agree on, derived from the inputs' (``core/unique_keys``).""" + return derived_keys(self.producer, self.upstreams, self) + @property def producer(self) -> SideEffectPod | None: # type: ignore[override] """The node's pod; ``None`` for a node loaded from a saved file (ITL-1094).""" diff --git a/tests/test_core/test_unique_keys.py b/tests/test_core/test_unique_keys.py new file mode 100644 index 000000000..a13396894 --- /dev/null +++ b/tests/test_core/test_unique_keys.py @@ -0,0 +1,301 @@ +"""Uniqueness certificates: what each stream and step certifies (``core/unique_keys``).""" + +from __future__ import annotations + +import warnings +from collections.abc import Callable +from datetime import datetime, timezone +from typing import Any + +import polars as pl +import pyarrow as pa +import pytest + +from orcapod import FunctionPod, function_pod +from orcapod.core.nodes import OperatorJobNode, SourceJobNode +from orcapod.core.operators import DropNulls, Join, SemiJoin +from orcapod.core.sources import ArrowTableSource, DictSource +from orcapod.core.streams import ArrowTableStream +from orcapod.core.unique_keys import ( + MAX_UNIQUE_KEYS, + certificate, + joined_keys, + renamed_keys, + unique_on, +) +from orcapod.databases import InMemoryArrowDatabase +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.types import CacheMode + +pytestmark = pytest.mark.filterwarnings("ignore") + + +def _keys(*keys: tuple[str, ...]) -> frozenset[frozenset[str]]: + return frozenset(frozenset(key) for key in keys) + + +def _table() -> pa.Table: + return pa.table( + { + "subject": ["a", "a", "b"], + "trial": [1, 2, 1], + "side": ["l", "r", "l"], + "x": [1.0, None, 3.0], + "y": [10, 20, 30], + } + ) + + +def _source( + record_id_columns: Any = ("subject", "trial"), + tags: tuple[str, ...] = ("side", "trial", "subject"), + table: pa.Table | None = None, + **kwargs: Any, +) -> ArrowTableSource: + return ArrowTableSource( + _table() if table is None else table, + tag_columns=tags, + record_id_columns=record_id_columns, + tag_only_columns=True, + **kwargs, + ) + + +KEY = ("subject", "trial") + + +def test_a_source_certifies_key_columns_that_are_all_tags() -> None: + assert _source().unique_keys == _keys(KEY) + assert _source(("trial", "subject")).unique_keys == _keys(KEY) # order is no matter + assert _source(tags=("subject", "side")).unique_keys == frozenset() # one is data + assert _source(None).unique_keys == frozenset() + assert _source(()).unique_keys == frozenset() + with_data_tags = ArrowTableSource( + _table(), + tag_columns=["subject", "trial"], + record_id_columns=["subject", "trial"], + tag_only_columns=False, + ) + assert with_data_tags.unique_keys == _keys(KEY) + + +def test_a_subclass_of_a_source_certifies_nothing() -> None: + class Repeating(ArrowTableSource): + pass + + source = Repeating( + _table(), + tag_columns=["subject", "trial"], + record_id_columns=["subject", "trial"], + ) + assert source.unique_keys == frozenset() + + +def test_a_raw_stream_certifies_nothing_also_with_a_producer() -> None: + raw = ArrowTableStream(_table(), tag_columns=["subject", "trial"]) + assert raw.unique_keys == frozenset() + made = ArrowTableStream( + _table(), + tag_columns=["subject", "trial"], + producer=DropNulls(), + upstreams=(_source(),), + ) + assert made.unique_keys == frozenset() + + +STEPS: list[tuple[str, Callable[[Any], StreamProtocol], frozenset[frozenset[str]]]] = [ + ("drop_nulls", lambda s: s.drop_nulls("x"), _keys(KEY)), + ("filter", lambda s: s.filter(side="l"), _keys(KEY)), + ("polars_filter", lambda s: s.polars_filter(pl.col("y") > 5), _keys(KEY)), + ("add_tags", lambda s: s.add_tags(run=1, cohort="A"), _keys(KEY)), + ("tag_by", lambda s: s.drop_nulls().tag_by("y"), _keys(KEY)), + ("select_data", lambda s: s.select_data_columns(["x"]), _keys(KEY)), + ("drop_data", lambda s: s.drop_data_columns(["y"]), _keys(KEY)), + ( + "select_tags_kept", + lambda s: s.select_tag_columns(["trial", "subject"]), + _keys(KEY), + ), + ( + "select_tags_lost", + lambda s: s.select_tag_columns(["side", "trial"]), + frozenset(), + ), + ("drop_tag_kept", lambda s: s.drop_tag_columns(["side"]), _keys(KEY)), + ("drop_tag_lost", lambda s: s.drop_tag_columns(["trial"]), frozenset()), + ("select_kept", lambda s: s.select_columns(["subject", "trial", "x"]), _keys(KEY)), + ("select_lost", lambda s: s.select_columns(["subject", "x"]), frozenset()), + ("drop_kept", lambda s: s.drop_columns(["side", "x"]), _keys(KEY)), + ("drop_lost", lambda s: s.drop_columns(["subject"]), frozenset()), + ("map_data", lambda s: s.map_data(x="z", y="w"), _keys(KEY)), + ("map_tags", lambda s: s.map_tags(trial="t", side="s"), _keys(("subject", "t"))), + ( + "map_tags_swapped", + lambda s: s.map_tags({"trial": "side", "side": "trial"}), + _keys(("subject", "side")), + ), + ( + "map_tags_drops_a_key", + lambda s: s.map_tags({"side": "s", "subject": "subject2"}, drop_unmapped=True), + frozenset(), + ), + ("map_columns", lambda s: s.map_columns(trial="t", x="z"), _keys(("subject", "t"))), + ("group_by", lambda s: s.group_by(["side", "trial"]), _keys(("side", "trial"))), + ("batch", lambda s: s.batch(2), frozenset()), + ( + "chain", + lambda s: s.drop_nulls().map_tags(subject="u").add_tags(k=1), + _keys(("u", "trial")), + ), +] + + +def _tag_rows(stream: StreamProtocol, names: frozenset[str]) -> list[tuple[Any, ...]]: + table = stream.as_table() + return list(zip(*(table.column(name).to_pylist() for name in sorted(names)))) + + +@pytest.mark.parametrize("label,step,expected", STEPS, ids=[s[0] for s in STEPS]) +def test_each_step_derives_its_certificate( + label: str, + step: Callable[[Any], StreamProtocol], + expected: frozenset[frozenset[str]], +) -> None: + result = step(_source()) + assert result.unique_keys == expected + for key in result.unique_keys: # and it holds + rows = _tag_rows(result, key) + assert len(rows) == len(set(rows)) + + +def _other(key: tuple[str, ...] | None, tags: tuple[str, ...]) -> ArrowTableSource: + table = pa.table({"trial": [1, 2], "depth": [5, 6], "z": [1, 2], "w": [3, 4]}) + return _source(key, tags, table, source_id="other") + + +def test_joins_derive_their_certificate() -> None: + left = _source() + lookup = _other(("trial",), ("depth", "trial")) + both = _other(("trial", "depth"), ("depth", "trial")) + none = _other(None, ("depth", "trial")) + # A lookup matches each left row at most once: the left key stays. + assert left.join(lookup).unique_keys == _keys(KEY) + assert lookup.join(left).unique_keys == _keys(KEY) + assert left.join(both).unique_keys == _keys((*KEY, "depth")) + assert left.join(none).unique_keys == frozenset() + assert left.join(lookup, _wide()).unique_keys == _keys(KEY) + assert left.semi_join(none).unique_keys == _keys(KEY) + assert none.semi_join(left).unique_keys == frozenset() + renamed = left.select_data_columns(["x"]) + assert renamed.rejoin(left.select_data_columns(["y"])).unique_keys == _keys(KEY) + + +def _wide() -> ArrowTableSource: + table = pa.table({"subject": ["a", "b"], "q": [1, 2]}) + return _source(("subject",), ("subject",), table, source_id="wide") + + +def test_a_one_to_one_join_keeps_both_keys() -> None: + a = _source(("trial",), ("trial",), pa.table({"trial": [1, 2], "x": [1, 2]})) + b = _source( + ("trial",), ("trial",), pa.table({"trial": [2, 1], "y": [1, 2]}), source_id="b" + ) + assert a.join(b).unique_keys == _keys(("trial",)) + + +def test_a_function_pod_and_a_side_effect_keep_the_certificate() -> None: + @function_pod(output_keys=["total", "half"]) + def add(x: float | None, y: int | None) -> tuple[float, float]: + return (x or 0.0) + (y or 0), (y or 0) / 2 + + assert add.pod(_source()).unique_keys == _keys(KEY) + assert isinstance(add.pod, FunctionPod) + + +def test_an_operator_subclass_certifies_nothing() -> None: + class Doubling(DropNulls): + pass + + class MyJoin(Join): + pass + + assert Doubling("x")(_source()).unique_keys == frozenset() + assert MyJoin()(_source(), _wide()).unique_keys == frozenset() + + +def test_a_source_slot_answers_as_its_bound_source() -> None: + source = _source() + node = SourceJobNode.from_stream(source) + assert node.unique_keys == _keys(KEY) + node.bound_source = None + assert node.unique_keys == frozenset() + + +@pytest.mark.parametrize("mode", list(CacheMode)) +def test_a_replaying_operator_node_certifies_nothing(mode: CacheMode) -> None: + """``REPLAY`` gives every logged run's rows, so a tag tuple can repeat.""" + node = OperatorJobNode(DropNulls("x"), (SourceJobNode.from_stream(_source()),)) + node.attach_databases(pipeline_database=InMemoryArrowDatabase(), cache_mode=mode) + expected = frozenset() if mode == CacheMode.REPLAY else _keys(KEY) + assert node.unique_keys == expected + + +def test_a_certificate_follows_a_changed_upstream() -> None: + node = SourceJobNode.from_stream(_source()) + operator = OperatorJobNode(DropNulls("x"), (node,)) + assert operator.unique_keys == _keys(KEY) + node.bound_source = _source(None) + assert operator.unique_keys == frozenset() + + +def test_a_certificate_enters_no_identity() -> None: + table = _table() + keyed = _source(source_id="s", table=table) + plain = _source(None, source_id="s", table=table) + assert keyed.unique_keys != plain.unique_keys + assert keyed.pipeline_hash() == plain.pipeline_hash() + derived = keyed.drop_nulls("x") + before = derived.content_hash() + _ = derived.unique_keys + assert derived.content_hash() == before + assert "unique_keys" not in keyed.to_config() + + +def test_a_tall_stack_of_diamonds_is_derived_once_per_stream() -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + stream: Any = _source() + for _ in range(40): # 2**40 ways down without the memo + stream = stream.semi_join(stream) + assert stream.unique_keys == _keys(KEY) + assert isinstance(stream.producer, SemiJoin) + + +def test_key_values_equal_under_a_join_are_refused_by_the_source() -> None: + at = datetime(2026, 1, 1, tzinfo=timezone.utc) + repeated = pa.table( + {"t": pa.array([at, at], pa.timestamp("ns", "UTC")), "x": [1, 2]} + ) + with pytest.raises(Exception, match="must be unique"): + _ = _source(("t",), ("t",), repeated) + with pytest.raises(Exception, match="cannot identify"): + _ = _source(("t",), ("t",), pa.table({"t": [0.0, -0.0], "x": [1, 2]})) + assert DictSource( + [{"k": 1, "x": 1}], tag_columns=["k"], record_id_columns="k" + ).unique_keys == _keys(("k",)) + + +def test_the_algebra() -> None: + assert certificate([("a", "b"), ("a",), ("b", "a")]) == _keys(("a",)) + many = certificate((f"k{i}",) for i in range(50)) + assert len(many) == MAX_UNIQUE_KEYS + assert unique_on(_keys(("a",)), ["b", "a"]) + assert not unique_on(_keys(("a", "b")), ["a"]) + assert not unique_on(frozenset(), ["a"]) + assert renamed_keys(_keys(("a", "b")), {"a": "b", "b": "a"}) == _keys(("a", "b")) + assert renamed_keys(_keys(("a",), ("b",)), {"b": "a"}, ["a"]) == _keys(("a",)) + a, b = _keys(("a",)), _keys(("a", "b")) + assert joined_keys(a, b, ["a"]) == _keys(("a", "b")) + assert joined_keys(a, _keys(("a",)), ["a"]) == _keys(("a",)) + assert joined_keys(a, b, []) == _keys(("a", "b")) + assert joined_keys(a, frozenset(), ["a"]) == frozenset() From 4876287107ab66d18dcdd7eade2dee4dc94fa18c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:31:36 -0800 Subject: [PATCH 05/26] test(operators): keys-only joins against the sync rows (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- .../operators/test_keys_only_joins.py | 504 ++++++++++++++++++ 1 file changed, 504 insertions(+) create mode 100644 tests/test_core/operators/test_keys_only_joins.py diff --git a/tests/test_core/operators/test_keys_only_joins.py b/tests/test_core/operators/test_keys_only_joins.py new file mode 100644 index 000000000..f0379d207 --- /dev/null +++ b/tests/test_core/operators/test_keys_only_joins.py @@ -0,0 +1,504 @@ +"""Joins on the async path hold keys and references, whatever their inputs certify. + +ITL-1464: the streaming kernels keep their inputs' join keys in memory and the rows in a +spool (``core/row_spool``), let a row go once it has matched when the other side is +certified unique on the keys (``core/unique_keys``), and send their output in bounded +pieces. The rows are those of the sync path, as a multiset, with every spool in memory or +on disk and for every kind of inputs: one to one, a lookup on either side, many to many. +""" + +from __future__ import annotations + +import asyncio +import functools +import random +import warnings +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.core.operators import Join, MergeJoin, SemiJoin +from orcapod.core.operators import streaming_joins +from orcapod.core.operators.streaming_joins import ( + StreamingJoin, + StreamingJoinKernel, + StreamingMergeJoin, + StreamingSemiJoin, +) +from orcapod.core.record_batch_channels import OutputChannel +from orcapod.core.row_spool import RowSpool +from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams import ArrowTableStream +from orcapod.errors import UpstreamFailedError +from orcapod.protocols.core_protocols import StreamProtocol + +from .test_streaming_joins import _arrivals, _check, _rows, _run, _sent, _transport # pyright: ignore[reportPrivateUsage] # the kernels' one oracle + +TIMEOUT = 30.0 + + +@pytest.fixture(autouse=True) +def _quiet() -> Any: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + yield + + +@pytest.fixture(params=["memory", "disk"]) +def spooled(request: pytest.FixtureRequest, tmp_path: Path, monkeypatch: Any) -> Path: + """Every spool in memory, or every row on disk; output in pieces of 3 rows.""" + limit = 0 if request.param == "disk" else 1 << 40 + monkeypatch.setattr( + streaming_joins, "RowSpool", functools.partial(RowSpool, limit, str(tmp_path)) + ) + monkeypatch.setattr(streaming_joins, "PAIRS_PER_BATCH", 3) + monkeypatch.setattr(streaming_joins, "_COMPACT_ROWS", 4) + return tmp_path + + +def _files(root: Path) -> list[Path]: + return list(root.rglob("*.arrow")) + + +def _source( + name: str, + tags: dict[str, list[Any]], + *, + key: Sequence[str] | None = None, + types: dict[str, pa.DataType] | None = None, + layout: str = "tags_first", + colliding: bool = False, +) -> ArrowTableSource: + """A source with these tags and two data columns, shuffled rows.""" + n = len(next(iter(tags.values()))) + order = random.Random(name).sample(range(n), n) + columns: dict[str, pa.Array[Any]] = { + t: pa.array([v[i] for i in order], (types or {}).get(t)) + for t, v in tags.items() + } + first = "value" if colliding else f"{name}_x" + data: dict[str, pa.Array[Any]] = { + first: pa.array([f"{name}{i}" for i in order], pa.large_string()), + f"{name}_y": pa.array([None if i % 4 == 1 else i / 2 for i in order]), + } + merged = {**columns, **data} if layout == "tags_first" else {**data, **columns} + names = list(reversed(merged)) if layout == "reversed" else list(merged) + return ArrowTableSource( + pa.table({c: merged[c] for c in names}), + tag_columns=list(tags) if layout == "tags_first" else list(reversed(tags)), + record_id_columns=key, + tag_only_columns=True, + source_id=name, + ) + + +def _pairs(n: int, m: int) -> dict[str, list[Any]]: + return { + "session": [f"s{i}" for i in range(n) for _ in range(m)], + "unit": [j for _ in range(n) for j in range(m)], + } + + +def _one_to_one(layout: str) -> list[ArrowTableSource]: + key = ("session", "unit") + return [ + _source("a", _pairs(4, 5), key=key, layout=layout), + _source("b", _pairs(5, 4), key=key[::-1], layout="reversed"), + ] + + +def _lookup(layout: str) -> list[ArrowTableSource]: + spikes = {**_pairs(6, 6), "n": list(range(36))} + spikes["session"] = [f"s{i % 5}" for i in range(36)] + return [ + _source("spikes", spikes, key=("n", "session"), layout=layout), + _source("units", _pairs(4, 5), key=("session", "unit"), layout="reversed"), + ] + + +def _many_to_many(layout: str) -> list[ArrowTableSource]: + left = {**_pairs(2, 3), "n": list(range(6))} + right = {"unit": [0, 1, 1, 2, 2, 2, 9], "m": list(range(7))} + return [ + _source("a", left, key=("n",), layout=layout), + _source("b", right, key=("m",), layout="reversed"), + ] + + +def _null_keys(layout: str) -> list[ArrowTableSource]: + """A unique side (a key is never null) against keys with nulls and repeats.""" + left = {"k": [1, None, 2, 2, None, 7], "n": list(range(6))} + return [ + _source("a", left, key=("n",), layout=layout), + _source("b", {"k": [1, 2, 3], "g": [1, 1, 2]}, key=("k",), layout="reversed"), + ] + + +def _cross(layout: str) -> list[ArrowTableSource]: + return [ + _source("a", {"i": [1, 2, 3], "i2": [1, 1, 1]}, key=("i",), layout=layout), + _source("b", {"j": [1, 2, 3, 4], "j2": [1, 1, 1, 1]}, key=("j",)), + ] + + +KINDS: dict[str, Callable[[str], list[ArrowTableSource]]] = { + "one_to_one": _one_to_one, + "lookup": _lookup, + "many_to_many": _many_to_many, + "null_keys": _null_keys, + "no_shared_tag": _cross, +} +LAYOUTS = ("tags_first", "data_first", "reversed") + + +def _join(inputs: Sequence[StreamProtocol]) -> StreamingJoinKernel: + return StreamingJoin(Join(), inputs) + + +def _semi(inputs: Sequence[StreamProtocol]) -> StreamingJoinKernel: + return StreamingSemiJoin(SemiJoin(), inputs) + + +def _merge(inputs: Sequence[StreamProtocol]) -> StreamingJoinKernel: + return StreamingMergeJoin(MergeJoin(), inputs) + + +@pytest.mark.parametrize("swapped", [False, True]) +@pytest.mark.parametrize("layout", LAYOUTS) +@pytest.mark.parametrize("kind", sorted(KINDS)) +def test_two_inputs_give_the_sync_rows( + spooled: Path, kind: str, layout: str, swapped: bool +) -> None: + inputs = KINDS[kind](layout) + if swapped: + inputs.reverse() + _check(_join, Join().static_process, inputs) + _check(_semi, SemiJoin().static_process, inputs) + _check(_merge, MergeJoin().static_process, inputs) + assert _files(spooled) == [] + + +@pytest.mark.parametrize("kind", ["one_to_one", "lookup", "many_to_many"]) +def test_merge_join_of_a_colliding_column(spooled: Path, kind: str) -> None: + (a, b) = KINDS[kind]("tags_first") + inputs = [ + stream.map_data({f"{name}_x": "value"}) + if hasattr(stream, "map_data") + else stream + for stream, name in ( + (a, a.source_id.split(":")[1]), + (b, b.source_id.split(":")[1]), + ) + ] + _check(_merge, MergeJoin().static_process, inputs) + _check(_merge, MergeJoin().static_process, inputs[::-1]) + assert _files(spooled) == [] + + +@pytest.mark.parametrize("order", [(0, 1, 2), (2, 0, 1), (1, 2, 0)]) +@pytest.mark.parametrize("keyed", ["all", "some", "none"]) +def test_three_inputs_give_the_sync_rows( + spooled: Path, keyed: str, order: tuple[int, ...] +) -> None: + spikes = {**_pairs(4, 5), "n": list(range(20))} + inputs = [ + _source("spikes", spikes, key=None if keyed == "none" else ("n",)), + _source( + "units", + _pairs(5, 4), + key=("session", "unit") if keyed == "all" else None, + layout="reversed", + ), + _source( + "sessions", + {"session": ["s0", "s1", "s3", "s9"], "day": [1, 2, 2, 3]}, + key=("session",) if keyed != "none" else None, + layout="data_first", + ), + ] + _check(_join, Join().static_process, [inputs[i] for i in order]) + assert _files(spooled) == [] + + +def test_float_keys_with_a_certified_side(spooled: Path) -> None: + """``GroupBy`` certifies float keys under the joins' equality (NaN, signed zero).""" + nan = float("nan") + values = [0.0, -0.0, nan, 1.5, float("-nan"), 1.5] + grouped = _source("g", {"f": values, "n": list(range(6))}).group_by("f") + assert grouped.unique_keys == frozenset({frozenset({"f"})}) + other = _source("o", {"f": [-0.0, nan, 1.5, 2.0, 0.0], "m": [1, 2, 3, 4, 5]}) + for inputs in ([grouped, other], [other, grouped]): + _check(_join, Join().static_process, inputs) + _check(_semi, SemiJoin().static_process, inputs) + + +# --------------------------------------------------------------------------- +# What is held +# --------------------------------------------------------------------------- + + +def _batches(stream: StreamProtocol, size: int) -> list[pa.RecordBatch]: + table = _sent(stream).combine_chunks() + return [ + batch + for start in range(0, table.num_rows, size) + for batch in table.slice(start, size).combine_chunks().to_batches() + ] + + +def _sorted_source(name: str, n: int, *, key: bool = True) -> ArrowTableSource: + return ArrowTableSource( + pa.table( + { + "t": list(range(n)), + "u": ["u"] * n, + f"{name}1": [1] * n, + f"{name}2": [2] * n, + } + ), + tag_columns=["u", "t"], + record_id_columns=["t"] if key else None, + tag_only_columns=True, + source_id=name, + ) + + +def test_a_one_to_one_join_in_step_holds_only_the_rows_between_the_inputs( + spooled: Path, +) -> None: + left, right = _sorted_source("a", 60), _sorted_source("b", 60) + kernel = _join([left, right]) + emitted = 0 + for mine, theirs in zip(_batches(left, 5), _batches(right, 5)): + kernel.push(0, mine) + assert kernel.held_rows == 5 + emitted += sum(b.num_rows for b in kernel.push(1, theirs)) + assert kernel.held_rows == 0 + assert _files(spooled) == [] # and the files went with their rows + assert emitted == 60 + + +def test_a_lookup_holds_the_unique_side_and_no_row_that_matched(spooled: Path) -> None: + spikes = _source( + "spikes", {"unit": [0, 1, 2, 3] * 10, "n": list(range(40))}, key=("n",) + ) + units = _source("units", {"unit": [0, 1, 2], "area": [1, 1, 2]}, key=("unit",)) + kernel = _join([spikes, units]) + (first, *rest) = _batches(spikes, 8) + kernel.push(0, first) + assert kernel.held_rows == 8 # arrived before any unit + (all_units,) = _batches(units, 3) + kernel.push(1, all_units) + assert kernel.held_rows == 2 + 3 # the spikes of unit 3, and the units + for batch in rest: + kernel.push(0, batch) + assert kernel.held_rows == 10 + 3 # unit 3 may still arrive + kernel.close(1) + assert kernel.held_rows == 3 # it did not + kernel.close(0) + assert kernel.held_rows == 0 + + +def test_without_a_certificate_nothing_that_may_match_again_is_let_go( + spooled: Path, +) -> None: + left, right = ( + _sorted_source("a", 6, key=False), + _sorted_source("b", 6, key=False), + ) + kernel = _join([left, right]) + (one,), (two,) = _batches(left, 6), _batches(right, 6) + kernel.push(0, one) + assert sum(b.num_rows for b in kernel.push(1, two)) == 6 + assert kernel.held_rows == 12 + kernel.release() + assert _files(spooled) == [] + + +def test_a_many_to_many_match_is_emitted_in_bounded_pieces(spooled: Path) -> None: + left = _source("a", {"k": [1] * 20 + [2], "n": list(range(21))}) + right = _source("b", {"k": [1] * 15 + [2], "m": list(range(16))}) + kernel = _join([left, right]) + (mine,), (theirs,) = _batches(left, 21), _batches(right, 16) + kernel.push(0, mine) + sizes = [batch.num_rows for batch in kernel.push(1, theirs)] + assert sum(sizes) == 20 * 15 + 1 + assert max(sizes) <= 3 + # One arriving row's matches are cut too. + many = _join([left, right]) + many.push(0, mine) + assert all(b.num_rows <= 3 for b in many.push(1, theirs.slice(0, 1))) + + +def test_a_semi_join_holds_each_right_key_once(spooled: Path) -> None: + left = _source("a", {"k": [1, 2], "n": [1, 2]}) + right = _source("b", {"k": [1, 1, 3, 3, 3] * 4, "m": list(range(20))}) + kernel = _semi([left, right]) + for batch in _batches(right, 5): + kernel.push(1, batch) + assert kernel.held_rows == 2 + + +# --------------------------------------------------------------------------- +# The channels +# --------------------------------------------------------------------------- + + +def _bounded(coroutine: Any) -> Any: + async def go() -> Any: + return await asyncio.wait_for(coroutine, TIMEOUT) + + return asyncio.run(go()) + + +@pytest.mark.parametrize("kind", sorted(KINDS)) +@pytest.mark.parametrize("op", [Join(), SemiJoin(), MergeJoin()], ids=lambda o: repr(o)) +def test_the_channel_result_is_the_sync_result_as_rows( + spooled: Path, op: Any, kind: str +) -> None: + inputs = KINDS[kind]("tags_first") + output = OutputChannel(op(*inputs)) + _bounded(op.async_execute_batches([s.open_channel() for s in inputs], output)) + assert _rows(_transport(output.result())) == _rows(_transport(op(*inputs))) + assert _files(spooled) == [] + + +def test_a_diamond_through_bounded_channels_does_not_wait_for_itself( + spooled: Path, +) -> None: + """Both inputs read one upstream, which sends to both and waits for the slower.""" + source = _sorted_source("a", 50) + left = source.select_data_columns(["a1"]) + right = source.select_data_columns(["a2"]) + + async def go() -> StreamProtocol: + one = OutputChannel(left, retain=False, buffer_size=1) + two = OutputChannel(right, retain=False, buffer_size=1) + op = Join() + output = OutputChannel(op(left, right)) + readers = [one.open_reader(), two.open_reader()] + + async def produce() -> None: + for channel, stream in ((two, right), (one, left)): + for batch in _batches(stream, 1): + await channel.send(batch) + await one.close() + await two.close() + + await asyncio.gather(produce(), op.async_execute_batches(readers, output)) + return output.result() + + result = _bounded(go()) + assert _rows(_transport(result)) == _rows(_transport(left.join(right))) + + +def test_a_failed_input_fails_the_output_and_leaves_no_file( + spooled: Path, request: pytest.FixtureRequest +) -> None: + left, right = _sorted_source("a", 20), _sorted_source("b", 20) + + async def go() -> None: + failing = OutputChannel(left, retain=False, buffer_size=4) + op = Join() + output = OutputChannel(op(left, right)) + reader = failing.open_reader() + run = asyncio.create_task( + op.async_execute_batches([reader, right.open_channel()], output) + ) + await failing.send(_batches(left, 5)[0]) + await asyncio.sleep(0.05) + if "disk" in request.node.name: + assert _files(spooled) + failing.fail(RuntimeError("the read broke")) + with pytest.raises(UpstreamFailedError, match="the read broke"): + await run + with pytest.raises(RuntimeError, match="the read broke"): + output.result() + + _bounded(go()) + assert _files(spooled) == [] + + +def test_a_cancelled_join_stops_its_readers_and_leaves_no_file(spooled: Path) -> None: + left, right = _sorted_source("a", 20), _sorted_source("b", 20) + + async def go() -> None: + waiting = OutputChannel(left, retain=False, buffer_size=1) + op = Join() + output = OutputChannel(op(left, right)) + run = asyncio.create_task( + op.async_execute_batches( + [waiting.open_reader(), right.open_channel()], output + ) + ) + await waiting.send(_batches(left, 5)[0]) + await asyncio.sleep(0.05) + run.cancel() + with pytest.raises(asyncio.CancelledError): + await run + # Nothing reads the producer's output any more, and it waits for nobody. + for batch in _batches(left, 5)[1:]: + await waiting.send(batch) + + _bounded(go()) + assert _files(spooled) == [] + + +def test_an_output_that_is_not_read_holds_the_join_back(spooled: Path) -> None: + left = _source("a", {"k": [1] * 30, "n": list(range(30))}) + right = _source("b", {"k": [1] * 30, "m": list(range(30))}) + + async def go() -> None: + op = Join() + result = op(left, right) + output = OutputChannel(result, retain=False, buffer_size=1) + reader = output.open_reader() + run = asyncio.create_task( + op.async_execute_batches( + [left.open_channel(), right.open_channel()], output + ) + ) + await asyncio.sleep(0.1) + assert not run.done() # 900 rows in pieces of 3: it waits for the reader + rows = sum([batch.num_rows async for batch in reader]) + await run + assert rows == 900 + + _bounded(go()) + + +def test_a_subclass_keeps_its_own_computation() -> None: + class Emptied(Join): + def static_process(self, *streams: StreamProtocol) -> StreamProtocol: + joined = super().static_process(*streams) + table = joined.as_table(columns={"source": True, "system_tags": True}) + return ArrowTableStream(table.slice(0, 1), tag_columns=joined.keys()[0]) + + inputs = _one_to_one("tags_first") + op = Emptied() + output = OutputChannel(op(*inputs)) + _bounded(op.async_execute_batches([s.open_channel() for s in inputs], output)) + assert output.result().as_table().num_rows == 1 + + +def test_a_random_arrival_of_everything_once_more(spooled: Path) -> None: + """Larger inputs, every kind of certificate, many interleavings.""" + rng = random.Random(0) + for n in (1, 40): + tags = { + "k": [rng.randrange(8) for _ in range(n)], + "h": [rng.choice("xy") for _ in range(n)], + "n": list(range(n)), + } + left = _source("a", tags, key=("n", "k")) + right = _source("b", {"k": list(range(8)), "q": [1] * 8}, key=("k",)) + tables = [_sent(left), _sent(right)] + expected = _rows(_transport(Join().static_process(left, right))) + for seed in range(30): + kernel = _join([left, right]) + batches = _run(kernel, _arrivals(tables, random.Random(seed))) + got = pa.Table.from_batches(batches) if batches else None + assert (_rows(got) if got is not None else {}) == expected From a6027682cfb7575b6d8e0bd33d5fe5905e891482 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:33:12 -0800 Subject: [PATCH 06/26] docs(dev): async join measurements script (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-joins/measure.py | 203 +++++++++++++++++++++++ 1 file changed, 203 insertions(+) create mode 100644 docs/dev/specs/itl-1464-joins/measure.py diff --git a/docs/dev/specs/itl-1464-joins/measure.py b/docs/dev/specs/itl-1464-joins/measure.py new file mode 100644 index 000000000..128054893 --- /dev/null +++ b/docs/dev/specs/itl-1464-joins/measure.py @@ -0,0 +1,203 @@ +"""One async join over record-batch channels, its time and peak memory (ITL-1464). + +Usage: ``measure.py [barrier]``. Synthetic rows; the inputs are sent batch by +batch through bounded channels (nothing else is held) and the output is read and dropped. +``barrier`` runs the join as before this change (every input read whole, then the sync +call). Cases: + +- ``lookup``: ``rows`` spikes against 300 units, the units arriving first; +- ``lookup_late``: the same, the units arriving after every spike; +- ``one_to_one``: two inputs of ``rows`` rows, unique on every shared tag, in step; +- ``one_to_one_late``: the same, one input arriving entirely before the other; +- ``many``: ``rows`` spikes against 1,000 events, neither unique on the session and + shank they share: five output rows per spike. +- ``semi``: ``rows`` spikes kept by the units that exist (300). +""" + +from __future__ import annotations + +import asyncio +import resource +import sys +import time +import warnings +from collections.abc import Iterator + +import numpy as np +import pyarrow as pa + +from orcapod.core.operators import Join, SemiJoin +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.record_batch_channels import OutputChannel +from orcapod.core.sources import ArrowTableSource +from orcapod.protocols.core_protocols import StreamProtocol + +BATCH = 8_192 +SESSION = "session-2026-01-01-000000-abcdef" + + +def _text(values: np.ndarray, pattern: str) -> pa.Array: + return pa.array([pattern % v for v in values.tolist()], pa.large_string()) + + +def spikes(start: int, n: int) -> pa.Table: + """Event rows: seven tags and data, as the measured spike table.""" + i = np.arange(start, start + n) + return pa.table( + { + "session": pa.array([SESSION] * n, pa.large_string()), + "unit": _text(i % 300, "unit-%05d"), + "spike": pa.array(i, pa.int64()), + "shank": pa.array(i % 200, pa.int64()), + "time": pa.array(i / 30_000.0), + "amplitude": pa.array((i % 97) * 1.5), + } + ) + + +def second(start: int, n: int) -> pa.Table: + """A second value per spike, for the one-to-one cases.""" + i = np.arange(start, start + n) + return pa.table( + { + "session": pa.array([SESSION] * n, pa.large_string()), + "unit": _text(i % 300, "unit-%05d"), + "spike": pa.array(i, pa.int64()), + "depth": pa.array(i % 13, pa.int64()), + "width": pa.array((i % 7) * 0.5), + } + ) + + +def units(start: int, n: int) -> pa.Table: + i = np.arange(start, start + n) + return pa.table( + { + "session": pa.array([SESSION] * n, pa.large_string()), + "unit": _text(i, "unit-%05d"), + "area": _text(i % 9, "area-%d"), + "quality": pa.array(i * 1.0), + } + ) + + +def events(start: int, n: int) -> pa.Table: + i = np.arange(start, start + n) + return pa.table( + { + "session": pa.array([SESSION] * n, pa.large_string()), + "shank": pa.array(i % 200, pa.int64()), + "event": pa.array(i, pa.int64()), + "onset": pa.array(i * 0.1), + "kind": _text(i % 4, "kind-%d"), + } + ) + + +class Input: + """An input: a small source of its kind describes it, its rows are made as sent.""" + + def __init__(self, name: str, make, rows: int, tags: list[str], key: list[str]): + self.make, self.rows, self.key, self.name = make, rows, key, name + self.tags = tags + self.stream = self.source(0, 4) + + def source(self, start: int, n: int) -> ArrowTableSource: + return ArrowTableSource( + self.make(start, n), + tag_columns=self.tags, + record_id_columns=self.key, + tag_only_columns=True, + source_id=self.name, + ) + + def batches(self) -> Iterator[pa.RecordBatch]: + for start in range(0, self.rows, BATCH): + stream: StreamProtocol = self.source(start, min(BATCH, self.rows - start)) + zero = StaticOutputOperatorPod._materialize_upstream([], self.stream) + names = zero.as_table(columns={"source": True, "system_tags": True}) + table = stream.as_table(columns={"source": True, "system_tags": True}) + yield from table.select(names.column_names).combine_chunks().to_batches() + + +async def run(case: str, rows: int, barrier: bool) -> tuple[int, float]: + big = Input( + "spikes", + spikes, + rows, + ["session", "unit", "spike"] + if not case.startswith("many") + else ["session", "shank", "spike"], + ["session", "unit", "spike"] if case != "many" else ["session", "spike"], + ) + if case.startswith("one_to_one"): + other = Input( + "second", + second, + rows, + ["spike", "unit", "session"], + ["session", "unit", "spike"], + ) + elif case == "many": + other = Input( + "events", events, 1_000, ["session", "shank", "event"], ["session", "event"] + ) + else: + other = Input("units", units, 300, ["unit", "session"], ["session", "unit"]) + op = SemiJoin() if case == "semi" else Join() + result = op(big.stream, other.stream) + output = OutputChannel(result, retain=False, buffer_size=2) + reader = output.open_reader() + channels = [ + OutputChannel(i.stream, retain=False, buffer_size=2) for i in (big, other) + ] + readers = [channel.open_reader() for channel in channels] + + async def produce(index: int, source: Input, after: asyncio.Event | None) -> None: + if after is not None: + await after.wait() + for batch in source.batches(): + await channels[index].send(batch) + await asyncio.sleep(0) + await channels[index].close() + done[index].set() + + done = [asyncio.Event(), asyncio.Event()] + first = {"lookup": 1, "many": 1, "semi": 1}.get(case) + waits: list[asyncio.Event | None] = [None, None] + if first is not None: + waits[1 - first] = done[first] + if case.endswith("late"): + waits[1] = done[0] + count = 0 + + async def consume() -> None: + nonlocal count + async for batch in reader: + count += batch.num_rows + + if barrier: + execute = StaticOutputOperatorPod.async_execute_batches(op, readers, output) + else: + execute = op.async_execute_batches(readers, output) + began = time.perf_counter() + await asyncio.gather( + produce(0, big, waits[0]), produce(1, other, waits[1]), consume(), execute + ) + return count, time.perf_counter() - began + + +if __name__ == "__main__": + warnings.simplefilter("ignore") + case, rows = sys.argv[1], int(sys.argv[2]) + barrier = "barrier" in sys.argv + base = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + count, seconds = asyncio.run(run(case, rows, barrier)) + peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + unit = 2**20 if sys.platform == "darwin" else 2**10 + print( + f"{case:16} rows={rows:>9,} {'barrier' if barrier else 'keys':8}" + + f" out={count:>11,} {seconds:7.1f} s" + + f" peak={peak / unit:8.0f} MiB (import {base / unit:.0f})" + + f" arrow_peak={pa.default_memory_pool().max_memory() / 2**20:8.0f} MiB" + ) From b03a944e7b5edcaae39df36c9f2cbb0b614ce93b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:37:57 -0800 Subject: [PATCH 07/26] perf(core): recipes through F, predicates and spills; design and tests (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1464.md | 7 + docs/dev/specs/itl-1464-tokens.md | 111 +++++ src/orcapod/core/nodes/source_node.py | 6 + src/orcapod/core/operators/filters.py | 5 +- .../core/operators/static_output_pod.py | 4 + src/orcapod/core/sources/base.py | 3 +- src/orcapod/core/streams/base.py | 9 +- src/orcapod/utils/source_tokens.py | 44 +- tests/test_core/streams/test_source_tokens.py | 449 ++++++++++++++++++ 9 files changed, 612 insertions(+), 26 deletions(-) create mode 100644 changelog.d/ITL-1464.md create mode 100644 docs/dev/specs/itl-1464-tokens.md create mode 100644 tests/test_core/streams/test_source_tokens.py diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md new file mode 100644 index 000000000..c9b7b4402 --- /dev/null +++ b/changelog.d/ITL-1464.md @@ -0,0 +1,7 @@ +### Changed + +- Reading a source and applying an operator that selects, renames, filters or tags rows + no longer builds the source-info text of every row and column. The text is built when + it is shown, stored or handed to a function, a part of the rows at a time, so these + steps take a few times the memory of their data instead of tens of times (ITL-1464). + Values, hashes and stored tables are unchanged. diff --git a/docs/dev/specs/itl-1464-tokens.md b/docs/dev/specs/itl-1464-tokens.md new file mode 100644 index 000000000..7473d3954 --- /dev/null +++ b/docs/dev/specs/itl-1464-tokens.md @@ -0,0 +1,111 @@ +# 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. + +## The cost + +A source row's token is `::::`, one per row and data +column: about 300 bytes each on the measured synthetic tables, 35 times the data +(`itl-1464-memory-diagnosis.md`). Everything in it is in the row's two system tags and +the column's name at the source. + +## The representation + +A `_source_x` column is **derived** while no one needs its text: a column of +`DerivedTokenType` (`src/orcapod/utils/source_tokens.py`), an internal Arrow extension +type. Its storage is a struct with no field, so a row has no byte, whatever the number of +rows. Its parameter is a recipe, `TokenRecipe(source_id, record_id, column)`: two +system-tag column names of the same table, and the column's name at the source. + +- `filter`, `take`, `slice`, `concat_tables`, `select` and `rename_columns` carry the + column with no special code, since it is one column like any other. The rows of the + table and their system tags move together, so the recipe stays right. +- Two columns have one Arrow type only with one recipe (`__eq__`), so Arrow itself refuses + to concatenate two that would read different columns. +- The system-tag names of a join change (`append_to_system_tags`): the recipes follow + there (`rename_read_columns`). The values of the system tags move between columns only + in `sort_system_tag_values` (inputs of one pipeline hash): the tokens that read them + become text first (`materialize_reading`). +- Text is made in one function, `materialize`, at most 65,536 rows at a time. + +A derived column is loud where it does not belong: reading a value, casting to text, +hashing, pickling and writing Parquet (so Delta) each raise. + +## Where a derived table can go + +`StreamProtocol.as_carried_table(columns=)` is the internal read: the table of `as_table` +with derived columns left as they are. Only library operators call it. The default is +`as_table` (text), so a user's operator, source or stream, and every job node today, is +given and gives text. `ArrowTableStream`, `DynamicPodStream`, and the sources over a held +or scanned table answer it without text. `as_table` with any columns, `iter_data`, `head`, +`run`, the data frame methods and the identity table give text, as before. A read without +the system tags gives text (the recipe would have nothing to read). + +## Producers of `_source_` columns + +| Producer | Form | +|---|---| +| `SourceStreamBuilder.attach_provenance` (every source's rows) | derived | +| `ArrowTableStream(source_info=...)` and a raw table's own `_source_` columns | as given (text) | +| `prepare_prefixed_columns` for a data column with no token | null text | +| `CachedSource`, `DerivedSource` over stored records | text, read from storage | +| `DerivedSource(tags_as_data=)` | derived (a new root, through the builder) | +| `PollingSource` | derived per batch; its combined stream is text (its batches are combined through `as_table`) | +| 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 | +| `Join`, `MergeJoin` merged or colliding columns | text | + +## Consumers + +| Consumer | What it needs | Step 1 | +|---|---|---| +| 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 | +| `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 | +| `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 `as_carried_table` | +| Function node pipeline table, result table, operator and source caches | stored text | unchanged: they read rows or `as_table` | +| Record-batch channels, streaming joins | types, values | unchanged (text) | +| Provenance trace (`pipeline/provenance.py`) | text | unchanged | +| Identity of a raw stream (`_identity_table`), record hashes | text | unchanged | + +## After each operator + +| Operator | Derivable after it? | +|---|---| +| filter, drop nulls, select, drop, rename, add tags, tag by | yes, all columns | +| 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) | +| 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. + +## Measured + +A synthetic time series table, about 2.2 million rows, 13 columns, about 250 MiB of Arrow data, read through +`SpiralDBTableSource` (`measure.py` of the diagnosis, one process per step). + +| Step | Peak RSS before | after | Arrow pool peak before | after | +|---|---|---|---|---| +| `as_table()`, `run()` | 10.8 GiB | 2.0 GiB | 9.3 GiB | 0.75 GiB | +| `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) | | | +| `group_by` | 20.9 GiB | 20.7 GiB (its lists are text) | 15.9 GiB | 15.9 GiB | diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b6b8bc0f6..2fc8678fd 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1271,6 +1271,12 @@ def run(self) -> StreamView: display_all_rows=False, ) + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The table of ``as_table(columns=columns)``; see ``StreamProtocol`` (ITL-1464).""" + return self.as_table(columns=columns) + def open_channel(self) -> RecordBatchInput: """Open an input channel on this node's rows, for async computation (ITL-1347). diff --git a/src/orcapod/core/operators/filters.py b/src/orcapod/core/operators/filters.py index 2a84592f5..491fa79b9 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -133,7 +133,10 @@ def _reads_only(self, columns: Collection[str]) -> bool: isinstance(predicate, pl.Expr) and not predicate.meta.has_multiple_outputs() and set(predicate.meta.root_names()) <= set(columns) - for predicate in self.predicates + for predicate in ( + *self.predicates, + *(v for v in self.constraints.values() if isinstance(v, pl.Expr)), + ) ) def validate_unary_input(self, stream: StreamProtocol) -> None: diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index c8f45d059..845a7d6a7 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -40,6 +40,7 @@ provisional_operator_name, warn_provisional_operator, ) +from orcapod.utils import source_tokens from orcapod.utils.provisional import note_provisional_use, provisional_class_name from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( @@ -579,6 +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. + continue values = table.column(index).to_pylist() kinds = {arrow_utils.source_info_arrow_type(value) for value in values} if len(kinds) != 1: diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 780e1c63a..100d67285 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -546,7 +546,8 @@ def as_carried_table( ``as_table``) gives that table. """ if type(self).as_table is RootSource.as_table and "as_table" not in vars(self): - return self._stream.as_carried_table(columns=columns) + stream: StreamBase = getattr(self, "_stream") # noqa: B009 # set by each subclass + return stream.as_carried_table(columns=columns) return super().as_carried_table(columns=columns) # ------------------------------------------------------------------------- diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 26fa6713d..833a17347 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -42,7 +42,7 @@ from orcapod.protocols.core_protocols.streams import RecordBatchInput from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Condition, Schema -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens if TYPE_CHECKING: from orcapod.types.explanation import Explanation @@ -340,7 +340,12 @@ def row_built_provenance(table: pa.Table) -> pa.Table: changed = False for field, column in zip(table.schema, table.columns, strict=True): if field.name.startswith(constants.SOURCE_PREFIX): - kind = _source_info_value_type(field.type) + # 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: column = column.cast(kind) new_field = pa.field(field.name, kind, nullable=field.nullable) diff --git a/src/orcapod/utils/source_tokens.py b/src/orcapod/utils/source_tokens.py index 9602c5b9f..0fd59bcfc 100644 --- a/src/orcapod/utils/source_tokens.py +++ b/src/orcapod/utils/source_tokens.py @@ -11,8 +11,8 @@ A derived column is an internal form of a table that operators pass on (``StreamProtocol.as_carried_table``). It never leaves the library: ``as_table``, rows, stored tables and everything hashed hold the text. A place that forgets fails loudly: no -value of a derived column can be read, cast to text, hashed, or written to Parquet (its -storage is a struct with no field, which Parquet refuses). +value of a derived column can be read, cast to text, hashed, pickled, or written to +Parquet (its storage is a struct with no field, which Parquet refuses). """ from __future__ import annotations @@ -20,7 +20,7 @@ import json from collections.abc import Collection, Mapping from dataclasses import dataclass -from typing import Any, NoReturn +from typing import Any, NoReturn, cast import pyarrow as pa import pyarrow.compute as pc @@ -71,11 +71,11 @@ def reads(self, columns: Collection[str]) -> bool: 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( + return pc.binary_join_element_wise( # pyright: ignore[reportCallIssue, reportUnknownVariableType] # the stubs leave out scalar arguments batch.column(self.source_id).cast(_TEXT), batch.column(self.record_id).cast(_TEXT), - pa.scalar(self.column, _TEXT), - pa.scalar(constants.BLOCK_SEPARATOR, _TEXT), + pa.scalar(self.column, _TEXT), # pyright: ignore[reportArgumentType] # as above + pa.scalar(constants.BLOCK_SEPARATOR, _TEXT), # pyright: ignore[reportArgumentType] # as above ) @@ -97,8 +97,9 @@ def as_py(self, *args: Any, **kwargs: Any) -> NoReturn: # pyright: ignore[repor class DerivedTokenType(pa.ExtensionType): """The Arrow type of a derived token column: no bytes, and the recipe. - Internal and never registered, so it is in no stored table and no schema Orcapod - presents or hashes. Two derived columns have one type only with one recipe. + Internal: in no stored table and no schema Orcapod presents or hashes. Not + registered with Arrow: a spilled table is written as its storage (no bytes) and + wrapped in its type again. Two derived columns have one type only with one recipe. """ def __init__(self, recipe: TokenRecipe) -> None: @@ -117,17 +118,29 @@ def __arrow_ext_deserialize__( def __arrow_ext_scalar_class__(self) -> type[pa.ExtensionScalar]: return _DerivedTokenScalar + def __reduce__(self) -> NoReturn: + """Refuse to be pickled: a table another process reads holds the text. + + Raises: + TypeError: Always. + """ + raise TypeError("a derived source-info token column is not pickled") + # pyarrow compares extension types by name and storage only; Arrow asks this. def __eq__(self, other: object) -> bool: return isinstance(other, DerivedTokenType) and self.recipe == other.recipe + def __ne__(self, other: object) -> bool: + return not self == other + def __hash__(self) -> int: return hash(self.recipe) def derived_array(recipe: TokenRecipe, rows: int) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array """A derived token column of ``rows`` rows: no row has a byte.""" - storage = pa.Array.from_buffers(pa.struct([]), rows, [None], 0, 0) + # 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) @@ -219,16 +232,3 @@ def rename_read_columns(table: pa.Table, names: Mapping[str, str]) -> pa.Table: derived_array(renamed, table.num_rows), ) return table - - -def text_schema(schema: pa.Schema) -> pa.Schema: - """``schema`` with each derived token column as the text it stands for.""" - if not derived_columns(schema): - return schema - return pa.schema( - [ - field.with_type(_TEXT) if derived_recipe(field.type) else field - for field in schema - ], - metadata=schema.metadata, - ) diff --git a/tests/test_core/streams/test_source_tokens.py b/tests/test_core/streams/test_source_tokens.py new file mode 100644 index 000000000..40eb740ea --- /dev/null +++ b/tests/test_core/streams/test_source_tokens.py @@ -0,0 +1,449 @@ +"""Source-info tokens carried as a recipe until their text is needed (ITL-1464). + +The oracle is the same operation with every source's tokens built as text at once, as +sources did before: values, types, nullability, row order and hashes are equal, and no +derived column reaches a user, a user's operator, a stored table, a hash or a pickle. +""" + +from __future__ import annotations + +import pickle +from collections.abc import Callable +from typing import Any + +import polars as pl +import pyarrow as pa +import pyarrow.compute as pc +import pyarrow.parquet as pq +import pytest + +from orcapod import contexts +from orcapod.core.data_tags import stream_data_tags +from orcapod.core.operators.base import UnaryOperator +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 +from orcapod.databases import InMemoryArrowDatabase +from orcapod.operators import ( + AddTags, + DropColumns, + DropNulls, + DropTagColumns, + MapColumns, + MapData, + MapTags, + PolarsFilter, + SelectDataColumns, + TagBy, +) +from orcapod.sources import ArrowTableSource, CachedSource +from orcapod.system_constants import constants +from orcapod.utils import arrow_utils, source_tokens +from tests.test_core.operators.test_async_sync_equivalence import ( + AFTER_OPERATOR_CASES, + CASES, + Case, +) +from tests.test_core.operators.test_row_built_form import assert_same_values + +CARRIED = {"source": True, "system_tags": True, "context": True} + + +@pytest.fixture +def text_sources(monkeypatch: pytest.MonkeyPatch) -> Callable[[], None]: + """Make every source built from now on hold its tokens as text.""" + add = arrow_utils.add_system_tag_columns + + def switch() -> None: + monkeypatch.setattr( + arrow_utils, + "add_system_tag_columns", + lambda *args: source_tokens.materialize(add(*args)), + ) + + return switch + + +def _table() -> pa.Table: + """Chunked, two tags (one a data-tag), two data columns, nulls.""" + whole = pa.table( + { + "k": pa.array(range(10), pa.int32()), + "j": pa.array([f"j{i % 3}" for i in range(10)]), + "x": pa.array([None if i % 4 == 0 else float(i) for i in range(10)]), + "y": pa.array([f"y{i}" for i in range(10)]), + } + ) + return pa.concat_tables([whole.slice(0, 3), whole.slice(3, 4), whole.slice(7)]) + + +def _source(**kwargs: Any) -> ArrowTableSource: + return ArrowTableSource( + _table(), + tag_columns=["k", "j"], + tag_only_columns=["j"], + record_id_columns=["k"], + **kwargs, + ) + + +def _plain_source() -> ArrowTableSource: + return ArrowTableSource( + _table(), tag_columns=["k", "j"], tag_only_columns=True, record_id_columns=["k"] + ) + + +def _derived(table: pa.Table) -> tuple[str, ...]: + return source_tokens.derived_columns(table.schema) + + +ROW_WISE: dict[str, Callable[[], Any]] = { + "drop_nulls": lambda: DropNulls(["x"])(_source()), + "drop_nulls_all": lambda: DropNulls()(_source()), + "polars_filter": lambda: PolarsFilter([pl.col("x") > 2, pl.col("j") == "j1"])( + _source() + ), + "polars_constraint": lambda: PolarsFilter([], {"j": "j1", "y": "y4"})(_source()), + "filter": lambda: _source().filter({"j": "j1", "y": "y4"}), + "map_data": lambda: MapData({"x": "y", "y": "x"})(_source()), + "map_data_tag": lambda: MapData({"k": "kk", "x": "z"})(_source()), + "map_tags": lambda: MapTags({"k": "kk", "j": "jj"})(_source()), + "map_tags_only": lambda: MapTags({"k": "kk", "j": "jj"}, tag_only=True)(_source()), + "map_columns": lambda: MapColumns({"j": "jj", "x": "z", "k": "kk"})( + _plain_source() + ), + "select_data": lambda: SelectDataColumns(["y"])(_source()), + "drop_tags": lambda: DropTagColumns(["k"])(_source()), + "drop_columns": lambda: DropColumns(["k", "x"])(_source()), + "add_tags": lambda: AddTags({"b": 1, "a": "q"})(_source()), + "tag_by": lambda: TagBy(["x"])(DropNulls(["x"])(_plain_source())), + "chain": lambda: ( + _source() + .drop_nulls(["x"]) + .map_data({"x": "y", "y": "x"}) + .polars_filter(pl.col("y") > 2) + .add_tags(c=1) + ), +} + + +@pytest.mark.parametrize("name", ROW_WISE) +def test_a_row_wise_operator_carries_the_tokens_and_gives_the_same_rows( + name: str, text_sources: Callable[[], None] +) -> None: + result = ROW_WISE[name]() + carried = result.as_carried_table(columns=CARRIED) + tokens = [c for c in carried.column_names if c.startswith(constants.SOURCE_PREFIX)] + assert tokens and set(_derived(carried)) == set(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] + digest = result.content_hash() + text_sources() + oracle = ROW_WISE[name]() + expected = oracle.as_table(all_info=True) + assert not _derived(oracle.as_carried_table(columns=CARRIED)) + 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 + ] + assert digest == oracle.content_hash() + + +@pytest.mark.parametrize( + "case", [*[pytest.param(c, id=c.label) for c in CASES], *AFTER_OPERATOR_CASES] +) +def test_every_operator_gives_what_text_sources_give( + case: Case, text_sources: Callable[[], None] +) -> None: + """Every operator of the equivalence corpus: the whole table, its carried form, and + F (the table a job node hands on) of the carried form.""" + result = case.make_op()(*case.make_sources()) + table = result.as_table(all_info=True) + carried = result.as_carried_table(columns=ZERO_ROW_INPUT_COLUMNS) + plain = result.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + built = source_tokens.materialize(carried) + assert built.schema.equals(plain.schema, check_metadata=True) + assert_same_values(built, plain) + if plain.num_rows: + formed = StaticOutputOperatorPod._row_built_form(carried, result.keys()) + from_text = StaticOutputOperatorPod._row_built_form(plain, result.keys()) + assert _derived(formed) or not _derived(carried) + formed = source_tokens.materialize(formed) + assert formed.schema.equals(from_text.schema, check_metadata=True) + assert_same_values(formed, from_text) + text_sources() + expected = case.make_op()(*case.make_sources()).as_table(all_info=True) + assert table.schema.equals(expected.schema, check_metadata=True) + assert_same_values(table, expected) + + +def _column_configs() -> list[dict[str, bool]]: + groups = ("source", "system_tags", "context", "content_hash", "sort_by_tags") + return [ + {g: bool(bits >> i & 1) for i, g in enumerate(groups)} + for bits in range(2 ** len(groups)) + ] + + +@pytest.mark.parametrize("make", [_source, ROW_WISE["chain"]], ids=["source", "chain"]) +def test_no_public_read_gives_a_derived_column(make: Callable[[], Any]) -> None: + stream = make() + tables: list[pa.Table] = [stream.as_table(columns=c) for c in _column_configs()] + tables += [stream.head(3, columns=c).table for c in _column_configs()] + tables += [stream.as_table(all_info=True), stream.head(3, all_info=True).table] + tables += [stream.run().table] + for tag, data in stream.flow(): + tables += [tag.as_table(all_info=True), data.as_table(all_info=True)] + assert all(isinstance(t, str) for t in data.source_info().values()) + tables.append(stream.as_polars_df(columns=CARRIED).to_arrow()) + tables.append(pa.Table.from_pandas(stream.as_pandas_df(columns=CARRIED))) + assert not stream.as_lazy_frame(columns=CARRIED).collect().is_empty() + for table in tables: + assert not _derived(table) + assert pa.struct([]) not in table.schema.types + _ = table.to_pylist() + for schema in (stream.arrow_schema(), *stream.output_schema(all_info=True)): + assert "derived" not in str(schema) + assert "derived_token" not in stream.run()._repr_html_() + repr(stream.run()) + + +def test_a_table_without_its_system_tags_holds_text() -> None: + """The recipe reads the system tags, so a table without them is never carried.""" + for config in ({"source": True}, {"source": True, "context": True}): + table = _source().as_carried_table(columns=config) + assert not _derived(table) + assert table.column("_source_x").type == pa.large_string() + + +class _ReadsEverything(UnaryOperator): + """A user's operator: reads every column of its input table.""" + + DATA_TAGS_ISSUE = None + seen: list[pa.Table] = [] + + def validate_unary_input(self, stream: Any) -> None: + pass + + def unary_output_schema(self, stream: Any, **kwargs: Any) -> Any: + return stream.output_schema(**kwargs) + + def identity_structure(self) -> Any: + return "ReadsEverything" + + def unary_static_process(self, stream: Any) -> Any: + table = stream.as_table(columns={"source": True, "system_tags": True}) + self.seen.append(table) + assert all(len(v) == len(table) for v in table.to_pydict().values()) + return ArrowTableStream( + table, tag_columns=stream.keys()[0], data_tags=stream_data_tags(stream) + ) + + +def test_a_users_operator_reads_text() -> None: + _ReadsEverything.seen = [] + result = _ReadsEverything()(_source()) + after = result.drop_nulls(["x"]) + table = after.as_table(columns=CARRIED) + (seen,) = _ReadsEverything.seen + assert not _derived(seen) + assert str(seen.column("_source_x")[1]).endswith('::{"k":1}::x') + assert table.column("_source_x").to_pylist() == [ + t for i, t in enumerate(seen.column("_source_x").to_pylist()) if i % 4 + ] + + +@pytest.mark.parametrize( + "predicate", + [ + pl.col("_source_x").str.ends_with("::x"), + pl.any_horizontal(pl.all().is_not_null()), + pl.any_horizontal(pl.col("^_source_.*$").str.contains("::")), + pl.concat_str(["_source_x", "_source_y"]).str.contains("::x"), + "x_is_big", + [True] * 5 + [False] * 5, + ], + ids=["named", "all", "regex", "concat", "name", "mask"], +) +def test_a_predicate_that_may_read_tokens_reads_text( + predicate: Any, text_sources: Callable[[], None] +) -> None: + def make() -> Any: + table = _table().append_column("x_is_big", pa.array([True, False] * 5)) + return PolarsFilter([predicate])(ArrowTableSource(table, tag_columns=["k"])) + + table = make().as_table(all_info=True) + text_sources() + expected = make().as_table(all_info=True) + assert table.num_rows > 0 + assert table.equals(expected) + + +def test_an_unknown_column_is_reported_as_with_text( + text_sources: Callable[[], None], +) -> None: + def message() -> str: + with pytest.raises(pl.exceptions.ColumnNotFoundError) as error: + _ = PolarsFilter([pl.col("nope") > 1])(_source()).as_table() + return str(error.value) + + got = message() + text_sources() + assert got == message() + + +def test_a_constraint_expression_may_read_tokens() -> None: + """``filter(x=)``: the value is looked into as a predicate is.""" + kept = PolarsFilter([], {"y": pl.col("_source_y").str.slice(0, 2)})(_source()) + assert kept.as_table().num_rows == 0 + + +def test_stored_rows_hold_text(text_sources: Callable[[], None]) -> None: + """A cached source stores every column, tokens and record hashes included.""" + + def stored() -> pa.Table: + database = InMemoryArrowDatabase() + cached = CachedSource(_source(), cache_database=database) + _ = cached.as_table() + table = cached.get_all_records() + assert table is not None + return table.drop_columns( + [c for c in table.column_names if "time" in c or c.endswith("_ts")] + ) + + table = stored() + assert not _derived(table) + text_sources() + expected = stored() + assert table.schema.equals(expected.schema, check_metadata=True) + assert table.equals(expected) + + +def test_a_derived_column_that_leaks_is_an_error() -> None: + carried = _source().as_carried_table(columns=CARRIED) + tokens = carried.column("_source_x") + with pytest.raises(TypeError, match="no value"): + _ = tokens.to_pylist() + with pytest.raises(pa.ArrowNotImplementedError): + _ = tokens.cast(pa.large_string()) + with pytest.raises(TypeError, match="not pickled"): + _ = pickle.dumps(carried) + with pytest.raises(pa.ArrowNotImplementedError): + pq.write_table(carried, pa.BufferOutputStream()) + with pytest.raises(Exception, match="no value|derived"): + _ = contexts.get_default_context().arrow_hasher.hash_table(carried) + + +def test_a_spilled_table_keeps_its_recipes() -> None: + """As the row spool writes it: an extension column's storage, wrapped when read.""" + carried: Any = _source().as_carried_table(columns=CARRIED).combine_chunks() + arrow: Any = pa + batch: Any = carried.to_batches()[0] + storage = arrow.RecordBatch.from_arrays( + [getattr(c, "storage", c) for c in batch.columns], names=batch.schema.names + ) + sink = pa.BufferOutputStream() + with pa.ipc.new_file(sink, storage.schema) as writer: + writer.write_batch(storage) + read = pa.ipc.open_file(sink.getvalue()).get_batch(0) + wrapped = arrow.Table.from_arrays( + [ + arrow.ExtensionArray.from_storage(f.type, c) + if isinstance(f.type, pa.BaseExtensionType) + else c + for f, c in zip(carried.schema, read.columns, strict=True) + ], + schema=carried.schema, + ) + order = pa.array([7, 2, 2, 9]) + assert _derived(wrapped) == _derived(carried) + assert source_tokens.materialize(wrapped.take(order)).equals( + source_tokens.materialize(carried).take(order) + ) + + +def test_a_carried_column_has_no_bytes_and_is_not_null() -> None: + carried = _source().as_carried_table(columns=CARRIED) + taken = carried.take(pa.array([1, 5])).filter(pc.field("k") > 1) + for table in (carried, taken, pa.concat_tables([carried, taken]).combine_chunks()): + for name in _derived(table): + assert table.column(name).nbytes == 0 + assert table.column(name).null_count == 0 + assert not table.schema.field(name).nullable + + +def test_recipes_tell_types_apart() -> None: + one, two = ( + source_tokens.derived_array(source_tokens.TokenRecipe("s", "r", c), 2) + for c in ("a", "b") + ) + assert one.type != two.type + assert pa.schema([("c", one.type)]) != pa.schema([("c", two.type)]) + with pytest.raises(pa.ArrowInvalid): + _ = pa.concat_tables([pa.table({"c": one}), pa.table({"c": two})]) + + +def test_extended_system_tag_names_are_followed_and_sorting_builds_the_text() -> None: + """A join's system-tag rename keeps the tokens derived; sorting the values of two + inputs with one pipeline hash builds them first, so each names its own row.""" + left, right = ( + _source(source_id=name).map_data( + {"x": f"x{name}", "y": f"y{name}", "k": f"k{name}"} + ) + for name in ("b", "a") + ) + tables = [ + arrow_utils.append_to_system_tags( + s.as_carried_table(columns={"source": True, "system_tags": True}), f"h:{i}" + ) + for i, s in enumerate((left, right)) + ] + plain = [source_tokens.materialize(t) for t in tables] + assert plain[0].column("_source_xb")[1].as_py().startswith("arrow_table_v1:b::") + joined = arrow_utils.hstack_tables(tables[0], tables[1].drop_columns(["k", "j"])) + assert _derived(joined) + done = arrow_utils.sort_system_tag_values(joined) + assert not _derived(done) + for table in plain: + for name in table.column_names: + if name.startswith(constants.SOURCE_PREFIX): + assert done.column(name).equals(table.column(name)) + + +def test_rows_are_built_a_part_at_a_time(monkeypatch: pytest.MonkeyPatch) -> None: + """Iteration builds text per part of the rows, whatever their chunks.""" + from orcapod.core.streams import arrow_table_stream + + expected = _source().as_table(columns=CARRIED) + sizes: list[int] = [] + build = source_tokens.materialize + + def record(table: pa.Table, names: Any = None) -> pa.Table: + sizes.append(table.num_rows) + return build(table, names) + + monkeypatch.setattr(arrow_table_stream, "ROWS_PER_PART", 4) + monkeypatch.setattr(source_tokens, "materialize", record) + rows = list(_source()) + assert sizes == [4, 4, 2] + assert [d.source_info()["x"] for _, d in rows] == expected.column( + "_source_x" + ).to_pylist() + + +def test_no_rows_hold_text_types() -> None: + table = _source().polars_filter(pl.col("k") > 100).as_table(all_info=True) + assert table.num_rows == 0 + assert table.schema.field("_source_x").type == pa.large_string() + assert table.schema.equals(_source().as_table(all_info=True).schema) + + +def test_a_source_with_its_own_read_gives_its_own_table() -> None: + """A subclass, or an object, with its own ``as_table`` is read through it.""" + + class Own(ArrowTableSource): + def as_table(self, **kwargs: Any) -> pa.Table: + return super().as_table(**kwargs).slice(0, 2) + + own = Own(_table(), tag_columns=["k"]) + assert own.drop_columns(["x"]).as_table().num_rows == 2 From 35fe2572918ba2cae3edb21c7c951edf4b7e65cc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:41:15 -0800 Subject: [PATCH 08/26] fix(core): row spool survives forks and failed spills; whole tables and slices without copying (ITL-1464) A forked child neither waits for a lock of its parent's threads nor touches its parent's files; a failed spill leaves the spool as it was; an unlocked or partly removed directory is swept. table() and slice() give rows through their mappings and outlive the spool. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/row_spool.py | 205 ++++++++++++++++++---- tests/test_core/test_row_spool.py | 283 +++++++++++++++++++++++++++++- 2 files changed, 448 insertions(+), 40 deletions(-) diff --git a/src/orcapod/core/row_spool.py b/src/orcapod/core/row_spool.py index e56b5c8d7..2ac0de2e2 100644 --- a/src/orcapod/core/row_spool.py +++ b/src/orcapod/core/row_spool.py @@ -15,13 +15,24 @@ of its own, removed at interpreter exit. A killed process leaves its directory behind; the next process to spill there removes it: every directory holds a lock file its process keeps locked, so a directory whose lock is free has no owner. (Without ``fcntl``, as on -Windows, nothing is swept.) A spool is not a store: nothing in it outlives the run, is +Windows, nothing is swept.) + +Ownership: a spool belongs to one thread (or one event loop) of the process that made it: +it has no lock of its own, and a forked child's copy refuses every use, so a child never +touches its parent's files. Different spools may be used from different threads. + +Rows: tables of one schema with at least one column, in Orcapod's normalized types (large +variants, no views). The byte limit bounds what the spool keeps; a ``take`` holds the rows +asked for, twice while it puts them in order, so a caller bounds what it asks for. + +A spool is not a store: nothing in it outlives the run, is found by a later process as rows, or enters a hash. """ from __future__ import annotations import atexit +import contextlib import os import shutil import tempfile @@ -50,28 +61,39 @@ class _ProcessDirectories: def __init__(self) -> None: self._guard = threading.Lock() - self._pid: int = os.getpid() self._held: dict[str, tuple[str, IO[str]]] = {} + self.root_lock: IO[str] | None = None + """The root's lock file while a directory is made.""" def get(self, root: str) -> str: """This process's directory under ``root``.""" with self._guard: - if self._pid != os.getpid(): - # A forked child: the directories held are its parent's. - self._pid, self._held = os.getpid(), {} if root not in self._held or not os.path.isdir(self._held[root][0]): self._held[root] = _make_process_directory(root) return self._held[root][0] def remove(self) -> None: """Remove this process's directories (at exit).""" - if self._pid != os.getpid(): - return # a forked child holds none of its own for directory, lock in self._held.values(): - shutil.rmtree(directory, ignore_errors=True) + _remove_process_directory(directory) lock.close() self._held = {} + def after_fork_in_child(self) -> None: + """Start empty: the directories are the parent's, and so are the locks. + + The guard may be held by a thread that does not exist in the child. The lock + files are closed, never unlocked: the parent's open files keep them locked, and + the child keeps none of them locked after the parent is gone. + """ + self._guard = threading.Lock() + inherited = [lock for _, lock in self._held.values()] + if self.root_lock is not None: + inherited.append(self.root_lock) + self._held, self.root_lock = {}, None + for lock in inherited: + lock.close() + def _make_process_directory(root: str) -> tuple[str, IO[str]]: """Make this process's directory under ``root``, locked, and sweep abandoned ones. @@ -86,14 +108,31 @@ def _make_process_directory(root: str) -> tuple[str, IO[str]]: name = os.path.join(root, f".{_PREFIX}{os.getuid()}.lock") flags = os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC with os.fdopen(os.open(name, flags, 0o600), "w") as root_lock: - fcntl.flock(root_lock, fcntl.LOCK_EX) - _sweep(root) - directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) - lock = open(os.path.join(directory, _LOCK_NAME), "w") - fcntl.flock(lock, fcntl.LOCK_EX) + _directories.root_lock = root_lock + try: + fcntl.flock(root_lock, fcntl.LOCK_EX) + _sweep(root) + directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) + lock = open(os.path.join(directory, _LOCK_NAME), "w") + fcntl.flock(lock, fcntl.LOCK_EX) + finally: + _directories.root_lock = None return directory, lock +def _remove_process_directory(directory: str) -> None: + """Remove a process's directory, its lock file last. + + Stopped part way, it leaves a directory a later sweep still recognizes. + """ + with contextlib.suppress(OSError): + for name in os.listdir(directory): + if name != _LOCK_NAME: + shutil.rmtree(os.path.join(directory, name), ignore_errors=True) + os.unlink(os.path.join(directory, _LOCK_NAME)) + os.rmdir(directory) + + def _sweep(root: str) -> None: """Remove this user's spool directories under ``root`` that no process holds.""" assert fcntl is not None @@ -104,18 +143,24 @@ def _sweep(root: str) -> None: if entry.name.startswith(_PREFIX) and entry.is_dir(follow_symlinks=False) ] for directory in candidates: - try: + # A directory held by a live process, being removed, or not a spool's is left. + with contextlib.suppress(OSError): if os.stat(directory).st_uid != os.getuid(): continue - with open(os.path.join(directory, _LOCK_NAME)) as lock: - fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) - shutil.rmtree(directory, ignore_errors=True) - except OSError: - continue # held by a live process, being removed, or not a spool's + try: + with open(os.path.join(directory, _LOCK_NAME)) as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + _remove_process_directory(directory) + except FileNotFoundError: + # Its process was killed before it made the lock file (the root's lock + # is held here, so none is being made): then it is empty. + os.rmdir(directory) _directories = _ProcessDirectories() _ = atexit.register(_directories.remove) +if hasattr(os, "register_at_fork"): + os.register_at_fork(after_in_child=_directories.after_fork_in_child) def _remove_directory(directory: str, owner: int) -> None: @@ -158,10 +203,12 @@ def __init__( self._memory_bytes: int = memory_bytes self._root: str | None = root self._closed: bool = False + self._owner: int = os.getpid() self._schema: pa.Schema | None = None self._segments: list[_Segment] = [] self._starts: npt.NDArray[np.int64] | None = None self._in_memory: int = 0 + self._discarded: bool = False self._directory: str | None = None self._cleanup: weakref.finalize[..., Any] | None = None # pyright: ignore[reportExplicitAny] # any finalizer self.size: int = 0 @@ -180,19 +227,41 @@ def append(self, table: pa.Table) -> None: Raises: ValueError: If the spool is closed. - OSError: If the rows in memory cannot be written to the local disk. + RuntimeError: In a process other than the one that made the spool. + OSError: If the rows in memory cannot be written to the local disk. The + spool is then as before the call, with no partial file. """ - if self._closed: - raise ValueError("the row spool is closed") + self._require_usable() if not table.num_rows: return + schema, size = self._schema, self.size if self._schema is None: self._schema = table.schema # One chunk that owns its rows: a slice would keep its whole parent alive. - self._add(_Segment(self.size, _owned(table))) + added = _Segment(self.size, _owned(table)) + self._add(added) self.size += table.num_rows if self._in_memory > self._memory_bytes: - self._spill() + try: + self._spill() + except BaseException: + # The new rows are in the last run, so they were not written. + self._segments.remove(added) + self._starts = None + if added.table is not None: + self._in_memory -= added.table.nbytes + self._schema, self.size = schema, size + raise + + def _require_usable(self) -> None: + """Refuse a closed spool, and a forked child's copy of its parent's.""" + if self._owner != os.getpid(): + raise RuntimeError( + "a row spool is used only in the process that made it: this is a " + + "forked child's copy" + ) + if self._closed: + raise ValueError("the row spool is closed") def _add(self, segment: _Segment) -> None: self._segments.append(segment) @@ -207,7 +276,12 @@ def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: Args: rows: Row numbers, at least one, none of them discarded. + + Raises: + ValueError: If the spool is closed. + RuntimeError: In a process other than the one that made the spool. """ + self._require_usable() if self._starts is None: self._starts = np.fromiter( (s.start for s in self._segments), np.int64, len(self._segments) @@ -234,9 +308,67 @@ def _take_from(self, segment: _Segment, local: pa.Array[Any]) -> pa.Table: # py if segment.table is not None: return segment.table.take(local) assert segment.path is not None and self._schema is not None + return _wrapped(self._stored(segment).take(local), self._schema) + + @staticmethod + def _stored(segment: _Segment) -> pa.Table: + """A segment's file as a table over its mapping, extension columns as storage. + + The mapping lives as long as a buffer of the table, also after the file is + deleted (POSIX). + """ + assert segment.path is not None with pa.memory_map(segment.path) as mapped: - stored = pa.ipc.open_file(mapped).read_all() - return _wrapped(stored.take(local), self._schema) + return pa.ipc.open_file(mapped).read_all() + + def table(self) -> pa.Table: + """Every row appended, in order, without copying it into memory. + + Rows in files are read through their mappings: a page is read when a value on it + is. The table stays valid after ``close`` and after the spool is gone: the rows' + memory or mapping lives until the table does (on POSIX, where a deleted file + stays mapped). + + Raises: + ValueError: If the spool is closed, a row was discarded, or nothing was ever + appended (the columns are then unknown). + RuntimeError: In a process other than the one that made the spool. + """ + return self.slice(0, self.size) + + def slice(self, start: int, length: int) -> pa.Table: + """``length`` rows from row number ``start`` on, fewer at the end. + + As ``table``: nothing is copied, and the result outlives the spool. + + Args: + start: The first row's number. + length: How many rows. + + Raises: + ValueError: As ``table``; also for a negative ``start`` or ``length``. + RuntimeError: In a process other than the one that made the spool. + """ + self._require_usable() + if start < 0 or length < 0: + raise ValueError(f"a slice of rows from {start}, {length} long") + if self._schema is None: + raise ValueError("nothing was appended to the row spool: no columns yet") + if self._discarded: + raise ValueError("rows of the row spool were discarded: no whole table") + end = min(start + length, self.size) + parts: list[pa.Table] = [] + for segment in self._segments: + first = max(start, segment.start) + last = min(end, segment.start + segment.rows) + if first >= last: + continue + if segment.table is not None: + part = segment.table + else: + part = _wrapped(self._stored(segment), self._schema) + parts.append(part.slice(first - segment.start, last - first)) + return pa.concat_tables(parts) if parts else self._schema.empty_table() def discard(self, rows: npt.NDArray[np.int64]) -> None: """Say that these rows are never fetched again. @@ -245,7 +377,12 @@ def discard(self, rows: npt.NDArray[np.int64]) -> None: Args: rows: Row numbers, each discarded once only. + + Raises: + ValueError: If the spool is closed. + RuntimeError: In a process other than the one that made the spool. """ + self._require_usable() if not len(rows): return starts = np.fromiter( @@ -253,6 +390,7 @@ def discard(self, rows: npt.NDArray[np.int64]) -> None: ) held_in = np.searchsorted(starts, rows, side="right") - 1 counts = np.bincount(held_in, minlength=len(self._segments)) + self._discarded = True emptied = False for index in np.flatnonzero(counts): segment = self._segments[int(index)] @@ -302,11 +440,16 @@ def _write(self, segment: _Segment) -> str: ) path = os.path.join(self._directory, f"{segment.start}.arrow") table = _as_storage(segment.table) - with ( - pa.OSFile(path, "wb") as sink, - pa.ipc.new_file(sink, table.schema) as writer, - ): - writer.write_table(table) + try: + with ( + pa.OSFile(path, "wb") as sink, + pa.ipc.new_file(sink, table.schema) as writer, + ): + writer.write_table(table) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(path) + raise return path def close(self) -> None: diff --git a/tests/test_core/test_row_spool.py b/tests/test_core/test_row_spool.py index 848fcb94a..6b7faa775 100644 --- a/tests/test_core/test_row_spool.py +++ b/tests/test_core/test_row_spool.py @@ -3,18 +3,20 @@ from __future__ import annotations import asyncio +import errno import gc import os +import signal import subprocess import sys from datetime import datetime, timezone from pathlib import Path +from typing import Any import numpy as np import pyarrow as pa import pytest -from orcapod.core import row_spool from orcapod.core.row_spool import RowSpool @@ -124,6 +126,66 @@ def test_rows_spilled_after_a_segment_between_them_was_freed(tmp_path: Path) -> spool.close() +@pytest.mark.parametrize("memory_bytes", [0, 3_000, 10**9]) +def test_the_whole_table_and_slices_of_it(tmp_path: Path, memory_bytes: int) -> None: + spool, rows = _filled(tmp_path, [1, 50, 7, 120, 3], memory_bytes) + assert spool.table().equals(rows, check_metadata=True) + for start, length in ((0, 1), (1, 50), (40, 100), (170, 50), (181, 1), (500, 2)): + part = spool.slice(start, length) + assert part.schema.equals(rows.schema, check_metadata=True) + assert part.equals(rows.slice(start, length)) + with pytest.raises(ValueError, match="slice"): + _ = spool.slice(-1, 2) + with pytest.raises(ValueError, match="slice"): + _ = spool.slice(1, -2) + spool.discard(np.array([3])) + with pytest.raises(ValueError, match="discarded"): + _ = spool.table() + spool.close() + with pytest.raises(ValueError, match="closed"): + _ = spool.table() + + +def test_a_spool_nothing_was_appended_to_has_no_table(tmp_path: Path) -> None: + spool = RowSpool(0, str(tmp_path)) + with pytest.raises(ValueError, match="nothing was appended"): + _ = spool.table() + spool.append(_table(0, 2)) + assert spool.slice(0, 0).equals(_table(0, 0)) + + +def test_the_table_is_mapped_and_not_copied(tmp_path: Path) -> None: + spool = RowSpool(0, str(tmp_path)) + for start in range(0, 40_000, 10_000): + spool.append(_table(start, 10_000)) + before = pa.total_allocated_bytes() + table = spool.table() + size = table.nbytes + assert size > 1_000_000 + assert pa.total_allocated_bytes() - before < size / 100 + spool.close() + + +@pytest.mark.skipif(sys.platform == "win32", reason="a mapped file cannot be deleted") +@pytest.mark.parametrize("memory_bytes", [0, 3_000, 10**9]) +@pytest.mark.parametrize("end", ["close", "collect"]) +def test_a_table_outlives_its_spool( + tmp_path: Path, memory_bytes: int, end: str +) -> None: + spool, rows = _filled(tmp_path, [40, 5_000, 40], memory_bytes) + table, part = spool.table(), spool.slice(30, 100) + if end == "close": + spool.close() + del spool + gc.collect() + assert _files(tmp_path) == [] + assert table.equals(rows, check_metadata=True) + table.validate(full=True) + del table + gc.collect() + assert part.equals(rows.slice(30, 100)) + + def test_nothing_is_written_below_the_limit(tmp_path: Path) -> None: spool, _ = _filled(tmp_path, [10, 10], 10**9) assert list(tmp_path.iterdir()) == [] @@ -219,6 +281,7 @@ def test_a_killed_process_is_swept_and_a_live_one_is_not(tmp_path: Path) -> None (held,) = tmp_path.glob("orcapod-spool-*") other = tmp_path / "orcapod-spool-not-ours" # no lock file: left alone other.mkdir() + (other / "file").touch() spool, _ = _filled(tmp_path, [10], 0) assert held.exists() and _files(held) assert other.exists() @@ -228,11 +291,213 @@ def test_a_killed_process_is_swept_and_a_live_one_is_not(tmp_path: Path) -> None assert not held.exists() -def test_a_forked_child_never_removes_its_parents_files(tmp_path: Path) -> None: - # A child inherits its parent's finalizers; the owner check is what stops them. - directory = tmp_path / "spool" - directory.mkdir() - row_spool._remove_directory(str(directory), os.getpid() + 1) # pyright: ignore[reportPrivateUsage] # the owner check itself - assert directory.exists() - row_spool._remove_directory(str(directory), os.getpid()) # pyright: ignore[reportPrivateUsage] # the owner check itself - assert not directory.exists() +_FORK = """ +import os, sys, signal, threading +import numpy as np, pyarrow as pa +from orcapod.core import row_spool +from orcapod.core.row_spool import RowSpool +case, root = sys.argv[1:] +table = pa.table({"x": [1, 2], "y": [3, 4]}) + +def in_child(function): + child = os.fork() + if child == 0: + signal.alarm(10) + try: + function() + except BaseException as error: + print(repr(error), file=sys.stderr, flush=True) + os._exit(1) + os._exit(0) + assert os.waitstatus_to_exitcode(os.waitpid(child, 0)[1]) == 0 + +if case == "guard_held": + # Another thread makes a directory while this one forks. + entered, release = threading.Event(), threading.Event() + def hold(): + with row_spool._directories._guard: + entered.set() + release.wait() + thread = threading.Thread(target=hold, daemon=True) + thread.start() + assert entered.wait(10) + def spill(): + with RowSpool(0, root) as spool: + spool.append(table) + assert spool.take(np.array([1])).equals(table.slice(1, 1)) + try: + in_child(spill) + finally: + release.set() + thread.join() +elif case == "inherited": + spool = RowSpool(0, root) + spool.append(table) + def use(): + for call in ( + lambda: spool.discard(np.array([0, 1])), + lambda: spool.take(np.array([0])), + lambda: spool.append(table), + ): + try: + call() + except RuntimeError as error: + assert "the process that made it" in str(error) + else: + raise AssertionError("a child used its parent's spool") + spool.close() + row_spool._directories.remove() + with RowSpool(0, root) as own: # sweeps, and leaves the parent's + own.append(table) + in_child(use) + assert spool.take(np.array([1, 0])).equals(table.take(pa.array([1, 0]))) + spool.close() +elif case == "outlived": + # A child that outlives its parent does not keep the parent's directory locked. + spool = RowSpool(0, root) + spool.append(table) + ready, wait = os.pipe() + child = os.fork() + if child == 0: + os.close(0) + os.write(wait, b"x") + os.close(1) + os.close(2) + signal.alarm(120) # never left behind + signal.pause() + os.read(ready, 1) + print(child, flush=True) + os.kill(os.getpid(), signal.SIGKILL) +""" + + +def _fork(case: str, root: Path) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-c", _FORK, case, str(root)], + capture_output=True, + text=True, + timeout=60, + check=False, + ) + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs fork") +@pytest.mark.parametrize("case", ["guard_held", "inherited"]) +def test_a_forked_child_neither_waits_for_nor_touches_its_parents_spools( + tmp_path: Path, case: str +) -> None: + done = _fork(case, tmp_path) + assert done.returncode == 0, done.stderr + # The child ended without its exit handlers (``os._exit``): its own directory is + # left, with no owner, for the next process to sweep. + (left,) = tmp_path.glob("orcapod-spool-*") + spool, _ = _filled(tmp_path, [10], 0) + assert not left.exists() + spool.close() + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs fork") +def test_a_child_that_outlives_its_killed_parent_does_not_stop_the_sweep( + tmp_path: Path, +) -> None: + done = _fork("outlived", tmp_path) + (left,) = tmp_path.glob("orcapod-spool-*") + child = int(done.stdout) + try: + spool, _ = _filled(tmp_path, [10], 0) + assert not left.exists() + spool.close() + finally: + os.kill(child, signal.SIGKILL) + + +@pytest.mark.parametrize("stage", ["write", "close"]) +def test_a_failed_spill_leaves_the_spool_as_it_was( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, stage: str +) -> None: + spool, rows = _filled(tmp_path, [40, 10], 1 << 14) + held, size = spool.memory_bytes, spool.size + assert held and _files(tmp_path) == [] + + class Full: + """A file writer that writes some bytes, then finds the disk full.""" + + def __init__(self, sink: Any, schema: pa.Schema) -> None: + self.sink = sink + + def __enter__(self) -> Full: + return self + + def __exit__(self, *exc: object) -> None: + if stage == "close": + raise OSError(errno.ENOSPC, "no space") + + def write_table(self, table: pa.Table) -> None: + self.sink.write(b"part of a file") + if stage == "write": + raise OSError(errno.ENOSPC, "no space") + + with monkeypatch.context() as patched: + patched.setattr(pa.ipc, "new_file", Full) + for _ in range(2): + with pytest.raises(OSError, match="no space"): + spool.append(_table(50, 5_000)) + assert (spool.memory_bytes, spool.size) == (held, size) + assert _files(tmp_path) == [] + everything = np.arange(50) + assert spool.take(everything).equals(rows.combine_chunks()) + spool.append(_table(50, 5_000)) # the retry: the rows once + assert spool.size == 5_050 + assert spool.take(np.array([5_049, 0, 50])).equals( + _table(0, 5_050).take(pa.array([5_049, 0, 50], pa.int64())) + ) + assert len(_files(tmp_path)) == 1 + spool.close() + + +def test_a_first_append_that_fails_decides_nothing( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def full(*args: object) -> None: + raise OSError(errno.ENOSPC, "no space") + + spool = RowSpool(0, str(tmp_path)) + with monkeypatch.context() as patched: + patched.setattr(pa.ipc, "new_file", full) + with pytest.raises(OSError, match="no space"): + spool.append(_table(0, 3)) + other = pa.table({"a": [1, 2], "b": [3, 4]}) # another schema: nothing was held + spool.append(other) + assert spool.take(np.array([1, 0])).equals(other.take(pa.array([1, 0], pa.int64()))) + spool.close() + + +def test_a_closed_spool_refuses_every_use(tmp_path: Path) -> None: + spool, _ = _filled(tmp_path, [10], 0) + spool.close() + with pytest.raises(ValueError, match="closed"): + _ = spool.take(np.array([0])) + with pytest.raises(ValueError, match="closed"): + spool.discard(np.array([0])) + + +@pytest.mark.skipif(sys.platform == "win32", reason="swept through fcntl locks") +def test_a_process_killed_before_it_locked_its_directory_is_swept( + tmp_path: Path, +) -> None: + left = tmp_path / "orcapod-spool-unlocked" + left.mkdir() + spool, _ = _filled(tmp_path, [10], 0) + assert not left.exists() + spool.close() + + +@pytest.mark.skipif(sys.platform == "win32", reason="swept through fcntl locks") +def test_a_removal_that_stopped_part_way_is_finished(tmp_path: Path) -> None: + left = tmp_path / "orcapod-spool-partly" + (left / "some-spool").mkdir(parents=True) + (left / "some-spool" / "0.arrow").touch() + (left / "lock").touch() + spool, _ = _filled(tmp_path, [10], 0) + assert not left.exists() + spool.close() From 6a6bea4559e3a9a0fe854fd33dbffcda954932a8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:49:15 -0800 Subject: [PATCH 09/26] docs(dev): keys-only joins and uniqueness certificates, with measurements (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-joins.md | 121 ++++++++++++++++++ docs/dev/specs/itl-1464-joins/measure.py | 20 ++- src/orcapod/core/operators/streaming_joins.py | 10 +- src/orcapod/core/unique_keys.py | 10 +- tests/test_core/test_unique_keys.py | 2 +- 5 files changed, 150 insertions(+), 13 deletions(-) create mode 100644 docs/dev/specs/itl-1464-joins.md diff --git a/docs/dev/specs/itl-1464-joins.md b/docs/dev/specs/itl-1464-joins.md new file mode 100644 index 000000000..26c6da6ee --- /dev/null +++ b/docs/dev/specs/itl-1464-joins.md @@ -0,0 +1,121 @@ +# Joins that hold keys, and certificates of unique tags (ITL-1464) + +Status: implemented with this document, November 25, 2026; design decisions approved by the +coordinator under the developer's delegation. It covers `Join`, `MergeJoin` and +`SemiJoin` over record-batch channels (`async_execute_batches`). No job node calls that +form yet: the transport work of ITL-1464 wires it, and until then a job's memory is as +before. The sync path is unchanged, and no hash, identity, stored row or golden value moves. + +## What an async join holds + +Each side of a binary join step keeps, per row that can still match, its prepared join keys +and its row number (a Polars frame, `streaming_joins._Side`); the rows are in a row spool +(`core/row_spool.py`). Matching is the sync path's (`join._matched_pairs` on +`arrow_keys.polars_key_frame`), one vectorized join per arriving batch, and every value is +taken from the rows by number, so it is the input's, bit for bit. + +| Case | Held | Let go | +|---|---|---| +| both sides unique on the shared tags (1:1) | keys of the rows not matched yet | both rows of a pair, when they match | +| one side unique (a lookup) | keys of the unique side; of the other side, rows that arrived and have not matched | a row of the other side, when it matches | +| neither (many to many) | keys of both sides | nothing while both inputs are open | +| any | | a side's rows, when the other side ends | +| `SemiJoin` | distinct right keys; undecided left rows' keys | a left row, when a right row matches it | + +One rule covers the first three: **a row is let go once it has matched if and only if the +other side is unique on the join keys.** A join of three or more inputs is a chain of such +steps in canonical order; each step's left side has the certificate of the rows joined so +far (`unique_keys.joined_keys`). + +Memory, per held row: the prepared key (16 bytes per string, plus its length when above 12 +bytes; 8 per integer, timestamp or float; 1 for the constant key), 8 for the row number, 1 +for the removal mask. Beside it: at most 64 MiB of rows per side before they go to disk, the +batches in flight, and one output piece of at most 8,192 pairs. Worst case, with no +certificate and neither input ended, the keys of both inputs. A many-to-many output is never +held: the pairs are counted first, then made in pieces; one arriving row with more pairs +than a piece has its pairs listed (16 bytes each, at most the held rows) and is sent in +pieces. + +Every input is read at once and to its end, at most 65,536 rows ahead of the join. Nothing +waits for one input to end, because both inputs may read one upstream (a diamond). + +Not covered: `Rejoin` stays a barrier on this path, because its kernel can differ from the +sync path for repeated origins with three or more inputs. A subclass of an operator runs its +own sync call over its whole inputs. + +## The row spool + +Rows past the memory limit become a file each: an uncompressed Arrow IPC file of one record +batch, read memory-mapped, under a directory of this process in the system's temporary +directory. A file is deleted when its last row is discarded; the rest at a normal end, a +failure, a cancellation, collection and exit. A killed process leaves its directory; the +next process to spill there removes it (it holds no lock any more). A spool belongs to one +thread of one process; a forked child's copy refuses every use. + +## Certificates + +`StreamProtocol.unique_keys` is a set of tag sets on which no two rows agree, under the +joins' equality. It is derived when asked and stored nowhere: in no hash, identity, config, +stored row or equality. A wrong certificate would lose rows, so only what is certain is +certified, and a rule is read from the exact class: a subclass certifies nothing unless it +declares a rule. + +| Stream | Certificate | +|---|---| +| `ArrowTableSource`, `DictSource`, `ListSource`, `DataFrameSource`, SQLite and PostgreSQL tables | the key columns, when all are tags | +| every other source; a raw `ArrowTableStream`, also with a producer | none | +| `DropNulls`, `Filter`, `PolarsFilter`, `AddTags`, `TagBy`, `Pick`, `Index`, `MapData`, the data column selections, function pods (`FunctionPod`, `CachedFunctionPod`), `SideEffectPod` | the input's | +| the tag selections and drops | the input's keys whose tags all stay | +| `MapTags`, `MapColumns` | the input's keys renamed, without those that lose a tag | +| `GroupBy` | its keys | +| `Batch` | none | +| `SemiJoin` | the left input's | +| `Join`, `MergeJoin` on shared tags S | unions of one key of each side; a side's own keys when the other side is unique on S | +| `Rejoin` | every input's (a row is in at most one result row) | +| a source slot | its bound source's | +| an operator job node in `REPLAY` mode | none: it replays every logged run | + +Why a source's key columns are certain: those source kinds build every row through +`SourceStreamBuilder`, which names a row by its key columns and refuses a null or repeated +key, on every read. The record id is a function of the key values and a key is a string, an +integer, a boolean, a timestamp or a date (never a float), so two rows whose keys are equal +to a join have one record id and are refused. + +That direction is the safe one for a database: a store whose equality is coarser than the +join's (a case-insensitive collation, padded `CHAR`) never holds two keys the join takes as +equal; one whose equality is finer (a float key, a timestamp read at a coarser unit) could. +No store is trusted here: the SQL sources are checked as read. A later step may trust a +store's key instead of checking it, only under those conditions and only for a key without +nulls. + +CSV and Delta (a running check is a later step), `CachedSource` (rows of earlier reads), +`DerivedSource` and `PollingSource` certify nothing. + +## Measured + +`docs/dev/specs/itl-1464-joins/measure.py`, each case in a fresh process, synthetic rows +with their source-info tokens, sent and read through bounded +channels. Peak RSS includes 143 MiB of imports and the mapped pages a join reads. "Barrier" +is the form before this change. It is the operator alone, not a job. + +| Case | Rows | Form | Output rows | Peak RSS | Arrow pool peak | Time | +|---|---|---|---|---|---|---| +| `lookup` | 1,000,000 | barrier | 1,000,000 | 1,793 MiB | 1,323 MiB | 2.3 s | +| `lookup` | 1,000,000 | keys | 1,000,000 | 259 MiB | 26 MiB | 2.4 s | +| `lookup` | 8,000,000 | keys | 8,000,000 | 257 MiB | 26 MiB | 19.9 s | +| `lookup_late` | 1,000,000 | keys | 1,000,000 | 756 MiB | 169 MiB | 5.4 s | +| `lookup_late` | 8,000,000 | keys | 8,000,000 | 2733 MiB | 392 MiB | 61.7 s | +| `one_to_one` | 1,000,000 | keys | 1,000,000 | 317 MiB | 64 MiB | 4.7 s | +| `one_to_one` | 8,000,000 | keys | 8,000,000 | 341 MiB | 64 MiB | 39.3 s | +| `one_to_one_late` | 1,000,000 | barrier | 1,000,000 | 2,574 MiB | 1,854 MiB | 4.4 s | +| `one_to_one_late` | 1,000,000 | keys | 1,000,000 | 741 MiB | 176 MiB | 5.1 s | +| `one_to_one_late` | 8,000,000 | keys | 8,000,000 | 2,301 MiB | 453 MiB | 60.0 s | +| `many` (5 per row) | 1,000,000 | barrier | 5,000,000 | 4,835 MiB | 4,111 MiB | 2.4 s | +| `many` | 1,000,000 | keys | 5,000,000 | 445 MiB | 144 MiB | 3.2 s | +| `many` | 8,000,000 | keys | 40,000,000 | 453 MiB | 146 MiB | 26.0 s | +| `semi` | 8,000,000 | keys | 8,000,000 | 252 MiB | 21 MiB | 19.6 s | + +`lookup`, `one_to_one` in step, `many` and `semi` do not grow with the rows. The late +cases grow with the keys of the input that arrived first, as the bound says. In `many` the +small side arrives first and ends, so it measures the bounded output and not the worst case +of two open inputs, which is the sum of both sides' keys. diff --git a/docs/dev/specs/itl-1464-joins/measure.py b/docs/dev/specs/itl-1464-joins/measure.py index 128054893..57954b458 100644 --- a/docs/dev/specs/itl-1464-joins/measure.py +++ b/docs/dev/specs/itl-1464-joins/measure.py @@ -21,7 +21,8 @@ import sys import time import warnings -from collections.abc import Iterator +from collections.abc import Callable, Iterator +from typing import Any import numpy as np import pyarrow as pa @@ -33,15 +34,15 @@ from orcapod.protocols.core_protocols import StreamProtocol BATCH = 8_192 -SESSION = "session-2026-01-01-000000-abcdef" +SESSION = "session-0123456789abcdef" -def _text(values: np.ndarray, pattern: str) -> pa.Array: +def _text(values: np.ndarray[Any, Any], pattern: str) -> pa.Array[Any]: return pa.array([pattern % v for v in values.tolist()], pa.large_string()) def spikes(start: int, n: int) -> pa.Table: - """Event rows: seven tags and data, as the measured spike table.""" + """Synthetic event rows: tags and data of several types.""" i = np.arange(start, start + n) return pa.table( { @@ -97,7 +98,14 @@ def events(start: int, n: int) -> pa.Table: class Input: """An input: a small source of its kind describes it, its rows are made as sent.""" - def __init__(self, name: str, make, rows: int, tags: list[str], key: list[str]): + def __init__( + self, + name: str, + make: Callable[[int, int], pa.Table], + rows: int, + tags: list[str], + key: list[str], + ): self.make, self.rows, self.key, self.name = make, rows, key, name self.tags = tags self.stream = self.source(0, 4) @@ -199,5 +207,5 @@ async def consume() -> None: f"{case:16} rows={rows:>9,} {'barrier' if barrier else 'keys':8}" + f" out={count:>11,} {seconds:7.1f} s" + f" peak={peak / unit:8.0f} MiB (import {base / unit:.0f})" - + f" arrow_peak={pa.default_memory_pool().max_memory() / 2**20:8.0f} MiB" + + f" arrow_peak={(pa.default_memory_pool().max_memory() or 0) / 2**20:8.0f} MiB" ) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 2af444484..ce57e52e5 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -2,7 +2,8 @@ The async path of ``Join``, ``MergeJoin``, ``SemiJoin`` and ``Rejoin`` (ITL-1347, stage 5) is to read its inputs as Arrow record batches, in whatever order they arrive; these -kernels are that computation, not yet wired into ``async_execute``. A kernel gives the +kernels are that computation (``run_kernel``, for the operators' +``async_execute_batches``; no job node calls that form yet). A kernel gives the rows of the operator's sync ``static_process`` over the same inputs as a multiset (row order is not a result on the async path; developer, November 22, 2026), within the limits each kernel's docstring states (``StreamingRejoin``: repeated origins with three @@ -49,8 +50,8 @@ no rows that shares a tag with the others empties the result (an inner join), so no row was emitted before it can refuse. ``SemiJoin`` with no shared tag passes every left row whatever its right input holds, and has no shared column to refuse. -- **Matching is the sync join's.** Each input keeps the rows it needs as Arrow tables and - a Polars frame of their prepared keys and row numbers (``arrow_keys.polars_key_frame``), +- **Matching is the sync join's.** Each input keeps the rows it needs in a row spool + (memory, then local disk; ``core/row_spool``) and a Polars frame of their prepared keys and row numbers (``arrow_keys.polars_key_frame``), with the constant key every join adds (``join._with_common_key``). An arriving batch's key frame is joined with the other side's accumulated key frame by the sync path's own rule (``join._matched_pairs``), in one vectorized join, never per row: a top-level @@ -67,7 +68,8 @@ the last step of F), so a kernel declares every such field nullable and the stream made from its batches settles them. -A kernel holds only what can still match: a side's rows are dropped when the other side +A kernel holds only what can still match: a row is let go once it has matched when the +other side is certified unique on the keys (``core/unique_keys``); a side's rows are dropped when the other side closes (nothing can arrive to match them), and an arriving row is not kept once the other side has closed. A row whose key holds a top-level null is never kept (it matches nothing). A step of a ``Join`` chain that can never emit again (a side closed holding no diff --git a/src/orcapod/core/unique_keys.py b/src/orcapod/core/unique_keys.py index a55e2191f..61875b0c4 100644 --- a/src/orcapod/core/unique_keys.py +++ b/src/orcapod/core/unique_keys.py @@ -18,7 +18,7 @@ class declares, at the time it is asked: nothing is stored on a stream, and noth from collections.abc import Iterable, Mapping, Sequence from contextvars import ContextVar -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Protocol if TYPE_CHECKING: from orcapod.protocols.core_protocols import StreamProtocol @@ -95,8 +95,14 @@ def joined_keys( return certificate(keys) +class _HasKeys(Protocol): + """What the certificate needs of the stream it is of.""" + + def keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: ... + + def derived_keys( - pod: object, upstreams: Sequence[StreamProtocol], stream: StreamProtocol + pod: object, upstreams: Sequence[StreamProtocol], stream: _HasKeys ) -> UniqueKeys: """The certificate of ``stream``, the result of ``pod`` over ``upstreams``. diff --git a/tests/test_core/test_unique_keys.py b/tests/test_core/test_unique_keys.py index a13396894..3d78ca5de 100644 --- a/tests/test_core/test_unique_keys.py +++ b/tests/test_core/test_unique_keys.py @@ -183,7 +183,7 @@ def test_joins_derive_their_certificate() -> None: assert lookup.join(left).unique_keys == _keys(KEY) assert left.join(both).unique_keys == _keys((*KEY, "depth")) assert left.join(none).unique_keys == frozenset() - assert left.join(lookup, _wide()).unique_keys == _keys(KEY) + assert Join()(left, lookup, _wide()).unique_keys == _keys(KEY) assert left.semi_join(none).unique_keys == _keys(KEY) assert none.semi_join(left).unique_keys == frozenset() renamed = left.select_data_columns(["x"]) From 9176ee76d8744bd481d6779f020404b6acda2f03 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:49:28 -0800 Subject: [PATCH 10/26] 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 [ From 1ce55338027e8b5efde79213d570e779af9975de Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:50:17 -0800 Subject: [PATCH 11/26] fix(core): unique_keys imports no protocol module (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/unique_keys.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/orcapod/core/unique_keys.py b/src/orcapod/core/unique_keys.py index 61875b0c4..0096c6b24 100644 --- a/src/orcapod/core/unique_keys.py +++ b/src/orcapod/core/unique_keys.py @@ -18,10 +18,7 @@ class declares, at the time it is asked: nothing is stored on a stream, and noth from collections.abc import Iterable, Mapping, Sequence from contextvars import ContextVar -from typing import TYPE_CHECKING, Protocol - -if TYPE_CHECKING: - from orcapod.protocols.core_protocols import StreamProtocol +from typing import Protocol UniqueKeys = frozenset[frozenset[str]] @@ -102,7 +99,7 @@ def keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: ... def derived_keys( - pod: object, upstreams: Sequence[StreamProtocol], stream: _HasKeys + pod: object, upstreams: Sequence[object], stream: _HasKeys ) -> UniqueKeys: """The certificate of ``stream``, the result of ``pod`` over ``upstreams``. From a04b7e47e0efbc894aca94ca4e309f9df43c7b77 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:53:57 -0800 Subject: [PATCH 12/26] fix(core): row spool locks no forked child inherits, and one call at a time across threads (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/row_spool.py | 289 ++++++++++++++++-------------- tests/test_core/test_row_spool.py | 126 ++++++++++++- 2 files changed, 279 insertions(+), 136 deletions(-) diff --git a/src/orcapod/core/row_spool.py b/src/orcapod/core/row_spool.py index 2ac0de2e2..94b3be6f9 100644 --- a/src/orcapod/core/row_spool.py +++ b/src/orcapod/core/row_spool.py @@ -5,21 +5,23 @@ rows by those numbers; ``discard`` says that rows are never fetched again. Format: rows wait in memory until they exceed a byte limit, then become one segment: an -Arrow IPC file of one record batch, uncompressed, read memory-mapped (a mapped page is -the operating system's to drop, not memory this process holds). An extension column is -written as its storage and wrapped again when read, so reading needs no registered type. +Arrow IPC file of one record batch, uncompressed, read memory-mapped. A mapped page is the +operating system's to drop: it counts in a process's resident size while it is there, but +it is no memory of Arrow's or of this process's own. An extension column is written as its +storage and wrapped again when read, so reading needs no registered type. Lifetime: a segment is deleted once every row of it is discarded; a spool's files are removed by ``close`` (a spool is a context manager: normal end, exception and cancellation alike) and when it is collected. A process keeps its spools in one directory of its own, removed at interpreter exit. A killed process leaves its directory behind; the next process to spill there removes it: every directory holds a lock file its process -keeps locked, so a directory whose lock is free has no owner. (Without ``fcntl``, as on -Windows, nothing is swept.) +keeps locked (a POSIX record lock, which a forked child does not inherit), so a directory +whose lock is free has no owner. (Without ``fcntl``, as on Windows, nothing is swept.) -Ownership: a spool belongs to one thread (or one event loop) of the process that made it: -it has no lock of its own, and a forked child's copy refuses every use, so a child never -touches its parent's files. Different spools may be used from different threads. +Ownership: a spool belongs to the process that made it, and any of its threads may use it: +one call at a time, a call after ``close`` refused. What ``table`` and ``slice`` returned +stays readable whatever happens to the spool. A forked child's copy refuses every read and +write, and its ``close`` does nothing, so a child never touches its parent's files. Rows: tables of one schema with at least one column, in Orcapod's normalized types (large variants, no views). The byte limit bounds what the spool keeps; a ``take`` holds the rows @@ -38,6 +40,7 @@ import tempfile import threading import weakref +from collections.abc import Collection from typing import IO, Any, Self import numpy as np @@ -61,15 +64,16 @@ class _ProcessDirectories: def __init__(self) -> None: self._guard = threading.Lock() + # Each root's directory, and its open lock file: never opened again, because + # closing any handle of a file gives up the process's record lock on it. self._held: dict[str, tuple[str, IO[str]]] = {} - self.root_lock: IO[str] | None = None - """The root's lock file while a directory is made.""" def get(self, root: str) -> str: """This process's directory under ``root``.""" with self._guard: if root not in self._held or not os.path.isdir(self._held[root][0]): - self._held[root] = _make_process_directory(root) + own = {os.path.basename(held) for held, _ in self._held.values()} + self._held[root] = _make_process_directory(root, own) return self._held[root][0] def remove(self) -> None: @@ -80,26 +84,24 @@ def remove(self) -> None: self._held = {} def after_fork_in_child(self) -> None: - """Start empty: the directories are the parent's, and so are the locks. + """Start empty: the directories are the parent's, and so are their locks. - The guard may be held by a thread that does not exist in the child. The lock - files are closed, never unlocked: the parent's open files keep them locked, and - the child keeps none of them locked after the parent is gone. + The guard may be held by a thread that does not exist in the child. """ self._guard = threading.Lock() - inherited = [lock for _, lock in self._held.values()] - if self.root_lock is not None: - inherited.append(self.root_lock) - self._held, self.root_lock = {}, None - for lock in inherited: - lock.close() + self._held = {} -def _make_process_directory(root: str) -> tuple[str, IO[str]]: +def _make_process_directory(root: str, own: Collection[str]) -> tuple[str, IO[str]]: """Make this process's directory under ``root``, locked, and sweep abandoned ones. Both happen under one lock of the root, so a sweep never sees a directory that is - made but not yet locked. + made but not yet locked. The locks are record locks: a child forked at any point + holds none of them. + + Args: + root: The directory to make it under. + own: The names of the directories this process holds already. """ os.makedirs(root, exist_ok=True) if fcntl is None: @@ -108,15 +110,11 @@ def _make_process_directory(root: str) -> tuple[str, IO[str]]: name = os.path.join(root, f".{_PREFIX}{os.getuid()}.lock") flags = os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC with os.fdopen(os.open(name, flags, 0o600), "w") as root_lock: - _directories.root_lock = root_lock - try: - fcntl.flock(root_lock, fcntl.LOCK_EX) - _sweep(root) - directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) - lock = open(os.path.join(directory, _LOCK_NAME), "w") - fcntl.flock(lock, fcntl.LOCK_EX) - finally: - _directories.root_lock = None + fcntl.lockf(root_lock, fcntl.LOCK_EX) + _sweep(root, own) + directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) + lock = open(os.path.join(directory, _LOCK_NAME), "w") + fcntl.lockf(lock, fcntl.LOCK_EX) return directory, lock @@ -133,14 +131,22 @@ def _remove_process_directory(directory: str) -> None: os.rmdir(directory) -def _sweep(root: str) -> None: - """Remove this user's spool directories under ``root`` that no process holds.""" +def _sweep(root: str, own: Collection[str]) -> None: + """Remove this user's spool directories under ``root`` that no process holds. + + Args: + root: The directory to look in. + own: The names of the directories this process holds: its own record locks do + not stop it, so they are left out by name. + """ assert fcntl is not None with os.scandir(root) as entries: candidates = [ entry.path for entry in entries - if entry.name.startswith(_PREFIX) and entry.is_dir(follow_symlinks=False) + if entry.name.startswith(_PREFIX) + and entry.name not in own + and entry.is_dir(follow_symlinks=False) ] for directory in candidates: # A directory held by a live process, being removed, or not a spool's is left. @@ -148,8 +154,8 @@ def _sweep(root: str) -> None: if os.stat(directory).st_uid != os.getuid(): continue try: - with open(os.path.join(directory, _LOCK_NAME)) as lock: - fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + with open(os.path.join(directory, _LOCK_NAME), "r+") as lock: + fcntl.lockf(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) _remove_process_directory(directory) except FileNotFoundError: # Its process was killed before it made the lock file (the root's lock @@ -204,6 +210,8 @@ def __init__( self._root: str | None = root self._closed: bool = False self._owner: int = os.getpid() + # One call at a time; a call waits for the one before it, ``close`` included. + self._lock = threading.RLock() self._schema: pa.Schema | None = None self._segments: list[_Segment] = [] self._starts: npt.NDArray[np.int64] | None = None @@ -231,35 +239,40 @@ def append(self, table: pa.Table) -> None: OSError: If the rows in memory cannot be written to the local disk. The spool is then as before the call, with no partial file. """ - self._require_usable() - if not table.num_rows: - return - schema, size = self._schema, self.size - if self._schema is None: - self._schema = table.schema - # One chunk that owns its rows: a slice would keep its whole parent alive. - added = _Segment(self.size, _owned(table)) - self._add(added) - self.size += table.num_rows - if self._in_memory > self._memory_bytes: - try: - self._spill() - except BaseException: - # The new rows are in the last run, so they were not written. - self._segments.remove(added) - self._starts = None - if added.table is not None: - self._in_memory -= added.table.nbytes - self._schema, self.size = schema, size - raise - - def _require_usable(self) -> None: - """Refuse a closed spool, and a forked child's copy of its parent's.""" + self._require_owner() + with self._lock: + self._require_usable() + if not table.num_rows: + return + schema, size = self._schema, self.size + if self._schema is None: + self._schema = table.schema + # One chunk that owns its rows: a slice would keep its whole parent alive. + added = _Segment(self.size, _owned(table)) + self._add(added) + self.size += table.num_rows + if self._in_memory > self._memory_bytes: + try: + self._spill() + except BaseException: + # The new rows are in the last run, so they were not written. + self._segments.remove(added) + self._starts = None + if added.table is not None: + self._in_memory -= added.table.nbytes + self._schema, self.size = schema, size + raise + + def _require_owner(self) -> None: + """Refuse a forked child's copy of its parent's spool, before its lock is touched.""" if self._owner != os.getpid(): raise RuntimeError( "a row spool is used only in the process that made it: this is a " + "forked child's copy" ) + + def _require_usable(self) -> None: + """Refuse a closed spool.""" if self._closed: raise ValueError("the row spool is closed") @@ -281,27 +294,29 @@ def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: ValueError: If the spool is closed. RuntimeError: In a process other than the one that made the spool. """ - self._require_usable() - if self._starts is None: - self._starts = np.fromiter( - (s.start for s in self._segments), np.int64, len(self._segments) - ) - held_in = np.searchsorted(self._starts, rows, side="right") - 1 - order = np.argsort(held_in, kind="stable") - sorted_rows, sorted_in = rows[order], held_in[order] - edges = np.flatnonzero(np.diff(sorted_in)) + 1 - parts: list[pa.Table] = [] - for group in np.split(np.arange(len(rows)), edges): - segment = self._segments[int(sorted_in[group[0]])] - local = pa.array(sorted_rows[group] - segment.start, pa.int64()) - parts.append(self._take_from(segment, local)) - if len(parts) == 1: - # One segment: the stable sort changed nothing. - return parts[0].combine_chunks() - taken = pa.concat_tables(parts).combine_chunks() - back = np.empty(len(order), np.int64) - back[order] = np.arange(len(order)) - return taken.take(pa.array(back, pa.int64())).combine_chunks() + self._require_owner() + with self._lock: + self._require_usable() + if self._starts is None: + self._starts = np.fromiter( + (s.start for s in self._segments), np.int64, len(self._segments) + ) + held_in = np.searchsorted(self._starts, rows, side="right") - 1 + order = np.argsort(held_in, kind="stable") + sorted_rows, sorted_in = rows[order], held_in[order] + edges = np.flatnonzero(np.diff(sorted_in)) + 1 + parts: list[pa.Table] = [] + for group in np.split(np.arange(len(rows)), edges): + segment = self._segments[int(sorted_in[group[0]])] + local = pa.array(sorted_rows[group] - segment.start, pa.int64()) + parts.append(self._take_from(segment, local)) + if len(parts) == 1: + # One segment: the stable sort changed nothing. + return parts[0].combine_chunks() + taken = pa.concat_tables(parts).combine_chunks() + back = np.empty(len(order), np.int64) + back[order] = np.arange(len(order)) + return taken.take(pa.array(back, pa.int64())).combine_chunks() def _take_from(self, segment: _Segment, local: pa.Array[Any]) -> pa.Table: # pyright: ignore[reportExplicitAny] # row numbers """Rows of one segment, by their numbers in it.""" @@ -349,26 +364,30 @@ def slice(self, start: int, length: int) -> pa.Table: ValueError: As ``table``; also for a negative ``start`` or ``length``. RuntimeError: In a process other than the one that made the spool. """ - self._require_usable() - if start < 0 or length < 0: - raise ValueError(f"a slice of rows from {start}, {length} long") - if self._schema is None: - raise ValueError("nothing was appended to the row spool: no columns yet") - if self._discarded: - raise ValueError("rows of the row spool were discarded: no whole table") - end = min(start + length, self.size) - parts: list[pa.Table] = [] - for segment in self._segments: - first = max(start, segment.start) - last = min(end, segment.start + segment.rows) - if first >= last: - continue - if segment.table is not None: - part = segment.table - else: - part = _wrapped(self._stored(segment), self._schema) - parts.append(part.slice(first - segment.start, last - first)) - return pa.concat_tables(parts) if parts else self._schema.empty_table() + self._require_owner() + with self._lock: + self._require_usable() + if start < 0 or length < 0: + raise ValueError(f"a slice of rows from {start}, {length} long") + if self._schema is None: + raise ValueError( + "nothing was appended to the row spool: no columns yet" + ) + if self._discarded: + raise ValueError("rows of the row spool were discarded: no whole table") + end = min(start + length, self.size) + parts: list[pa.Table] = [] + for segment in self._segments: + first = max(start, segment.start) + last = min(end, segment.start + segment.rows) + if first >= last: + continue + if segment.table is not None: + part = segment.table + else: + part = _wrapped(self._stored(segment), self._schema) + parts.append(part.slice(first - segment.start, last - first)) + return pa.concat_tables(parts) if parts else self._schema.empty_table() def discard(self, rows: npt.NDArray[np.int64]) -> None: """Say that these rows are never fetched again. @@ -382,27 +401,29 @@ def discard(self, rows: npt.NDArray[np.int64]) -> None: ValueError: If the spool is closed. RuntimeError: In a process other than the one that made the spool. """ - self._require_usable() - if not len(rows): - return - starts = np.fromiter( - (s.start for s in self._segments), np.int64, len(self._segments) - ) - held_in = np.searchsorted(starts, rows, side="right") - 1 - counts = np.bincount(held_in, minlength=len(self._segments)) - self._discarded = True - emptied = False - for index in np.flatnonzero(counts): - segment = self._segments[int(index)] - segment.live -= int(counts[index]) - if not segment.live: - if segment.table is not None: - self._in_memory -= segment.table.nbytes - segment.drop() - emptied = True - if emptied: - self._segments = [s for s in self._segments if s.live] - self._starts = None + self._require_owner() + with self._lock: + self._require_usable() + if not len(rows): + return + starts = np.fromiter( + (s.start for s in self._segments), np.int64, len(self._segments) + ) + held_in = np.searchsorted(starts, rows, side="right") - 1 + counts = np.bincount(held_in, minlength=len(self._segments)) + self._discarded = True + emptied = False + for index in np.flatnonzero(counts): + segment = self._segments[int(index)] + segment.live -= int(counts[index]) + if not segment.live: + if segment.table is not None: + self._in_memory -= segment.table.nbytes + segment.drop() + emptied = True + if emptied: + self._segments = [s for s in self._segments if s.live] + self._starts = None def _spill(self) -> None: """Write the segments in memory to one file, as one segment.""" @@ -453,14 +474,20 @@ def _write(self, segment: _Segment) -> str: return path def close(self) -> None: - """Let every row go and remove the files. Calling it again does nothing.""" - self._closed = True - self._segments = [] - self._starts = None - self._in_memory = 0 - if self._cleanup is not None: - _ = self._cleanup() - self._directory = self._cleanup = None + """Let every row go and remove the files. Calling it again does nothing. + + It waits for a call of another thread to end. In a forked child it does nothing. + """ + if self._owner != os.getpid(): + return + with self._lock: + self._closed = True + self._segments = [] + self._starts = None + self._in_memory = 0 + if self._cleanup is not None: + _ = self._cleanup() + self._directory = self._cleanup = None def __enter__(self) -> Self: return self diff --git a/tests/test_core/test_row_spool.py b/tests/test_core/test_row_spool.py index 6b7faa775..67b69651b 100644 --- a/tests/test_core/test_row_spool.py +++ b/tests/test_core/test_row_spool.py @@ -9,6 +9,9 @@ import signal import subprocess import sys +import threading +from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import TimeoutError as FutureTimeout from datetime import datetime, timezone from pathlib import Path from typing import Any @@ -352,6 +355,44 @@ def use(): in_child(use) assert spool.take(np.array([1, 0])).equals(table.take(pa.array([1, 0]))) spool.close() +elif case in ("root_lock", "unpublished"): + # A fork while another thread has just opened the root's lock file, or has made a + # directory and not yet recorded it; then the parent is killed holding the lock. + opened, resume = threading.Event(), threading.Event() + name = "fdopen" if case == "root_lock" else "_make_process_directory" + where = os if case == "root_lock" else row_spool + original = getattr(where, name) + def paused(*args, **kwargs): + result = original(*args, **kwargs) + opened.set() + resume.wait(30) + return result + setattr(where, name, paused) + if case == "root_lock": + import fcntl + locked, take_lock = threading.Event(), fcntl.lockf + def lockf(*args): + take_lock(*args) + locked.set() + threading.Event().wait(30) + fcntl.lockf = lockf + spool = RowSpool(0, root) + threading.Thread(target=spool.append, args=(table,), daemon=True).start() + assert opened.wait(10) + ready, wait = os.pipe() + child = os.fork() + if child == 0: + signal.alarm(120) # never left behind + os.write(wait, b"x") + os.close(1) + os.close(2) + signal.pause() + os.read(ready, 1) + if case == "root_lock": + resume.set() + assert locked.wait(10) + print(child, flush=True) + os.kill(os.getpid(), signal.SIGKILL) elif case == "outlived": # A child that outlives its parent does not keep the parent's directory locked. spool = RowSpool(0, root) @@ -397,15 +438,21 @@ def test_a_forked_child_neither_waits_for_nor_touches_its_parents_spools( @pytest.mark.skipif(not hasattr(os, "fork"), reason="needs fork") -def test_a_child_that_outlives_its_killed_parent_does_not_stop_the_sweep( - tmp_path: Path, +@pytest.mark.parametrize("case", ["outlived", "root_lock", "unpublished"]) +def test_a_child_that_outlives_its_killed_parent_holds_none_of_its_locks( + tmp_path: Path, case: str ) -> None: - done = _fork("outlived", tmp_path) - (left,) = tmp_path.glob("orcapod-spool-*") + done = _fork(case, tmp_path) + left = list(tmp_path.glob("orcapod-spool-*")) + assert bool(left) == (case != "root_lock") child = int(done.stdout) try: + # Another process spills at once, and sweeps what the killed one left. + other = _child(tmp_path, "exit") + _ = other.communicate(timeout=30) + assert other.returncode == 0 + assert not any(directory.exists() for directory in left) spool, _ = _filled(tmp_path, [10], 0) - assert not left.exists() spool.close() finally: os.kill(child, signal.SIGKILL) @@ -501,3 +548,72 @@ def test_a_removal_that_stopped_part_way_is_finished(tmp_path: Path) -> None: spool, _ = _filled(tmp_path, [10], 0) assert not left.exists() spool.close() + + +def test_a_process_never_sweeps_its_own_directory(tmp_path: Path) -> None: + """Its own record lock would not stop it: also when a root has two names.""" + root, alias = tmp_path / "root", tmp_path / "alias" + root.mkdir() + alias.symlink_to(root, target_is_directory=True) + first, rows = _filled(root, [10], 0) + second, _ = _filled(alias, [10], 0) + assert len(list(root.glob("orcapod-spool-*"))) == 2 + # And the first directory is still locked for every other process. + other = _child(root, "exit") + _ = other.communicate() + assert other.returncode == 0 + assert first.take(np.array([9])).equals(rows.slice(9, 1)) + first.close() + second.close() + + +@pytest.mark.parametrize("read", ["take", "table", "slice"]) +def test_a_close_waits_for_a_read_of_another_thread( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, read: str +) -> None: + spool, rows = _filled(tmp_path, [10, 10], 0) + about_to_map, go_on = threading.Event(), threading.Event() + original = pa.memory_map + + def parked(path: str) -> Any: + about_to_map.set() + assert go_on.wait(10) + return original(path) + + monkeypatch.setattr(pa, "memory_map", parked) + reads: dict[str, Any] = { + "take": lambda: spool.take(np.arange(20)), + "table": spool.table, + "slice": lambda: spool.slice(0, 20), + } + with ThreadPoolExecutor(2) as pool: + result = pool.submit(reads[read]) + assert about_to_map.wait(10) + closed = pool.submit(spool.close) + with pytest.raises(FutureTimeout): + closed.result(timeout=0.1) + go_on.set() + assert result.result(10).equals(rows) + closed.result(10) + assert _files(tmp_path) == [] + with pytest.raises(ValueError, match="closed"): + reads[read]() + + +def test_threads_append_and_read_one_spool(tmp_path: Path) -> None: + spool = RowSpool(1 << 12, str(tmp_path)) + + def work(number: int) -> None: + for i in range(20): + spool.append(pa.table({"a": [number] * 5, "b": [i] * 5})) + rows = np.arange(0, spool.size, 7) + assert spool.take(rows).num_rows == len(rows) + _ = spool.table() + + with ThreadPoolExecutor(4) as pool: + for done in [pool.submit(work, n) for n in range(4)]: + done.result(60) + assert spool.size == spool.table().num_rows == 400 + counts = spool.table().group_by(["a", "b"]).aggregate([([], "count_all")]) + assert set(counts.column("count_all").to_pylist()) == {5} + spool.close() From a5e72b733d08e7c3a9631d5985a3929c5edd4aa0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:01:44 -0800 Subject: [PATCH 13/26] docs(dev): the many-to-many worst case of an async join, measured (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-joins.md | 12 ++++++---- docs/dev/specs/itl-1464-joins/measure.py | 30 ++++++++++++++++++++---- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/docs/dev/specs/itl-1464-joins.md b/docs/dev/specs/itl-1464-joins.md index 26c6da6ee..109395761 100644 --- a/docs/dev/specs/itl-1464-joins.md +++ b/docs/dev/specs/itl-1464-joins.md @@ -104,7 +104,7 @@ is the form before this change. It is the operator alone, not a job. | `lookup` | 1,000,000 | keys | 1,000,000 | 259 MiB | 26 MiB | 2.4 s | | `lookup` | 8,000,000 | keys | 8,000,000 | 257 MiB | 26 MiB | 19.9 s | | `lookup_late` | 1,000,000 | keys | 1,000,000 | 756 MiB | 169 MiB | 5.4 s | -| `lookup_late` | 8,000,000 | keys | 8,000,000 | 2733 MiB | 392 MiB | 61.7 s | +| `lookup_late` | 8,000,000 | keys | 8,000,000 | 2,733 MiB | 392 MiB | 61.7 s | | `one_to_one` | 1,000,000 | keys | 1,000,000 | 317 MiB | 64 MiB | 4.7 s | | `one_to_one` | 8,000,000 | keys | 8,000,000 | 341 MiB | 64 MiB | 39.3 s | | `one_to_one_late` | 1,000,000 | barrier | 1,000,000 | 2,574 MiB | 1,854 MiB | 4.4 s | @@ -113,9 +113,13 @@ is the form before this change. It is the operator alone, not a job. | `many` (5 per row) | 1,000,000 | barrier | 5,000,000 | 4,835 MiB | 4,111 MiB | 2.4 s | | `many` | 1,000,000 | keys | 5,000,000 | 445 MiB | 144 MiB | 3.2 s | | `many` | 8,000,000 | keys | 40,000,000 | 453 MiB | 146 MiB | 26.0 s | +| `many_open` (5 per row) | 1,000,000 | barrier | 5,000,000 | 6,068 MiB | 5,002 MiB | 4.2 s | +| `many_open` | 1,000,000 | keys | 5,000,000 | 992 MiB | 384 MiB | 5.6 s | +| `many_open` | 4,000,000 | keys | 20,000,000 | 1,691 MiB | 633 MiB | 23.5 s | +| `many_open` | 8,000,000 | keys | 40,000,000 | 2,629 MiB | 941 MiB | 57.3 s | | `semi` | 8,000,000 | keys | 8,000,000 | 252 MiB | 21 MiB | 19.6 s | `lookup`, `one_to_one` in step, `many` and `semi` do not grow with the rows. The late -cases grow with the keys of the input that arrived first, as the bound says. In `many` the -small side arrives first and ends, so it measures the bounded output and not the worst case -of two open inputs, which is the sum of both sides' keys. +cases grow with the keys of the input that arrived first, as the bound says. `many` ends its small +side first, so it measures the bounded output; `many_open` is the worst case, two open inputs +with no certificate, and grows with the keys of both. diff --git a/docs/dev/specs/itl-1464-joins/measure.py b/docs/dev/specs/itl-1464-joins/measure.py index 57954b458..02a03e22e 100644 --- a/docs/dev/specs/itl-1464-joins/measure.py +++ b/docs/dev/specs/itl-1464-joins/measure.py @@ -11,6 +11,8 @@ - ``one_to_one_late``: the same, one input arriving entirely before the other; - ``many``: ``rows`` spikes against 1,000 events, neither unique on the session and shank they share: five output rows per spike. +- ``many_open``: two inputs of ``rows`` rows in step, neither unique on the session and + burst they share: five output rows per row, and both sides' keys held to the end. - ``semi``: ``rows`` spikes kept by the units that exist (300). """ @@ -50,6 +52,7 @@ def spikes(start: int, n: int) -> pa.Table: "unit": _text(i % 300, "unit-%05d"), "spike": pa.array(i, pa.int64()), "shank": pa.array(i % 200, pa.int64()), + "burst": pa.array(i // 5, pa.int64()), "time": pa.array(i / 30_000.0), "amplitude": pa.array((i % 97) * 1.5), } @@ -82,6 +85,20 @@ def units(start: int, n: int) -> pa.Table: ) +def marks(start: int, n: int) -> pa.Table: + """Rows five of which share a burst, as five spikes do.""" + i = np.arange(start, start + n) + return pa.table( + { + "session": pa.array([SESSION] * n, pa.large_string()), + "burst": pa.array(i // 5, pa.int64()), + "mark": pa.array(i, pa.int64()), + "level": pa.array(i * 0.1), + "kind": _text(i % 4, "kind-%d"), + } + ) + + def events(start: int, n: int) -> pa.Table: i = np.arange(start, start + n) return pa.table( @@ -129,14 +146,15 @@ def batches(self) -> Iterator[pa.RecordBatch]: async def run(case: str, rows: int, barrier: bool) -> tuple[int, float]: + tags = {"many": "shank", "many_open": "burst"}.get(case, "unit") big = Input( "spikes", spikes, rows, - ["session", "unit", "spike"] - if not case.startswith("many") - else ["session", "shank", "spike"], - ["session", "unit", "spike"] if case != "many" else ["session", "spike"], + ["session", tags, "spike"], + ["session", "spike"] + if case.startswith("many") + else ["session", "unit", "spike"], ) if case.startswith("one_to_one"): other = Input( @@ -146,6 +164,10 @@ async def run(case: str, rows: int, barrier: bool) -> tuple[int, float]: ["spike", "unit", "session"], ["session", "unit", "spike"], ) + elif case == "many_open": + other = Input( + "marks", marks, rows, ["session", "burst", "mark"], ["session", "mark"] + ) elif case == "many": other = Input( "events", events, 1_000, ["session", "shank", "event"], ["session", "event"] From e94ad6e4e09d8e94b8627026d36c3e4f1cfe9f39 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:10:39 -0800 Subject: [PATCH 14/26] feat(operators): record-batch channels and join kernels carry derived source-info tokens (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-joins/measure.py | 2 +- .../core/operators/static_output_pod.py | 41 ++++- src/orcapod/core/operators/streaming_joins.py | 53 ++++++- src/orcapod/core/record_batch_channels.py | 6 +- src/orcapod/core/streams/base.py | 2 +- .../test_record_batch_channels.py | 5 +- .../operators/test_keys_only_joins.py | 146 ++++++++++++++++++ .../operators/test_record_batch_execution.py | 6 +- .../test_pipeline/test_review_findings_510.py | 4 +- 9 files changed, 251 insertions(+), 14 deletions(-) diff --git a/docs/dev/specs/itl-1464-joins/measure.py b/docs/dev/specs/itl-1464-joins/measure.py index 02a03e22e..fc79d9cb9 100644 --- a/docs/dev/specs/itl-1464-joins/measure.py +++ b/docs/dev/specs/itl-1464-joins/measure.py @@ -141,7 +141,7 @@ def batches(self) -> Iterator[pa.RecordBatch]: stream: StreamProtocol = self.source(start, min(BATCH, self.rows - start)) zero = StaticOutputOperatorPod._materialize_upstream([], self.stream) names = zero.as_table(columns={"source": True, "system_tags": True}) - table = stream.as_table(columns={"source": True, "system_tags": True}) + table = getattr(stream, "as_carried_table", stream.as_table)(columns={"source": True, "system_tags": True}) yield from table.select(names.column_names).combine_chunks().to_batches() diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index eb4359229..4fc0ed2b2 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1183,7 +1183,7 @@ async def _send_result(result: StreamProtocol, output: RecordBatchOutput) -> Non output: The channel to send into; a result with no rows sends nothing. """ table = row_built_columns( - result.as_table(columns=ZERO_ROW_INPUT_COLUMNS), result.keys() + result.as_carried_table(columns=ZERO_ROW_INPUT_COLUMNS), result.keys() ) for batch in table.to_batches(): if batch.num_rows: @@ -1401,7 +1401,9 @@ def settle_token_types( if not field.name.startswith(constants.SOURCE_PREFIX): continue kinds: set[pa.DataType] - if pa.types.is_large_string(field.type): + # A derived column settles as the text its recipe gives (ITL-1464). + derived = source_tokens.derived_recipe(field.type) is not None + if derived or pa.types.is_large_string(field.type): kinds = {pa.large_string()} else: kinds = { @@ -1413,7 +1415,8 @@ def settle_token_types( if len(kinds) > 1: raise SourceInfoTypesDisagree(field.name) (kind,) = kinds - _ = _named_tokens_as(column, kind, field.name) # representable, or refused + if not derived: + _ = _named_tokens_as(column, kind, field.name) # representable, or refused settled[field.name] = kind return settled @@ -1493,6 +1496,31 @@ def _named_tokens_as( raise RowBuiltFormUnavailable(f"{name}: {error}") from error +def _with_one_token_form(batches: Sequence[pa.RecordBatch]) -> list[pa.RecordBatch]: + """``batches`` with each source-info column in one form in all of them. + + A column every batch derives by one recipe stays derived; one that some batches hold + as text, or derive otherwise, is text in all of them (ITL-1464). + + Args: + batches: Record batches of one stream's rows. + """ + kinds: dict[str, set[pa.DataType]] = {} + for batch in batches: + for field in batch.schema: + if field.name.startswith(constants.SOURCE_PREFIX): + kinds.setdefault(field.name, set()).add(field.type) + mixed = {name for name, types in kinds.items() if len(types) > 1} + formed: list[pa.RecordBatch] = [] + for batch in batches: + if mixed & set(source_tokens.derived_columns(batch.schema)): + table = source_tokens.materialize(pa.Table.from_batches([batch]), mixed) + formed.extend(table.combine_chunks().to_batches()) + else: + formed.append(batch) + return formed + + def concatenate_batches(batches: Sequence[pa.RecordBatch]) -> pa.Table | None: """Put a stream's record batches under one another, or ``None`` with no row. @@ -1523,11 +1551,14 @@ def concatenate_batches(batches: Sequence[pa.RecordBatch]) -> pa.Table | None: settled = settle_token_types(batch, settled) prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) opened: list[pa.RecordBatch] = [] - for batch in rows: + for batch in _with_one_token_form(rows): columns: list[Any] = [] # pyright: ignore[reportExplicitAny] # any column fields: list[pa.Field[Any]] = [] # pyright: ignore[reportExplicitAny] # any field for field, column in zip(batch.schema, batch.columns, strict=True): - if field.name in settled: + if ( + field.name in settled + and source_tokens.derived_recipe(field.type) is None + ): column = _named_tokens_as(column, settled[field.name], field.name) field = pa.field(field.name, settled[field.name]) if field.name.startswith(prefixes): diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index ce57e52e5..afe9201c2 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -129,7 +129,7 @@ from orcapod.protocols.core_protocols.streams import RecordBatchInput, RecordBatchOutput from orcapod.core.unique_keys import joined_keys, unique_on from orcapod.system_constants import constants -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens # The column groups an operator input and result are read with: user tags, system tags, # data and source info. No meta column and no context column: neither is transported. @@ -551,6 +551,9 @@ def __init__( # (``settle_token_types``): the input's complete table must still be buildable, # as the sync path builds it before matching. self._token_types: list[dict[str, pa.DataType]] = [{} for _ in self.inputs] + # The form of each input's source-info columns, as its first batch with rows + # holds them: text, or derived by a recipe (``source_tokens``, ITL-1464). + self._token_forms: list[dict[str, pa.DataType] | None] = [None] * len(inputs) self._emitted_any: bool = False # The sync path over no rows: its checks, and the output's columns. self.zero_row_result: StreamProtocol = operator.static_process(*self._zero_rows) @@ -725,12 +728,18 @@ def _as_input_table(self, input_index: int, batch: pa.RecordBatch) -> pa.Table: + f"the column(s) {missing} its stream describes" ) table = pa.Table.from_batches([batch]).select(layout.names) + table = self._in_one_token_form(input_index, table) columns = list(table.columns) + fields = list(layout) for index, (field, actual) in enumerate(zip(layout, table.schema)): if field.type == actual.type: continue if not table.num_rows and pa.types.is_null(actual.type): continue + if source_tokens.derived_recipe(actual.type) is not None: + # No token is null, and the recipe's text is the layout's type. + fields[index] = field.with_type(actual.type) + continue if table.num_rows and field.name.startswith(constants.SOURCE_PREFIX): # A batch's token type follows its own tokens and can be shallower # than the layout's (a null or an empty list fixes fewer list @@ -751,7 +760,38 @@ def _as_input_table(self, input_index: int, batch: pa.RecordBatch) -> pa.Table: self._token_types[input_index] = token_types if not table.num_rows: return layout.empty_table() - return pa.Table.from_arrays(columns, schema=layout) + return pa.Table.from_arrays(columns, schema=pa.schema(fields)) + + def _in_one_token_form(self, input_index: int, table: pa.Table) -> pa.Table: + """``table`` with its source-info columns in the form of the input's first batch. + + A column that batch held as text becomes text; one it derived must be derived by + the same recipe, since the rows held already have no text. + + Raises: + ValueError: If a later batch holds such a column in another form. + """ + if not table.num_rows: + return table + kept = self._token_forms[input_index] + if kept is None: + kept = { + field.name: field.type + for field in table.schema + if source_tokens.derived_recipe(field.type) is not None + } + self._token_forms[input_index] = kept + texts = set(table.column_names) - set(kept) + table = source_tokens.materialize(table, texts) + for name, kind in kept.items(): + actual = table.schema.field(name).type + if actual != kind: + raise ValueError( + f"{type(self).__name__}: the source-info column {name!r} of input " + + f"{input_index} changed its form between batches: {kind}, then " + + f"{actual}. A producer sends each such column in one form." + ) + return table def _check_settled_token_types( self, input_index: int, token_types: Mapping[str, pa.DataType] @@ -996,6 +1036,9 @@ def __init__(self, operator: MergeJoin, inputs: Sequence[StreamProtocol]) -> Non for name in sorted(merged) if f"{constants.SOURCE_PREFIX}{name}" in right_names } + self._in_both = set(self._layouts[0].names) & { + self._rename.get(name, name) for name in right_names + } self._colliding = (set(left_data) & set(right_data)) - merged self._captured = ( set(left_tags) | set(left_data) | set(right_tags) | set(right_data) @@ -1103,6 +1146,8 @@ def _finish( for left_name, right_name in self._rename.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 for name in sorted(self._colliding): source_name = f"{constants.SOURCE_PREFIX}{name}" pairs = [(name, output_types[name])] @@ -1155,6 +1200,8 @@ def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: table = table.rename_columns( [self._rename.get(c, c) for c in table.column_names] ) + # A source-info column both inputs have becomes a list of both tokens: text. + table = source_tokens.materialize(table, self._in_both) return self._link.push(input_index, table) def release(self) -> None: @@ -1728,6 +1775,8 @@ def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: """ if not self._links: return [table] + # Rejoin compares shared source-info columns by value: text. + table = source_tokens.materialize(table) table = _with_context(table, self._contexts[input_index]) position = self._position[input_index] step, side = (0, 0) if position == 0 else (position - 1, 1) diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 3e94bbe12..5a251f592 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -29,7 +29,7 @@ from orcapod.core.streams.record_batch_input import InputChannel from orcapod.errors import UpstreamFailedError from orcapod.system_constants import constants -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens if TYPE_CHECKING: from orcapod.protocols.core_protocols import StreamProtocol @@ -429,6 +429,10 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: expected = declared.field(column.name) carried = arrow_utils.normalize_to_large_types(expected.type) if column.name.startswith(constants.SOURCE_PREFIX): + if source_tokens.derived_recipe(column.type) is not None: + if column.metadata: + return f"column {column.name!r} carries field metadata" + continue if not _is_token_type(column.type): return f"column {column.name!r} is {column.type}, not a token type" if column.metadata or not column.type.equals( diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index d991204f4..b0a0a1f2e 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -577,7 +577,7 @@ def _row_built_table(self) -> pa.Table: retyped as a row retypes it. Only a stream that holds such a column (a raw ``ArrowTableStream``) is read that way, and its reads have no effect. """ - table = self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + table = self._stream.as_carried_table(columns=ZERO_ROW_INPUT_COLUMNS) if not system_tags_as_rows_give(table): from orcapod.core.operators.static_output_pod import ( StaticOutputOperatorPod, diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index d4416e6db..635dbc85c 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -23,6 +23,7 @@ import pyarrow as pa import pytest +from orcapod.utils import source_tokens from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, RecordBatchOutput, @@ -135,7 +136,9 @@ def test_a_channel_opened_on_a_stream_delivers_its_rows_and_refers_to_it() -> No as_protocol: RecordBatchInput = channel # what an operator reads (type-checked) assert as_protocol.stream is stream batches = run(stream.open_channel().collect) - assert same(pa.Table.from_batches(batches), R(stream)) + # Tokens may be derived on a channel; their text is the rows' (ITL-1464). + text = source_tokens.materialize(pa.Table.from_batches(batches)) + assert same(text, R(stream)) delivered = run(lambda: channel.to_stream()) assert same(delivered.as_table(columns=ALL), R(stream)) assert delivered.keys() == stream.keys() diff --git a/tests/test_core/operators/test_keys_only_joins.py b/tests/test_core/operators/test_keys_only_joins.py index f0379d207..3d9dc039c 100644 --- a/tests/test_core/operators/test_keys_only_joins.py +++ b/tests/test_core/operators/test_keys_only_joins.py @@ -13,6 +13,7 @@ import functools import random import warnings +from collections import Counter from collections.abc import Callable, Sequence from pathlib import Path from typing import Any @@ -34,6 +35,7 @@ from orcapod.core.streams import ArrowTableStream from orcapod.errors import UpstreamFailedError from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.utils import source_tokens from .test_streaming_joins import _arrivals, _check, _rows, _run, _sent, _transport # pyright: ignore[reportPrivateUsage] # the kernels' one oracle @@ -502,3 +504,147 @@ def test_a_random_arrival_of_everything_once_more(spooled: Path) -> None: batches = _run(kernel, _arrivals(tables, random.Random(seed))) got = pa.Table.from_batches(batches) if batches else None assert (_rows(got) if got is not None else {}) == expected + + +# --------------------------------------------------------------------------- +# Batches whose source-info tokens are derived (``utils/source_tokens``) +# --------------------------------------------------------------------------- + + +def _carried(stream: StreamProtocol) -> pa.Table: + """An input's rows as a channel sends them: its tokens derived where they can be.""" + feed = stream.open_channel() + + async def read() -> list[pa.RecordBatch]: + return await feed.collect() + + return pa.Table.from_batches(asyncio.run(read())) + + +def _check_derived( + make_kernel: Callable[[Sequence[StreamProtocol]], StreamingJoinKernel], + sync: Callable[..., StreamProtocol], + inputs: Sequence[StreamProtocol], + texts: Sequence[bool] = (False, False, False), +) -> list[pa.RecordBatch]: + """Check the rows of a kernel fed derived batches (text for ``texts``).""" + tables = [ + source_tokens.materialize(_carried(s)) if text else _carried(s) + for s, text in zip(inputs, texts) + ] + for table, text in zip(tables, texts): + assert bool(source_tokens.derived_columns(table.schema)) != text + expected = _rows(_transport(sync(*inputs))) + batches: list[pa.RecordBatch] = [] + for seed in range(6): + kernel = make_kernel(inputs) + batches = _run(kernel, _arrivals(tables, random.Random(seed))) + rows: Any = Counter() + for batch in batches: + rows += _rows(source_tokens.materialize(pa.Table.from_batches([batch]))) + assert rows == expected + assert kernel.held_rows == 0 + return batches + + +@pytest.mark.parametrize("texts", [(False, False), (True, False), (False, True)]) +@pytest.mark.parametrize("kind", sorted(KINDS)) +def test_derived_tokens_give_the_sync_rows( + spooled: Path, kind: str, texts: tuple[bool, bool] +) -> None: + inputs = KINDS[kind]("reversed") + for make, op in ((_join, Join()), (_semi, SemiJoin()), (_merge, MergeJoin())): + _ = _check_derived(make, op.static_process, inputs, texts) + assert _files(spooled) == [] + + +def test_a_join_carries_derived_tokens_through(spooled: Path) -> None: + """They cost nothing held: no text is built for a join of different pipelines.""" + inputs = KINDS["lookup"]("tags_first") + batches = _check_derived(_join, Join().static_process, inputs) + derived = source_tokens.derived_columns(batches[0].schema) + assert len(derived) == 4 # two data columns of each input + + +def _data_tagged(name: str, n: int) -> ArrowTableSource: + return ArrowTableSource( + pa.table( + { + "k": [i % 3 for i in range(n)], + "g": ["ab"[i % 2] for i in range(n)], + f"{name}1": list(range(n)), + f"{name}2": [f"{name}{i}" for i in range(n)], + } + ), + tag_columns=["g", "k"], + source_id=name, + ) + + +@pytest.mark.parametrize( + "texts", [(False, False, False), (True, False, False), (False, True, True)] +) +def test_merged_data_tags_of_derived_tokens( + spooled: Path, texts: tuple[bool, bool, bool] +) -> None: + inputs = [_data_tagged(name, 5 + i) for i, name in enumerate("abc")] + _ = _check_derived(_join, Join().static_process, inputs, texts) + _ = _check_derived(_merge, MergeJoin().static_process, inputs[:2], texts[:2]) + _ = _check_derived(_semi, SemiJoin().static_process, inputs[:2], texts[:2]) + + +def test_inputs_of_one_pipeline_hash_sort_their_system_tags(spooled: Path) -> None: + """Their system-tag values move, so a token derived from them is built first.""" + inputs = [ + ArrowTableSource( + pa.table( + {"k": [1, 2, 1], "j": [1, 1, 2], "v": ["x", "y", "z"], "w": [1, 2, 3]} + ), + tag_columns=["j", "k"], + tag_only_columns=True, + source_id=name, + ) + for name in ("second", "first") + ] + _ = _check_derived(_merge, MergeJoin().static_process, inputs) + renamed = [s.map_data({"v": f"v{i}", "w": f"w{i}"}) for i, s in enumerate(inputs)] + _ = _check_derived(_join, Join().static_process, renamed) + + +def test_a_producer_that_changes_a_tokens_form(spooled: Path) -> None: + left, right = KINDS["one_to_one"]("tags_first") + (derived,) = _carried(left).combine_chunks().to_batches() + (text,) = source_tokens.materialize(_carried(left)).combine_chunks().to_batches() + # Text first: later derived batches are built as text. + kernel = _join([left, right]) + _ = kernel.push(0, text.slice(0, 3)) + _ = kernel.push(0, derived.slice(3)) + out = [b for batch in _carried(right).to_batches() for b in kernel.push(1, batch)] + got = source_tokens.materialize(pa.Table.from_batches(out)) + assert _rows(got) == _rows(_transport(left.join(right))) + # Derived first: the rows held have no text, so text is refused, changing nothing. + other = _join([left, right]) + _ = other.push(0, derived.slice(0, 3)) + with pytest.raises(ValueError, match="changed its form"): + _ = other.push(0, text.slice(3)) + assert other.held_rows == 3 + + +@pytest.mark.parametrize("op", [Join(), SemiJoin(), MergeJoin()], ids=lambda o: repr(o)) +def test_an_operator_after_a_join_gets_derived_batches(spooled: Path, op: Any) -> None: + """A chain over channels: the join's output is another operator's input.""" + inputs = KINDS["lookup"]("reversed") + joined = op(*inputs) + then = joined.drop_nulls("spikes_y") + + async def go() -> StreamProtocol: + middle = OutputChannel(joined) + last = OutputChannel(then) + reader = middle.open_reader() + await asyncio.gather( + op.async_execute_batches([s.open_channel() for s in inputs], middle), + then.producer.async_execute_batches([reader], last), + ) + return last.result() + + assert _rows(_transport(_bounded(go()))) == _rows(_transport(then)) diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index f6762c14d..b61559c1f 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -42,6 +42,7 @@ from orcapod.pipeline import SyncPipelineOrchestrator from orcapod.pipeline.job import PipelineJob from orcapod.system_constants import constants +from orcapod.utils import source_tokens from tests.test_core.operators.test_rejoin import other_context # noqa: F401 # the fixture from orcapod.errors import UpstreamFailedError from orcapod.protocols.core_protocols import StreamProtocol @@ -322,7 +323,10 @@ async def go() -> list[pa.RecordBatch]: return received received = asyncio.run(go()) - table = pa.Table.from_batches(received) if received else None + # A batch may carry derived tokens (ITL-1464): their text is what the rows give. + table = ( + source_tokens.materialize(pa.Table.from_batches(received)) if received else None + ) assert (table.num_rows if table is not None else 0) == expected.num_rows if table is not None: assert table.to_pylist() == expected.to_pylist() diff --git a/tests/test_pipeline/test_review_findings_510.py b/tests/test_pipeline/test_review_findings_510.py index d2467f69f..488ae59d1 100644 --- a/tests/test_pipeline/test_review_findings_510.py +++ b/tests/test_pipeline/test_review_findings_510.py @@ -166,9 +166,9 @@ def test_a_failed_batch_preparation_is_raised_again_without_a_second_read() -> N base = _plain() class Failing: - def as_table(self, **kwargs: Any) -> Any: + def as_carried_table(self, **kwargs: Any) -> Any: reads.append(1) - return base.as_table(**kwargs) + return base.as_carried_table(**kwargs) def keys(self, **kwargs: Any) -> Any: raise RuntimeError("keys failed") From 37826edcc8d15caa557821e49051da74f8a327b9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:15:19 -0800 Subject: [PATCH 15/26] fix(core): certify only exact classes and unreplaced instances; a join's row mask is bounded by the rows held (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-joins.md | 12 ++- src/orcapod/core/cached_function_pod.py | 4 +- src/orcapod/core/exact_class.py | 37 ++++++++ src/orcapod/core/function_pod.py | 4 +- src/orcapod/core/nodes/function_node.py | 6 +- src/orcapod/core/nodes/operator_node.py | 8 +- src/orcapod/core/nodes/source_node.py | 12 ++- src/orcapod/core/operators/join.py | 6 +- src/orcapod/core/operators/merge_join.py | 6 +- src/orcapod/core/operators/semijoin.py | 6 +- .../core/operators/static_output_pod.py | 4 +- src/orcapod/core/operators/streaming_joins.py | 37 +++++--- src/orcapod/core/sources/base.py | 10 ++- src/orcapod/core/streams/base.py | 40 ++------- src/orcapod/core/unique_keys.py | 29 +++++-- src/orcapod/side_effects.py | 8 +- .../operators/test_keys_only_joins.py | 84 +++++++++++++++++++ tests/test_core/test_unique_keys.py | 63 ++++++++++++++ 18 files changed, 302 insertions(+), 74 deletions(-) create mode 100644 src/orcapod/core/exact_class.py diff --git a/docs/dev/specs/itl-1464-joins.md b/docs/dev/specs/itl-1464-joins.md index 109395761..3caba5025 100644 --- a/docs/dev/specs/itl-1464-joins.md +++ b/docs/dev/specs/itl-1464-joins.md @@ -36,7 +36,8 @@ held: the pairs are counted first, then made in pieces; one arriving row with mo than a piece has its pairs listed (16 bytes each, at most the held rows) and is sent in pieces. -Every input is read at once and to its end, at most 65,536 rows ahead of the join. Nothing +Every input is read at once and to its end, each until 65,536 rows wait for the join (the +producer's last batch is taken whole, whatever its size). Nothing waits for one input to end, because both inputs may read one upstream (a diamond). Not covered: `Rejoin` stays a barrier on this path, because its kernel can differ from the @@ -50,15 +51,18 @@ batch, read memory-mapped, under a directory of this process in the system's tem directory. A file is deleted when its last row is discarded; the rest at a normal end, a failure, a cancellation, collection and exit. A killed process leaves its directory; the next process to spill there removes it (it holds no lock any more). A spool belongs to one -thread of one process; a forked child's copy refuses every use. +process, whose threads may all use it, one call at a time; a forked child's copy refuses +every read and write. ## Certificates `StreamProtocol.unique_keys` is a set of tag sets on which no two rows agree, under the joins' equality. It is derived when asked and stored nowhere: in no hash, identity, config, stored row or equality. A wrong certificate would lose rows, so only what is certain is -certified, and a rule is read from the exact class: a subclass certifies nothing unless it -declares a rule. +certified: a rule is read from the exact class, and only while no member of the instance is +replaced (`reads_as_its_class`), for the source, the pod, the stream and the node alike. A +subclass or a customized instance certifies nothing, and a customized join runs its own sync +call over its whole inputs. | Stream | Certificate | |---|---| diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 23f262ac7..724a4bebb 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -6,7 +6,7 @@ import logging from datetime import datetime, timezone from collections.abc import Iterator -from typing import TYPE_CHECKING, Any +from typing import ClassVar, TYPE_CHECKING, Any from orcapod.core.unique_keys import UniqueKeys from orcapod.core.data_function import CachedDataFunction @@ -514,6 +514,8 @@ class _CachedFunctionPodStream(FunctionPodStream): table has no meta columns unless asked for, as an uncached pod's table. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: for tag, data in super().iter_data(): yield tag, _without_stored_meta(data) diff --git a/src/orcapod/core/exact_class.py b/src/orcapod/core/exact_class.py new file mode 100644 index 000000000..40f9c429b --- /dev/null +++ b/src/orcapod/core/exact_class.py @@ -0,0 +1,37 @@ +"""Whether an object is exactly its class: what it does is what the class defines.""" + +from __future__ import annotations + +import functools +import inspect + + +def reads_as_its_class(obj: object, cls: type) -> bool: + """Whether ``obj`` is exactly ``cls`` and reads only through ``cls``'s own members. + + Exact, never by inspection of what a subclass overrides: ``type(obj) is cls``, and + ``obj`` holds no attribute of its own that shadows a method or a property of + ``cls`` (an ``iter_data`` replaced on the instance). A ``functools.cached_property`` + keeps its value in the instance by design and is not a shadow. A subclass, however + small, is never ``cls`` here (ITL-1347). + + Args: + obj: The object to check. + cls: The class whose reading is proven. + + Returns: + Whether ``obj`` reads as ``cls`` does. + """ + if type(obj) is not cls: + return False + own = getattr(obj, "__dict__", None) + if not own: + return True + missing = object() + for name in own: + member = inspect.getattr_static(cls, name, missing) + if member is missing or isinstance(member, functools.cached_property): + continue + if callable(member) or hasattr(type(member), "__get__"): + return False + return True diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 4a4fd51ce..4556400c9 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -7,7 +7,7 @@ from abc import abstractmethod from collections.abc import Callable, Collection, Iterable, Iterator, Sequence from functools import update_wrapper, wraps -from typing import TYPE_CHECKING, Any, Literal, Protocol, cast +from typing import ClassVar, TYPE_CHECKING, Any, Literal, Protocol, cast import pyarrow as pa @@ -1143,6 +1143,8 @@ def _no_content_hashes() -> pa.Array[Any]: class FunctionPodStream(StreamBase): """Recomputable stream wrapping a data function.""" + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def __init__( self, function_pod: FunctionPodProtocol, input_stream: StreamProtocol, **kwargs ) -> None: diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index c2ea7c490..7f1d55e75 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -27,7 +27,7 @@ from collections.abc import Callable, Iterator, Mapping, Sequence from datetime import datetime, timezone from functools import partial -from typing import Any, Literal, NamedTuple, cast +from typing import ClassVar, Any, Literal, NamedTuple, cast import polars as pl import pyarrow as pa @@ -1024,6 +1024,8 @@ class FunctionNode(FunctionNodeBase): and serialized to disk via ``Pipeline.save()``. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def __init__( self, function_pod: FunctionPodProtocol, @@ -1416,6 +1418,8 @@ class FunctionJobNode(ProvenanceMethods, RunHoldingNode, FunctionNodeBase): execution. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + # Set once a read has reported the stored rows it skipped (rows of another data # context); a class default so nodes rebuilt from a saved descriptor start unset. _skipped_rows_reported: bool = False diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 5c6ccd300..f234514ae 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -22,12 +22,13 @@ import logging from abc import abstractmethod from collections.abc import Collection, Iterator, Mapping, Sequence -from typing import TYPE_CHECKING, Any, Literal, cast +from typing import ClassVar, TYPE_CHECKING, Any, Literal, cast import pyarrow as pa import pyarrow.compute as pc from orcapod import contexts +from orcapod.core.exact_class import reads_as_its_class from orcapod.core.unique_keys import NO_UNIQUE_KEYS, UniqueKeys, derived_keys from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.core.data_tags import ( @@ -51,7 +52,6 @@ ZERO_ROW_INPUT_COLUMNS, StreamBase, check_head_size, - reads_as_its_class, short_stream_repr, system_tags_as_rows_give, ) @@ -605,6 +605,8 @@ class OperatorNode(OperatorNodeBase): and serialized to disk via ``Pipeline.save()``. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Raise ``PipelineJobRequiredError`` — blueprint nodes cannot produce data. @@ -844,6 +846,8 @@ class OperatorJobNode(ProvenanceMethods, RunHoldingNode, OperatorNodeBase): - **REPLAY**: skip computation, flow cached results downstream. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + # Set once a read has reported the stored rows it skipped (rows of another data # context); a class default so nodes rebuilt from a saved descriptor start unset. _skipped_rows_reported: bool = False diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index e9a80bf98..c334885a7 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -16,12 +16,13 @@ from abc import ABC, abstractmethod from collections.abc import AsyncIterator, Collection, Iterator, Mapping, Sequence from datetime import datetime -from typing import TYPE_CHECKING, Any +from typing import ClassVar, TYPE_CHECKING, Any import pyarrow as pa from orcapod import contexts -from orcapod.core.unique_keys import NO_UNIQUE_KEYS, UniqueKeys +from orcapod.core.exact_class import reads_as_its_class +from orcapod.core.unique_keys import NO_UNIQUE_KEYS, UniqueKeys, derives_unique_keys from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase @@ -33,7 +34,6 @@ ZERO_ROW_INPUT_COLUMNS, CompleteStreamFeed, keys_of_rows, - reads_as_its_class, system_tags_as_rows_give, stream_arrow_schema, schema_requires_io, @@ -912,6 +912,8 @@ def explain(self) -> Explanation: @property def unique_keys(self) -> UniqueKeys: """The bound stream's unique keys (``core/unique_keys``); none when unbound.""" + if not derives_unique_keys(self): + return NO_UNIQUE_KEYS bound = self._bound_stream() return NO_UNIQUE_KEYS if bound is None else bound.unique_keys @@ -1475,6 +1477,8 @@ class SourceNode(SourceNodeBase): — identical to the old ``SourceSpec`` — so existing DB paths remain valid. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def _typed_zero_row_table(self) -> "pa.Table | None": """The slot's zero-row table from its own Arrow schemas (ITL-640). @@ -1593,6 +1597,8 @@ class SourceJobNode(ProvenanceMethods, SourceNodeBase): *bound_source* is ``None``. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def __init__( self, name: str, diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 9ad39005b..1fc35edce 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -9,6 +9,7 @@ import pyarrow as pa from orcapod.protocols.core_protocols.streams import RecordBatchInput, RecordBatchOutput +from orcapod.core.exact_class import reads_as_its_class from orcapod.core.unique_keys import UniqueKeys, joined_keys from orcapod.types.explanation import plain_repr from orcapod.core.operators.meta_columns import ( @@ -719,8 +720,9 @@ async def async_execute_batches( inputs: One input channel per input stream, in the operator's order. output: The channel the result's record batches are sent into. """ - if type(self) is not Join: - # A subclass may compute other rows: its own sync call over all of its inputs. + if not reads_as_its_class(self, Join): + # A subclass, or an instance with a member replaced, may compute other rows: + # its own sync call over all of its inputs. await super().async_execute_batches(inputs, output) return # The kernels are built on this module's join rules. diff --git a/src/orcapod/core/operators/merge_join.py b/src/orcapod/core/operators/merge_join.py index 4abe330d8..49bfd85e7 100644 --- a/src/orcapod/core/operators/merge_join.py +++ b/src/orcapod/core/operators/merge_join.py @@ -5,6 +5,7 @@ import pyarrow as pa from orcapod.protocols.core_protocols.streams import RecordBatchInput, RecordBatchOutput +from orcapod.core.exact_class import reads_as_its_class from orcapod.core.unique_keys import UniqueKeys, joined_keys from orcapod.types.explanation import plain_repr from orcapod.core.operators.base import ( @@ -607,8 +608,9 @@ async def async_execute_batches( inputs: One input channel per input stream, in the operator's order. output: The channel the result's record batches are sent into. """ - if type(self) is not MergeJoin: - # A subclass may compute other rows: its own sync call over all of its inputs. + if not reads_as_its_class(self, MergeJoin): + # A subclass, or an instance with a member replaced, may compute other rows: + # its own sync call over all of its inputs. await super().async_execute_batches(inputs, output) return # The kernels are built on this module's join rules. diff --git a/src/orcapod/core/operators/semijoin.py b/src/orcapod/core/operators/semijoin.py index 2ab81df26..1f89135a1 100644 --- a/src/orcapod/core/operators/semijoin.py +++ b/src/orcapod/core/operators/semijoin.py @@ -9,6 +9,7 @@ import pyarrow.compute as pc from orcapod.protocols.core_protocols.streams import RecordBatchInput, RecordBatchOutput +from orcapod.core.exact_class import reads_as_its_class from orcapod.core.unique_keys import UniqueKeys from orcapod.types.explanation import plain_repr from orcapod.channels import ChannelClosed, ReadableChannel, WritableChannel @@ -344,8 +345,9 @@ async def async_execute_batches( inputs: One input channel per input stream, in the operator's order. output: The channel the result's record batches are sent into. """ - if type(self) is not SemiJoin: - # A subclass may compute other rows: its own sync call over all of its inputs. + if not reads_as_its_class(self, SemiJoin): + # A subclass, or an instance with a member replaced, may compute other rows: + # its own sync call over all of its inputs. await super().async_execute_batches(inputs, output) return # The kernels are built on this module's join rules. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 335087a82..28ee1e5ea 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -18,6 +18,7 @@ import pyarrow as pa import pyarrow.compute as pc +from orcapod.core.exact_class import reads_as_its_class from orcapod.core.unique_keys import UniqueKeys, derived_keys from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, @@ -47,7 +48,6 @@ ZERO_ROW_INPUT_COLUMNS, StreamBase, check_head_size, - reads_as_its_class, short_stream_repr, typed_zero_row_input, typed_zero_row_table, @@ -1816,6 +1816,8 @@ def produced_stream(stream: StreamProtocol) -> StreamProtocol: class DynamicPodStream(StreamBase): """Recomputable stream wrapping a ``StaticOutputOperatorPod`` invocation.""" + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def __init__( self, pod: StaticOutputOperatorPod, diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index ce57e52e5..676534eae 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -323,8 +323,10 @@ def __init__( self._constant_key: bool = constant_key self._frames: list[pl.DataFrame] = [] self._spool: RowSpool = RowSpool() - # Whether each row is still held, by its number (grown by doubling). + # Whether each row is still held, by its number less ``_base`` (grown by + # doubling); no row numbered below ``_base`` is held. self._alive: npt.NDArray[np.bool_] = np.ones(0, dtype=np.bool_) + self._base: int = 0 self._removed_count: int = 0 def key_frame(self, table: pa.Table) -> pl.DataFrame: @@ -341,14 +343,15 @@ def append(self, table: pa.Table, frame: pl.DataFrame) -> None: self._frames.append(frame.with_columns(pl.col(self.row) + self._spool.size)) self._spool.append(table) self.rows += table.num_rows - if self._spool.size > len(self._alive): - grown = np.ones(2 * self._spool.size, dtype=np.bool_) + numbered = self._spool.size - self._base + if numbered > len(self._alive): + grown = np.ones(2 * numbered, dtype=np.bool_) grown[: len(self._alive)] = self._alive self._alive = grown def held(self, rows: npt.NDArray[np.int64]) -> npt.NDArray[np.int64]: """Those of ``rows`` that were not removed.""" - return rows[self._alive[rows]] + return rows[self._alive[rows - self._base]] def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: """The held rows with these numbers, in this order.""" @@ -369,23 +372,32 @@ def remove(self, rows: npt.NDArray[np.int64]) -> None: return self._spool.discard(rows) self.rows -= len(rows) - self._alive[rows] = False + self._alive[rows - self._base] = False self._removed_count += len(rows) - if self._removed_count >= max(self.rows, _COMPACT_ROWS): + if not self.rows or self._removed_count >= max(self.rows, _COMPACT_ROWS): self._compact() def _compact(self) -> None: - """Drop the removed rows from the key frame.""" + """Drop the removed rows from the key frame, and the numbers below the rest.""" + self._removed_count = 0 + if not self.rows: + self._frames, self._base = [], self._spool.size + self._alive = np.ones(0, dtype=np.bool_) + return frame = self.frame() rows = frame.get_column(self.row).to_numpy() - self._frames = [frame.filter(pl.Series(self._alive[rows]))] - self._removed_count = 0 + kept = frame.filter(pl.Series(self._alive[rows - self._base])) + self._frames = [kept] + # The frame's rows are in the order of their numbers. + base = int(kept.get_column(self.row)[0]) + self._alive = self._alive[base - self._base :].copy() + self._base = base def clear(self) -> None: """Drop every row held, and their files.""" self._frames = [] self._alive = np.ones(0, dtype=np.bool_) - self._removed_count = 0 + self._removed_count, self._base = 0, 0 self._spool.close() self._spool = RowSpool() self.rows = 0 @@ -1797,7 +1809,8 @@ async def run_kernel( Every input is read at once and to its end, whatever the others do: the inputs may be two readers of one upstream, which a wait would block, and an input's read error - must be met. Each input reads ahead at most ``PUSH_ROWS`` rows and waits, and the + must be met. Each input reads ahead until it holds ``PUSH_ROWS`` rows + (its producer's last batch whole, whatever its size) and waits, and the output's batches are sent one at a time, so a slow reader of the output holds the join back. @@ -1869,7 +1882,7 @@ def __init__(self, changed: asyncio.Event) -> None: self._ended: bool = False async def fill(self, channel: RecordBatchInput, claim: object) -> None: - """Read ``channel`` to its end, waiting while ``PUSH_ROWS`` rows are unread.""" + """Read ``channel`` to its end, waiting while ``PUSH_ROWS`` rows or more are unread.""" try: _ = channel.reserve(claim) async for batch in channel: diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index b1cc18d68..33f65e679 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -5,11 +5,11 @@ from typing import TYPE_CHECKING, Any, ClassVar, TypeVar from orcapod import contexts +from orcapod.core.exact_class import reads_as_its_class from orcapod.core.unique_keys import NO_UNIQUE_KEYS, UniqueKeys, certificate from orcapod.config import OrcapodConfig from orcapod.core.streams.base import ( StreamBase, - reads_as_its_class, typed_arrow_schemas, typed_zero_row_table, ) @@ -395,7 +395,8 @@ def row_limit(self) -> int | None: Declared ``True`` only by the library source kinds whose rows all pass ``SourceStreamBuilder``, which names each row by its key columns and refuses a - repeat, each on its own class: read for the exact class only, never inherited. + repeat, each on its own class: read for the exact class only, never inherited, and + for an instance with no member replaced. """ @property @@ -405,7 +406,10 @@ def unique_keys(self) -> UniqueKeys: Two rows that agree on the key columns under the joins' equality have one record id, which is a function of the values (a key is never a float). """ - if vars(type(self)).get("KEY_COLUMNS_CHECKED") is not True: + kind = type(self) + if vars(kind).get("KEY_COLUMNS_CHECKED") is not True: + return NO_UNIQUE_KEYS + if not reads_as_its_class(self, kind): return NO_UNIQUE_KEYS key = frozenset(self._key_columns) if not key or not key <= set(self.keys()[0]): diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index b34dc2565..f9246bdb8 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1,7 +1,5 @@ from __future__ import annotations -import functools -import inspect import logging from abc import abstractmethod from collections import deque @@ -17,7 +15,7 @@ from contextlib import contextmanager from contextvars import ContextVar from datetime import datetime -from typing import TYPE_CHECKING, Any, cast +from typing import ClassVar, TYPE_CHECKING, Any, cast import pandas as pd import polars as pl @@ -54,37 +52,6 @@ logger = logging.getLogger(__name__) -def reads_as_its_class(obj: object, cls: type) -> bool: - """Whether ``obj`` is exactly ``cls`` and reads only through ``cls``'s own members. - - Exact, never by inspection of what a subclass overrides: ``type(obj) is cls``, and - ``obj`` holds no attribute of its own that shadows a method or a property of - ``cls`` (an ``iter_data`` replaced on the instance). A ``functools.cached_property`` - keeps its value in the instance by design and is not a shadow. A subclass, however - small, is never ``cls`` here (ITL-1347). - - Args: - obj: The object to check. - cls: The class whose reading is proven. - - Returns: - Whether ``obj`` reads as ``cls`` does. - """ - if type(obj) is not cls: - return False - own = getattr(obj, "__dict__", None) - if not own: - return True - missing = object() - for name in own: - member = inspect.getattr_static(cls, name, missing) - if member is missing or isinstance(member, functools.cached_property): - continue - if callable(member) or hasattr(type(member), "__get__"): - return False - return True - - def system_tags_as_rows_give(table: pa.Table) -> bool: """Whether every system-tag column is what the row rebuild gives: non-null text. @@ -1387,6 +1354,11 @@ def index( return Index(column, i, out=out, fail_on_miss=fail_on_miss)(self, label=label) + DERIVES_UNIQUE_KEYS: ClassVar[bool] = False + """Whether ``unique_keys`` is derived for this class: read for the exact class only, + each declaring it, and only while no member is replaced on the instance + (``core/unique_keys``).""" + @property def unique_keys(self) -> UniqueKeys: """The tag sets no two rows agree on (``core/unique_keys``). diff --git a/src/orcapod/core/unique_keys.py b/src/orcapod/core/unique_keys.py index 0096c6b24..0a429a7a7 100644 --- a/src/orcapod/core/unique_keys.py +++ b/src/orcapod/core/unique_keys.py @@ -10,8 +10,10 @@ tags. Every other stream derives its certificate from its inputs' by the rule its pod's class declares, at the time it is asked: nothing is stored on a stream, and nothing here enters a hash, an identity, a config, a stored row or equality. A rule is read from the -pod's exact class: a subclass, which may change the rows, certifies nothing unless it -declares a rule itself. +pod's exact class, and only for a pod and a stream that are exactly their classes, with +no member replaced on the instance (``reads_as_its_class``): a subclass or a customized +instance may give other rows, so it certifies nothing. A stream class takes part by +declaring ``DERIVES_UNIQUE_KEYS`` itself. """ from __future__ import annotations @@ -20,6 +22,8 @@ class declares, at the time it is asked: nothing is stored on a stream, and noth from contextvars import ContextVar from typing import Protocol +from orcapod.core.exact_class import reads_as_its_class + UniqueKeys = frozenset[frozenset[str]] NO_UNIQUE_KEYS: UniqueKeys = frozenset() @@ -92,6 +96,18 @@ def joined_keys( return certificate(keys) +def derives_unique_keys(stream: object) -> bool: + """Whether a stream's class takes part, and the stream is exactly of it. + + Args: + stream: A stream. + """ + kind = type(stream) + if vars(kind).get("DERIVES_UNIQUE_KEYS") is not True: + return False + return reads_as_its_class(stream, kind) + + class _HasKeys(Protocol): """What the certificate needs of the stream it is of.""" @@ -103,8 +119,9 @@ def derived_keys( ) -> UniqueKeys: """The certificate of ``stream``, the result of ``pod`` over ``upstreams``. - The pod's class declares its rule as a method ``derive_unique_keys(*upstreams)``; - without one on the exact class, nothing is certified. + The pod's class declares its rule as a method ``derive_unique_keys(*upstreams)``. + Nothing is certified without one on the exact class, or when the pod or the stream is + not exactly its class (module docstring). Args: pod: The producing pod. @@ -112,7 +129,9 @@ def derived_keys( stream: Its result, whose tags the keys must be among. """ rule = vars(type(pod)).get("derive_unique_keys") - if rule is None: + if rule is None or not reads_as_its_class(pod, type(pod)): + return NO_UNIQUE_KEYS + if not derives_unique_keys(stream): return NO_UNIQUE_KEYS memo = _MEMO.get() token = None diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 4280eefe0..874f91758 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -13,7 +13,7 @@ import datetime import logging from collections.abc import Callable, Collection, Iterator, Sequence -from typing import TYPE_CHECKING, Any, Literal, cast +from typing import ClassVar, TYPE_CHECKING, Any, Literal, cast import pyarrow as pa from typing_extensions import override @@ -130,6 +130,8 @@ class SideEffectPodStream(StreamBase): No invocation log is written in standalone mode (``pipeline_run_id=None``). """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def __init__( self, side_effect_pod: SideEffectPod, @@ -918,6 +920,8 @@ class SideEffectNode(StreamBase): label: Optional display label. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + node_type = "side_effect" def __init__( @@ -1101,6 +1105,8 @@ class SideEffectJobNode(RunHoldingNode, SideEffectNode): label: Optional display label. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def __init__( self, side_effect_pod: SideEffectPod, diff --git a/tests/test_core/operators/test_keys_only_joins.py b/tests/test_core/operators/test_keys_only_joins.py index f0379d207..de5087dd6 100644 --- a/tests/test_core/operators/test_keys_only_joins.py +++ b/tests/test_core/operators/test_keys_only_joins.py @@ -502,3 +502,87 @@ def test_a_random_arrival_of_everything_once_more(spooled: Path) -> None: batches = _run(kernel, _arrivals(tables, random.Random(seed))) got = pa.Table.from_batches(batches) if batches else None assert (_rows(got) if got is not None else {}) == expected + + +@pytest.mark.parametrize("spare", ["source", "operator"]) +def test_a_customized_input_that_repeats_a_key_loses_no_row( + spooled: Path, spare: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """Review of #565: the instance gives two rows of a key its class would refuse.""" + left = _source("a", {"k": [1], "n": [7]}, key=("k",)) + twice = _source("b", {"k": [1, 1], "m": [1, 2]}) + once = _source("b", {"k": [1], "m": [1]}, key=("k",)) + if spare == "source": + right: Any = once + right.as_table = twice.as_table + right.iter_data = twice.iter_data + else: + op: Any = SemiJoin() + op.binary_static_process = lambda *_: twice + right = op(once, once) + monkeypatch.setattr(streaming_joins, "PUSH_ROWS", 1) + join = Join() + output = OutputChannel(join(left, right)) + inputs = [left.open_channel(), right.open_channel()] + _bounded(join.async_execute_batches(inputs, output)) + assert output.result().as_table().num_rows == 2 + + +@pytest.mark.parametrize("op", [Join(), SemiJoin(), MergeJoin()], ids=lambda o: repr(o)) +def test_a_customized_join_keeps_its_own_computation(op: Any) -> None: + inputs = _one_to_one("tags_first") + original = op.static_process + + def first_row(*streams: StreamProtocol) -> StreamProtocol: + joined = original(*streams) + table = joined.as_table(columns={"source": True, "system_tags": True}) + return ArrowTableStream(table.slice(0, 1), tag_columns=joined.keys()[0]) + + op.static_process = first_row + output = OutputChannel(op(*inputs)) + _bounded(op.async_execute_batches([s.open_channel() for s in inputs], output)) + assert output.result().as_table().num_rows == 1 + + +def test_what_an_in_step_join_keeps_does_not_grow_with_the_rows_that_passed( + spooled: Path, +) -> None: + """Review of #565: the held-row mask was numbered from the first row ever held.""" + left, right = _sorted_source("a", 400), _sorted_source("b", 400) + kernel = StreamingJoin(Join(), [left, right]) + (link,) = kernel._links # pyright: ignore[reportPrivateUsage] # what it keeps + for mine, theirs in zip(_batches(left, 4), _batches(right, 4)): + _ = kernel.push(0, mine) + _ = kernel.push(1, theirs) + for side in link.sides: + assert len(side._alive) <= 8 # pyright: ignore[reportPrivateUsage] # what it keeps + assert sum(f.height for f in side._frames) <= 4 # pyright: ignore[reportPrivateUsage] # what it keeps + + +def test_rows_held_for_long_among_rows_that_pass_are_matched_at_the_end( + spooled: Path, +) -> None: + """The numbering is moved past removed rows while earlier and later ones are held.""" + n = 200 + left = _sorted_source("a", n) + right = _sorted_source("b", n) + kernel = _join([left, right]) + mine = _sent(left).sort_by("t") + theirs = _sent(right).sort_by("t") + waiting = [5, 6, 90, 150] + passing = [i for i in range(n) if i not in waiting] + got = 0 + for batch in mine.combine_chunks().to_batches(max_chunksize=10): + got += sum(b.num_rows for b in kernel.push(0, batch)) + low = batch.column("t")[0].as_py() + rows = [i for i in passing if low <= i < low + 10] + (part,) = theirs.take(pa.array(rows)).combine_chunks().to_batches() + got += sum(b.num_rows for b in kernel.push(1, part)) + assert got == len(passing) + assert kernel.held_rows == len(waiting) + (last,) = theirs.take(pa.array(waiting)).combine_chunks().to_batches() + out = pa.Table.from_batches(kernel.push(1, last)) + assert sorted(str(t) for t in out.column("t").to_pylist()) == sorted( + map(str, waiting) + ) + assert kernel.held_rows == 0 diff --git a/tests/test_core/test_unique_keys.py b/tests/test_core/test_unique_keys.py index 3d78ca5de..3339ea637 100644 --- a/tests/test_core/test_unique_keys.py +++ b/tests/test_core/test_unique_keys.py @@ -299,3 +299,66 @@ def test_the_algebra() -> None: assert joined_keys(a, _keys(("a",)), ["a"]) == _keys(("a",)) assert joined_keys(a, b, []) == _keys(("a", "b")) assert joined_keys(a, frozenset(), ["a"]) == frozenset() + + +# --------------------------------------------------------------------------- +# A customized instance certifies nothing: its rows may be other rows +# --------------------------------------------------------------------------- + + +def _replaced(obj: Any, name: str) -> Any: + """``obj`` with a method replaced on the instance (by an equal one).""" + original = getattr(obj, name) + setattr(obj, name, lambda *args, **kwargs: original(*args, **kwargs)) + return obj + + +@pytest.mark.parametrize("name", ["as_table", "iter_data", "open_channel", "keys"]) +def test_a_source_with_a_replaced_reader_certifies_nothing(name: str) -> None: + source = _replaced(_source(), name) + assert source.unique_keys == frozenset() + assert source.drop_nulls("x").unique_keys == frozenset() + assert SourceJobNode.from_stream(source).unique_keys == frozenset() + + +OPERATORS: list[Callable[[Any], Any]] = [ + lambda s: DropNulls("x"), + lambda s: s.filter(side="l").producer, + lambda s: s.group_by(["side"]).producer, + lambda s: s.map_tags(trial="t").producer, + lambda s: s.add_tags(k=1).producer, + lambda s: s.select_data_columns(["x"]).producer, +] + + +@pytest.mark.parametrize("make", OPERATORS) +@pytest.mark.parametrize("name", ["unary_static_process", "static_process"]) +def test_an_operator_with_a_replaced_body_certifies_nothing( + make: Callable[[Any], Any], name: str +) -> None: + assert make(_source())(_source()).unique_keys != frozenset() + assert _replaced(make(_source()), name)(_source()).unique_keys == frozenset() + + +def test_a_stream_or_node_with_a_replaced_reader_certifies_nothing() -> None: + assert _replaced(_source().drop_nulls("x"), "as_table").unique_keys == frozenset() + node = OperatorJobNode(DropNulls("x"), (SourceJobNode.from_stream(_source()),)) + assert node.unique_keys == _keys(KEY) + assert _replaced(node, "iter_data").unique_keys == frozenset() + slot = SourceJobNode.from_stream(_source()) + assert _replaced(slot, "as_table").unique_keys == frozenset() + + class MyNode(OperatorJobNode): + pass + + own = MyNode(DropNulls("x"), (SourceJobNode.from_stream(_source()),)) + assert own.unique_keys == frozenset() + + +def test_a_function_pod_with_a_replaced_call_certifies_nothing() -> None: + @function_pod(output_keys="total") + def add(x: float | None, y: int | None) -> float: + return (x or 0.0) + (y or 0) + + assert add.pod(_source()).unique_keys == _keys(KEY) + assert _replaced(add.pod, "process_data")(_source()).unique_keys == frozenset() From 7062127c1d3ebb05fb3acd3a171ece0063e0914e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:16:53 -0800 Subject: [PATCH 16/26] fix(core): the carried read is private and exact; hashes and stores refuse recipes (ITL-1464) Review of PRs 563 and 564. Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-tokens.md | 27 ++- src/orcapod/core/nodes/source_node.py | 6 - src/orcapod/core/operators/add_tags.py | 7 +- .../core/operators/column_selection.py | 35 +++- src/orcapod/core/operators/drop_nulls.py | 7 +- src/orcapod/core/operators/filter.py | 7 +- src/orcapod/core/operators/filters.py | 6 +- src/orcapod/core/operators/mappers.py | 21 +- src/orcapod/core/operators/meta_columns.py | 5 +- .../core/operators/static_output_pod.py | 35 +++- src/orcapod/core/operators/tag_by.py | 7 +- .../core/sources/arrow_table_source.py | 1 + src/orcapod/core/sources/base.py | 17 +- src/orcapod/core/sources/csv_source.py | 1 + src/orcapod/core/sources/data_frame_source.py | 1 + src/orcapod/core/sources/db_table_source.py | 1 + .../core/sources/delta_table_source.py | 1 + src/orcapod/core/sources/derived_source.py | 7 +- src/orcapod/core/sources/dict_source.py | 1 + src/orcapod/core/sources/list_source.py | 1 + .../core/sources/postgresql_table_source.py | 1 + .../core/sources/spiraldb_table_source.py | 11 +- .../core/sources/sqlite_table_source.py | 1 + .../core/streams/arrow_table_stream.py | 9 +- src/orcapod/core/streams/base.py | 12 -- src/orcapod/core/streams/carried.py | 46 +++++ .../databases/connector_arrow_database.py | 2 + src/orcapod/databases/delta_lake_databases.py | 3 +- src/orcapod/databases/in_memory_databases.py | 2 + src/orcapod/hashing/arrow_hashers.py | 3 + .../protocols/core_protocols/streams.py | 11 -- src/orcapod/utils/source_tokens.py | 15 +- tests/test_core/streams/test_source_tokens.py | 186 ++++++++++++++++-- 33 files changed, 379 insertions(+), 117 deletions(-) create mode 100644 src/orcapod/core/streams/carried.py diff --git a/docs/dev/specs/itl-1464-tokens.md b/docs/dev/specs/itl-1464-tokens.md index 7473d3954..c15c94a0d 100644 --- a/docs/dev/specs/itl-1464-tokens.md +++ b/docs/dev/specs/itl-1464-tokens.md @@ -30,17 +30,26 @@ system-tag column names of the same table, and the column's name at the source. - Text is made in one function, `materialize`, at most 65,536 rows at a time. A derived column is loud where it does not belong: reading a value, casting to text, -hashing, pickling and writing Parquet (so Delta) each raise. +hashing, pickling, storing and writing Parquet each raise. ## Where a derived table can go -`StreamProtocol.as_carried_table(columns=)` is the internal read: the table of `as_table` -with derived columns left as they are. Only library operators call it. The default is -`as_table` (text), so a user's operator, source or stream, and every job node today, is -given and gives text. `ArrowTableStream`, `DynamicPodStream`, and the sources over a held -or scanned table answer it without text. `as_table` with any columns, `iter_data`, `head`, -`run`, the data frame methods and the identity table give text, as before. A read without -the system tags gives text (the recipe would have nothing to read). +`core/streams/carried.py` holds the internal read, `carried_table(stream, columns)`: the +table of `as_table` with derived columns left as they are. It is a private library function, +no part of a stream's interface. Both ends are exact: + +- the stream: its own class declares `_carried_table` (the library's `ArrowTableStream`, + `DynamicPodStream` and source kinds), and the object reads as that class + (`reads_as_its_class`). A subclass, a replaced `as_table` and a user's stream are read + through `as_table`, and give text; +- the reader: an operator whose own class declares `CARRIES_TOKENS`, through + `StaticOutputOperatorPod._input_table`. A user's operator, also a subclass of a library + one, reads text. + +`as_table` with any columns, `iter_data`, `head`, `run`, the data frame methods and the +identity table give text, as before, and so does a read without the system tags (the recipe +would have nothing to read). The Arrow hashers (schemas, and tables without rows too) and +every database's `add_records` refuse a derived column by name (`refuse_derived`). ## Producers of `_source_` columns @@ -72,7 +81,7 @@ the system tags gives text (the recipe would have nothing to read). | `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 | | `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 `as_carried_table` | +| Job nodes (`core/nodes/*`) | the stored text; the kept table | text until the transport calls `carried_table` | | Function node pipeline table, result table, operator and source caches | stored text | unchanged: they read rows or `as_table` | | Record-batch channels, streaming joins | types, values | unchanged (text) | | Provenance trace (`pipeline/provenance.py`) | text | unchanged | diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 2fc8678fd..b6b8bc0f6 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1271,12 +1271,6 @@ def run(self) -> StreamView: display_all_rows=False, ) - def as_carried_table( - self, *, columns: ColumnConfig | dict[str, Any] | None = None - ) -> "pa.Table": - """The table of ``as_table(columns=columns)``; see ``StreamProtocol`` (ITL-1464).""" - return self.as_table(columns=columns) - def open_channel(self) -> RecordBatchInput: """Open an input channel on this node's rows, for async computation (ITL-1347). diff --git a/src/orcapod/core/operators/add_tags.py b/src/orcapod/core/operators/add_tags.py index efedd2592..812fcdf1a 100644 --- a/src/orcapod/core/operators/add_tags.py +++ b/src/orcapod/core/operators/add_tags.py @@ -116,6 +116,8 @@ class AddTags(UnaryOperator): ``::`` separator). """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). PROVISIONAL: ClassVar[bool] = True @@ -322,13 +324,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ tag_keys, _ = stream.keys() data_context = stream.data_context # pyright: ignore[reportAttributeAccessIssue] # StreamProtocol omits data_context, which every concrete stream provides (ITL-844) - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) return ArrowTableStream( self._with_constants(table, tag_keys, data_context.type_converter), diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index 9cfd73cbd..964f5f838 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -57,6 +57,8 @@ class SelectTagColumns(UnaryOperator): Operator that selects specified columns from a stream. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True @@ -90,13 +92,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("All tag columns are selected. Returning stream unaltered.") return stream - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) # A dropped data-tag leaves its column as plain data (specification @@ -196,6 +199,8 @@ class SelectDataColumns(UnaryOperator): Operator that selects specified columns from a stream. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True @@ -229,7 +234,8 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("All data columns are selected. Returning stream unaltered.") return stream - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, @@ -352,6 +358,8 @@ class DropTagColumns(UnaryOperator): Operator that drops specified columns from a stream. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True @@ -388,13 +396,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("No tag columns to drop. Returning stream unaltered.") return stream - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) # A dropped data-tag leaves its column as plain data (specification @@ -496,6 +505,8 @@ class DropDataColumns(UnaryOperator): Operator that drops specified columns from a stream. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True @@ -534,13 +545,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: associated_source_columns = [ f"{constants.SOURCE_PREFIX}{c}" for c in columns_to_drop ] - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) # A data-tag whose data column is removed keeps its column as a plain # tag with the same values (specification section 7.2). @@ -774,13 +786,14 @@ def validate_unary_input(self, stream: StreamProtocol) -> None: def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: tag_columns, data_columns = self._user_columns(stream) tags_removed, data_removed = self._removals(tag_columns, data_columns) - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) removed = { *tags_removed, @@ -881,6 +894,8 @@ class DropColumns(_TagAndDataColumnsOperator): be dropped: a stream needs at least one data column. """ + CARRIES_TOKENS: ClassVar[bool] = True + _verb: ClassVar[str] = "drop" def _removed(self, columns: Collection[str]) -> list[str]: @@ -905,6 +920,8 @@ class SelectColumns(_TagAndDataColumnsOperator): named: a stream needs at least one data column. """ + CARRIES_TOKENS: ClassVar[bool] = True + _verb: ClassVar[str] = "select" def _removed(self, columns: Collection[str]) -> list[str]: diff --git a/src/orcapod/core/operators/drop_nulls.py b/src/orcapod/core/operators/drop_nulls.py index 028bcfa8c..03780ede0 100644 --- a/src/orcapod/core/operators/drop_nulls.py +++ b/src/orcapod/core/operators/drop_nulls.py @@ -90,6 +90,8 @@ class DropNulls(UnaryOperator): ValueError: If ``columns`` is an empty collection. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True @@ -316,13 +318,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: A stream over the surviving rows, in input order, with the named columns non-nullable. A result with no rows has the same schema. """ - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) tag_columns, data_columns = stream.keys() return ArrowTableStream( diff --git a/src/orcapod/core/operators/filter.py b/src/orcapod/core/operators/filter.py index b8e3621e1..7f80fe975 100644 --- a/src/orcapod/core/operators/filter.py +++ b/src/orcapod/core/operators/filter.py @@ -74,6 +74,8 @@ class Filter(UnaryOperator): TypeError: If ``condition`` is neither a condition nor a mapping. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): a data-tag is one column, named alike as tag or data. DATA_TAGS_ISSUE: ClassVar[str | None] = None @@ -243,13 +245,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ # Every system column passes through: source info, system tags and each row's # data context (a raw stream may hold several). - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) tag_columns, data_columns = stream.keys() self._check_arrow(table.schema, _user_columns(tag_columns, data_columns)) diff --git a/src/orcapod/core/operators/filters.py b/src/orcapod/core/operators/filters.py index 491fa79b9..e0de9aad8 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -40,6 +40,8 @@ class PolarsFilter(UnaryOperator): Operator that applies Polars filtering to a stream """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. DATA_TAGS_ISSUE: ClassVar[str | None] = None @@ -71,8 +73,8 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: return stream # TODO: improve efficiency here... - whole = stream.as_carried_table( - columns={"source": True, "system_tags": True, "sort_by_tags": False} + whole = self._input_table( + stream, columns={"source": True, "system_tags": True, "sort_by_tags": False} ) # Polars reads no derived token column: one is left out, and put back for the # rows kept (its recipe reads the system tags kept with them, ITL-1464), unless diff --git a/src/orcapod/core/operators/mappers.py b/src/orcapod/core/operators/mappers.py index 184f66252..47cbde20b 100644 --- a/src/orcapod/core/operators/mappers.py +++ b/src/orcapod/core/operators/mappers.py @@ -91,6 +91,8 @@ class MapData(UnaryOperator): ``SelectTagColumns`` and the other column operators. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True @@ -179,13 +181,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: # nothing to rename in the data, return stream as is return stream - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) # A data-tag column keeps its tag under its own name, now plain; the @@ -365,6 +368,8 @@ class MapTags(UnaryOperator): tag_only: Rename data-tags in the tag role only. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). PROVISIONAL: ClassVar[bool] = True @@ -457,13 +462,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: # nothing to rename or drop in the tags, return stream as is return stream - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) name_map = { @@ -664,6 +670,8 @@ class MapColumns(UnaryOperator): or (with ``drop_unmapped``) no data column would remain. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True @@ -799,13 +807,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: tag_renames, data_renames, tags_dropped, data_dropped = self._plan( tag_columns, data_columns ) - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) dropped = { *tags_dropped, diff --git a/src/orcapod/core/operators/meta_columns.py b/src/orcapod/core/operators/meta_columns.py index a2312b830..fd6a7b00f 100644 --- a/src/orcapod/core/operators/meta_columns.py +++ b/src/orcapod/core/operators/meta_columns.py @@ -19,6 +19,7 @@ from orcapod.channels import WritableChannel from orcapod.core.data_tags import stream_data_tags, with_data_tags_first +from orcapod.core.streams.carried import carried_table from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants @@ -112,8 +113,8 @@ def without_input_meta( """ if not _carries_meta(stream, inputs): return stream - table = stream.as_carried_table( - columns={"source": True, "system_tags": True, "context": True} + table = carried_table( + stream, {"source": True, "system_tags": True, "context": True} ) tag_columns = stream.keys()[0] return ArrowTableStream( diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 845a7d6a7..c17ec38ad 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -43,6 +43,7 @@ from orcapod.utils import source_tokens from orcapod.utils.provisional import note_provisional_use, provisional_class_name from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.carried import carried_table from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, StreamBase, @@ -118,6 +119,14 @@ class StaticOutputOperatorPod(TraceableBase): (``async_execute_batches``); every other operator needs all of an input first. """ + CARRIES_TOKENS: ClassVar[bool] = False + """Whether the operator passes derived token columns on (ITL-1464). + + Declared by a library operator that never reads the values of a source-info column + it passes on, or builds their text itself. It holds for exactly the class that + declares it, never for a subclass (``_input_table``). + """ + OUTPUT_SCHEMA_IS_INPUT_SCHEMA: ClassVar[bool] = False """Whether the output has exactly its single input's columns and Arrow types. @@ -221,6 +230,24 @@ def check_data_tag_support(self, *streams: StreamProtocol) -> None: if any(stream_data_tags(stream) for stream in streams): raise not_supported_yet(type(self).__name__, self.DATA_TAGS_ISSUE) + def _input_table( + self, stream: StreamProtocol, columns: dict[str, Any] + ) -> "pa.Table": + """The table of ``stream`` as this operator reads it. + + Derived token columns as they are (``carried_table``) for an operator whose class + declares ``CARRIES_TOKENS`` itself and is used as that class; text for any other, + so a user's operator, also one that subclasses a library operator, reads text. + + Args: + stream: An input stream. + columns: The column groups, as for ``as_table``. + """ + kind = type(self) + if vars(kind).get("CARRIES_TOKENS") is True and reads_as_its_class(self, kind): + return carried_table(stream, columns) + return stream.as_table(columns=columns) + def pipeline_identity_structure(self) -> Any: """Return the pipeline identity, which defaults to content identity for operators.""" return self.identity_structure() @@ -1751,6 +1778,8 @@ class _RowsOfStream(ArrowTableStream): data_context: The rows' data context; ``None`` for the default. """ + _carried_table = ArrowTableStream._carried_table # pyright: ignore[reportPrivateUsage] # read as its base is + def __init__( self, table: pa.Table, @@ -2049,15 +2078,13 @@ def as_table( ) return self._cached_stream.as_table(columns=columns, all_info=all_info) - def as_carried_table( - self, *, columns: ColumnConfig | dict[str, Any] | None = None - ) -> "pa.Table": + def _carried_table(self, config: ColumnConfig) -> "pa.Table": """The operator's result, derived token columns as they are (ITL-1464).""" self._refresh() assert self._cached_stream is not None, ( "StreamProtocol has not been updated or is empty." ) - return self._cached_stream.as_carried_table(columns=columns) + return carried_table(self._cached_stream, config) def iter_data( self, diff --git a/src/orcapod/core/operators/tag_by.py b/src/orcapod/core/operators/tag_by.py index a7cbe5f7a..7a9dfffae 100644 --- a/src/orcapod/core/operators/tag_by.py +++ b/src/orcapod/core/operators/tag_by.py @@ -73,6 +73,8 @@ class TagBy(UnaryOperator): column name, or one holding ``::``. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). PROVISIONAL: ClassVar[bool] = True @@ -209,13 +211,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ tag_columns, _ = stream.keys() # The context column too, so each row keeps its own data context key. - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) return ArrowTableStream( table, diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index f05485472..d70b3f1f9 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -92,6 +92,7 @@ class ArrowTableSource(RootSource): # The version of this kind's implementation, in the kind part (ITL-1425). SOURCE_VERSION: ClassVar[int] = 1 TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 100d67285..2fad18ee3 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -6,6 +6,7 @@ from orcapod import contexts from orcapod.config import OrcapodConfig +from orcapod.core.streams.carried import carried_table from orcapod.core.streams.base import ( StreamBase, reads_as_its_class, @@ -537,18 +538,14 @@ def as_table( """Delegate to the underlying stream's as_table.""" return self._stream.as_table(columns=columns, all_info=all_info) - def as_carried_table( - self, *, columns: ColumnConfig | dict[str, Any] | None = None - ) -> "pa.Table": - """The underlying stream's table, derived token columns as they are (ITL-1464). + def _carried_from_stream(self, config: ColumnConfig) -> "pa.Table": + """``as_table`` above, derived token columns as they are (ITL-1464). - A source that reads its rows its own way (a subclass, or an object, with its own - ``as_table``) gives that table. + What a source kind that reads through ``_stream`` declares as its + ``_carried_table`` (``core/streams/carried.py``). """ - if type(self).as_table is RootSource.as_table and "as_table" not in vars(self): - stream: StreamBase = getattr(self, "_stream") # noqa: B009 # set by each subclass - return stream.as_carried_table(columns=columns) - return super().as_carried_table(columns=columns) + stream: StreamBase = getattr(self, "_stream") # noqa: B009 # set by each subclass + return carried_table(stream, config) # ------------------------------------------------------------------------- # The start-of-run check (ITL-1102) diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index f39681d9e..095fcce76 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -280,6 +280,7 @@ class CSVSource(RootSource): SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 6c65bf64d..0f41f442f 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -47,6 +47,7 @@ class DataFrameSource(RootSource): # The version of this kind's implementation, in the kind part (ITL-1425). SOURCE_VERSION: ClassVar[int] = 1 TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 86ea349d5..b50ad5e6a 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -84,6 +84,7 @@ class DBTableSource(RootSource): SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 239c00191..608c783ae 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -53,6 +53,7 @@ class DeltaTableSource(RootSource): SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index ab1a585b1..6ae376410 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -23,6 +23,7 @@ normalize_record_id_columns, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.carried import carried_table from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -813,8 +814,6 @@ def as_table( ) -> "pa.Table": return self._get_stream().as_table(columns=columns, all_info=all_info) - def as_carried_table( - self, *, columns: ColumnConfig | dict[str, Any] | None = None - ) -> "pa.Table": + def _carried_table(self, config: ColumnConfig) -> "pa.Table": """The source's table, derived token columns as they are (ITL-1464).""" - return self._get_stream().as_carried_table(columns=columns) + return carried_table(self._get_stream(), config) diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index fdf7c1f34..0cbdbcf1a 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -43,6 +43,7 @@ class DictSource(RootSource): # The version of this kind's implementation, in the kind part (ITL-1425). SOURCE_VERSION: ClassVar[int] = 1 TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index f18da3433..2902262cb 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -42,6 +42,7 @@ def _default_tag(element: Any, idx: int) -> dict[str, Any]: # The version of this kind's implementation, in the kind part (ITL-1425). SOURCE_VERSION: ClassVar[int] = 1 TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index 58acc1f17..e7585811e 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -176,6 +176,7 @@ class PostgreSQLTableSource(DBTableSource): SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = DBTableSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index b1dba51bb..f3b1241fb 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -62,6 +62,7 @@ row_identifiers, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.carried import carried_table from orcapod.core.streams.base import StreamBase, check_head_size from orcapod.core.streams.view import ViewStatus, StreamView from orcapod.databases.spiraldb_connector import ( @@ -963,20 +964,16 @@ def as_table( columns=columns, all_info=all_info ) - def as_carried_table( - self, *, columns: ColumnConfig | dict[str, Any] | None = None - ) -> "pa.Table": + def _carried_table(self, config: ColumnConfig) -> "pa.Table": """Scan the table as ``as_table`` does, building no source-info text (ITL-1464).""" - return self._whole_stream(self._batch_streams()).as_carried_table( - columns=columns - ) + return carried_table(self._whole_stream(self._batch_streams()), config) def _whole_stream(self, streams: Iterator["ArrowTableStream"]) -> StreamBase: """Return the rows of ``streams`` (batches of one read) as one stream.""" # One stream over all the rows, so that a whole-table option (sorting by # tags) applies across batches. enriched = {"source": True, "system_tags": True} - tables = [stream.as_carried_table(columns=enriched) for stream in streams] + tables = [carried_table(stream, enriched) for stream in streams] if not tables: return self._stream return ArrowTableStream( diff --git a/src/orcapod/core/sources/sqlite_table_source.py b/src/orcapod/core/sources/sqlite_table_source.py index eab59a821..b197e8c2a 100644 --- a/src/orcapod/core/sources/sqlite_table_source.py +++ b/src/orcapod/core/sources/sqlite_table_source.py @@ -105,6 +105,7 @@ class SQLiteTableSource(DBTableSource): SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = DBTableSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 09f1b1d4e..4860839f1 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -354,11 +354,8 @@ def as_table( columns_config = ColumnConfig.handle_config(columns, all_info=all_info) return self._assemble_table(columns_config, limit=None) - def as_carried_table( - self, *, columns: ColumnConfig | dict[str, Any] | None = None - ) -> "pa.Table": - """The table with its derived token columns as they are (ITL-1464).""" - config = ColumnConfig.handle_config(columns) + def _carried_table(self, config: ColumnConfig) -> "pa.Table": + """The table with its derived token columns as they are (``carried_table``).""" return self._assemble_table(config, limit=None, carried=config.system_tags) def head( @@ -405,7 +402,7 @@ def _assemble_table( Args: columns_config: The column groups to include, and whether to sort by tags. limit: Assemble only the first ``limit`` rows; ``None`` for all of them. - carried: Leave a derived token column derived (``as_carried_table``), which + carried: Leave a derived token column derived (``carried_table``), which needs the system tags in the table; ``False`` gives its text. """ output_table = self._table diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 833a17347..eeaa7a16f 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1514,18 +1514,6 @@ def as_table( all_info: bool = False, ) -> "pa.Table": ... - def as_carried_table( - self, *, columns: ColumnConfig | dict[str, Any] | None = None - ) -> "pa.Table": - """The table of ``as_table(columns=columns)``, as operators pass it on. - - A source-info column may be derived (``utils/source_tokens.py``): a recipe over - the table's system tags in place of its text, which ``source_tokens.materialize`` - builds. Internal: never stored, hashed or shown (ITL-1464). A stream that holds - none gives ``as_table``. - """ - return self.as_table(columns=columns) - def as_polars_df( self, *, diff --git a/src/orcapod/core/streams/carried.py b/src/orcapod/core/streams/carried.py new file mode 100644 index 000000000..5fca2f948 --- /dev/null +++ b/src/orcapod/core/streams/carried.py @@ -0,0 +1,46 @@ +"""Reading a stream's table with its derived token columns as they are (ITL-1464). + +``carried_table`` is how the library's own operators read their inputs: the table of +``as_table``, where a source-info column may be a recipe in place of its text +(``utils/source_tokens.py``). It is no part of a stream's interface. Only a stream whose +class is a library class that declares ``_carried_table`` itself, read as that class +(``reads_as_its_class``: no subclass, nothing replaced on the object), is read this way; +every other stream, a subclass with its own ``as_table`` or a user's stream, is read +through ``as_table`` and gives text. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from orcapod.core.streams.base import reads_as_its_class +from orcapod.types import ColumnConfig + +if TYPE_CHECKING: + import pyarrow as pa + + from orcapod.protocols.core_protocols import StreamProtocol + +CARRIED_TABLE = "_carried_table" +"""The method a library class declares when its table may hold derived columns.""" + + +def carried_table( + stream: StreamProtocol, + columns: ColumnConfig | dict[str, Any], # pyright: ignore[reportExplicitAny] # as as_table +) -> pa.Table: + """``stream.as_table(columns=columns)``, derived token columns as they are. + + Args: + stream: The stream. + columns: The column groups, as for ``as_table``. + + Returns: + The table, for library code that passes it on; never for a user, a user's + operator or function, a store or a hash. + """ + kind = type(stream) + read: Any = vars(kind).get(CARRIED_TABLE) # pyright: ignore[reportExplicitAny] # a method + if read is None or not reads_as_its_class(stream, kind): + return stream.as_table(columns=columns) + return read(stream, ColumnConfig.handle_config(columns)) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 6ae7f757c..20b4421b1 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -27,6 +27,7 @@ import pyarrow as pa import pyarrow.compute as pc +from orcapod.utils import source_tokens from orcapod.databases._pending_commits import PendingCommit, PendingCommits from orcapod.databases.utils import ( coerce_record_id, @@ -438,6 +439,7 @@ def add_records( ) -> None: """Add multiple records to the pending batch.""" self._validate_record_path(record_path) + source_tokens.refuse_derived(records.schema) if records.num_rows == 0: return diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index c88b322d8..e369b1735 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -63,7 +63,7 @@ TypeIdentityError, UnstorableColumnError, ) -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: @@ -2747,6 +2747,7 @@ def add_records( ValueError: If any record IDs already exist and skip_duplicates=False """ self._validate_record_path(record_path) + source_tokens.refuse_derived(records.schema) if records.num_rows == 0: return diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 2ccb4d696..92b270874 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -9,6 +9,7 @@ import pyarrow as pa import pyarrow.compute as pc +from orcapod.utils import source_tokens from orcapod.databases._pending_commits import PendingCommit, PendingCommits from orcapod.databases._row_index import KeyIndex, compact_tail, matching_rows from orcapod.databases.utils import ( @@ -242,6 +243,7 @@ def add_records( flush: bool = False, ) -> None: self._validate_record_path(record_path) + source_tokens.refuse_derived(records.schema) if records.num_rows == 0: return diff --git a/src/orcapod/hashing/arrow_hashers.py b/src/orcapod/hashing/arrow_hashers.py index cf520d9f8..800086a68 100644 --- a/src/orcapod/hashing/arrow_hashers.py +++ b/src/orcapod/hashing/arrow_hashers.py @@ -18,6 +18,7 @@ from orcapod.logical_types.identifier import LogicalTypeIdentifierError from orcapod.hashing.visitors import SemanticHashingVisitor from orcapod.logical_types.canonical_form import storage_form_schema +from orcapod.utils import source_tokens from orcapod.utils.arrow_utils import normalize_extension_columns from orcapod.types import ContentHash @@ -231,6 +232,7 @@ def hash_schema(self, schema: "pa.Schema") -> ContentHash: column that keeps the identifier, so ``hash_schema(table.schema)`` is not the schema inside ``hash_table(table)``, and nothing may rely on it. """ + source_tokens.refuse_derived(schema) schema = storage_form_schema(schema) include_meta = has_extension_metadata(schema) or has_extension_type(schema) if include_meta: @@ -329,6 +331,7 @@ def _digest( Returns: The starfix digest (version prefix included). """ + source_tokens.refuse_derived(table.schema) if isinstance(table, pa.RecordBatch): table = pa.Table.from_batches([table]) diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index b35e38beb..c8c72abd6 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -255,17 +255,6 @@ def async_iter_data(self) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: """ ... - def as_carried_table( - self, *, columns: ColumnConfig | dict[str, Any] | None = None - ) -> "pa.Table": - """The table of ``as_table(columns=columns)``, as operators pass it on. - - A source-info column may be derived (``utils/source_tokens.py``): a recipe over - the table's system tags in place of its text. Internal: never stored, hashed or - shown (ITL-1464). - """ - ... - def as_table( self, *, diff --git a/src/orcapod/utils/source_tokens.py b/src/orcapod/utils/source_tokens.py index 0fd59bcfc..915586db3 100644 --- a/src/orcapod/utils/source_tokens.py +++ b/src/orcapod/utils/source_tokens.py @@ -9,7 +9,7 @@ column as any other; nothing is computed until the text is needed (``materialize``). A derived column is an internal form of a table that operators pass on -(``StreamProtocol.as_carried_table``). It never leaves the library: ``as_table``, rows, +(``core/streams/carried.py``). It never leaves the library: ``as_table``, rows, stored tables and everything hashed hold the text. A place that forgets fails loudly: no value of a derived column can be read, cast to text, hashed, pickled, or written to Parquet (its storage is a struct with no field, which Parquet refuses). @@ -154,6 +154,19 @@ 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 refuse_derived(schema: pa.Schema) -> None: + """Raise if a column of ``schema`` is derived: hashes and stores take text only. + + Raises: + TypeError: Naming the derived columns. + """ + if derived := derived_columns(schema): + raise TypeError( + f"columns {list(derived)} are derived source-info tokens: their text must " + + "be built first (source_tokens.materialize)" + ) + + def materialize(table: pa.Table, names: Collection[str] | None = None) -> pa.Table: """Return ``table`` with its derived token columns as text. diff --git a/tests/test_core/streams/test_source_tokens.py b/tests/test_core/streams/test_source_tokens.py index 40eb740ea..c87163199 100644 --- a/tests/test_core/streams/test_source_tokens.py +++ b/tests/test_core/streams/test_source_tokens.py @@ -9,6 +9,7 @@ import pickle from collections.abc import Callable +from pathlib import Path from typing import Any import polars as pl @@ -22,8 +23,14 @@ from orcapod.core.operators.base import UnaryOperator from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.carried import carried_table from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS -from orcapod.databases import InMemoryArrowDatabase +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + InMemoryArrowDatabase, + SQLiteConnector, +) from orcapod.operators import ( AddTags, DropColumns, @@ -36,7 +43,8 @@ SelectDataColumns, TagBy, ) -from orcapod.sources import ArrowTableSource, CachedSource +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.sources import ArrowTableSource, CachedSource, SpiralDBTableSource from orcapod.system_constants import constants from orcapod.utils import arrow_utils, source_tokens from tests.test_core.operators.test_async_sync_equivalence import ( @@ -45,6 +53,7 @@ Case, ) from tests.test_core.operators.test_row_built_form import assert_same_values +from tests.test_databases import fake_spiral_sdk as fake CARRIED = {"source": True, "system_tags": True, "context": True} @@ -115,6 +124,9 @@ def _derived(table: pa.Table) -> tuple[str, ...]: "select_data": lambda: SelectDataColumns(["y"])(_source()), "drop_tags": lambda: DropTagColumns(["k"])(_source()), "drop_columns": lambda: DropColumns(["k", "x"])(_source()), + "select_columns": lambda: _source().select_columns(["k", "y"]), + "select_tags": lambda: _source().select_tag_columns(["k"]), + "drop_data": lambda: _source().drop_data_columns(["y"]), "add_tags": lambda: AddTags({"b": 1, "a": "q"})(_source()), "tag_by": lambda: TagBy(["x"])(DropNulls(["x"])(_plain_source())), "chain": lambda: ( @@ -132,7 +144,7 @@ def test_a_row_wise_operator_carries_the_tokens_and_gives_the_same_rows( name: str, text_sources: Callable[[], None] ) -> None: result = ROW_WISE[name]() - carried = result.as_carried_table(columns=CARRIED) + carried = carried_table(result, CARRIED) tokens = [c for c in carried.column_names if c.startswith(constants.SOURCE_PREFIX)] assert tokens and set(_derived(carried)) == set(tokens) table = result.as_table(all_info=True) @@ -141,7 +153,7 @@ def test_a_row_wise_operator_carries_the_tokens_and_gives_the_same_rows( text_sources() oracle = ROW_WISE[name]() expected = oracle.as_table(all_info=True) - assert not _derived(oracle.as_carried_table(columns=CARRIED)) + assert not _derived(carried_table(oracle, CARRIED)) assert table.schema.equals(expected.schema, check_metadata=True) assert_same_values(table, expected) assert rows == [ @@ -160,7 +172,7 @@ def test_every_operator_gives_what_text_sources_give( F (the table a job node hands on) of the carried form.""" result = case.make_op()(*case.make_sources()) table = result.as_table(all_info=True) - carried = result.as_carried_table(columns=ZERO_ROW_INPUT_COLUMNS) + carried = carried_table(result, ZERO_ROW_INPUT_COLUMNS) plain = result.as_table(columns=ZERO_ROW_INPUT_COLUMNS) built = source_tokens.materialize(carried) assert built.schema.equals(plain.schema, check_metadata=True) @@ -211,7 +223,7 @@ def test_no_public_read_gives_a_derived_column(make: Callable[[], Any]) -> None: def test_a_table_without_its_system_tags_holds_text() -> None: """The recipe reads the system tags, so a table without them is never carried.""" for config in ({"source": True}, {"source": True, "context": True}): - table = _source().as_carried_table(columns=config) + table = carried_table(_source(), config) assert not _derived(table) assert table.column("_source_x").type == pa.large_string() @@ -320,7 +332,7 @@ def stored() -> pa.Table: def test_a_derived_column_that_leaks_is_an_error() -> None: - carried = _source().as_carried_table(columns=CARRIED) + carried = carried_table(_source(), CARRIED) tokens = carried.column("_source_x") with pytest.raises(TypeError, match="no value"): _ = tokens.to_pylist() @@ -330,13 +342,47 @@ def test_a_derived_column_that_leaks_is_an_error() -> None: _ = pickle.dumps(carried) with pytest.raises(pa.ArrowNotImplementedError): pq.write_table(carried, pa.BufferOutputStream()) - with pytest.raises(Exception, match="no value|derived"): - _ = contexts.get_default_context().arrow_hasher.hash_table(carried) + hasher = contexts.get_default_context().arrow_hasher + for hash_it in ( + lambda: hasher.hash_table(carried), + lambda: hasher.hash_table(carried.slice(0, 0)), + lambda: hasher.hash_schema(carried.schema), + lambda: hasher.hash_table_strict(carried), + lambda: hasher.hash_table_ordered(carried), + ): + with pytest.raises(TypeError, match="derived"): + _ = hash_it() + + +@pytest.mark.parametrize("rows", [0, 3]) +@pytest.mark.parametrize("kind", ["memory", "delta", "connector"]) +def test_a_store_refuses_a_derived_column(kind: str, rows: int, tmp_path: Path) -> None: + carried = carried_table(_source(), CARRIED).slice(0, rows) + records = carried.append_column( + "rid", pa.array([str(i).encode() for i in range(rows)], pa.large_binary()) + ) + databases: dict[str, Callable[[], Any]] = { + "memory": InMemoryArrowDatabase, + "delta": lambda: DeltaTableDatabase(str(tmp_path / "delta")), + "connector": lambda: ConnectorArrowDatabase( + SQLiteConnector(str(tmp_path / "store.db")) + ), + } + database = databases[kind]() + with pytest.raises(TypeError, match="derived"): + database.add_records(("t",), records, record_id_column="rid", flush=True) + + +def test_the_carried_read_is_no_part_of_a_stream() -> None: + """Review of PR 563: no public name gives a derived column.""" + for stream in (_source(), ROW_WISE["chain"]()): + assert not [n for n in dir(stream) if "carried" in n and not n.startswith("_")] + assert "carried" not in " ".join(dir(StreamProtocol)) def test_a_spilled_table_keeps_its_recipes() -> None: """As the row spool writes it: an extension column's storage, wrapped when read.""" - carried: Any = _source().as_carried_table(columns=CARRIED).combine_chunks() + carried: Any = carried_table(_source(), CARRIED).combine_chunks() arrow: Any = pa batch: Any = carried.to_batches()[0] storage = arrow.RecordBatch.from_arrays( @@ -363,7 +409,7 @@ def test_a_spilled_table_keeps_its_recipes() -> None: def test_a_carried_column_has_no_bytes_and_is_not_null() -> None: - carried = _source().as_carried_table(columns=CARRIED) + carried = carried_table(_source(), CARRIED) taken = carried.take(pa.array([1, 5])).filter(pc.field("k") > 1) for table in (carried, taken, pa.concat_tables([carried, taken]).combine_chunks()): for name in _derived(table): @@ -394,7 +440,7 @@ def test_extended_system_tag_names_are_followed_and_sorting_builds_the_text() -> ) tables = [ arrow_utils.append_to_system_tags( - s.as_carried_table(columns={"source": True, "system_tags": True}), f"h:{i}" + carried_table(s, {"source": True, "system_tags": True}), f"h:{i}" ) for i, s in enumerate((left, right)) ] @@ -438,12 +484,114 @@ def test_no_rows_hold_text_types() -> None: assert table.schema.equals(_source().as_table(all_info=True).schema) -def test_a_source_with_its_own_read_gives_its_own_table() -> None: - """A subclass, or an object, with its own ``as_table`` is read through it.""" +class _OwnSource(ArrowTableSource): + def as_table(self, **kwargs: Any) -> pa.Table: + return super().as_table(**kwargs).slice(0, 2) + + +class _OwnStream(ArrowTableStream): + def as_table(self, **kwargs: Any) -> pa.Table: + return super().as_table(**kwargs).slice(0, 2) + + +class _OwnSpiral(SpiralDBTableSource): + def as_table(self, **kwargs: Any) -> pa.Table: + return super().as_table(**kwargs).slice(0, 2) + + +class _Forwarding: + """A stream of the read interface as it is, forwarding to another.""" + + def __init__(self, inner: Any) -> None: + self.inner = inner + + def __getattr__(self, name: str) -> Any: + if name.startswith("_"): + raise AttributeError(name) + return getattr(self.inner, name) + + +def _raw(kind: type[ArrowTableStream]) -> ArrowTableStream: + return kind( + carried_table(_source(), {"source": True, "system_tags": True}), + tag_columns=["k", "j"], + data_tags=["k"], + ) + + +def _replaced() -> Any: + source = _source() + read = source.as_table + setattr(source, "as_table", lambda **kwargs: read(**kwargs).slice(0, 2)) # noqa: B010 # the point + return source + + +@pytest.mark.parametrize("kind", ["source", "stream", "spiral", "replaced"]) +def test_a_stream_with_its_own_read_is_read_through_it( + kind: str, tmp_path: Path +) -> None: + """Review of PRs 563 and 564: a subclass, or an object, with its own ``as_table``.""" + with fake.install(tmp_path): + if kind == "spiral": + table = fake.ExternalProject("example").create_table( + "default.demo", key_schema=pa.schema([("k", pa.uint64())]) + ) + table.write( + pa.table({"k": pa.array([1, 2, 3], pa.uint64()), "x": [3.0, 4.0, 5.0]}) + ) + own: Any = { + "source": lambda: _OwnSource(_table(), tag_columns=["k"]), + "stream": lambda: _raw(_OwnStream), + "spiral": lambda: _OwnSpiral("example", "demo"), + "replaced": _replaced, + }[kind]() + assert not _derived(carried_table(own, CARRIED)) + assert own.map_data({"x": "z"}).as_table().num_rows == 2 + assert own.polars_filter(pl.col("k") > -1).as_table().num_rows == 2 + + +def test_a_stream_without_the_internal_read_is_read_as_before() -> None: + forwarding: Any = _Forwarding(_source()) + assert not _derived(carried_table(forwarding, CARRIED)) + result = DropNulls(["x"]).static_process(forwarding) + assert result.as_table(all_info=True).equals( + DropNulls(["x"]).static_process(_source()).as_table(all_info=True) + ) + + +class _OwnDropNulls(DropNulls): + """A user's operator over a library one.""" + + seen: list[pa.Table] = [] + + def unary_static_process(self, stream: Any) -> Any: + self.seen.append(self._input_table(stream, CARRIED)) + return super().unary_static_process(stream) + + +def test_a_subclass_of_a_library_operator_reads_text() -> None: + _OwnDropNulls.seen = [] + result = _OwnDropNulls(["x"])(_source()) + assert not _derived(carried_table(result, CARRIED)) + (seen,) = _OwnDropNulls.seen + assert not _derived(seen) - class Own(ArrowTableSource): - def as_table(self, **kwargs: Any) -> pa.Table: - return super().as_table(**kwargs).slice(0, 2) - own = Own(_table(), tag_columns=["k"]) - assert own.drop_columns(["x"]).as_table().num_rows == 2 +def test_every_library_source_is_read_without_text() -> None: + """Each kind declares the read itself; the ones with rows of their own do not.""" + from orcapod import sources + + declared = { + name + for name in dir(sources) + if isinstance(cls := getattr(sources, name), type) + and "_carried_table" in vars(cls) + } + kinds = { + name + for name in dir(sources) + if isinstance(cls := getattr(sources, name), type) + and vars(cls).get("TABLE_IS_ROWS") is True + } + assert kinds - declared == {"CachedSource"} + assert declared <= kinds From 5b0e1c06a00feb0e78b5d093a11b59e71215608e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:17:56 -0800 Subject: [PATCH 17/26] docs(dev): derived tokens in async joins, measured (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-joins.md | 23 +++++++++++++++++++++++ docs/dev/specs/itl-1464-joins/measure.py | 4 +++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/docs/dev/specs/itl-1464-joins.md b/docs/dev/specs/itl-1464-joins.md index 3caba5025..c62281c75 100644 --- a/docs/dev/specs/itl-1464-joins.md +++ b/docs/dev/specs/itl-1464-joins.md @@ -127,3 +127,26 @@ is the form before this change. It is the operator alone, not a job. cases grow with the keys of the input that arrived first, as the bound says. `many` ends its small side first, so it measures the bounded output; `many_open` is the worst case, two open inputs with no certificate, and grows with the keys of both. + +## Batches with derived source-info tokens + +A channel and the kernels take a batch whose source-info columns are derived +(`utils/source_tokens.py`): such a column has no bytes, so it costs a held or spooled row +nothing. The form is the input's first batch's, per column. Text first: a later derived +batch is built as text. Derived first: a later batch in another form is refused, because the +rows held have no text; a producer sends each column in one form. Rows sent through an +output channel may mix forms: `concatenate_batches` builds the text of a column that does. + +Text is built where values are needed: a source-info column both inputs of a `MergeJoin` +have, a merged data-tag one side of which is text, and the tokens that read system tags whose +values a join of one pipeline hash sorts. `Rejoin`'s kernel, not wired, builds all of it. + +| Case (8,000,000 rows) | Text: peak RSS, Arrow pool, time | Derived | +|---|---|---| +| `lookup` | 257 MiB, 26 MiB, 19.9 s | 224 MiB, 10 MiB, 20.7 s | +| `lookup_late` | 2,733 MiB, 392 MiB, 61.7 s | 2,722 MiB, 376 MiB, 45.1 s | +| `one_to_one_late` | 2,301 MiB, 453 MiB, 60.0 s | 2,292 MiB, 435 MiB, 61.4 s | +| `many_open` | 2,629 MiB, 941 MiB, 57.3 s | 2,484 MiB, 855 MiB, 50.8 s | + +Peak memory hardly moves, because the rows were on disk already: what is left in the late and +open cases is the keys. The times were taken with other work on the machine. diff --git a/docs/dev/specs/itl-1464-joins/measure.py b/docs/dev/specs/itl-1464-joins/measure.py index fc79d9cb9..46ba50d25 100644 --- a/docs/dev/specs/itl-1464-joins/measure.py +++ b/docs/dev/specs/itl-1464-joins/measure.py @@ -141,7 +141,9 @@ def batches(self) -> Iterator[pa.RecordBatch]: stream: StreamProtocol = self.source(start, min(BATCH, self.rows - start)) zero = StaticOutputOperatorPod._materialize_upstream([], self.stream) names = zero.as_table(columns={"source": True, "system_tags": True}) - table = getattr(stream, "as_carried_table", stream.as_table)(columns={"source": True, "system_tags": True}) + table = getattr(stream, "as_carried_table", stream.as_table)( + columns={"source": True, "system_tags": True} + ) yield from table.select(names.column_names).combine_chunks().to_batches() From 5d401534ef24c9f67b97b45ca706315a3ca73a05 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:35:10 -0800 Subject: [PATCH 18/26] wip: index the side that ends first (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/operators/rejoin.py | 24 ++ src/orcapod/core/operators/streaming_joins.py | 405 ++++++++---------- .../operators/test_keys_only_joins.py | 286 ++++++++++++- .../operators/test_streaming_joins.py | 34 +- 4 files changed, 490 insertions(+), 259 deletions(-) diff --git a/src/orcapod/core/operators/rejoin.py b/src/orcapod/core/operators/rejoin.py index df2991d9b..19df074e2 100644 --- a/src/orcapod/core/operators/rejoin.py +++ b/src/orcapod/core/operators/rejoin.py @@ -26,6 +26,8 @@ import polars as pl import pyarrow as pa +from orcapod.core.exact_class import reads_as_its_class +from orcapod.protocols.core_protocols.streams import RecordBatchInput, RecordBatchOutput from orcapod.core.unique_keys import UniqueKeys, certificate from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.data_tags import data_tag_names, data_tags_first @@ -648,6 +650,28 @@ def _rejoin_pair( table, left.schema, right.schema, shared_tags ) + async def async_execute_batches( + self, inputs: Sequence[RecordBatchInput], output: RecordBatchOutput + ) -> None: + """Run over input channels of Arrow record batches. + + Two inputs: ``streaming_joins.StreamingRejoin``, which holds the rows not matched + yet, their shared columns in memory and the rows spooled. One input, or three or + more: every input is read first, then the sync call (with three or more, which + repeats of an origin row are matched follows the whole inputs). + + Args: + inputs: One input channel per input stream, in the operator's order. + output: The channel the result's record batches are sent into. + """ + if len(inputs) != 2 or not reads_as_its_class(self, Rejoin): + await super().async_execute_batches(inputs, output) + return + # The kernels are built on this module's rejoin rules. + from orcapod.core.operators.streaming_joins import StreamingRejoin, run_kernel + + await run_kernel(lambda streams: StreamingRejoin(self, streams), inputs, output) + async def async_execute( self, inputs: Sequence[ReadableChannel[tuple[TagProtocol, DataProtocol]]], diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index f464847d9..e9c0813a6 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -88,7 +88,6 @@ import numpy.typing as npt import polars as pl import pyarrow as pa -import pyarrow.compute as pc from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.arrow_keys import polars_key_frame @@ -349,6 +348,35 @@ def append(self, table: pa.Table, frame: pl.DataFrame) -> None: grown[: len(self._alive)] = self._alive self._alive = grown + def spool(self, table: pa.Table) -> None: + """Hold ``table``'s rows without their keys, until ``index`` or ``replay``.""" + self._spool.append(table) + self.rows += table.num_rows + + def index(self) -> None: + """Prepare the keys of the rows held without them (every row held).""" + for rows in self._row_blocks(): + # Only the keys are read, and nothing is copied. + table = self._spool.slice(int(rows[0]), len(rows)) + frame = self.key_frame(table.select(self.keys) if self.keys else table) + self._frames.append(frame.with_columns(pl.col(self.row) + int(rows[0]))) + self._alive = np.ones(self._spool.size, dtype=np.bool_) + + def replay(self) -> Iterator[pa.Table]: + """Give the rows held without keys, in order, in blocks, and let each block go. + + A block's rows are let go once the next one is asked for. + """ + for rows in self._row_blocks(): + yield self._spool.take(rows) + self._spool.discard(rows) + self.rows -= len(rows) + + def _row_blocks(self) -> Iterator[npt.NDArray[np.int64]]: + """The row numbers of the rows held, none let go, ``PUSH_ROWS`` at a time.""" + for start in range(0, self._spool.size, PUSH_ROWS): + yield np.arange(start, min(start + PUSH_ROWS, self._spool.size)) + def held(self, rows: npt.NDArray[np.int64]) -> npt.NDArray[np.int64]: """Those of ``rows`` that were not removed.""" return rows[self._alive[rows - self._base]] @@ -366,6 +394,14 @@ def frame(self) -> pl.DataFrame: self._frames = [pl.concat(self._frames, rechunk=False)] return self._frames[0] + def held_frame(self) -> pl.DataFrame: + """The key frame of the rows held, without the removed ones.""" + frame = self.frame() + if not self._removed_count: + return frame + rows = frame.get_column(self.row).to_numpy() + return frame.filter(pl.Series(self._alive[rows - self._base])) + def remove(self, rows: npt.NDArray[np.int64]) -> None: """Let rows go that can never match again: each is held, each given once.""" if not len(rows): @@ -413,6 +449,12 @@ class _BinaryLink: unique: Whether each side is certified unique on the keys: no two of its rows match one row of the other side. A row is let go once it has matched if, and only if, the other side is unique: it can match nothing else. + + With both sides unique (one to one) rows are matched as they arrive and let go. Any + other link holds the keys of one side only: while both sides are open, the rows of + both are spooled without keys and nothing is emitted; when a side ends, its keys are + prepared, the other side's spooled rows are matched with them and let go, and every + row still to arrive is matched at once and not held. """ def __init__( @@ -423,6 +465,7 @@ def __init__( ) -> None: self.unique: tuple[bool, bool] = unique self.keys: list[str] = list(keys) + self.one_to_one: bool = all(unique) self.sides: tuple[_Side, _Side] = (_Side(keys, _ROW[0]), _Side(keys, _ROW[1])) self._finish: Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table] = finish @@ -474,6 +517,22 @@ def push(self, side: int, table: pa.Table) -> Iterator[pa.Table]: table = table.filter(_has_whole_key(table, self.keys)) if not table.num_rows: return + if not self.one_to_one and not other.closed: + this.spool(table) + return + yield from self._match(side, table) + + def _match(self, side: int, table: pa.Table) -> Iterator[pa.Table]: + """Match ``table``'s rows, whose keys are whole, with the other side's keys. + + Args: + side: The side the rows are of. + table: The rows. + + Yields: + The output rows of the pairs, in pieces. + """ + this, other = self.sides[side], self.sides[1 - side] frame = this.key_frame(table) this_unique, other_unique = self.unique[side], self.unique[1 - side] matched = np.zeros(table.num_rows, dtype=np.bool_) @@ -507,10 +566,25 @@ def push(self, side: int, table: pa.Table) -> Iterator[pa.Table]: frame = this.key_frame(table) this.append(table, frame) - def close(self, side: int) -> None: - """Note that ``side`` ends: the other side's rows can never match again.""" - self.sides[side].closed = True - self.sides[1 - side].clear() + def close(self, side: int) -> Iterator[pa.Table]: + """Note that ``side`` ends: the other side's rows are needed no longer. + + Args: + side: The side that ends. + + Yields: + The output rows that decides: those of the other side's spooled rows, when + ``side`` is the first of a link's sides to end. + """ + this, other = self.sides[side], self.sides[1 - side] + this.closed = True + if this.rows and other.rows and not self.one_to_one and not other.closed: + this.index() + for table in other.replay(): + yield from self._match(1 - side, table) + elif not self.one_to_one and not other.closed: + this.index() + other.clear() class StreamingJoinKernel(ABC): @@ -617,10 +691,19 @@ def iter_push( def close(self, input_index: int) -> list[pa.RecordBatch]: """Note that an input has ended; return the output rows that decides. + ``iter_close`` with its batches collected: for an output known to be small. + """ + return list(self.iter_close(input_index)) + + def iter_close(self, input_index: int) -> Iterator[pa.RecordBatch]: + """Note that an input has ended; yield the output rows that decides. + + The iterator must be read to its end before the kernel is used again. + Args: input_index: The input, in call order. - Returns: + Yields: The output record batches, possibly none. Raises: @@ -631,15 +714,14 @@ def close(self, input_index: int) -> list[pa.RecordBatch]: """ self._require_open(input_index) self._closed[input_index] = True - emitted = list(self._emitted(self._close(input_index))) + yield from self._emitted(self._close(input_index)) if all(self._closed): self._check_settled_against_empty_inputs() result = self._check_empty_inputs() - if result is not None and not self._emitted_any and not emitted: + if result is not None and not self._emitted_any: # No row: the output is the sync path's result over the inputs as # they ended, whose types an empty input decides. self.zero_row_result = result - return emitted def _check_settled_against_empty_inputs(self) -> None: """Compare the settled token types with the inputs that delivered no rows. @@ -691,8 +773,8 @@ def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: """ @abstractmethod - def _close(self, input_index: int) -> list[pa.Table]: - """Note an input's end; return the output tables that decides. + def _close(self, input_index: int) -> Iterable[pa.Table]: + """Note an input's end; give the output tables that decides. Args: input_index: The input, in call order; open until this call. @@ -966,16 +1048,25 @@ def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: def _through(self, step: int, side: int, table: pa.Table) -> Iterator[pa.Table]: """Push rows into a step, and what it emits through the steps after it.""" for result in self._links[step].push(side, table): - if step == len(self._links) - 1: - yield result - elif step not in self._sinks: - yield from self._through(step + 1, 0, result) + yield from self._after(step, result) + + def _after(self, step: int, result: pa.Table) -> Iterator[pa.Table]: + """Take rows a step emitted through the steps after it.""" + if step == len(self._links) - 1: + yield result + elif step not in self._sinks: + yield from self._through(step + 1, 0, result) + + def _end(self, step: int, side: int) -> Iterator[pa.Table]: + """End a step's side, and take what that emits through the steps after it.""" + for result in self._links[step].close(side): + yield from self._after(step, result) def release(self) -> None: for link in self._links: link.release() - def _close(self, input_index: int) -> list[pa.Table]: + def _close(self, input_index: int) -> Iterator[pa.Table]: """End an input's side of its step, and every side that can no longer receive. A step that can never emit again (``_BinaryLink.exhausted``) closes its @@ -984,19 +1075,19 @@ def _close(self, input_index: int) -> list[pa.Table]: the sync path joins those steps before it reaches the empty one, and a merge refuses token lists of different lengths (a value-decided refusal, module docstring). Those steps keep matching, and the last of them drops its output - (``_sinks``). Closing never emits a row. + (``_sinks``). Args: input_index: The input, in call order. - Returns: - No table. + Yields: + The last step's output, possibly none. """ if not self._links: - return [] + return position = self._position[input_index] step, side = (0, 0) if position == 0 else (position - 1, 1) - self._links[step].close(side) + yield from self._end(step, side) for step, link in enumerate(self._links): if not link.exhausted: continue @@ -1012,8 +1103,7 @@ def _close(self, input_index: int) -> list[pa.Table]: step + 1 < len(self._links) and not self._links[step + 1].sides[0].closed ): - self._links[step + 1].close(0) - return [] + yield from self._end(step + 1, 0) class StreamingMergeJoin(StreamingJoinKernel): @@ -1219,18 +1309,17 @@ def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: def release(self) -> None: self._link.release() - def _close(self, input_index: int) -> list[pa.Table]: - self._link.close(input_index) - return [] + def _close(self, input_index: int) -> Iterable[pa.Table]: + return self._link.close(input_index) class StreamingSemiJoin(StreamingJoinKernel): - """``SemiJoin`` on record batches: the left input streams. + """``SemiJoin`` on record batches: the right input's keys are held. - A left row is emitted as soon as its key is among the right rows seen so far; a left - row with no such match waits until a right row matches it or the right input closes, - when it is dropped. The right input's rows are held as keys only, while the left - input is open. With no tag shared by the inputs, every left row passes, as + Which left rows are kept is decided by the whole right input, of which only the + distinct keys are held. Left rows that arrive before it has ended are spooled without + keys and decided when it ends; the left rows after that are decided at once and not + held. With no tag shared by the inputs, every left row passes as it arrives, as ``static_process`` returns the left stream. Args: @@ -1244,8 +1333,7 @@ def __init__(self, operator: SemiJoin, inputs: Sequence[StreamProtocol]) -> None super().__init__(operator, inputs) left, right = inputs self._keys = list(SemiJoin._match_keys(left.keys()[0], right.keys()[0])) # pyright: ignore[reportPrivateUsage] # SemiJoin's one rule - # The left rows not decided yet (keys, the rows spooled), and the distinct keys of - # the right rows. + # The left rows not decided yet, spooled, and the distinct keys of the right rows. self._waiting = _Side(self._keys, _ROW[0], constant_key=False) self._right_frames: list[pl.DataFrame] = [] # Whether Polars tells key values apart as its joins do (no nested key). @@ -1279,60 +1367,53 @@ def _matched( def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: if not self._keys: return [table] if input_index == 0 else [] - if input_index == 0: - return self._push_left(table) - return self._push_right(table) + # A row whose key holds a top-level null matches nothing, on either side. + table = table.filter(_has_whole_key(table, self._keys)) + if not table.num_rows: + return [] + if input_index == 1: + self._hold_right(table) + return [] + if self._closed[1]: + return self._decided(table) + self._waiting.spool(table) + return [] - def _push_left(self, table: pa.Table) -> Iterator[pa.Table]: - """Emit the left rows a right row matched already; hold the undecided ones.""" - frame = self._waiting.key_frame(table) - kept = np.zeros(table.num_rows, dtype=np.bool_) - if (right_keys := self._right_keys()) is not None: - kept[self._matched(frame, right_keys)] = True - mask = pa.array(kept) - if not self._closed[1]: - # A left row whose key holds a top-level null never matches. - undecided = table.filter( - pc.and_(pc.invert(mask), _has_whole_key(table, self._keys)) - ) - self._waiting.append(undecided, self._waiting.key_frame(undecided)) - yield table.filter(mask) - - def _push_right(self, table: pa.Table) -> Iterator[pa.Table]: - """Hold the right rows' keys; emit the waiting left rows they decide.""" - # Only rows whose keys hold no top-level null (the sync path drops those: such a - # key never matches). - keys = table.select(self._keys) - keys = keys.filter(_has_whole_key(keys, self._keys)) - if not keys.num_rows: + def _decided(self, table: pa.Table) -> Iterator[pa.Table]: + """The left rows of ``table`` whose key is among the right rows'.""" + right_keys = self._right_keys() + if right_keys is None: return - frame = polars_key_frame(keys, self._keys) + kept = np.zeros(table.num_rows, dtype=np.bool_) + kept[self._matched(self._waiting.key_frame(table), right_keys)] = True + decided = table.filter(pa.array(kept)) + for start in range(0, decided.num_rows, PAIRS_PER_BATCH): + yield decided.slice(start, PAIRS_PER_BATCH) + + def _hold_right(self, table: pa.Table) -> None: + """Hold the keys of right rows, each once.""" + if self._closed[0] and not self._waiting.rows: + return # no left row to decide + frame = polars_key_frame(table.select(self._keys), self._keys) + held = self._right_keys() if self._distinct: frame = frame.unique() - if not self._closed[0]: - held = self._right_keys() - if held is not None and self._distinct: - new = frame.join(held, on=self._keys, how="anti") - else: - new = frame - if new.height: - self._right_frames.append(new) - if not self._waiting.rows: - return - decided = self._waiting.held(self._matched(self._waiting.frame(), frame)) - for start in range(0, len(decided), PAIRS_PER_BATCH): - rows = decided[start : start + PAIRS_PER_BATCH] - yield self._waiting.take(rows) - self._waiting.remove(rows) + if held is not None: + frame = frame.join(held, on=self._keys, how="anti") + if frame.height: + self._right_frames.append(frame) - def _close(self, input_index: int) -> list[pa.Table]: + def _close(self, input_index: int) -> Iterator[pa.Table]: if input_index == 0: - # No left row will arrive: the right keys can match nothing new. + if self._closed[1] or not self._waiting.rows: + # No left row is left to decide. + self._right_frames = [] + return + for table in self._waiting.replay(): + yield from self._decided(table) + self._waiting.clear() + if self._closed[0]: self._right_frames = [] - else: - # No right row will arrive: the undecided left rows never match. - self._waiting.clear() - return [] # The occurrence-number column of a Rejoin key frame, and the prefix of the other side's @@ -1361,40 +1442,6 @@ def _with_system_tags(table: pa.Table, keys: Sequence[str]) -> pa.Table: return table.filter(_has_whole_key(table, keys)) -def _take_rows(table: pa.Table, rows: np.ndarray[Any, np.dtype[np.int64]]) -> pa.Table: - """The rows of ``table`` with these numbers, in this order, without combining chunks. - - Arrow's ``take`` on a chunked column concatenates its chunks first, a copy of the - whole column. Here only the chunks that hold a wanted row are read: each one's rows - are taken from it alone, and the small result is put in the order asked for. - - Args: - table: A table, of any number of chunks. - rows: Row numbers in ``table``. - - Returns: - The rows, as one chunk. - """ - batches = table.to_batches() - if len(batches) <= 1: - return table.take(pa.array(rows, pa.int64())) - lengths = np.fromiter((b.num_rows for b in batches), np.int64, len(batches)) - starts = np.concatenate([np.zeros(1, np.int64), np.cumsum(lengths)[:-1]]) - chunks = np.searchsorted(starts, rows, side="right") - 1 - order = np.argsort(chunks, kind="stable") - sorted_rows, sorted_chunks = rows[order], chunks[order] - edges = np.flatnonzero(np.diff(sorted_chunks)) + 1 - parts: list[pa.Table] = [] - for group in np.split(np.arange(len(sorted_rows)), edges): - chunk = int(sorted_chunks[group[0]]) - local = sorted_rows[group] - starts[chunk] - parts.append( - pa.Table.from_batches([batches[chunk]]).take(pa.array(local, pa.int64())) - ) - taken = pa.concat_tables(parts).combine_chunks() - return taken.take(pa.array(np.argsort(order, kind="stable"), pa.int64())) - - def _occurrences(frame: pl.DataFrame, among: Sequence[str]) -> pl.DataFrame: """Number each row among the rows before it equal to it in ``among`` (0, 1, ...). @@ -1407,85 +1454,6 @@ def _occurrences(frame: pl.DataFrame, among: Sequence[str]) -> pl.DataFrame: ) -class _Remaining: - """An input's rows not matched yet, with a key frame and a mask of removed rows. - - Removing a row only clears its mask bit; the rows are compacted when the removed - ones are the majority, so a batch never copies the whole table. - - Args: - columns: The shared columns of the key frame (system tags first). - row: The row-number column. - """ - - def __init__(self, columns: Sequence[str], row: str) -> None: - self.columns: list[str] = list(columns) - self.row: str = row - self.closed: bool = False - self.schema: pa.Schema | None = None - self._tables: list[pa.Table] = [] - self._frames: list[pl.DataFrame] = [] - self._alive: list[np.ndarray[Any, np.dtype[np.bool_]]] = [] - self._table: pa.Table | None = None - self._frame: pl.DataFrame | None = None - self.size: int = 0 - self.rows: int = 0 - - def append(self, table: pa.Table) -> None: - """Hold ``table``'s rows.""" - if not table.num_rows: - return - frame = polars_key_frame(table, self.columns, self.row) - self._frames.append(frame.with_columns(pl.col(self.row) + self.size)) - self._tables.append(table) - self._alive.append(np.ones(table.num_rows, dtype=np.bool_)) - self._table, self._frame = None, None - self.size += table.num_rows - self.rows += table.num_rows - - def table(self) -> pa.Table: - """Every row appended and not compacted away, numbered as in ``frame``.""" - if self._table is None: - self._table = pa.concat_tables(self._tables) - self._tables = [self._table] - return self._table - - def frame(self) -> pl.DataFrame: - """The key frame of the rows not removed, in the order they arrived.""" - if self._frame is None: - frame = pl.concat(self._frames, rechunk=False) - alive = np.concatenate(self._alive) - self._frames, self._alive = [frame], [alive] - self._frame = frame.filter(pl.Series(alive)) - return self._frame - - def remove(self, rows: np.ndarray[Any, np.dtype[np.int64]]) -> None: - """Remove the rows with these numbers (each held and not removed yet).""" - if not len(rows): - return - self.frame() - alive = self._alive[0] - alive[rows] = False - self.rows -= len(rows) - self._frame = None - if self.rows * 2 < self.size: - self._compact() - - def _compact(self) -> None: - """Drop the removed rows and number the rest from 0.""" - alive = np.concatenate(self._alive) - table = self.table().filter(pa.array(alive)) - self.clear() - self.append(table) - - def clear(self) -> None: - """Drop every row held.""" - self._tables, self._frames, self._alive = [], [], [] - self._table, self._frame = None, None - self.size = 0 - self.rows = 0 - - class _RejoinLink: """One step of ``Rejoin``: a symmetric match of two sides on every shared column. @@ -1505,9 +1473,9 @@ def __init__( self.system: list[str] = list(system) self.others: list[str] = list(others) self.shared: list[str] = [*system, *others] - self.sides: tuple[_Remaining, _Remaining] = ( - _Remaining(self.shared, _ROW[0]), - _Remaining(self.shared, _ROW[1]), + self.sides: tuple[_Side, _Side] = ( + _Side(self.shared, _ROW[0], constant_key=False), + _Side(self.shared, _ROW[1], constant_key=False), ) self._finish: Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table] = finish # The shared columns other than system tags in which rows of one origin row @@ -1556,48 +1524,35 @@ def push(self, side: int, table: pa.Table) -> pa.Table | None: result = None unmatched = np.ones(table.num_rows, dtype=np.bool_) if other.rows: - held = _occurrences(other.frame(), self.shared) + held = _occurrences(other.held_frame(), self.shared) pairs = frame.join( held, on=[*self.shared, _OCCURRENCE], how="inner", nulls_equal=True ) if pairs.height: - mine = pairs.get_column(row).to_numpy() - theirs = pairs.get_column(other_row).to_numpy() + mine = pairs.get_column(row).to_numpy().astype(np.int64) + theirs = pairs.get_column(other_row).to_numpy().astype(np.int64) unmatched[mine] = False - tables = (table, other.table()) if side == 0 else (other.table(), table) - rows = (mine, theirs) if side == 0 else (theirs, mine) - result = self._pairs(*tables, *rows) + taken = (table.take(pa.array(mine, pa.int64())), other.take(theirs)) + result = self._pairs(*(taken if side == 0 else taken[::-1])) other.remove(theirs) rest = table.filter(pa.array(unmatched)) if not unmatched.all() else table if rest.num_rows and other.rows and self.others: self._note_differing(rest, other, side) if not other.closed: - this.append(rest) + this.append(rest, this.key_frame(rest)) return result - def _pairs( - self, - left: pa.Table, - right: pa.Table, - left_rows: np.ndarray[Any, np.dtype[np.int64]], - right_rows: np.ndarray[Any, np.dtype[np.int64]], - ) -> pa.Table: - """The matched pairs as ``Rejoin._rejoin_pair`` builds them, by row number. - - Values are taken from the chunks that hold them (``_take_rows``): no held - table is copied. - """ - left_taken = _take_rows(left, left_rows) - right_taken = _take_rows(right, right_rows) + def _pairs(self, left: pa.Table, right: pa.Table) -> pa.Table: + """The matched pairs as ``Rejoin._rejoin_pair`` builds them, from their rows.""" names: list[str] = [] arrays: list[Any] = [] for name in left.column_names: names.append(name) - arrays.append(left_taken.column(name)) + arrays.append(left.column(name)) for name in right.column_names: if name not in left.column_names: names.append(name) - arrays.append(right_taken.column(name)) + arrays.append(right.column(name)) assert self.sides[0].schema is not None assert self.sides[1].schema is not None return self._finish( @@ -1606,7 +1561,7 @@ def _pairs( self.sides[1].schema, ) - def _note_differing(self, rest: pa.Table, other: _Remaining, side: int) -> None: + def _note_differing(self, rest: pa.Table, other: _Side, side: int) -> None: """Note the shared columns in which unmatched rows of one origin row differ. One more join, of the arriving rows that matched nothing on the system tags only @@ -1623,7 +1578,7 @@ def _note_differing(self, rest: pa.Table, other: _Remaining, side: int) -> None: return origin = [*self.system, _OCCURRENCE] mine = _occurrences(polars_key_frame(rest, self.shared, row), self.system) - theirs = _occurrences(other.frame(), self.system).select( + theirs = _occurrences(other.held_frame(), self.system).select( [*origin, *(pl.col(name).alias(_OTHER + name) for name in names)] ) pairs = mine.select([*origin, *names]).join(theirs, on=origin, how="inner") @@ -1660,7 +1615,7 @@ class StreamingRejoin(StreamingJoinKernel): occurrence numbers of the remaining rows. That is O(held rows) per batch, as in the ``Join`` kernels, plus O(m log m) to take the m pairs it makes from the held chunks (``_take_rows``: one vectorized chunk lookup and one sort for all of them), never by - copying a whole held table; a compaction copies the remaining rows when half of + copying a whole held table; a compaction copies the remaining keys when half of those held were removed. A long run of one-row batches against a large buffer is quadratic in the rows. @@ -1758,6 +1713,10 @@ def __init__(self, operator: Rejoin, inputs: Sequence[StreamProtocol]) -> None: def held_rows(self) -> int: return sum(link.held_rows for link in self._links) + def release(self) -> None: + for link in self._links: + link.release() + def _link_finish( self, shared_tags: set[str] ) -> Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table]: @@ -1899,7 +1858,7 @@ async def run_kernel( progressed = True await readers[index] # raises what ended it, if anything did open_inputs.discard(index) - for result in kernel.close(index): + for result in kernel.iter_close(index): await output.send(result) if not progressed: _ = await changed.wait() diff --git a/tests/test_core/operators/test_keys_only_joins.py b/tests/test_core/operators/test_keys_only_joins.py index 2e8ab2301..ca1a5bcef 100644 --- a/tests/test_core/operators/test_keys_only_joins.py +++ b/tests/test_core/operators/test_keys_only_joins.py @@ -21,12 +21,13 @@ import pyarrow as pa import pytest -from orcapod.core.operators import Join, MergeJoin, SemiJoin +from orcapod.core.operators import Join, MergeJoin, Rejoin, SemiJoin from orcapod.core.operators import streaming_joins from orcapod.core.operators.streaming_joins import ( StreamingJoin, StreamingJoinKernel, StreamingMergeJoin, + StreamingRejoin, StreamingSemiJoin, ) from orcapod.core.record_batch_channels import OutputChannel @@ -283,30 +284,64 @@ def test_a_one_to_one_join_in_step_holds_only_the_rows_between_the_inputs( assert emitted == 60 -def test_a_lookup_holds_the_unique_side_and_no_row_that_matched(spooled: Path) -> None: +def _keys_held(kernel: StreamingJoinKernel) -> list[int]: + """How many rows' keys each side of a kernel's links holds.""" + return [ + sum(frame.height for frame in side._frames) # pyright: ignore[reportPrivateUsage] # what it keeps + for link in kernel._links # pyright: ignore[reportPrivateUsage, reportAttributeAccessIssue] # what it keeps + for side in link.sides + ] + + +@pytest.mark.parametrize("first", [0, 1]) +def test_a_lookup_holds_the_keys_of_the_side_that_ends_first( + spooled: Path, first: int +) -> None: spikes = _source( "spikes", {"unit": [0, 1, 2, 3] * 10, "n": list(range(40))}, key=("n",) ) units = _source("units", {"unit": [0, 1, 2], "area": [1, 1, 2]}, key=("unit",)) - kernel = _join([spikes, units]) - (first, *rest) = _batches(spikes, 8) - kernel.push(0, first) - assert kernel.held_rows == 8 # arrived before any unit - (all_units,) = _batches(units, 3) - kernel.push(1, all_units) - assert kernel.held_rows == 2 + 3 # the spikes of unit 3, and the units - for batch in rest: - kernel.push(0, batch) - assert kernel.held_rows == 10 + 3 # unit 3 may still arrive - kernel.close(1) - assert kernel.held_rows == 3 # it did not - kernel.close(0) + inputs = [spikes, units] + batches = [_batches(spikes, 8), _batches(units, 2)] + kernel = StreamingJoin(Join(), inputs) + for batch in batches[first]: + assert kernel.push(first, batch) == [] + early = batches[1 - first][0] + assert kernel.push(1 - first, early) == [] + assert _keys_held(kernel) == [0, 0] # rows, no keys + emitted = sum(b.num_rows for b in kernel.close(first)) + assert emitted == (6 if first == 1 else 20) + side = kernel._position[first] # pyright: ignore[reportPrivateUsage] # its side + held = _keys_held(kernel) + assert held[1 - side] == 0 # the other side never has keys, before or after + assert 0 < held[side] <= sum(b.num_rows for b in batches[first]) + for batch in batches[1 - first][1:]: + emitted += sum(b.num_rows for b in kernel.push(1 - first, batch)) + assert _keys_held(kernel)[1 - side] == 0 + assert emitted == 30 + assert kernel.close(1 - first) == [] assert kernel.held_rows == 0 + assert _files(spooled) == [] -def test_without_a_certificate_nothing_that_may_match_again_is_let_go( +def test_a_row_of_a_lookup_indexed_first_is_let_go_when_it_matches( spooled: Path, ) -> None: + """The other side is unique, so an indexed row can match only once.""" + spikes = _source("spikes", {"unit": [0, 0, 1, 2], "n": [1, 2, 3, 4]}, key=("n",)) + units = _source("units", {"unit": [0, 1, 2], "area": [1, 1, 2]}, key=("unit",)) + kernel = _join([spikes, units]) + (all_spikes,), all_units = _batches(spikes, 4), _batches(units, 1) + kernel.push(0, all_spikes) + kernel.close(0) + held = 4 + for batch in all_units: + held -= sum(b.num_rows for b in kernel.push(1, batch)) + assert kernel.held_rows == held + assert held == 0 + + +def test_without_a_certificate_the_indexed_rows_stay(spooled: Path) -> None: left, right = ( _sorted_source("a", 6, key=False), _sorted_source("b", 6, key=False), @@ -314,8 +349,11 @@ def test_without_a_certificate_nothing_that_may_match_again_is_let_go( kernel = _join([left, right]) (one,), (two,) = _batches(left, 6), _batches(right, 6) kernel.push(0, one) - assert sum(b.num_rows for b in kernel.push(1, two)) == 6 + kernel.push(1, two) assert kernel.held_rows == 12 + assert sum(b.num_rows for b in kernel.close(0)) == 6 + assert kernel.held_rows == 6 # the left ones: a right row may still match them + assert sum(b.num_rows for b in kernel.push(1, two)) == 6 kernel.release() assert _files(spooled) == [] @@ -323,18 +361,48 @@ def test_without_a_certificate_nothing_that_may_match_again_is_let_go( def test_a_many_to_many_match_is_emitted_in_bounded_pieces(spooled: Path) -> None: left = _source("a", {"k": [1] * 20 + [2], "n": list(range(21))}) right = _source("b", {"k": [1] * 15 + [2], "m": list(range(16))}) - kernel = _join([left, right]) (mine,), (theirs,) = _batches(left, 21), _batches(right, 16) - kernel.push(0, mine) - sizes = [batch.num_rows for batch in kernel.push(1, theirs)] - assert sum(sizes) == 20 * 15 + 1 - assert max(sizes) <= 3 + # Replayed when a side ends, and probed after it: both in pieces. + replayed = _join([left, right]) + replayed.push(0, mine) + replayed.push(1, theirs) + probed = _join([left, right]) + probed.push(0, mine) + probed.close(0) + for batches in (replayed.close(0), probed.push(1, theirs)): + sizes = [batch.num_rows for batch in batches] + assert sum(sizes) == 20 * 15 + 1 + assert max(sizes) <= 3 # One arriving row's matches are cut too. many = _join([left, right]) many.push(0, mine) + many.close(0) assert all(b.num_rows <= 3 for b in many.push(1, theirs.slice(0, 1))) +def test_replayed_rows_leave_the_disk_as_they_are_matched( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Each input's rows are on disk at most once, and go while they are replayed.""" + monkeypatch.setattr( + streaming_joins, "RowSpool", functools.partial(RowSpool, 0, str(tmp_path)) + ) + monkeypatch.setattr(streaming_joins, "PUSH_ROWS", 4) + left = _source("a", {"k": [1, 2] * 20, "n": list(range(40))}) + right = _source("b", {"k": [1, 2], "m": [1, 2]}) + kernel = _join([left, right]) + for batch in _batches(left, 4): + kernel.push(0, batch) + (small,) = _batches(right, 2) + kernel.push(1, small) + assert len(_files(tmp_path)) == 11 + seen = [len(_files(tmp_path)) for _ in kernel.iter_close(1)] + assert seen == sorted(seen, reverse=True) + assert seen[-1] <= 2 and len(_files(tmp_path)) == 1 # the indexed side's rows + kernel.release() + assert _files(tmp_path) == [] + + def test_a_semi_join_holds_each_right_key_once(spooled: Path) -> None: left = _source("a", {"k": [1, 2], "n": [1, 2]}) right = _source("b", {"k": [1, 1, 3, 3, 3] * 4, "m": list(range(20))}) @@ -732,3 +800,177 @@ def test_rows_held_for_long_among_rows_that_pass_are_matched_at_the_end( map(str, waiting) ) assert kernel.held_rows == 0 + + +# --------------------------------------------------------------------------- +# Long second inputs, and an end in the middle of a replay +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("op", [Join(), SemiJoin(), MergeJoin()], ids=lambda o: repr(o)) +def test_an_endless_input_is_joined_as_it_arrives_once_the_other_has_ended( + spooled: Path, op: Any +) -> None: + """It never ends: every row after the first input's end is sent, and none held.""" + endless = _source("a", {"k": [1, 2, 3, 4], "n": [1, 2, 3, 4]}) + small = _source("b", {"k": [1, 2], "m": [1, 2]}, key=("k",)) + result = op(endless, small) + + async def go() -> int: + channel = OutputChannel(endless, retain=False, buffer_size=1) + output = OutputChannel(result, retain=False, buffer_size=1) + reader, results = channel.open_reader(), output.open_reader() + run = asyncio.create_task( + op.async_execute_batches([reader, small.open_channel()], output) + ) + + async def produce() -> None: + while True: + for batch in _batches(endless, 2): + await channel.send(batch) + + producing = asyncio.create_task(produce()) + rows = 0 + async for batch in results: + rows += batch.num_rows + if rows > 300: + break + # What was spooled before the small input ended has been replayed and let go. + assert len(_files(spooled)) <= 2 + for task in (run, producing): + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + return rows + + assert _bounded(go()) > 300 + assert _files(spooled) == [] + + +@pytest.mark.parametrize("end", ["cancel", "close_reader"]) +@pytest.mark.parametrize("op", [Join(), SemiJoin(), MergeJoin()], ids=lambda o: repr(o)) +def test_a_join_that_ends_while_replaying_leaves_nothing( + spooled: Path, op: Any, end: str +) -> None: + left = _source("a", {"k": [1, 2] * 100, "n": list(range(200))}) + right = _source("b", {"k": [1, 2], "m": [1, 2]}) + + async def go() -> None: + late = OutputChannel(right, retain=False, buffer_size=4) + output = OutputChannel(op(left, right), retain=False, buffer_size=1) + results = output.open_reader() + run = asyncio.create_task( + op.async_execute_batches([left.open_channel(), late.open_reader()], output) + ) + await asyncio.sleep(0.05) # the left rows are spooled, the left input ended + for batch in _batches(right, 1): + await late.send(batch) + await late.close() + _ = await results.receive() # the replay has begun, and waits for this reader + await asyncio.sleep(0.05) + assert not run.done() + if end == "cancel": + run.cancel() + with pytest.raises(asyncio.CancelledError): + await run + with pytest.raises(UpstreamFailedError): + _ = await results.receive() + else: + await results.close() + await run # no reader: it ends normally + + _bounded(go()) + assert _files(spooled) == [] + + +def test_an_input_that_fails_after_the_other_ended_fails_the_join( + spooled: Path, +) -> None: + left = _source("a", {"k": [1, 2] * 10, "n": list(range(20))}) + right = _source("b", {"k": [1, 2], "m": [1, 2]}) + + async def go() -> None: + failing = OutputChannel(left, retain=False, buffer_size=8) + op = Join() + output = OutputChannel(op(left, right)) + run = asyncio.create_task( + op.async_execute_batches( + [failing.open_reader(), right.open_channel()], output + ) + ) + await failing.send(_batches(left, 5)[0]) + await asyncio.sleep(0.05) + failing.fail(RuntimeError("the read broke")) + with pytest.raises(UpstreamFailedError, match="the read broke"): + await run + + _bounded(go()) + assert _files(spooled) == [] + + +# --------------------------------------------------------------------------- +# Rejoin of two inputs +# --------------------------------------------------------------------------- + + +def _branches(kind: str) -> list[Any]: + source = _source( + "a", + {**_pairs(4, 5), "n": list(range(20))}, + key=("n", "unit"), + layout="reversed", + ) + if kind == "data_tags": + source = _data_tagged("a", 20) + return [ + source.select_data_columns(["a1", "k"]), + source.select_data_columns(["a2"]), + ] + first = source.select_data_columns(["a_x"]) + second = source.select_data_columns(["a_y"]) + if kind == "filtered": + return [first, second.drop_nulls("a_y")] + if kind == "differing_tag": + return [first, second.map_data(a_y="z")] + if kind == "empty": + return [first, second.filter(session="none")] + return [first, second] + + +@pytest.mark.parametrize("swapped", [False, True]) +@pytest.mark.parametrize( + "kind", ["plain", "filtered", "differing_tag", "empty", "data_tags"] +) +def test_rejoin_of_two_branches_over_channels( + spooled: Path, kind: str, swapped: bool +) -> None: + inputs = _branches(kind)[:: -1 if swapped else 1] + op = Rejoin() + output = OutputChannel(op(*inputs)) + _bounded(op.async_execute_batches([s.open_channel() for s in inputs], output)) + assert _rows(_transport(output.result())) == _rows(_transport(op(*inputs))) + assert _files(spooled) == [] + + +def test_rejoin_holds_only_rows_not_matched_yet(spooled: Path) -> None: + inputs = _branches("plain") + kernel = StreamingRejoin(Rejoin(), inputs) + for mine, theirs in zip(_batches(inputs[0], 5), _batches(inputs[1], 5)): + assert kernel.push(0, mine) == [] + assert kernel.held_rows == 5 + assert sum(b.num_rows for b in kernel.push(1, theirs)) == 5 + assert kernel.held_rows == 0 + assert _files(spooled) == [] + + +def test_rejoin_of_three_inputs_is_a_barrier_and_equal(spooled: Path) -> None: + source = _source("a", {**_pairs(4, 5), "n": list(range(20))}, key=("n",)) + inputs = [ + source.select_data_columns(["a_x"]), + source.select_data_columns(["a_y"]), + source.map_data(a_x="x2", a_y="y2"), + ] + op = Rejoin() + output = OutputChannel(op(*inputs)) + _bounded(op.async_execute_batches([s.open_channel() for s in inputs], output)) + assert _rows(_transport(output.result())) == _rows(_transport(op(*inputs))) diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index 4aad0842d..587cfb3c7 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -694,13 +694,15 @@ def test_semi_join_holds_undecided_left_rows_only_until_the_right_input_ends() - left_table = _transport(left) assert kernel.push(0, left_table.to_batches()[0]) == [] assert kernel.held_rows == left_table.num_rows - emitted = kernel.push(1, _transport(right).to_batches()[0]) - matched = sum(batch.num_rows for batch in emitted) - assert matched > 0 - assert kernel.held_rows == left_table.num_rows - matched + 1 - # The right input ends: the undecided left rows are dropped; the right keys stay - # for left rows still to arrive. - kernel.close(1) + assert kernel.push(1, _transport(right).to_batches()[0]) == [] + assert kernel.held_rows == left_table.num_rows + 1 + # The right input ends: the left rows are decided; the right keys stay for left rows + # still to arrive, which are decided at once. + matched = sum(batch.num_rows for batch in kernel.close(1)) + assert 0 < matched < left_table.num_rows + assert kernel.held_rows == 1 + again = kernel.push(0, left_table.to_batches()[0]) + assert sum(batch.num_rows for batch in again) == matched assert kernel.held_rows == 1 kernel.close(0) assert kernel.held_rows == 0 @@ -881,13 +883,15 @@ def test_source_info_lists_of_different_lengths_raise_when_their_batch_arrives( ) -> None: # The descriptions agree (one type of token list); the lengths are values. The # sync path refuses the run; the kernel raises the same error when the offending - # pair arrives, after the rows already decided (module docstring). + # pair is matched, after the rows already decided (module docstring): when its batch + # arrives, once the other input has ended. left = _data_tag_stream("v", [["a"], ["b"]]) right = _data_tag_stream("w", [["c"], ["d", "e"]]) with pytest.raises(ValueError, match="different lengths") as sync_error: operator.static_process(_row_built(left), _row_built(right)) instance = kernel(operator, (left, right)) instance.push(0, _sent(left).combine_chunks().to_batches()[0]) + assert instance.close(0) == [] sent = _sent(right).combine_chunks() emitted = instance.push(1, sent.slice(0, 1).to_batches()[0]) assert sum(batch.num_rows for batch in emitted) == 1 @@ -947,13 +951,12 @@ def test_semi_join_never_holds_a_left_row_with_a_null_key(pool: str) -> None: kernel = StreamingSemiJoin(SemiJoin(), (left, right)) assert kernel.push(0, left_rows.to_batches()[0]) == [] assert kernel.held_rows == left_rows.num_rows - null_keys - # The left input ends and the right rows arrive: every left row with a key is - # emitted, and nothing is held. - kernel.close(0) - emitted = kernel.push(1, _sent(right).combine_chunks().to_batches()[0]) + # Every left row with a key is emitted when the right input ends, and none is held. + assert kernel.close(0) == [] + assert kernel.push(1, _sent(right).combine_chunks().to_batches()[0]) == [] + emitted = kernel.close(1) assert sum(batch.num_rows for batch in emitted) == left_rows.num_rows - null_keys assert kernel.held_rows == 0 - assert kernel.close(1) == [] def test_join_still_refuses_merged_source_info_when_a_later_input_ends_empty() -> None: @@ -987,8 +990,10 @@ def stream(data: str, tokens: list[list[str]]) -> ArrowTableStream: kernel = StreamingJoin(Join(), inputs) assert kernel.close(empty) == [] kernel.push(first, _sent(inputs[first]).combine_chunks().to_batches()[0]) + kernel.push(second, _sent(inputs[second]).combine_chunks().to_batches()[0]) + # The first of the two to end decides their pairs. with pytest.raises(ValueError, match="different lengths") as kernel_error: - kernel.push(second, _sent(inputs[second]).combine_chunks().to_batches()[0]) + kernel.close(first) assert str(kernel_error.value) == str(sync_error.value) checked += 1 assert checked > 0 @@ -1081,6 +1086,7 @@ def test_with_several_offending_pairs_the_first_observed_is_refused( for whole in (0, 1): instance = kernel(operator, inputs) instance.push(whole, _sent(inputs[whole]).combine_chunks().to_batches()[0]) + assert instance.close(whole) == [] first_row = _sent(inputs[1 - whole]).combine_chunks().slice(0, 1) with pytest.raises(ValueError, match=form) as error: instance.push(1 - whole, first_row.to_batches()[0]) From 5bc743d32eee81b2f32fdcea8357680cb82ab3b6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 03:00:59 -0800 Subject: [PATCH 19/26] perf(operators): an async join indexes its smaller input only; two-input Rejoin streams; channels give text to public reads (ITL-1464) Review of #565 and #567: a held row costs what is held, whatever was held before it; a channel's public read gives text and reads a stream through its own reader; batches may mix text and derived tokens however they arrive. Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-joins/measure.py | 65 +++- src/orcapod/core/operators/batch.py | 2 +- .../core/operators/static_output_pod.py | 4 +- src/orcapod/core/operators/streaming_joins.py | 300 +++++++++++------- .../core/streams/arrow_table_stream.py | 3 +- src/orcapod/core/streams/base.py | 3 +- src/orcapod/core/streams/carried.py | 16 +- .../core/streams/record_batch_input.py | 38 ++- .../protocols/core_protocols/streams.py | 8 + .../test_record_batch_channels.py | 8 +- .../operators/test_keys_only_joins.py | 212 +++++++++++-- .../test_pipeline/test_review_findings_510.py | 4 +- 12 files changed, 473 insertions(+), 190 deletions(-) diff --git a/docs/dev/specs/itl-1464-joins/measure.py b/docs/dev/specs/itl-1464-joins/measure.py index 46ba50d25..64a79dea7 100644 --- a/docs/dev/specs/itl-1464-joins/measure.py +++ b/docs/dev/specs/itl-1464-joins/measure.py @@ -13,26 +13,32 @@ shank they share: five output rows per spike. - ``many_open``: two inputs of ``rows`` rows in step, neither unique on the session and burst they share: five output rows per row, and both sides' keys held to the end. +- ``rejoin``: one stream of ``rows`` rows split in two branches and rejoined, in step; +- ``semi_late``: ``semi``, the units arriving after every spike; - ``semi``: ``rows`` spikes kept by the units that exist (300). """ from __future__ import annotations import asyncio +import contextlib import resource import sys import time import warnings from collections.abc import Callable, Iterator +from pathlib import Path from typing import Any import numpy as np import pyarrow as pa -from orcapod.core.operators import Join, SemiJoin +from orcapod.core.operators import Join, Rejoin, SemiJoin from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.record_batch_channels import OutputChannel +from orcapod.core import row_spool from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams.carried import carried_table from orcapod.protocols.core_protocols import StreamProtocol BATCH = 8_192 @@ -122,32 +128,44 @@ def __init__( rows: int, tags: list[str], key: list[str], + columns: list[str] | None = None, ): self.make, self.rows, self.key, self.name = make, rows, key, name self.tags = tags + self.columns = columns self.stream = self.source(0, 4) - def source(self, start: int, n: int) -> ArrowTableSource: - return ArrowTableSource( + def source(self, start: int, n: int) -> StreamProtocol: + source = ArrowTableSource( self.make(start, n), tag_columns=self.tags, record_id_columns=self.key, tag_only_columns=True, source_id=self.name, ) + return source.select_data_columns(self.columns) if self.columns else source def batches(self) -> Iterator[pa.RecordBatch]: for start in range(0, self.rows, BATCH): stream: StreamProtocol = self.source(start, min(BATCH, self.rows - start)) zero = StaticOutputOperatorPod._materialize_upstream([], self.stream) names = zero.as_table(columns={"source": True, "system_tags": True}) - table = getattr(stream, "as_carried_table", stream.as_table)( - columns={"source": True, "system_tags": True} - ) + table = carried_table(stream, {"source": True, "system_tags": True}) yield from table.select(names.column_names).combine_chunks().to_batches() -async def run(case: str, rows: int, barrier: bool) -> tuple[int, float]: +def on_disk() -> int: + """The bytes of this process's spool files now.""" + held = row_spool._directories._held.values() # pyright: ignore[reportPrivateUsage] # where they are + files = [f for directory, _ in held for f in Path(directory).rglob("*.arrow")] + total = 0 + for file in files: + with contextlib.suppress(FileNotFoundError): + total += file.stat().st_size + return total + + +async def run(case: str, rows: int, barrier: bool) -> tuple[int, float, int]: tags = {"many": "shank", "many_open": "burst"}.get(case, "unit") big = Input( "spikes", @@ -158,7 +176,12 @@ async def run(case: str, rows: int, barrier: bool) -> tuple[int, float]: if case.startswith("many") else ["session", "unit", "spike"], ) - if case.startswith("one_to_one"): + if case == "rejoin": + big, other = ( + Input("spikes", spikes, rows, big.tags, big.key, columns) + for columns in (["time"], ["amplitude", "shank"]) + ) + elif case.startswith("one_to_one"): other = Input( "second", second, @@ -176,7 +199,13 @@ async def run(case: str, rows: int, barrier: bool) -> tuple[int, float]: ) else: other = Input("units", units, 300, ["unit", "session"], ["session", "unit"]) - op = SemiJoin() if case == "semi" else Join() + op = ( + SemiJoin() + if case.startswith("semi") + else Rejoin() + if case == "rejoin" + else Join() + ) result = op(big.stream, other.stream) output = OutputChannel(result, retain=False, buffer_size=2) reader = output.open_reader() @@ -205,18 +234,29 @@ async def produce(index: int, source: Input, after: asyncio.Event | None) -> Non async def consume() -> None: nonlocal count - async for batch in reader: + async for batch in reader.carried(): count += batch.num_rows if barrier: execute = StaticOutputOperatorPod.async_execute_batches(op, readers, output) else: execute = op.async_execute_batches(readers, output) + disk = 0 + + async def watch() -> None: + nonlocal disk + while True: + disk = max(disk, on_disk()) + await asyncio.sleep(0.2) + + watching = asyncio.create_task(watch()) began = time.perf_counter() await asyncio.gather( produce(0, big, waits[0]), produce(1, other, waits[1]), consume(), execute ) - return count, time.perf_counter() - began + seconds = time.perf_counter() - began + _ = watching.cancel() + return count, seconds, disk if __name__ == "__main__": @@ -224,7 +264,7 @@ async def consume() -> None: case, rows = sys.argv[1], int(sys.argv[2]) barrier = "barrier" in sys.argv base = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss - count, seconds = asyncio.run(run(case, rows, barrier)) + count, seconds, disk = asyncio.run(run(case, rows, barrier)) peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss unit = 2**20 if sys.platform == "darwin" else 2**10 print( @@ -232,4 +272,5 @@ async def consume() -> None: + f" out={count:>11,} {seconds:7.1f} s" + f" peak={peak / unit:8.0f} MiB (import {base / unit:.0f})" + f" arrow_peak={(pa.default_memory_pool().max_memory() or 0) / 2**20:8.0f} MiB" + + f" disk={disk / 2**20:7.0f} MiB" ) diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index e7a1969f8..3215f8267 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -328,7 +328,7 @@ async def async_execute_batches( try: waiting: list[pa.RecordBatch] = [] rows = 0 - async for batch in channel: + async for batch in channel.carried(): if not batch.num_rows: continue # nothing to batch, nothing to hold waiting.append(batch) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 2a7694b00..feab7f617 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1169,7 +1169,7 @@ async def async_execute_batches( # cannot make one table with the earlier ones is refused, as the sync # path refuses the whole input, never processed alone. settled: dict[str, pa.DataType] = {} - async for batch in channel: + async for batch in channel.carried(): settled = settle_token_types(batch, settled) await self._send_processed([batch], channel.stream, output) else: @@ -1210,7 +1210,7 @@ async def _send_result(result: StreamProtocol, output: RecordBatchOutput) -> Non output: The channel to send into; a result with no rows sends nothing. """ table = row_built_columns( - result.as_carried_table(columns=ZERO_ROW_INPUT_COLUMNS), result.keys() + carried_table(result, ZERO_ROW_INPUT_COLUMNS), result.keys() ) for batch in table.to_batches(): if batch.num_rows: diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index e9c0813a6..c2f54c23d 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -145,7 +145,7 @@ # The pair-count column of a many-to-many match, and how many removed rows a side's key # frame holds before it is compacted. _COUNT = "__streaming_count" -_COMPACT_ROWS = 65_536 +_COMPACT_ROWS = 1_024 # How many rows of one input are read ahead and pushed at once. A push joins its rows with # every key held, so rows that have arrived already are pushed together. @@ -302,6 +302,87 @@ def _side_by_side(left: pa.Table, right: pa.Table, keys: Sequence[str]) -> pa.Ta return pa.Table.from_arrays(arrays, names=names) +class _Rows: + """Rows numbered from 0 in the order held, spooled. + + Rows of one input may hold a source-info column as text in one batch and derived in + another (``source_tokens``): each run of rows of one form has a spool of its own, and + rows fetched from several are given as text. + """ + + def __init__(self) -> None: + self.size: int = 0 + self._runs: list[tuple[int, pa.Schema, RowSpool]] = [] + + def append(self, table: pa.Table) -> None: + """Hold ``table``'s rows, numbered from ``size`` on.""" + if not table.num_rows: + return + if not self._runs or not self._runs[-1][1].equals( + table.schema, check_metadata=True + ): + self._runs.append((self.size, table.schema, RowSpool())) + self._runs[-1][2].append(table) + self.size += table.num_rows + + def _by_run( + self, rows: npt.NDArray[np.int64] + ) -> Iterator[tuple[RowSpool, npt.NDArray[np.int64], npt.NDArray[np.int64]]]: + """Each run that holds some of ``rows``: its spool, their positions in ``rows`` + and their numbers in the spool.""" + starts = np.array([start for start, _, _ in self._runs], dtype=np.int64) + runs = np.searchsorted(starts, rows, side="right") - 1 + for run in np.unique(runs): + positions = np.flatnonzero(runs == run) + start, _, spool = self._runs[int(run)] + yield spool, positions, rows[positions] - start + + def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: + """The rows with these numbers, in this order.""" + parts = [(at, spool.take(local)) for spool, at, local in self._by_run(rows)] + if len(parts) == 1: + return parts[0][1] + taken = _one_form([part for _, part in parts]).combine_chunks() + order = np.argsort(np.concatenate([at for at, _ in parts])) + return taken.take(pa.array(order, pa.int64())) + + def block(self, start: int, length: int) -> pa.Table: + """``length`` rows from ``start`` on, none of them discarded, without copying.""" + parts: list[pa.Table] = [] + for run_start, _, spool in self._runs: + first = max(start - run_start, 0) + last = min(start + length - run_start, spool.size) + if first < last: + parts.append(spool.slice(first, last - first)) + return _one_form(parts) + + def discard(self, rows: npt.NDArray[np.int64]) -> None: + """Say that these rows are never fetched again.""" + for spool, _, local in self._by_run(rows): + spool.discard(local) + + def close(self) -> None: + """Let every row and file go.""" + for _, _, spool in self._runs: + spool.close() + self._runs = [] + + +def _one_form(tables: Sequence[pa.Table]) -> pa.Table: + """``tables`` under one another, a source-info column of several forms as text. + + Args: + tables: Rows of one input, at least one table. + """ + kinds: dict[str, set[pa.DataType]] = {} + for table in tables: + for field in table.schema: + if field.name.startswith(constants.SOURCE_PREFIX): + kinds.setdefault(field.name, set()).add(field.type) + mixed = {name for name, types in kinds.items() if len(types) > 1} + return pa.concat_tables([source_tokens.materialize(t, mixed) for t in tables]) + + class _Side: """One side of a symmetric join: its rows' key frame, the rows themselves spooled. @@ -317,15 +398,15 @@ def __init__( self.keys: list[str] = list(keys) self.row: str = row self.closed: bool = False - self.schema: pa.Schema | None = None self.rows: int = 0 self._constant_key: bool = constant_key + self._rows: _Rows = _Rows() + # The key frame, and beside its rows their numbers (ascending) and whether each + # is still held: as long as the frame, whatever the numbers are. self._frames: list[pl.DataFrame] = [] - self._spool: RowSpool = RowSpool() - # Whether each row is still held, by its number less ``_base`` (grown by - # doubling); no row numbered below ``_base`` is held. - self._alive: npt.NDArray[np.bool_] = np.ones(0, dtype=np.bool_) - self._base: int = 0 + self._numbers: npt.NDArray[np.int64] = np.empty(0, dtype=np.int64) + self._alive: npt.NDArray[np.bool_] = np.empty(0, dtype=np.bool_) + self._count: int = 0 self._removed_count: int = 0 def key_frame(self, table: pa.Table) -> pl.DataFrame: @@ -338,57 +419,65 @@ def append(self, table: pa.Table, frame: pl.DataFrame) -> None: """Hold ``table``'s rows, with ``frame`` from ``key_frame``.""" if not table.num_rows: return - # Numbered after the rows already held, as the spool numbers them. - self._frames.append(frame.with_columns(pl.col(self.row) + self._spool.size)) - self._spool.append(table) + self._add_frame(frame, self._rows.size) + self._rows.append(table) self.rows += table.num_rows - numbered = self._spool.size - self._base - if numbered > len(self._alive): - grown = np.ones(2 * numbered, dtype=np.bool_) - grown[: len(self._alive)] = self._alive - self._alive = grown + + def _add_frame(self, frame: pl.DataFrame, first: int) -> None: + """Hold the keys of rows numbered from ``first``, in ``frame``'s order.""" + self._frames.append(frame.with_columns(pl.col(self.row) + first)) + count = self._count + frame.height + if count > len(self._numbers): + for name in ("_numbers", "_alive"): + old = getattr(self, name) + grown = np.empty(2 * count, dtype=old.dtype) + grown[: self._count] = old[: self._count] + setattr(self, name, grown) + self._numbers[self._count : count] = np.arange(first, first + frame.height) + self._alive[self._count : count] = True + self._count = count def spool(self, table: pa.Table) -> None: """Hold ``table``'s rows without their keys, until ``index`` or ``replay``.""" - self._spool.append(table) + self._rows.append(table) self.rows += table.num_rows def index(self) -> None: """Prepare the keys of the rows held without them (every row held).""" - for rows in self._row_blocks(): + for start in range(0, self._rows.size, PUSH_ROWS): # Only the keys are read, and nothing is copied. - table = self._spool.slice(int(rows[0]), len(rows)) - frame = self.key_frame(table.select(self.keys) if self.keys else table) - self._frames.append(frame.with_columns(pl.col(self.row) + int(rows[0]))) - self._alive = np.ones(self._spool.size, dtype=np.bool_) + table = self._rows.block(start, min(PUSH_ROWS, self._rows.size - start)) + self._add_frame( + self.key_frame(table.select(self.keys) if self.keys else table), start + ) def replay(self) -> Iterator[pa.Table]: """Give the rows held without keys, in order, in blocks, and let each block go. A block's rows are let go once the next one is asked for. """ - for rows in self._row_blocks(): - yield self._spool.take(rows) - self._spool.discard(rows) + for start in range(0, self._rows.size, PUSH_ROWS): + rows = np.arange(start, min(start + PUSH_ROWS, self._rows.size)) + yield self._rows.take(rows) + self._rows.discard(rows) self.rows -= len(rows) - def _row_blocks(self) -> Iterator[npt.NDArray[np.int64]]: - """The row numbers of the rows held, none let go, ``PUSH_ROWS`` at a time.""" - for start in range(0, self._spool.size, PUSH_ROWS): - yield np.arange(start, min(start + PUSH_ROWS, self._spool.size)) - def held(self, rows: npt.NDArray[np.int64]) -> npt.NDArray[np.int64]: - """Those of ``rows`` that were not removed.""" - return rows[self._alive[rows - self._base]] + """Those of ``rows``, numbers in the key frame, that were not removed.""" + return rows[self._alive[self._positions(rows)]] + + def _positions(self, rows: npt.NDArray[np.int64]) -> npt.NDArray[np.int64]: + """Where the rows with these numbers are in the key frame.""" + return np.searchsorted(self._numbers[: self._count], rows) def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: """The held rows with these numbers, in this order.""" - return self._spool.take(rows) + return self._rows.take(rows) def frame(self) -> pl.DataFrame: """The key frame of the rows held and, until compacted, of removed ones. - A caller whose removed rows can match again asks ``held`` which are held. + A caller whose removed rows can match again asks ``held_frame``. """ if len(self._frames) != 1: self._frames = [pl.concat(self._frames, rechunk=False)] @@ -399,44 +488,36 @@ def held_frame(self) -> pl.DataFrame: frame = self.frame() if not self._removed_count: return frame - rows = frame.get_column(self.row).to_numpy() - return frame.filter(pl.Series(self._alive[rows - self._base])) + return frame.filter(pl.Series(self._alive[: self._count])) def remove(self, rows: npt.NDArray[np.int64]) -> None: """Let rows go that can never match again: each is held, each given once.""" if not len(rows): return - self._spool.discard(rows) + self._rows.discard(rows) self.rows -= len(rows) - self._alive[rows - self._base] = False + self._alive[self._positions(rows)] = False self._removed_count += len(rows) if not self.rows or self._removed_count >= max(self.rows, _COMPACT_ROWS): self._compact() def _compact(self) -> None: - """Drop the removed rows from the key frame, and the numbers below the rest.""" + """Drop the removed rows from the key frame.""" + if self.rows: + self._frames = [self.held_frame()] + self._numbers = self._numbers[: self._count][self._alive[: self._count]] + else: + self._frames, self._numbers = [], np.empty(0, dtype=np.int64) + self._count = len(self._numbers) + self._alive = np.ones(self._count, dtype=np.bool_) self._removed_count = 0 - if not self.rows: - self._frames, self._base = [], self._spool.size - self._alive = np.ones(0, dtype=np.bool_) - return - frame = self.frame() - rows = frame.get_column(self.row).to_numpy() - kept = frame.filter(pl.Series(self._alive[rows - self._base])) - self._frames = [kept] - # The frame's rows are in the order of their numbers. - base = int(kept.get_column(self.row)[0]) - self._alive = self._alive[base - self._base :].copy() - self._base = base def clear(self) -> None: """Drop every row held, and their files.""" - self._frames = [] - self._alive = np.ones(0, dtype=np.bool_) - self._removed_count, self._base = 0, 0 - self._spool.close() - self._spool = RowSpool() self.rows = 0 + self._compact() + self._rows.close() + self._rows = _Rows() class _BinaryLink: @@ -451,10 +532,12 @@ class _BinaryLink: only if, the other side is unique: it can match nothing else. With both sides unique (one to one) rows are matched as they arrive and let go. Any - other link holds the keys of one side only: while both sides are open, the rows of - both are spooled without keys and nothing is emitted; when a side ends, its keys are - prepared, the other side's spooled rows are matched with them and let go, and every - row still to arrive is matched at once and not held. + other link holds the keys of its smaller side only. Rows are spooled without keys + until a side is known to be the smaller one: when one has ended, the other is spooled + on until it has as many rows (the ended side is indexed) or ends with fewer (it is + indexed itself). An ended side of at most ``PUSH_ROWS`` rows is indexed at once. Then + the other side's spooled rows are matched with the index and let go, and every row + still to arrive is matched at once and not held. """ def __init__( @@ -466,6 +549,7 @@ def __init__( self.unique: tuple[bool, bool] = unique self.keys: list[str] = list(keys) self.one_to_one: bool = all(unique) + self._indexed: bool = self.one_to_one self.sides: tuple[_Side, _Side] = (_Side(keys, _ROW[0]), _Side(keys, _ROW[1])) self._finish: Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table] = finish @@ -506,8 +590,6 @@ def push(self, side: int, table: pa.Table) -> Iterator[pa.Table]: The output rows of the new pairs, in pieces of at most ``PAIRS_PER_BATCH``. """ this, other = self.sides[side], self.sides[1 - side] - if this.schema is None: - this.schema = table.schema if other.closed and not other.rows: # Nothing can pair with these rows, and none is held: no key to prepare. return @@ -517,10 +599,28 @@ def push(self, side: int, table: pa.Table) -> Iterator[pa.Table]: table = table.filter(_has_whole_key(table, self.keys)) if not table.num_rows: return - if not self.one_to_one and not other.closed: - this.spool(table) + if self._indexed: + yield from self._match(side, table) return - yield from self._match(side, table) + this.spool(table) + if other.closed and this.rows >= other.rows: + yield from self._index(1 - side) + + def _index(self, side: int) -> Iterator[pa.Table]: + """Index ``side``, which has ended, and match the other side's spooled rows. + + Args: + side: The side no larger than the other. + + Yields: + The output rows of the pairs, in pieces. + """ + self._indexed = True + self.sides[side].index() + other = self.sides[1 - side] + for table in other.replay(): + yield from self._match(1 - side, table) + other.clear() def _match(self, side: int, table: pa.Table) -> Iterator[pa.Table]: """Match ``table``'s rows, whose keys are whole, with the other side's keys. @@ -549,12 +649,8 @@ def _match(self, side: int, table: pa.Table) -> Iterator[pa.Table]: gone.append(theirs) taken = (table.take(pa.array(mine, pa.int64())), other.take(theirs)) left, right = taken if side == 0 else (taken[1], taken[0]) - assert self.sides[0].schema is not None - assert self.sides[1].schema is not None yield self._finish( - _side_by_side(left, right, self.keys), - self.sides[0].schema, - self.sides[1].schema, + _side_by_side(left, right, self.keys), left.schema, right.schema ) if gone: other.remove(np.concatenate(gone)) @@ -573,17 +669,22 @@ def close(self, side: int) -> Iterator[pa.Table]: side: The side that ends. Yields: - The output rows that decides: those of the other side's spooled rows, when - ``side`` is the first of a link's sides to end. + The output rows that decides: those of spooled rows, when it is now known + which side is the smaller one. """ this, other = self.sides[side], self.sides[1 - side] this.closed = True - if this.rows and other.rows and not self.one_to_one and not other.closed: - this.index() - for table in other.replay(): - yield from self._match(1 - side, table) - elif not self.one_to_one and not other.closed: - this.index() + if not self._indexed: + if other.closed: + # Both ended: ``other`` ended first, with more rows than this one. + if this.rows: + yield from self._index(side) + this.clear() + elif this.rows and (this.rows <= PUSH_ROWS or other.rows >= this.rows): + yield from self._index(side) + return + elif this.rows: + return other.clear() @@ -637,9 +738,6 @@ def __init__( # (``settle_token_types``): the input's complete table must still be buildable, # as the sync path builds it before matching. self._token_types: list[dict[str, pa.DataType]] = [{} for _ in self.inputs] - # The form of each input's source-info columns, as its first batch with rows - # holds them: text, or derived by a recipe (``source_tokens``, ITL-1464). - self._token_forms: list[dict[str, pa.DataType] | None] = [None] * len(inputs) self._emitted_any: bool = False # The sync path over no rows: its checks, and the output's columns. self.zero_row_result: StreamProtocol = operator.static_process(*self._zero_rows) @@ -822,7 +920,6 @@ def _as_input_table(self, input_index: int, batch: pa.RecordBatch) -> pa.Table: + f"the column(s) {missing} its stream describes" ) table = pa.Table.from_batches([batch]).select(layout.names) - table = self._in_one_token_form(input_index, table) columns = list(table.columns) fields = list(layout) for index, (field, actual) in enumerate(zip(layout, table.schema)): @@ -856,37 +953,6 @@ def _as_input_table(self, input_index: int, batch: pa.RecordBatch) -> pa.Table: return layout.empty_table() return pa.Table.from_arrays(columns, schema=pa.schema(fields)) - def _in_one_token_form(self, input_index: int, table: pa.Table) -> pa.Table: - """``table`` with its source-info columns in the form of the input's first batch. - - A column that batch held as text becomes text; one it derived must be derived by - the same recipe, since the rows held already have no text. - - Raises: - ValueError: If a later batch holds such a column in another form. - """ - if not table.num_rows: - return table - kept = self._token_forms[input_index] - if kept is None: - kept = { - field.name: field.type - for field in table.schema - if source_tokens.derived_recipe(field.type) is not None - } - self._token_forms[input_index] = kept - texts = set(table.column_names) - set(kept) - table = source_tokens.materialize(table, texts) - for name, kind in kept.items(): - actual = table.schema.field(name).type - if actual != kind: - raise ValueError( - f"{type(self).__name__}: the source-info column {name!r} of input " - + f"{input_index} changed its form between batches: {kind}, then " - + f"{actual}. A producer sends each such column in one form." - ) - return table - def _check_settled_token_types( self, input_index: int, token_types: Mapping[str, pa.DataType] ) -> None: @@ -1514,8 +1580,6 @@ def push(self, side: int, table: pa.Table) -> pa.Table | None: The output rows of the matched pairs, or ``None`` when there is none. """ this, other = self.sides[side], self.sides[1 - side] - if this.schema is None: - this.schema = table.schema table = _with_system_tags(table, self.system) if not table.num_rows: return None @@ -1553,12 +1617,8 @@ def _pairs(self, left: pa.Table, right: pa.Table) -> pa.Table: if name not in left.column_names: names.append(name) arrays.append(right.column(name)) - assert self.sides[0].schema is not None - assert self.sides[1].schema is not None return self._finish( - pa.Table.from_arrays(arrays, names=names), - self.sides[0].schema, - self.sides[1].schema, + pa.Table.from_arrays(arrays, names=names), left.schema, right.schema ) def _note_differing(self, rest: pa.Table, other: _Side, side: int) -> None: @@ -1893,7 +1953,7 @@ async def fill(self, channel: RecordBatchInput, claim: object) -> None: """Read ``channel`` to its end, waiting while ``PUSH_ROWS`` rows or more are unread.""" try: _ = channel.reserve(claim) - async for batch in channel: + async for batch in channel.carried(): if not batch.num_rows: continue self._batches.append(batch) diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 4860839f1..dcc6d3e91 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -354,8 +354,9 @@ def as_table( columns_config = ColumnConfig.handle_config(columns, all_info=all_info) return self._assemble_table(columns_config, limit=None) - def _carried_table(self, config: ColumnConfig) -> "pa.Table": + def _carried_table(self, columns: ColumnConfig | dict[str, Any]) -> "pa.Table": """The table with its derived token columns as they are (``carried_table``).""" + config = ColumnConfig.handle_config(columns) return self._assemble_table(config, limit=None, carried=config.system_tags) def head( diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index a9720b97d..b3ce4fcf2 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -21,6 +21,7 @@ import polars as pl import pyarrow as pa +from orcapod.core.streams.carried import carried_table from orcapod.core.unique_keys import NO_UNIQUE_KEYS, UniqueKeys from orcapod.core.base import TraceableBase from orcapod.core.data_tags import data_tag_names @@ -544,7 +545,7 @@ def _row_built_table(self) -> pa.Table: retyped as a row retypes it. Only a stream that holds such a column (a raw ``ArrowTableStream``) is read that way, and its reads have no effect. """ - table = self._stream.as_carried_table(columns=ZERO_ROW_INPUT_COLUMNS) + table = carried_table(self._stream, ZERO_ROW_INPUT_COLUMNS) if not system_tags_as_rows_give(table): from orcapod.core.operators.static_output_pod import ( StaticOutputOperatorPod, diff --git a/src/orcapod/core/streams/carried.py b/src/orcapod/core/streams/carried.py index 5fca2f948..50e5ea17e 100644 --- a/src/orcapod/core/streams/carried.py +++ b/src/orcapod/core/streams/carried.py @@ -11,23 +11,19 @@ class is a library class that declares ``_carried_table`` itself, read as that c from __future__ import annotations -from typing import TYPE_CHECKING, Any +from typing import Any -from orcapod.core.streams.base import reads_as_its_class -from orcapod.types import ColumnConfig +import pyarrow as pa -if TYPE_CHECKING: - import pyarrow as pa - - from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.core.exact_class import reads_as_its_class CARRIED_TABLE = "_carried_table" """The method a library class declares when its table may hold derived columns.""" def carried_table( - stream: StreamProtocol, - columns: ColumnConfig | dict[str, Any], # pyright: ignore[reportExplicitAny] # as as_table + stream: Any, # pyright: ignore[reportExplicitAny] # a stream (the protocol would make an import cycle) + columns: Any, # pyright: ignore[reportExplicitAny] # as as_table ) -> pa.Table: """``stream.as_table(columns=columns)``, derived token columns as they are. @@ -43,4 +39,4 @@ def carried_table( read: Any = vars(kind).get(CARRIED_TABLE) # pyright: ignore[reportExplicitAny] # a method if read is None or not reads_as_its_class(stream, kind): return stream.as_table(columns=columns) - return read(stream, ColumnConfig.handle_config(columns)) + return read(stream, columns) diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py index c7919638b..1d31594b6 100644 --- a/src/orcapod/core/streams/record_batch_input.py +++ b/src/orcapod/core/streams/record_batch_input.py @@ -21,11 +21,12 @@ from collections.abc import AsyncIterator, Coroutine from typing import TYPE_CHECKING, Any, Protocol +import pyarrow as pa + from orcapod.channels import ChannelClosed +from orcapod.utils import source_tokens if TYPE_CHECKING: - import pyarrow as pa - from orcapod.protocols.core_protocols.streams import StreamProtocol SOURCE_BATCH_ROWS = 65_536 @@ -235,7 +236,34 @@ def _belong_to_caller(self) -> None: ) async def receive(self) -> pa.RecordBatch: - """Return the next Arrow record batch. + """Return the next Arrow record batch, its source-info tokens as text. + + The text of a derived token column (``utils/source_tokens.py``) is built here: a + recipe leaves the library in no batch. The rest is as ``_receive_carried``. + """ + batch = await self._receive_carried() + if not source_tokens.derived_columns(batch.schema): + return batch + table = source_tokens.materialize(pa.Table.from_batches([batch])) + return table.combine_chunks().to_batches()[0] + + async def carried(self) -> AsyncIterator[pa.RecordBatch]: + """Iterate over the remaining record batches as they travel, for an operator. + + Their source-info columns may be derived; the end and the errors are those of + iterating the channel. + """ + while True: + try: + batch = await self._receive_carried() + except ChannelClosed: + if self._ended and not self._closed: + return + raise + yield batch + + async def _receive_carried(self) -> pa.RecordBatch: + """Return the next Arrow record batch, as it travels. A read that is cancelled while it waits closes the channel, as ``close`` does: a consumer that stops reading never holds its producer. @@ -365,7 +393,9 @@ async def _to_stream(self, claim: object) -> StreamProtocol: if opened_on is not None and getattr(opened_on, ROW_BUILT_OUTPUT, False): await self.close() return opened_on - return stream_from_batches(self._stream, await self.collect()) + return stream_from_batches( + self._stream, [batch async for batch in self.carried()] + ) async def collect(self) -> list[pa.RecordBatch]: """Read to the end and return every remaining record batch, in arrival order. diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index f83b2ea88..091ee81bb 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -682,6 +682,14 @@ def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: """Iterate over the remaining record batches, in arrival order.""" ... + def carried(self) -> AsyncIterator[pa.RecordBatch]: + """Iterate over the remaining record batches as they travel, for an operator. + + Their source-info columns may be derived (``utils/source_tokens.py``): internal. + Every other read gives their text. + """ + ... + async def collect(self) -> list[pa.RecordBatch]: """Read to the end and return every remaining record batch, in arrival order.""" ... diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 635dbc85c..e9b80d526 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -875,13 +875,15 @@ async def read() -> None: def test_opening_a_channel_computes_nothing() -> None: - """The stream's table is read at the first ``receive``, not when the channel opens.""" + """The stream's table is read at the first ``receive``, not when the channel opens. + + A library class's table is read with its tokens as they are (``carried_table``).""" stream = source() with mock.patch.object( ArrowTableSource, - "as_table", + "_carried_table", autospec=True, - side_effect=ArrowTableSource.as_table, + side_effect=ArrowTableSource._carried_table, ) as read: channel = stream.open_channel() assert read.call_count == 0 diff --git a/tests/test_core/operators/test_keys_only_joins.py b/tests/test_core/operators/test_keys_only_joins.py index ca1a5bcef..ce1683403 100644 --- a/tests/test_core/operators/test_keys_only_joins.py +++ b/tests/test_core/operators/test_keys_only_joins.py @@ -32,7 +32,7 @@ ) from orcapod.core.record_batch_channels import OutputChannel from orcapod.core.row_spool import RowSpool -from orcapod.core.sources import ArrowTableSource +from orcapod.core.sources import ArrowTableSource, DictSource from orcapod.core.streams import ArrowTableStream from orcapod.errors import UpstreamFailedError from orcapod.protocols.core_protocols import StreamProtocol @@ -52,12 +52,14 @@ def _quiet() -> Any: @pytest.fixture(params=["memory", "disk"]) def spooled(request: pytest.FixtureRequest, tmp_path: Path, monkeypatch: Any) -> Path: - """Every spool in memory, or every row on disk; output in pieces of 3 rows.""" + """Every spool in memory, or every row on disk; output in pieces of 3 rows, and an + ended side of more than 2 rows indexed only once it is known to be the smaller.""" limit = 0 if request.param == "disk" else 1 << 40 monkeypatch.setattr( streaming_joins, "RowSpool", functools.partial(RowSpool, limit, str(tmp_path)) ) monkeypatch.setattr(streaming_joins, "PAIRS_PER_BATCH", 3) + monkeypatch.setattr(streaming_joins, "PUSH_ROWS", 2) monkeypatch.setattr(streaming_joins, "_COMPACT_ROWS", 4) return tmp_path @@ -294,7 +296,7 @@ def _keys_held(kernel: StreamingJoinKernel) -> list[int]: @pytest.mark.parametrize("first", [0, 1]) -def test_a_lookup_holds_the_keys_of_the_side_that_ends_first( +def test_a_join_holds_the_keys_of_its_smaller_side_whichever_ends_first( spooled: Path, first: int ) -> None: spikes = _source( @@ -304,32 +306,65 @@ def test_a_lookup_holds_the_keys_of_the_side_that_ends_first( inputs = [spikes, units] batches = [_batches(spikes, 8), _batches(units, 2)] kernel = StreamingJoin(Join(), inputs) + small = kernel._position[1] # pyright: ignore[reportPrivateUsage] # its side + emitted = 0 + + def step(out: list[pa.RecordBatch]) -> None: + nonlocal emitted + emitted += sum(b.num_rows for b in out) + held = _keys_held(kernel) + assert held[1 - small] == 0 # the larger side never has keys + assert held[small] <= 3 + for batch in batches[first]: - assert kernel.push(first, batch) == [] - early = batches[1 - first][0] - assert kernel.push(1 - first, early) == [] - assert _keys_held(kernel) == [0, 0] # rows, no keys - emitted = sum(b.num_rows for b in kernel.close(first)) - assert emitted == (6 if first == 1 else 20) - side = kernel._position[first] # pyright: ignore[reportPrivateUsage] # its side - held = _keys_held(kernel) - assert held[1 - side] == 0 # the other side never has keys, before or after - assert 0 < held[side] <= sum(b.num_rows for b in batches[first]) - for batch in batches[1 - first][1:]: - emitted += sum(b.num_rows for b in kernel.push(1 - first, batch)) - assert _keys_held(kernel)[1 - side] == 0 + step(kernel.push(first, batch)) + step(kernel.close(first)) + assert emitted == 0 + for batch in batches[1 - first]: + step(kernel.push(1 - first, batch)) + if first == 0: + assert emitted == 0 # the units may still be more than the spikes + step(kernel.close(1 - first)) assert emitted == 30 - assert kernel.close(1 - first) == [] assert kernel.held_rows == 0 assert _files(spooled) == [] -def test_a_row_of_a_lookup_indexed_first_is_let_go_when_it_matches( +def test_an_ended_side_is_indexed_once_the_other_has_as_many_rows( spooled: Path, +) -> None: + """The wait is bounded by the ended side's rows: nothing waits for an end.""" + left = _source("a", {"k": [1, 2] * 5, "n": list(range(10))}) + right = _source("b", {"k": [1, 2] * 50, "m": list(range(100))}) + kernel = _join([left, right]) + for batch in _batches(left, 5): + assert kernel.push(0, batch) == [] + assert kernel.close(0) == [] + emitted = [ + sum(b.num_rows for b in kernel.push(1, batch)) for batch in _batches(right, 5) + ] + assert emitted[:2] == [0, 50] # ten rows arrived: the left ten are indexed + assert emitted[2:] == [25] * 18 + assert kernel.held_rows == 10 + + +def test_a_small_ended_side_is_indexed_at_once(spooled: Path) -> None: + left = _source("a", {"k": [1, 2], "n": [1, 2]}) + right = _source("b", {"k": [1, 2] * 5, "m": list(range(10))}) + kernel = _join([left, right]) + for batch in _batches(left, 2): + kernel.push(0, batch) + kernel.close(0) + assert sum(b.num_rows for b in kernel.push(1, _batches(right, 1)[0])) == 1 + + +def test_a_row_of_a_lookup_indexed_first_is_let_go_when_it_matches( + spooled: Path, monkeypatch: pytest.MonkeyPatch ) -> None: """The other side is unique, so an indexed row can match only once.""" spikes = _source("spikes", {"unit": [0, 0, 1, 2], "n": [1, 2, 3, 4]}, key=("n",)) units = _source("units", {"unit": [0, 1, 2], "area": [1, 1, 2]}, key=("unit",)) + monkeypatch.setattr(streaming_joins, "PUSH_ROWS", 64) # indexed at once kernel = _join([spikes, units]) (all_spikes,), all_units = _batches(spikes, 4), _batches(units, 1) kernel.push(0, all_spikes) @@ -358,7 +393,10 @@ def test_without_a_certificate_the_indexed_rows_stay(spooled: Path) -> None: assert _files(spooled) == [] -def test_a_many_to_many_match_is_emitted_in_bounded_pieces(spooled: Path) -> None: +def test_a_many_to_many_match_is_emitted_in_bounded_pieces( + spooled: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(streaming_joins, "PUSH_ROWS", 64) # indexed at once left = _source("a", {"k": [1] * 20 + [2], "n": list(range(21))}) right = _source("b", {"k": [1] * 15 + [2], "m": list(range(16))}) (mine,), (theirs,) = _batches(left, 21), _batches(right, 16) @@ -584,7 +622,7 @@ def _carried(stream: StreamProtocol) -> pa.Table: feed = stream.open_channel() async def read() -> list[pa.RecordBatch]: - return await feed.collect() + return [batch async for batch in feed.carried()] return pa.Table.from_batches(asyncio.run(read())) @@ -679,23 +717,55 @@ def test_inputs_of_one_pipeline_hash_sort_their_system_tags(spooled: Path) -> No _ = _check_derived(_join, Join().static_process, renamed) -def test_a_producer_that_changes_a_tokens_form(spooled: Path) -> None: +@pytest.mark.parametrize("first", ["text", "derived"]) +def test_a_producer_that_changes_a_tokens_form(spooled: Path, first: str) -> None: left, right = KINDS["one_to_one"]("tags_first") (derived,) = _carried(left).combine_chunks().to_batches() (text,) = source_tokens.materialize(_carried(left)).combine_chunks().to_batches() - # Text first: later derived batches are built as text. + one, two = (text, derived) if first == "text" else (derived, text) kernel = _join([left, right]) - _ = kernel.push(0, text.slice(0, 3)) - _ = kernel.push(0, derived.slice(3)) - out = [b for batch in _carried(right).to_batches() for b in kernel.push(1, batch)] - got = source_tokens.materialize(pa.Table.from_batches(out)) - assert _rows(got) == _rows(_transport(left.join(right))) - # Derived first: the rows held have no text, so text is refused, changing nothing. - other = _join([left, right]) - _ = other.push(0, derived.slice(0, 3)) - with pytest.raises(ValueError, match="changed its form"): - _ = other.push(0, text.slice(3)) - assert other.held_rows == 3 + _ = kernel.push(0, one.slice(0, 3)) + _ = kernel.push(0, two.slice(3)) + rows: Any = Counter() + for batch in _carried(right).to_batches(): + for out in kernel.push(1, batch): + rows += _rows(source_tokens.materialize(pa.Table.from_batches([out]))) + assert rows == _rows(_transport(left.join(right))) + + +@pytest.mark.parametrize("staged", [False, True]) +@pytest.mark.parametrize("kind", ["one_to_one", "lookup", "many_to_many"]) +@pytest.mark.parametrize("op", [Join(), SemiJoin(), MergeJoin()], ids=lambda o: repr(o)) +def test_batches_of_both_forms_however_they_arrive( + spooled: Path, op: Any, kind: str, staged: bool +) -> None: + """Review of #567: grouped arrivals succeeded where staged ones were refused.""" + inputs = KINDS[kind]("tags_first") + expected = _rows(_transport(op(*inputs))) + tables = [_carried(s) for s in inputs] + + async def go() -> StreamProtocol: + channels = [OutputChannel(s, retain=False, buffer_size=8) for s in inputs] + output = OutputChannel(op(*inputs)) + readers = [channel.open_reader() for channel in channels] + run = asyncio.create_task(op.async_execute_batches(readers, output)) + for channel, table in zip(channels, tables): + size = max(1, table.num_rows // 3) + for start in range(0, table.num_rows, size): + part = table.slice(start, size) + if (start // size) % 2: + part = source_tokens.materialize(part) + for batch in part.combine_chunks().to_batches(): + await channel.send(batch) + if staged: + await asyncio.sleep(0.01) + for channel in channels: + await channel.close() + await run + return output.result() + + assert _rows(_transport(_bounded(go()))) == expected + assert _files(spooled) == [] @pytest.mark.parametrize("op", [Join(), SemiJoin(), MergeJoin()], ids=lambda o: repr(o)) @@ -824,10 +894,13 @@ async def go() -> int: op.async_execute_batches([reader, small.open_channel()], output) ) + batches = _batches(endless, 2) + async def produce() -> None: while True: - for batch in _batches(endless, 2): + for batch in batches: await channel.send(batch) + await asyncio.sleep(0) # also when nobody reads any more producing = asyncio.create_task(produce()) rows = 0 @@ -974,3 +1047,74 @@ def test_rejoin_of_three_inputs_is_a_barrier_and_equal(spooled: Path) -> None: output = OutputChannel(op(*inputs)) _bounded(op.async_execute_batches([s.open_channel() for s in inputs], output)) assert _rows(_transport(output.result())) == _rows(_transport(op(*inputs))) + + +def test_one_old_row_does_not_pin_what_later_rows_cost(spooled: Path) -> None: + """Review of #565: a mask numbered from an old row grew with every later one.""" + left, right = _sorted_source("a", 400), _sorted_source("b", 400) + kernel = StreamingJoin(Join(), [left, right]) + (link,) = kernel._links # pyright: ignore[reportPrivateUsage] # what it keeps + lefts, rights = _batches(left, 4), _batches(right, 4) + _ = kernel.push(0, lefts[0]) # never matched until the end + for mine, theirs in zip(lefts[1:], rights[1:]): + _ = kernel.push(0, mine) + _ = kernel.push(1, theirs) + for side in link.sides: + assert len(side._alive) <= 32 # pyright: ignore[reportPrivateUsage] # what it keeps + assert len(side._numbers) <= 32 # pyright: ignore[reportPrivateUsage] # what it keeps + assert kernel.held_rows == 4 + assert sum(b.num_rows for b in kernel.push(1, rights[0])) == 4 + + +def test_a_public_read_of_a_channel_gives_text() -> None: + """Review of #567: a recipe reached a consumer, which could write it to a file.""" + source = _data_tagged("a", 5) + + async def read() -> list[list[pa.RecordBatch]]: + sent = OutputChannel(source) + for batch in _carried_batches: + await sent.send(batch) + await sent.close() + feeds = [source.open_channel, sent.open_reader] + return [ + [await feed().receive() for feed in feeds], + [batch for feed in feeds async for batch in feed()], + [batch for feed in feeds for batch in await feed().collect()], + ] + + _carried_batches = _carried(source).combine_chunks().to_batches() + assert source_tokens.derived_columns(_carried_batches[0].schema) + for batches in _bounded(read()): + assert len(batches) == 2 + for batch in batches: + assert source_tokens.derived_columns(batch.schema) == () + assert pa.Table.from_batches([batch]).to_pylist() == ( + _transport(source).select(batch.schema.names).to_pylist() + ) + + +def test_a_channel_reads_a_stream_through_its_own_reader() -> None: + """Review of #567: a subclass's ``as_table`` was bypassed.""" + + class OneRow(ArrowTableStream): + def as_table(self, **kwargs: Any) -> pa.Table: # pyright: ignore[reportIncompatibleMethodOverride] # a user's reader + return super().as_table(**kwargs).slice(0, 1) + + stream = OneRow(pa.table({"k": [1, 2], "x": [1, 2]}), tag_columns=["k"]) + batches = _bounded(stream.open_channel().collect()) + assert sum(batch.num_rows for batch in batches) == 1 + + +def test_rows_with_logical_types_are_replayed(spooled: Path) -> None: + """A logical type (a ``Path``) among the columns of rows held and replayed.""" + rows = [ + {"k": i % 2, "n": i, "p": Path(f"/x/{i}"), "q": [Path("/y")]} for i in range(9) + ] + left = DictSource( + rows, tag_columns=["n", "k"], tag_only_columns=True, source_id="left" + ) + right = _source("b", {"k": [0, 1], "m": [1, 2]}) + for inputs in ([left, right], [right, left]): + _check(_join, Join().static_process, inputs, range(4)) + _check(_semi, SemiJoin().static_process, inputs, range(4)) + _check(_merge, MergeJoin().static_process, inputs, range(4)) diff --git a/tests/test_pipeline/test_review_findings_510.py b/tests/test_pipeline/test_review_findings_510.py index 488ae59d1..d2467f69f 100644 --- a/tests/test_pipeline/test_review_findings_510.py +++ b/tests/test_pipeline/test_review_findings_510.py @@ -166,9 +166,9 @@ def test_a_failed_batch_preparation_is_raised_again_without_a_second_read() -> N base = _plain() class Failing: - def as_carried_table(self, **kwargs: Any) -> Any: + def as_table(self, **kwargs: Any) -> Any: reads.append(1) - return base.as_carried_table(**kwargs) + return base.as_table(**kwargs) def keys(self, **kwargs: Any) -> Any: raise RuntimeError("keys failed") From 2252309782c2e950e1fc501f252bac03815a01cb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 03:14:30 -0800 Subject: [PATCH 20/26] docs(dev): async joins hold their smaller input's keys, measured (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-joins.md | 145 +++++++++--------- src/orcapod/core/operators/streaming_joins.py | 12 +- 2 files changed, 80 insertions(+), 77 deletions(-) diff --git a/docs/dev/specs/itl-1464-joins.md b/docs/dev/specs/itl-1464-joins.md index c62281c75..a7df95ed4 100644 --- a/docs/dev/specs/itl-1464-joins.md +++ b/docs/dev/specs/itl-1464-joins.md @@ -1,48 +1,59 @@ # Joins that hold keys, and certificates of unique tags (ITL-1464) Status: implemented with this document, November 25, 2026; design decisions approved by the -coordinator under the developer's delegation. It covers `Join`, `MergeJoin` and -`SemiJoin` over record-batch channels (`async_execute_batches`). No job node calls that -form yet: the transport work of ITL-1464 wires it, and until then a job's memory is as +coordinator under the developer's delegation. It covers `Join`, `MergeJoin`, `SemiJoin` and +two-input `Rejoin` over record-batch channels (`async_execute_batches`). No job node calls +that form yet: the transport work of ITL-1464 wires it, and until then a job's memory is as before. The sync path is unchanged, and no hash, identity, stored row or golden value moves. ## What an async join holds -Each side of a binary join step keeps, per row that can still match, its prepared join keys -and its row number (a Polars frame, `streaming_joins._Side`); the rows are in a row spool +A binary join step keeps, per row of **one** side that can still match, its prepared join +keys and its row number (a Polars frame, `streaming_joins._Side`); rows are in a row spool (`core/row_spool.py`). Matching is the sync path's (`join._matched_pairs` on `arrow_keys.polars_key_frame`), one vectorized join per arriving batch, and every value is taken from the rows by number, so it is the input's, bit for bit. -| Case | Held | Let go | +| Step | Held | When rows are emitted | |---|---|---| -| both sides unique on the shared tags (1:1) | keys of the rows not matched yet | both rows of a pair, when they match | -| one side unique (a lookup) | keys of the unique side; of the other side, rows that arrived and have not matched | a row of the other side, when it matches | -| neither (many to many) | keys of both sides | nothing while both inputs are open | -| any | | a side's rows, when the other side ends | -| `SemiJoin` | distinct right keys; undecided left rows' keys | a left row, when a right row matches it | - -One rule covers the first three: **a row is let go once it has matched if and only if the -other side is unique on the join keys.** A join of three or more inputs is a chain of such -steps in canonical order; each step's left side has the certificate of the rows joined so -far (`unique_keys.joined_keys`). - -Memory, per held row: the prepared key (16 bytes per string, plus its length when above 12 -bytes; 8 per integer, timestamp or float; 1 for the constant key), 8 for the row number, 1 -for the removal mask. Beside it: at most 64 MiB of rows per side before they go to disk, the -batches in flight, and one output piece of at most 8,192 pairs. Worst case, with no -certificate and neither input ended, the keys of both inputs. A many-to-many output is never -held: the pairs are counted first, then made in pieces; one arriving row with more pairs -than a piece has its pairs listed (16 bytes each, at most the held rows) and is sent in -pieces. - -Every input is read at once and to its end, each until 65,536 rows wait for the join (the -producer's last batch is taken whole, whatever its size). Nothing -waits for one input to end, because both inputs may read one upstream (a diamond). - -Not covered: `Rejoin` stays a barrier on this path, because its kernel can differ from the -sync path for repeated origins with three or more inputs. A subclass of an operator runs its -own sync call over its whole inputs. +| both sides certified unique on the shared tags (1:1) | keys of the rows not matched yet; both rows of a pair go when they match | as they match | +| any other | keys of the smaller side; a row of it goes when it matches, if the other side is certified unique | once the smaller side is known | +| `SemiJoin` | the distinct keys of the right input | once the right input has ended | +| `Rejoin` of two inputs | shared columns of the rows not matched yet | as they match | + +**Which side is indexed.** While both sides are open, the rows of both are spooled without +keys. When a side ends with at most 65,536 rows it is indexed. When it ends with more, the +other side is spooled on until it has as many rows (the ended side is indexed) or ends with +fewer (it is indexed itself). The other side's spooled rows are then matched, a block at a +time, and let go; rows still to arrive are matched at once and not held. + +**Cost.** *Latency*: such a step gives no row before a side has ended and, when that side is +large, before the other has delivered as many rows or ended. An endless second input is +joined as it arrives from then on. *Disk*: each side's rows are written at most once, so at +most both inputs' rows; a chain's middle result counts as an input of its next step. A +replayed file is deleted when its rows are matched. + +**Nothing is held back.** Every input is read at once and to its end, each until 65,536 rows +wait for the join (the producer's last batch is taken whole). Draining one side while the +other waits is not safe, not even for inputs with no common upstream: of two joins of the +same two producers, one may hold back the one the other waits for. + +A join of three or more inputs is a chain of such steps in canonical order; each step's left +side has the certificate of the rows joined so far (`unique_keys.joined_keys`). + +Memory, per indexed row: the prepared key (16 bytes per string, plus its length when above +12 bytes; 8 per integer, timestamp or float; 1 for the constant key), 8 for the row number, +9 for its place and whether it is held. Beside it: at most 64 MiB of rows per side before +they go to disk, the batches in flight, a block of 65,536 rows being replayed, and one +output piece of at most 8,192 pairs. A many-to-many output is never held: the pairs are +counted first, then made in pieces; one arriving row with more pairs than a piece has its +pairs listed (16 bytes each, at most the indexed rows) and is sent in pieces. + +`Rejoin` of three or more inputs stays a barrier, because with repeated origin rows which +repeats are matched follows the whole inputs. A subclass or a customized instance of an +operator runs its own sync call over its whole inputs. A stream must implement the whole +`StreamProtocol` (`unique_keys` included): protocols are internal, and every stream class +of the library and everything built on `StreamBase` does. ## The row spool @@ -102,51 +113,41 @@ with their source-info tokens, sent and read through bounded channels. Peak RSS includes 143 MiB of imports and the mapped pages a join reads. "Barrier" is the form before this change. It is the operator alone, not a job. -| Case | Rows | Form | Output rows | Peak RSS | Arrow pool peak | Time | -|---|---|---|---|---|---|---| -| `lookup` | 1,000,000 | barrier | 1,000,000 | 1,793 MiB | 1,323 MiB | 2.3 s | -| `lookup` | 1,000,000 | keys | 1,000,000 | 259 MiB | 26 MiB | 2.4 s | -| `lookup` | 8,000,000 | keys | 8,000,000 | 257 MiB | 26 MiB | 19.9 s | -| `lookup_late` | 1,000,000 | keys | 1,000,000 | 756 MiB | 169 MiB | 5.4 s | -| `lookup_late` | 8,000,000 | keys | 8,000,000 | 2,733 MiB | 392 MiB | 61.7 s | -| `one_to_one` | 1,000,000 | keys | 1,000,000 | 317 MiB | 64 MiB | 4.7 s | -| `one_to_one` | 8,000,000 | keys | 8,000,000 | 341 MiB | 64 MiB | 39.3 s | -| `one_to_one_late` | 1,000,000 | barrier | 1,000,000 | 2,574 MiB | 1,854 MiB | 4.4 s | -| `one_to_one_late` | 1,000,000 | keys | 1,000,000 | 741 MiB | 176 MiB | 5.1 s | -| `one_to_one_late` | 8,000,000 | keys | 8,000,000 | 2,301 MiB | 453 MiB | 60.0 s | -| `many` (5 per row) | 1,000,000 | barrier | 5,000,000 | 4,835 MiB | 4,111 MiB | 2.4 s | -| `many` | 1,000,000 | keys | 5,000,000 | 445 MiB | 144 MiB | 3.2 s | -| `many` | 8,000,000 | keys | 40,000,000 | 453 MiB | 146 MiB | 26.0 s | -| `many_open` (5 per row) | 1,000,000 | barrier | 5,000,000 | 6,068 MiB | 5,002 MiB | 4.2 s | -| `many_open` | 1,000,000 | keys | 5,000,000 | 992 MiB | 384 MiB | 5.6 s | -| `many_open` | 4,000,000 | keys | 20,000,000 | 1,691 MiB | 633 MiB | 23.5 s | -| `many_open` | 8,000,000 | keys | 40,000,000 | 2,629 MiB | 941 MiB | 57.3 s | -| `semi` | 8,000,000 | keys | 8,000,000 | 252 MiB | 21 MiB | 19.6 s | - -`lookup`, `one_to_one` in step, `many` and `semi` do not grow with the rows. The late -cases grow with the keys of the input that arrived first, as the bound says. `many` ends its small -side first, so it measures the bounded output; `many_open` is the worst case, two open inputs -with no certificate, and grows with the keys of both. +| Case | Rows | Form | Output rows | Peak RSS | Arrow pool peak | Disk peak | Time | +|---|---|---|---|---|---|---|---| +| `lookup` (300 units first) | 1,000,000 | barrier | 1,000,000 | 1,793 MiB | 1,323 MiB | | 2.3 s | +| `lookup` | 8,000,000 | keys | 8,000,000 | 221 MiB | 10 MiB | 0 | 21.3 s | +| `lookup_late` | 1,000,000 | keys | 1,000,000 | 455 MiB | 131 MiB | 128 MiB | 2.7 s | +| `lookup_late` | 8,000,000 | keys | 8,000,000 | 481 MiB | 132 MiB | 1,480 MiB | 21.0 s | +| `one_to_one` (in step) | 8,000,000 | keys | 8,000,000 | 262 MiB | 27 MiB | 0 | 39.2 s | +| `one_to_one_late` | 1,000,000 | barrier | 1,000,000 | 2,574 MiB | 1,854 MiB | | 4.4 s | +| `one_to_one_late` | 1,000,000 | keys | 1,000,000 | 754 MiB | 157 MiB | 128 MiB | 5.5 s | +| `one_to_one_late` | 8,000,000 | keys | 8,000,000 | 2,456 MiB | 435 MiB | 1,480 MiB | 64.6 s | +| `many` (5 per row) | 1,000,000 | barrier | 5,000,000 | 4,835 MiB | 4,111 MiB | | 2.4 s | +| `many` | 8,000,000 | keys | 40,000,000 | 330 MiB | 57 MiB | 0 | 29.8 s | +| `many_open` (5 per row) | 1,000,000 | barrier | 5,000,000 | 6,068 MiB | 5,002 MiB | | 4.2 s | +| `many_open` | 1,000,000 | keys | 5,000,000 | 684 MiB | 194 MiB | 259 MiB | 6.9 s | +| `many_open` | 8,000,000 | keys | 40,000,000 | 1,793 MiB | 423 MiB | 2,528 MiB | 62.4 s | +| `semi` | 8,000,000 | keys | 8,000,000 | 214 MiB | 8 MiB | 0 | 20.1 s | +| `semi_late` | 8,000,000 | keys | 8,000,000 | 477 MiB | 132 MiB | 1,480 MiB | 19.6 s | +| `rejoin` (two branches in step) | 8,000,000 | keys | 8,000,000 | 320 MiB | 51 MiB | 0 | 51.9 s | + +The "keys" rows are with derived tokens, the barrier rows (measured before) with text. The +disk peak is sampled every 0.2 s. What still grows with the rows: `many_open`, two inputs of +equal size with no certificate, by the keys of one of them; and `one_to_one_late`, where one +certified input arrives whole before the other, by its keys. Times were taken with other +work on the machine. ## Batches with derived source-info tokens A channel and the kernels take a batch whose source-info columns are derived (`utils/source_tokens.py`): such a column has no bytes, so it costs a held or spooled row -nothing. The form is the input's first batch's, per column. Text first: a later derived -batch is built as text. Derived first: a later batch in another form is refused, because the -rows held have no text; a producer sends each column in one form. Rows sent through an -output channel may mix forms: `concatenate_batches` builds the text of a column that does. +nothing. Derived columns travel between the library's operators only +(`RecordBatchInput.carried`): every public read of a channel (`receive`, iteration, +`collect`) gives text, and a stream is read through its own `as_table` unless its class is a +library class that declares the carried read. Batches of one input may hold a column as text +in one and derived in another, however they arrive; rows fetched from both are text. Text is built where values are needed: a source-info column both inputs of a `MergeJoin` have, a merged data-tag one side of which is text, and the tokens that read system tags whose values a join of one pipeline hash sorts. `Rejoin`'s kernel, not wired, builds all of it. - -| Case (8,000,000 rows) | Text: peak RSS, Arrow pool, time | Derived | -|---|---|---| -| `lookup` | 257 MiB, 26 MiB, 19.9 s | 224 MiB, 10 MiB, 20.7 s | -| `lookup_late` | 2,733 MiB, 392 MiB, 61.7 s | 2,722 MiB, 376 MiB, 45.1 s | -| `one_to_one_late` | 2,301 MiB, 453 MiB, 60.0 s | 2,292 MiB, 435 MiB, 61.4 s | -| `many_open` | 2,629 MiB, 941 MiB, 57.3 s | 2,484 MiB, 855 MiB, 50.8 s | - -Peak memory hardly moves, because the rows were on disk already: what is left in the late and -open cases is the keys. The times were taken with other work on the machine. diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index c2f54c23d..a264c7cff 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -51,7 +51,8 @@ row was emitted before it can refuse. ``SemiJoin`` with no shared tag passes every left row whatever its right input holds, and has no shared column to refuse. - **Matching is the sync join's.** Each input keeps the rows it needs in a row spool - (memory, then local disk; ``core/row_spool``) and a Polars frame of their prepared keys and row numbers (``arrow_keys.polars_key_frame``), + (memory, then local disk; ``core/row_spool``) and, when it is indexed, a Polars frame + of their prepared keys and row numbers (``arrow_keys.polars_key_frame``), with the constant key every join adds (``join._with_common_key``). An arriving batch's key frame is joined with the other side's accumulated key frame by the sync path's own rule (``join._matched_pairs``), in one vectorized join, never per row: a top-level @@ -68,10 +69,11 @@ the last step of F), so a kernel declares every such field nullable and the stream made from its batches settles them. -A kernel holds only what can still match: a row is let go once it has matched when the -other side is certified unique on the keys (``core/unique_keys``); a side's rows are dropped when the other side -closes (nothing can arrive to match them), and an arriving row is not kept once the -other side has closed. A row whose key holds a top-level null is never kept (it matches +A kernel holds the keys of one side of a step only (``_BinaryLink``): both sides' while both +are certified unique on the keys (``core/unique_keys``), a pair's rows being let go when they +match; otherwise the smaller side's, known once a side has ended. A side's rows are dropped +when the other side ends and has been matched with them, and an arriving row is not kept +once the other side has been indexed. A row whose key holds a top-level null is never kept (it matches nothing). A step of a ``Join`` chain that can never emit again (a side closed holding no row that can match) closes its successor's left side and releases the earlier steps, except those the sync path still merges before it (``StreamingJoin._close``). From 7f2635f0f80b4cdfbe50fb8ca3befec78f4b463d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 03:18:38 -0800 Subject: [PATCH 21/26] fix(operators): a join's held rows cost what is held, whatever was held before them (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/operators/streaming_joins.py | 73 +++++++++++-------- .../operators/test_keys_only_joins.py | 17 +++++ 2 files changed, 59 insertions(+), 31 deletions(-) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 676534eae..827809ca2 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -146,7 +146,7 @@ # The pair-count column of a many-to-many match, and how many removed rows a side's key # frame holds before it is compacted. _COUNT = "__streaming_count" -_COMPACT_ROWS = 65_536 +_COMPACT_ROWS = 1_024 # How many rows of one input are read ahead and pushed at once. A push joins its rows with # every key held, so rows that have arrived already are pushed together. @@ -323,10 +323,11 @@ def __init__( self._constant_key: bool = constant_key self._frames: list[pl.DataFrame] = [] self._spool: RowSpool = RowSpool() - # Whether each row is still held, by its number less ``_base`` (grown by - # doubling); no row numbered below ``_base`` is held. - self._alive: npt.NDArray[np.bool_] = np.ones(0, dtype=np.bool_) - self._base: int = 0 + # Beside the key frame's rows, their numbers (ascending) and whether each is still + # held: as long as the frame, whatever the numbers are. + self._numbers: npt.NDArray[np.int64] = np.empty(0, dtype=np.int64) + self._alive: npt.NDArray[np.bool_] = np.empty(0, dtype=np.bool_) + self._count: int = 0 self._removed_count: int = 0 def key_frame(self, table: pa.Table) -> pl.DataFrame: @@ -340,18 +341,28 @@ def append(self, table: pa.Table, frame: pl.DataFrame) -> None: if not table.num_rows: return # Numbered after the rows already held, as the spool numbers them. - self._frames.append(frame.with_columns(pl.col(self.row) + self._spool.size)) + first = self._spool.size + self._frames.append(frame.with_columns(pl.col(self.row) + first)) self._spool.append(table) self.rows += table.num_rows - numbered = self._spool.size - self._base - if numbered > len(self._alive): - grown = np.ones(2 * numbered, dtype=np.bool_) - grown[: len(self._alive)] = self._alive - self._alive = grown + count = self._count + table.num_rows + if count > len(self._numbers): + for name in ("_numbers", "_alive"): + old = getattr(self, name) + grown = np.empty(2 * count, dtype=old.dtype) + grown[: self._count] = old[: self._count] + setattr(self, name, grown) + self._numbers[self._count : count] = np.arange(first, self._spool.size) + self._alive[self._count : count] = True + self._count = count def held(self, rows: npt.NDArray[np.int64]) -> npt.NDArray[np.int64]: - """Those of ``rows`` that were not removed.""" - return rows[self._alive[rows - self._base]] + """Those of ``rows``, numbers in the key frame, that were not removed.""" + return rows[self._alive[self._positions(rows)]] + + def _positions(self, rows: npt.NDArray[np.int64]) -> npt.NDArray[np.int64]: + """Where the rows with these numbers are in the key frame.""" + return np.searchsorted(self._numbers[: self._count], rows) def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: """The held rows with these numbers, in this order.""" @@ -366,41 +377,41 @@ def frame(self) -> pl.DataFrame: self._frames = [pl.concat(self._frames, rechunk=False)] return self._frames[0] + def held_frame(self) -> pl.DataFrame: + """The key frame of the rows held, without the removed ones.""" + frame = self.frame() + if not self._removed_count: + return frame + return frame.filter(pl.Series(self._alive[: self._count])) + def remove(self, rows: npt.NDArray[np.int64]) -> None: """Let rows go that can never match again: each is held, each given once.""" if not len(rows): return self._spool.discard(rows) self.rows -= len(rows) - self._alive[rows - self._base] = False + self._alive[self._positions(rows)] = False self._removed_count += len(rows) if not self.rows or self._removed_count >= max(self.rows, _COMPACT_ROWS): self._compact() def _compact(self) -> None: - """Drop the removed rows from the key frame, and the numbers below the rest.""" + """Drop the removed rows from the key frame.""" + if self.rows: + self._frames = [self.held_frame()] + self._numbers = self._numbers[: self._count][self._alive[: self._count]] + else: + self._frames, self._numbers = [], np.empty(0, dtype=np.int64) + self._count = len(self._numbers) + self._alive = np.ones(self._count, dtype=np.bool_) self._removed_count = 0 - if not self.rows: - self._frames, self._base = [], self._spool.size - self._alive = np.ones(0, dtype=np.bool_) - return - frame = self.frame() - rows = frame.get_column(self.row).to_numpy() - kept = frame.filter(pl.Series(self._alive[rows - self._base])) - self._frames = [kept] - # The frame's rows are in the order of their numbers. - base = int(kept.get_column(self.row)[0]) - self._alive = self._alive[base - self._base :].copy() - self._base = base def clear(self) -> None: """Drop every row held, and their files.""" - self._frames = [] - self._alive = np.ones(0, dtype=np.bool_) - self._removed_count, self._base = 0, 0 + self.rows = 0 + self._compact() self._spool.close() self._spool = RowSpool() - self.rows = 0 class _BinaryLink: diff --git a/tests/test_core/operators/test_keys_only_joins.py b/tests/test_core/operators/test_keys_only_joins.py index de5087dd6..ef05a4051 100644 --- a/tests/test_core/operators/test_keys_only_joins.py +++ b/tests/test_core/operators/test_keys_only_joins.py @@ -586,3 +586,20 @@ def test_rows_held_for_long_among_rows_that_pass_are_matched_at_the_end( map(str, waiting) ) assert kernel.held_rows == 0 + + +def test_one_old_row_does_not_pin_what_later_rows_cost(spooled: Path) -> None: + """Review of #565: a mask numbered from an old row grew with every later one.""" + left, right = _sorted_source("a", 400), _sorted_source("b", 400) + kernel = StreamingJoin(Join(), [left, right]) + (link,) = kernel._links # pyright: ignore[reportPrivateUsage] # what it keeps + lefts, rights = _batches(left, 4), _batches(right, 4) + _ = kernel.push(0, lefts[0]) # never matched until the end + for mine, theirs in zip(lefts[1:], rights[1:]): + _ = kernel.push(0, mine) + _ = kernel.push(1, theirs) + for side in link.sides: + assert len(side._alive) <= 32 # pyright: ignore[reportPrivateUsage] # what it keeps + assert len(side._numbers) <= 32 # pyright: ignore[reportPrivateUsage] # what it keeps + assert kernel.held_rows == 4 + assert sum(b.num_rows for b in kernel.push(1, rights[0])) == 4 From f6d04868ef40189a2458f4c003bff891a037e1d7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 03:20:28 -0800 Subject: [PATCH 22/26] docs(dev): what async joins change for users, and the bytes of a held key row (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-joins.md | 34 ++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/docs/dev/specs/itl-1464-joins.md b/docs/dev/specs/itl-1464-joins.md index a7df95ed4..adc584487 100644 --- a/docs/dev/specs/itl-1464-joins.md +++ b/docs/dev/specs/itl-1464-joins.md @@ -55,6 +55,22 @@ operator runs its own sync call over its whole inputs. A stream must implement t `StreamProtocol` (`unique_keys` included): protocols are internal, and every stream class of the library and everything built on `StreamBase` does. +## What changes for users + +Once job nodes run joins this way (async runs only; the sync path is unchanged): + +- **Memory**: an async join holds the join keys of its smaller input (of both inputs' rows not + matched yet, when both are certified unique on the shared tags) and no rows beyond 64 MiB + per input, whatever its inputs and output are. +- **Latency**: a join that is not one to one gives its first row only once one input has + ended and, when that input has more than 65,536 rows, once the other has delivered as many + or ended. A semi-join gives its first row once its right input has ended. One-to-one joins + and two-input rejoins give rows as they match. +- **Local disk**: at most both inputs' rows (a chain's middle results count as inputs), in + the system's temporary directory, removed when the join ends, however it ends. A full disk + fails the run with the operating system's error. +- **Row order** of an async result still follows arrival and is not a result. + ## The row spool Rows past the memory limit become a file each: an uncompressed Arrow IPC file of one record @@ -151,3 +167,21 @@ in one and derived in another, however they arrive; rows fetched from both are t Text is built where values are needed: a source-info column both inputs of a `MergeJoin` have, a merged data-tag one side of which is text, and the tokens that read system tags whose values a join of one pipeline hash sorts. `Rejoin`'s kernel, not wired, builds all of it. + +## The bytes of a held key row + +Measured on 4,000,000 rows with the keys of the benchmark (two strings of 24 and 10 +characters and one integer), as the growth of the process's physical footprint: + +| Form held | Bytes per row | Probe of 65,536 rows | +|---|---|---| +| the prepared key frame (what a join holds) | 95 | 26 ms, and about 100 more bytes per row while it runs | +| the same, strings as Polars categories | 38 | 15 ms, about 115 more | +| a 64-bit hash of the prepared key and a row number | 23 | 5 ms, 4 more | + +The key's own data is 51 bytes; the rest is the string views and buffers Polars keeps. Not +built: the hash form would keep one equality rule (candidates with equal hashes are matched +by `join._matched_pairs` on the keys of the rows fetched for the output), but rests on equal +keys having equal hashes under the join's equality, which was checked +for floats (signed zero, every NaN), lists and structs. An index alone is not a full +join: these are measurements of the frames, not of a whole join. From 982f1dcedd8518638c45b1867801218063f98f1a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 03:20:45 -0800 Subject: [PATCH 23/26] docs(dev): correct the split of a held key row's bytes (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-joins.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/dev/specs/itl-1464-joins.md b/docs/dev/specs/itl-1464-joins.md index adc584487..ae6785c16 100644 --- a/docs/dev/specs/itl-1464-joins.md +++ b/docs/dev/specs/itl-1464-joins.md @@ -179,7 +179,7 @@ characters and one integer), as the growth of the process's physical footprint: | the same, strings as Polars categories | 38 | 15 ms, about 115 more | | a 64-bit hash of the prepared key and a row number | 23 | 5 ms, 4 more | -The key's own data is 51 bytes; the rest is the string views and buffers Polars keeps. Not +Of the 95 bytes, 42 are the key's data, 9 the row number and the constant key; the rest is the string views and buffers Polars keeps. Not built: the hash form would keep one equality rule (candidates with equal hashes are matched by `join._matched_pairs` on the keys of the rows fetched for the output), but rests on equal keys having equal hashes under the join's equality, which was checked From faa4d88e6238dbc8ebcf492ac629342b6d6a564d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 03:31:34 -0800 Subject: [PATCH 24/26] test(operators): random graphs show no certificate changes a result (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-joins.md | 45 ++- .../operators/test_certificate_graphs.py | 356 ++++++++++++++++++ 2 files changed, 394 insertions(+), 7 deletions(-) create mode 100644 tests/test_core/operators/test_certificate_graphs.py diff --git a/docs/dev/specs/itl-1464-joins.md b/docs/dev/specs/itl-1464-joins.md index ae6785c16..a784a8cea 100644 --- a/docs/dev/specs/itl-1464-joins.md +++ b/docs/dev/specs/itl-1464-joins.md @@ -166,7 +166,7 @@ in one and derived in another, however they arrive; rows fetched from both are t Text is built where values are needed: a source-info column both inputs of a `MergeJoin` have, a merged data-tag one side of which is text, and the tokens that read system tags whose -values a join of one pipeline hash sorts. `Rejoin`'s kernel, not wired, builds all of it. +values a join of one pipeline hash sorts. `Rejoin`'s kernel builds all of it. ## The bytes of a held key row @@ -179,9 +179,40 @@ characters and one integer), as the growth of the process's physical footprint: | the same, strings as Polars categories | 38 | 15 ms, about 115 more | | a 64-bit hash of the prepared key and a row number | 23 | 5 ms, 4 more | -Of the 95 bytes, 42 are the key's data, 9 the row number and the constant key; the rest is the string views and buffers Polars keeps. Not -built: the hash form would keep one equality rule (candidates with equal hashes are matched -by `join._matched_pairs` on the keys of the rows fetched for the output), but rests on equal -keys having equal hashes under the join's equality, which was checked -for floats (signed zero, every NaN), lists and structs. An index alone is not a full -join: these are measurements of the frames, not of a whole join. +Of the 95 bytes, 42 are the key's data and 9 the row number and the constant key; the rest is +the string views and buffers Polars keeps. The join's own 9 bytes per row (its place and +whether it is held) are beside every form. These are measurements of the frames, not of a +whole join. + +### A hash index (not built; for the developer) + +The index would hold, for a key without a nested column, the 64-bit `hash_rows` of the +prepared key and the row number. An arriving batch's hashes pick candidate pairs; the rows of +the candidates are fetched, as they are for the output anyway, and each candidate pair is +matched by `join._matched_pairs` on its real keys (with the pair's number as one more key). +So there is one equality rule, and two keys of one hash cost a fetch, never a wrong row. + +Gain, estimated and not measured: the 1:1 case with one input entirely first (2,456 MiB at +8,000,000 rows) would fall well below 1 GiB, and a probe would take a fifth of the time. + +Risk: it rests on keys that a join takes as equal having equal hashes, across frames, chunks +and slices. Polars documents no such promise for `hash_rows`. If it failed, a pair would be +missing from the output and nothing would say so. The coordinator deferred it for that +reason (November 25, 2026): the memory of today's form fits the target. + +Checked so far, by hand and not as a test: signed zeros and NaNs of several payloads at +64 bits, signed zeros and NaNs at 32 bits, floats in lists and structs, strings across chunks +and slices. + +Test plan, if it is built: + +1. For every key type a join allows (`arrow_keys.part_without_rule`), every pair of values of + the types' edge pools: the join's equality implies equal hashes. +2. The same with the two keys in different frames, chunk layouts, slices and frames of other + columns beside them, and with strings on both sides of the 12-byte view limit. +3. The certificate graphs (`test_certificate_graphs.py`) and every kernel test, run with both + indexes: equal rows. +4. A run with every hash forced equal (all candidates), and with a hash of few bits: equal + rows, bounded memory of the candidates. +5. A check at the first batch of a run that Polars' hashes of fixed vectors (signed zeros, + NaN payloads, a sliced string) agree with the join; if not, the frame index is used. diff --git a/tests/test_core/operators/test_certificate_graphs.py b/tests/test_core/operators/test_certificate_graphs.py new file mode 100644 index 000000000..9a56c5184 --- /dev/null +++ b/tests/test_core/operators/test_certificate_graphs.py @@ -0,0 +1,356 @@ +"""Random graphs: a certificate never changes a result, and every certificate holds. + +ITL-1464: a join on the async path lets a row go when the other side is certified unique on +the keys (``core/unique_keys``), so a wrong certificate would lose rows. Random graphs of +sources (with and without unique tags, with and without nulls), operators and joins, with +shared upstreams, are run three ways and compared as sets of rows: on the sync path; on +record-batch channels, every operator in its own task, the batches cut and the spools +filled at random; and the same with certificates ignored. Every stream's certificate is also +checked on its rows directly, with the joins' equality. + +``python -m tests.test_core.operators.test_certificate_graphs FIRST COUNT`` runs more seeds. +""" + +from __future__ import annotations + +import asyncio +import functools +import random +import sys +import warnings +from collections import Counter +from collections.abc import Iterator +from pathlib import Path +from typing import Any +from unittest import mock + +import numpy as np +import pyarrow as pa +import pytest + +from orcapod.core.function_pod import FunctionPodStream, function_pod +from orcapod.core.operators import MergeJoin, Rejoin +from orcapod.core.operators import streaming_joins +from orcapod.core.operators.arrow_keys import polars_key_frame +from orcapod.core.operators.static_output_pod import DynamicPodStream +from orcapod.core.record_batch_channels import OutputChannel +from orcapod.core.row_spool import RowSpool +from orcapod.core.sources import ArrowTableSource +from orcapod.errors import InputValidationError +from orcapod.protocols.core_protocols import StreamProtocol + +from .test_streaming_joins import _rows, _transport # pyright: ignore[reportPrivateUsage] # the one oracle + +SEEDS = range(80) +TIMEOUT = 60.0 +MAX_ROWS = 400 + +TAGS = { + "a": pa.int64(), + "b": pa.large_string(), + "c": pa.int64(), + "f": pa.float64(), +} +POOLS: dict[str, list[Any]] = { + "a": [1, 2, 3], + "b": ["x", "y", "a longer string than a view holds"], + "c": [0, 1, None], + "f": [0.0, -0.0, float("nan"), float("-nan"), 1.5], +} + + +def _source(rng: random.Random, name: str) -> Any: + """A source with two to four tags, two data columns, and perhaps checked keys.""" + tags = rng.sample(sorted(TAGS), rng.randint(2, 4)) + n = rng.randint(1, 12) + rows = [tuple(rng.choice(POOLS[t]) for t in tags) for _ in range(n)] + key: list[str] | None = None + candidates = [t for t in tags if t in ("a", "b")] + if candidates and rng.random() < 0.6: + # Key columns hold each value combination once. + key = rng.sample(candidates, rng.randint(1, len(candidates))) + seen: set[Any] = set() + kept: list[Any] = [] + for row in rows: + value = tuple(row[tags.index(t)] for t in key) + if value not in seen: + seen.add(value) + kept.append(row) + rows = kept + columns: dict[str, Any] = { + t: pa.array([row[i] for row in rows], TAGS[t]) for i, t in enumerate(tags) + } + columns["x"] = pa.array([f"{name}{i}" for i in range(len(rows))], pa.large_string()) + columns["y"] = pa.array([None if i % 3 == 1 else i for i in range(len(rows))]) + names = rng.sample(sorted(columns), len(columns)) + return ArrowTableSource( + pa.table({c: columns[c] for c in names}), + tag_columns=rng.sample(tags, len(tags)), + record_id_columns=key, + tag_only_columns=rng.random() < 0.8, + source_id=name, + ) + + +@function_pod(output_keys=["x", "y"]) +def relabel(x: str | None, y: int | None) -> tuple[str | None, int | None]: + """A function pod over the two data columns.""" + return (x or "") + "!", y + + +class _Graphs: + """Streams made at random from earlier ones. + + Args: + rng: What decides. + """ + + def __init__(self, rng: random.Random) -> None: + self.rng = rng + self.made = 0 + + def fresh(self, stream: Any) -> Any: + """``stream`` with its plain data columns renamed, so that no join collides.""" + self.made += 1 + tags, data = stream.keys() + renames = {d: f"{d[:1]}{self.made}" for d in data if d not in tags} + return stream.map_data(renames) if renames else stream + + def unary(self, stream: Any) -> Any: + rng = self.rng + tags, data = stream.keys() + plain = [d for d in data if d not in tags] + some_tags = rng.sample(tags, rng.randint(1, len(tags))) + steps = [ + lambda: stream.select_tag_columns(some_tags), + lambda: stream.drop_tag_columns([rng.choice(tags)]), + lambda: stream.map_tags( + {t: {"a": "c", "c": "a"}.get(t, t) for t in some_tags if t in "ac"} + ), + lambda: stream.map_tags({rng.choice(tags): "z"}), + lambda: stream.map_tags({some_tags[0]: "z"}, drop_unmapped=True), + lambda: stream.add_tags(a=1) if "a" not in tags else stream.add_tags(k=2), + lambda: stream.drop_nulls(), + lambda: stream.drop_nulls(rng.choice([*tags, *plain])), + lambda: stream.filter({rng.choice(tags): 1}), + *[lambda: stream.group_by(some_tags)] * 3, + lambda: stream.drop_nulls().tag_by(rng.choice(plain)), + lambda: stream.select_columns([*some_tags, *plain]), + lambda: stream.drop_columns([some_tags[0]]), + lambda: stream.map_columns({some_tags[0]: "w"}), + lambda: relabel.pod(stream) if set(plain) == {"x", "y"} else stream, + ] + return rng.choice(steps)() + + def binary(self, left: Any, right: Any, third: Any) -> Any: + rng = self.rng + kind = rng.choice(["join", "join", "join3", "semi", "merge", "rejoin"]) + if kind == "semi": + return left.semi_join(right) + if kind == "rejoin": + plain = [d for d in left.keys()[1] if d not in left.keys()[0]] + half = max(1, len(plain) // 2) + branch = left.select_data_columns(plain[half:]) + if rng.random() < 0.5: + branch = branch.drop_nulls() + return Rejoin()(left.select_data_columns(plain[:half]), branch) + if kind == "merge": + return MergeJoin()(left, right) + if kind == "join3": + return self.fresh(left).join(self.fresh(right), self.fresh(third)) + return self.fresh(left).join(self.fresh(right)) + + def graph(self) -> Any: + """The last stream of a random graph.""" + rng = self.rng + streams: list[Any] = [_source(rng, f"s{i}") for i in range(rng.randint(2, 4))] + if rng.random() < 0.4: + streams.append(relabel.pod(rng.choice(streams))) + for _ in range(rng.randint(3, 8)): + try: + if rng.random() < 0.5: + made = self.unary(rng.choice(streams[-3:])) + else: + made = self.binary(*(rng.choice(streams) for _ in range(3))) + if not 0 < made.as_table().num_rows <= MAX_ROWS: + continue + except (InputValidationError, ValueError, KeyError, NotImplementedError): + continue # not a valid step here + streams.append(made) + return streams[-1] + + +def _is_step(stream: Any) -> bool: + """Whether a stream is an operator's result (run over channels here).""" + return isinstance(stream, DynamicPodStream) + + +def _reached(stream: Any, found: dict[int, Any]) -> Iterator[Any]: + """Every stream ``stream`` is made of, each once, its inputs first.""" + if id(stream) in found: + return + found[id(stream)] = stream + if _is_step(stream) or isinstance(stream, FunctionPodStream): + for upstream in stream.upstreams: + yield from _reached(upstream, found) + yield stream + + +async def _run(stream: Any, rng: random.Random) -> StreamProtocol: + """Run a graph over bounded channels, one task per stream, every batch cut at random.""" + streams = list(_reached(stream, {})) + channels = { + id(s): OutputChannel(s, retain=s is stream, buffer_size=rng.randint(1, 3)) + for s in streams + } + readers = { + id(s): [channels[id(u)].open_reader() for u in s.upstreams] + for s in streams + if _is_step(s) + } + fed = {id(u) for s in streams if _is_step(s) for u in s.upstreams} + + async def give(source: Any) -> None: + output = channels[id(source)] + async for batch in source.open_channel().carried(): + start = 0 + while start < batch.num_rows: + size = rng.randint(1, 5) + await output.send(batch.slice(start, size)) + start += size + if rng.random() < 0.3: + await asyncio.sleep(0) + await output.close() + + tasks = [ + s.producer.async_execute_batches(readers[id(s)], channels[id(s)]) + if _is_step(s) + else give(s) + for s in streams + if _is_step(s) or id(s) in fed + ] + rng.shuffle(tasks) + _ = await asyncio.wait_for(asyncio.gather(*tasks), TIMEOUT) + return channels[id(stream)].result() + + +def _async_rows(stream: Any, seed: int, root: Path, *, certified: bool) -> Counter[Any]: + """The rows of a graph run over channels.""" + rng = random.Random(seed) + patches: dict[str, Any] = { + "RowSpool": functools.partial( + RowSpool, rng.choice([0, 2_000, 10**9]), str(root) + ), + "PUSH_ROWS": rng.choice([1, 4, 64]), + "PAIRS_PER_BATCH": rng.choice([1, 7, 64]), + "_COMPACT_ROWS": rng.choice([1, 8]), + } + if not certified: + patches["unique_on"] = lambda keys, columns: False + with mock.patch.multiple(streaming_joins, **patches): + return _rows(_transport(asyncio.run(_run(stream, rng)))) + + +def _repeats(stream: Any, key: frozenset[str]) -> bool: + """Whether two rows agree on ``key`` under the joins' equality (a null is none's).""" + table = stream.as_table().select(sorted(key)) + whole = np.ones(table.num_rows, dtype=np.bool_) + for column in table.columns: + whole &= np.asarray(column.is_valid()) + frame = polars_key_frame(table.filter(pa.array(whole)), sorted(key)) + return frame.height != frame.unique().height + + +def check_seed(seed: int, root: Path) -> tuple[int, bool]: + """Check one random graph. + + Returns: + How many joins of it had a certified side, and whether it is a graph to run. + """ + stream = _Graphs(random.Random(seed)).graph() + reached = list(_reached(stream, {})) + for part in reached: + for key in part.unique_keys: + assert not _repeats(part, key), (seed, part, key) + if not _is_step(stream): + return 0, False + expected = _rows(_transport(stream)) + used: list[bool] = [] + original = streaming_joins.unique_on + + def counted(keys: Any, columns: Any) -> bool: + used.append(original(keys, columns)) + return used[-1] + + with mock.patch.object(streaming_joins, "unique_on", counted): + assert _async_rows(stream, seed, root, certified=True) == expected, seed + assert _async_rows(stream, seed + 1, root, certified=True) == expected, seed + assert _async_rows(stream, seed, root, certified=False) == expected, seed + assert list(root.rglob("*.arrow")) == [], seed + return sum(used), True + + +@pytest.mark.filterwarnings("ignore") +@pytest.mark.parametrize("seed", SEEDS) +def test_a_certificate_changes_no_result(seed: int, tmp_path: Path) -> None: + _ = check_seed(seed, tmp_path) + + +@pytest.mark.filterwarnings("ignore") +def test_the_graphs_use_certificates_and_every_kind_of_step(tmp_path: Path) -> None: + """The seeds above reach what they are for.""" + steps: Counter[str] = Counter() + certified = 0 + for seed in SEEDS: + if seed < 30: + used, _ = check_seed(seed, tmp_path) + certified += used + for part in _reached(_Graphs(random.Random(seed)).graph(), {}): + kind = part.producer if part.producer is not None else part + steps[type(kind).__name__] += 1 + assert certified >= 8 + for name in ( + "Join", + "SemiJoin", + "MergeJoin", + "Rejoin", + "GroupBy", + "MapTags", + "FunctionPod", + ): + assert steps[name] >= 2, (name, steps) + + +def test_a_wrong_certificate_is_seen(tmp_path: Path) -> None: + """The check itself: with every stream certified unique, some graph loses rows.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + for seed in SEEDS: + stream = _Graphs(random.Random(seed)).graph() + if not _is_step(stream): + continue + expected = _rows(_transport(stream)) + with mock.patch.object(streaming_joins, "unique_on", lambda *_: True): + if _async_rows(stream, seed, tmp_path, certified=True) != expected: + return + raise AssertionError("no graph tells a wrong certificate") + + +if __name__ == "__main__": + import tempfile + + warnings.simplefilter("ignore") + first, count = int(sys.argv[1]), int(sys.argv[2]) + ran = certified = failed = 0 + with tempfile.TemporaryDirectory() as directory: + for seed in range(first, first + count): + try: + used, is_run = check_seed(seed, Path(directory)) + except Exception as error: # noqa: BLE001 # report and go on + failed += 1 + print("seed", seed, type(error).__name__, str(error)[:300], flush=True) + continue + ran, certified = ran + is_run, certified + (used > 0) + print( + f"{count} seeds, {ran} graphs run, {certified} used a certificate, {failed} failed" + ) From c6f0ccbc2c9771cc5661da0828717f0e4d80f6f7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 03:38:04 -0800 Subject: [PATCH 25/26] fix(operators): one memory limit for mixed token forms, no recipe in a channel's protocol, a turn for other tasks between batches (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-joins.md | 10 +- docs/dev/specs/itl-1464-joins/measure.py | 4 +- src/orcapod/core/operators/batch.py | 3 +- .../core/operators/static_output_pod.py | 4 +- src/orcapod/core/operators/streaming_joins.py | 32 +++- src/orcapod/core/row_spool.py | 14 ++ src/orcapod/core/streams/carried.py | 22 +++ .../core/streams/record_batch_input.py | 28 ++-- .../protocols/core_protocols/streams.py | 8 - .../operators/test_certificate_graphs.py | 3 +- .../operators/test_keys_only_joins.py | 148 +++++++++++++++++- tests/test_core/test_row_spool.py | 14 ++ 12 files changed, 248 insertions(+), 42 deletions(-) diff --git a/docs/dev/specs/itl-1464-joins.md b/docs/dev/specs/itl-1464-joins.md index a784a8cea..e0db714d1 100644 --- a/docs/dev/specs/itl-1464-joins.md +++ b/docs/dev/specs/itl-1464-joins.md @@ -159,10 +159,16 @@ work on the machine. A channel and the kernels take a batch whose source-info columns are derived (`utils/source_tokens.py`): such a column has no bytes, so it costs a held or spooled row nothing. Derived columns travel between the library's operators only -(`RecordBatchInput.carried`): every public read of a channel (`receive`, iteration, +(`streams/carried.py`; a channel's protocol has no such read): every public read of a channel (`receive`, iteration, `collect`) gives text, and a stream is read through its own `as_table` unless its class is a library class that declares the carried read. Batches of one input may hold a column as text -in one and derived in another, however they arrive; rows fetched from both are text. +in one and derived in another, however they arrive: from the first change on, rows are held +as text, the rows before it go to disk, and rows fetched from both are text. + +Channels carry no per-row data context, as before (ITL-1347): every row of an input has its +stream's. A two-input `Rejoin` of raw streams that hold rows of several contexts therefore +matches on the streams' contexts over channels, where the sync path over the raw streams +matches on each row's. This is unchanged: the barrier did the same (ITL-1359). Text is built where values are needed: a source-info column both inputs of a `MergeJoin` have, a merged data-tag one side of which is text, and the tokens that read system tags whose diff --git a/docs/dev/specs/itl-1464-joins/measure.py b/docs/dev/specs/itl-1464-joins/measure.py index 64a79dea7..b45de8f74 100644 --- a/docs/dev/specs/itl-1464-joins/measure.py +++ b/docs/dev/specs/itl-1464-joins/measure.py @@ -38,7 +38,7 @@ from orcapod.core.record_batch_channels import OutputChannel from orcapod.core import row_spool from orcapod.core.sources import ArrowTableSource -from orcapod.core.streams.carried import carried_table +from orcapod.core.streams.carried import carried_batches, carried_table from orcapod.protocols.core_protocols import StreamProtocol BATCH = 8_192 @@ -234,7 +234,7 @@ async def produce(index: int, source: Input, after: asyncio.Event | None) -> Non async def consume() -> None: nonlocal count - async for batch in reader.carried(): + async for batch in carried_batches(reader): count += batch.num_rows if barrier: diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index 3215f8267..2405b05d8 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -6,6 +6,7 @@ import numpy as np import pyarrow as pa +from orcapod.core.streams.carried import carried_batches from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, @@ -328,7 +329,7 @@ async def async_execute_batches( try: waiting: list[pa.RecordBatch] = [] rows = 0 - async for batch in channel.carried(): + async for batch in carried_batches(channel): if not batch.num_rows: continue # nothing to batch, nothing to hold waiting.append(batch) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index feab7f617..cc4a063dd 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -45,7 +45,7 @@ from orcapod.utils import source_tokens from orcapod.utils.provisional import note_provisional_use, provisional_class_name from orcapod.core.streams.arrow_table_stream import ArrowTableStream -from orcapod.core.streams.carried import carried_table +from orcapod.core.streams.carried import carried_batches, carried_table from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, StreamBase, @@ -1169,7 +1169,7 @@ async def async_execute_batches( # cannot make one table with the earlier ones is refused, as the sync # path refuses the whole input, never processed alone. settled: dict[str, pa.DataType] = {} - async for batch in channel.carried(): + async for batch in carried_batches(channel): settled = settle_token_types(batch, settled) await self._send_processed([batch], channel.stream, output) else: diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index a264c7cff..6126c3920 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -128,6 +128,7 @@ from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.core_protocols.streams import RecordBatchInput, RecordBatchOutput +from orcapod.core.streams.carried import carried_batches from orcapod.core.unique_keys import joined_keys, unique_on from orcapod.system_constants import constants from orcapod.utils import arrow_utils, source_tokens @@ -308,8 +309,10 @@ class _Rows: """Rows numbered from 0 in the order held, spooled. Rows of one input may hold a source-info column as text in one batch and derived in - another (``source_tokens``): each run of rows of one form has a spool of its own, and - rows fetched from several are given as text. + another (``source_tokens``). Rows are held in the form of the first ones; from the + first rows in another form on, rows are held as text. So there are at most two spools, + the first of which keeps no row in memory once there is a second, and rows fetched + from both are given as text. """ def __init__(self) -> None: @@ -320,9 +323,12 @@ def append(self, table: pa.Table) -> None: """Hold ``table``'s rows, numbered from ``size`` on.""" if not table.num_rows: return - if not self._runs or not self._runs[-1][1].equals( - table.schema, check_metadata=True - ): + schema = self._runs[-1][1] if self._runs else table.schema + if not table.schema.equals(schema, check_metadata=True): + table = source_tokens.materialize(table) + if not self._runs or not table.schema.equals(schema, check_metadata=True): + if self._runs: + self._runs[-1][2].spill() self._runs.append((self.size, table.schema, RowSpool())) self._runs[-1][2].append(table) self.size += table.num_rows @@ -1913,7 +1919,7 @@ async def run_kernel( for batch in _push_sizes(batches): progressed = True for result in kernel.iter_push(index, batch): - await output.send(result) + await _send(output, result) # The readers get a turn also when nothing was sent. await asyncio.sleep(0) if ended: @@ -1921,7 +1927,7 @@ async def run_kernel( await readers[index] # raises what ended it, if anything did open_inputs.discard(index) for result in kernel.iter_close(index): - await output.send(result) + await _send(output, result) if not progressed: _ = await changed.wait() except BaseException as error: @@ -1937,6 +1943,16 @@ async def run_kernel( await finish_operator(inputs, output) +async def _send(output: RecordBatchOutput, batch: pa.RecordBatch) -> None: + """Send a batch and give every other task a turn, also when the send did not wait. + + A cancellation, or a reader that closes, is met between two batches, however many a + replay gives. + """ + await output.send(batch) + await asyncio.sleep(0) + + class _ReadAhead: """The record batches one input delivered and the join has not pushed yet. @@ -1955,7 +1971,7 @@ async def fill(self, channel: RecordBatchInput, claim: object) -> None: """Read ``channel`` to its end, waiting while ``PUSH_ROWS`` rows or more are unread.""" try: _ = channel.reserve(claim) - async for batch in channel.carried(): + async for batch in carried_batches(channel): if not batch.num_rows: continue self._batches.append(batch) diff --git a/src/orcapod/core/row_spool.py b/src/orcapod/core/row_spool.py index 94b3be6f9..d7dd5b260 100644 --- a/src/orcapod/core/row_spool.py +++ b/src/orcapod/core/row_spool.py @@ -276,6 +276,20 @@ def _require_usable(self) -> None: if self._closed: raise ValueError("the row spool is closed") + def spill(self) -> None: + """Write the rows in memory to a file, so that none stays in memory. + + Raises: + ValueError: If the spool is closed. + RuntimeError: In a process other than the one that made the spool. + OSError: If they cannot be written; the rows then stay in memory. + """ + self._require_owner() + with self._lock: + self._require_usable() + if self._in_memory: + self._spill() + def _add(self, segment: _Segment) -> None: self._segments.append(segment) self._starts = None diff --git a/src/orcapod/core/streams/carried.py b/src/orcapod/core/streams/carried.py index 50e5ea17e..81c7f513b 100644 --- a/src/orcapod/core/streams/carried.py +++ b/src/orcapod/core/streams/carried.py @@ -11,6 +11,7 @@ class is a library class that declares ``_carried_table`` itself, read as that c from __future__ import annotations +from collections.abc import AsyncIterator from typing import Any import pyarrow as pa @@ -40,3 +41,24 @@ def carried_table( if read is None or not reads_as_its_class(stream, kind): return stream.as_table(columns=columns) return read(stream, columns) + + +CARRIED_BATCHES = "_carried_batches" +"""The method of the library's channel class whose batches may hold derived columns.""" + + +def carried_batches(channel: Any) -> AsyncIterator[pa.RecordBatch]: # pyright: ignore[reportExplicitAny] # a channel (its protocol would make an import cycle) + """The remaining record batches of a channel, derived token columns as they are. + + For library code that passes them on, as ``carried_table`` is for tables, and by the + same rule: only the library's own channel class, read as that class, is read this + way; any other channel is iterated and gives what it gives. + + Args: + channel: An input channel (``RecordBatchInput``). + """ + kind = type(channel) + read: Any = vars(kind).get(CARRIED_BATCHES) # pyright: ignore[reportExplicitAny] # a method + if read is None or not reads_as_its_class(channel, kind): + return aiter(channel) + return read(channel) diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py index 1d31594b6..815a68268 100644 --- a/src/orcapod/core/streams/record_batch_input.py +++ b/src/orcapod/core/streams/record_batch_input.py @@ -247,21 +247,6 @@ async def receive(self) -> pa.RecordBatch: table = source_tokens.materialize(pa.Table.from_batches([batch])) return table.combine_chunks().to_batches()[0] - async def carried(self) -> AsyncIterator[pa.RecordBatch]: - """Iterate over the remaining record batches as they travel, for an operator. - - Their source-info columns may be derived; the end and the errors are those of - iterating the channel. - """ - while True: - try: - batch = await self._receive_carried() - except ChannelClosed: - if self._ended and not self._closed: - return - raise - yield batch - async def _receive_carried(self) -> pa.RecordBatch: """Return the next Arrow record batch, as it travels. @@ -394,9 +379,20 @@ async def _to_stream(self, claim: object) -> StreamProtocol: await self.close() return opened_on return stream_from_batches( - self._stream, [batch async for batch in self.carried()] + self._stream, [batch async for batch in self._carried_batches()] ) + async def _carried_batches(self) -> AsyncIterator[pa.RecordBatch]: + """The remaining record batches as they travel (``carried_batches``).""" + while True: + try: + batch = await self._receive_carried() + except ChannelClosed: + if self._ended and not self._closed: + return + raise + yield batch + async def collect(self) -> list[pa.RecordBatch]: """Read to the end and return every remaining record batch, in arrival order. diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 091ee81bb..f83b2ea88 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -682,14 +682,6 @@ def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: """Iterate over the remaining record batches, in arrival order.""" ... - def carried(self) -> AsyncIterator[pa.RecordBatch]: - """Iterate over the remaining record batches as they travel, for an operator. - - Their source-info columns may be derived (``utils/source_tokens.py``): internal. - Every other read gives their text. - """ - ... - async def collect(self) -> list[pa.RecordBatch]: """Read to the end and return every remaining record batch, in arrival order.""" ... diff --git a/tests/test_core/operators/test_certificate_graphs.py b/tests/test_core/operators/test_certificate_graphs.py index 9a56c5184..6167d8e99 100644 --- a/tests/test_core/operators/test_certificate_graphs.py +++ b/tests/test_core/operators/test_certificate_graphs.py @@ -36,6 +36,7 @@ from orcapod.core.record_batch_channels import OutputChannel from orcapod.core.row_spool import RowSpool from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams.carried import carried_batches from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import StreamProtocol @@ -212,7 +213,7 @@ async def _run(stream: Any, rng: random.Random) -> StreamProtocol: async def give(source: Any) -> None: output = channels[id(source)] - async for batch in source.open_channel().carried(): + async for batch in carried_batches(source.open_channel()): start = 0 while start < batch.num_rows: size = rng.randint(1, 5) diff --git a/tests/test_core/operators/test_keys_only_joins.py b/tests/test_core/operators/test_keys_only_joins.py index ce1683403..30cca135d 100644 --- a/tests/test_core/operators/test_keys_only_joins.py +++ b/tests/test_core/operators/test_keys_only_joins.py @@ -16,11 +16,13 @@ from collections import Counter from collections.abc import Callable, Sequence from pathlib import Path -from typing import Any +from typing import Any, cast import pyarrow as pa import pytest +import orcapod.contexts as contexts + from orcapod.core.operators import Join, MergeJoin, Rejoin, SemiJoin from orcapod.core.operators import streaming_joins from orcapod.core.operators.streaming_joins import ( @@ -30,13 +32,18 @@ StreamingRejoin, StreamingSemiJoin, ) +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.record_batch_channels import OutputChannel from orcapod.core.row_spool import RowSpool from orcapod.core.sources import ArrowTableSource, DictSource from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.carried import carried_batches +from orcapod.core.streams.record_batch_input import InputChannel from orcapod.errors import UpstreamFailedError from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.system_constants import constants from orcapod.utils import source_tokens +from tests.test_core.operators.test_rejoin import other_context # noqa: F401 # the fixture from .test_streaming_joins import _arrivals, _check, _rows, _run, _sent, _transport # pyright: ignore[reportPrivateUsage] # the kernels' one oracle @@ -622,7 +629,7 @@ def _carried(stream: StreamProtocol) -> pa.Table: feed = stream.open_channel() async def read() -> list[pa.RecordBatch]: - return [batch async for batch in feed.carried()] + return [batch async for batch in carried_batches(feed)] return pa.Table.from_batches(asyncio.run(read())) @@ -1118,3 +1125,140 @@ def test_rows_with_logical_types_are_replayed(spooled: Path) -> None: _check(_join, Join().static_process, inputs, range(4)) _check(_semi, SemiJoin().static_process, inputs, range(4)) _check(_merge, MergeJoin().static_process, inputs, range(4)) + + +@pytest.mark.parametrize("first", [0, 1]) +def test_alternating_token_forms_keep_one_memory_limit( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, first: int +) -> None: + """Review of #567: a spool per change of form kept every one of them in memory.""" + spools: list[RowSpool] = [] + + def make() -> RowSpool: + spools.append(RowSpool(20_000, str(tmp_path))) + return spools[-1] + + monkeypatch.setattr(streaming_joins, "RowSpool", make) + left = ArrowTableSource( + pa.table( + { + "k": [i % 2 for i in range(64)], + "n": list(range(64)), + "x": [f"{i}" + "x" * 1_000 for i in range(64)], + "y": list(range(64)), + } + ), + tag_columns=["n", "k"], + tag_only_columns=True, + source_id="left", + ) + right = _source("b", {"k": [0, 1], "m": [1, 2]}) + derived = _carried(left).combine_chunks() + forms = [derived, source_tokens.materialize(derived)] + kernel = _join([left, right]) + for i in range(64): + (batch,) = forms[(i + first) % 2].slice(i, 1).combine_chunks().to_batches() + assert kernel.push(0, batch) == [] + assert sum(spool.memory_bytes for spool in spools) <= 20_000 + # One spool per side to start with, and at most one more. + assert len([spool for spool in spools if spool.size]) <= 2 + assert len(_files(tmp_path)) < 10 + for batch in _carried(right).to_batches(): + kernel.push(1, batch) + rows: Any = Counter() + for out in [*kernel.close(1), *kernel.close(0)]: + rows += _rows(source_tokens.materialize(pa.Table.from_batches([out]))) + assert rows == _rows(_transport(left.join(right))) + assert _files(tmp_path) == [] + + +def test_no_read_of_a_channel_gives_a_recipe() -> None: + """Review of #567: the channel's own protocol offered the internal form.""" + channel = _data_tagged("a", 3).open_channel() + assert [n for n in dir(channel) if "carried" in n and not n.startswith("_")] == [] + + +def test_a_channel_of_a_users_class_is_read_through_its_own_reads() -> None: + source = _source("a", {"k": [1, 2, 3], "n": [1, 2, 3]}) + inner = source.open_channel() + + class OneRow(InputChannel): + async def receive(self) -> pa.RecordBatch: + return (await super().receive()).slice(0, 1) + + channel = OneRow(source, cast(InputChannel, inner)._feed) # pyright: ignore[reportPrivateUsage] # a user's channel over a feed + + async def read() -> int: + return sum([b.num_rows async for b in carried_batches(channel)]) + + assert _bounded(read()) == 1 + + +@pytest.mark.parametrize("op", [Join(), SemiJoin(), MergeJoin()], ids=lambda o: repr(o)) +def test_a_replay_whose_sends_never_wait_can_be_cancelled( + spooled: Path, op: Any +) -> None: + """Review of #567: the whole replay ran before any other task had a turn.""" + left = _source("a", {"k": [1, 2] * 100, "n": list(range(200))}) + right = _source("b", {"k": [1, 2], "m": [1, 2]}) + sent = 0 + began = asyncio.Event() + + class Sink(OutputChannel): + async def send(self, batch: pa.RecordBatch) -> None: + nonlocal sent + sent += batch.num_rows + began.set() + await super().send(batch) + + async def go() -> None: + sink = Sink(op(left, right), retain=False) # no reader: a send never waits + run = asyncio.create_task( + op.async_execute_batches([left.open_channel(), right.open_channel()], sink) + ) + await began.wait() + run.cancel() + with pytest.raises(asyncio.CancelledError): + await run + + _bounded(go()) + assert 0 < sent < 100 + assert _files(spooled) == [] + + +def test_rejoin_over_channels_equals_its_barrier_for_rows_of_several_contexts( + spooled: Path, + other_context: contexts.DataContext, # noqa: F811 # the fixture, by name +) -> None: + """Channels carry no per-row data context, so the two forms see one (ITL-1359).""" + default = contexts.get_default_context() + + def branch(name: str, second: str) -> ArrowTableStream: + table = pa.table( + { + "k": [1, 2], + "_tag_source_id::t": pa.array(["s", "s"], pa.large_string()), + "_tag_record_id::t": pa.array(["r1", "r2"], pa.large_string()), + name: [10, 20], + constants.CONTEXT_KEY: pa.array( + [default.context_key, second], pa.large_string() + ), + } + ) + return ArrowTableStream(table, tag_columns=["k"], data_context=default) + + inputs = [branch("a", other_context.context_key), branch("b", default.context_key)] + op = Rejoin() + + async def go(*, barrier: bool) -> StreamProtocol: + output = OutputChannel(op(*inputs)) + channels = [s.open_channel() for s in inputs] + if barrier: + await StaticOutputOperatorPod.async_execute_batches(op, channels, output) + else: + await op.async_execute_batches(channels, output) + return output.result() + + assert _rows(_transport(_bounded(go(barrier=False)))) == _rows( + _transport(_bounded(go(barrier=True))) + ) diff --git a/tests/test_core/test_row_spool.py b/tests/test_core/test_row_spool.py index 67b69651b..5bfb11a19 100644 --- a/tests/test_core/test_row_spool.py +++ b/tests/test_core/test_row_spool.py @@ -189,6 +189,20 @@ def test_a_table_outlives_its_spool( assert part.equals(rows.slice(30, 100)) +def test_rows_are_written_when_asked(tmp_path: Path) -> None: + spool, rows = _filled(tmp_path, [10, 5], 10**9) + spool.spill() + spool.spill() # nothing in memory: nothing to write + assert spool.memory_bytes == 0 + assert len(_files(tmp_path)) == 1 + spool.append(_table(15, 5)) + assert spool.memory_bytes + assert spool.table().equals(pa.concat_tables([rows, _table(15, 5)])) + spool.close() + with pytest.raises(ValueError, match="closed"): + spool.spill() + + def test_nothing_is_written_below_the_limit(tmp_path: Path) -> None: spool, _ = _filled(tmp_path, [10, 10], 10**9) assert list(tmp_path.iterdir()) == [] From 31cb626be4a4b44a01f688a7e2d9a84cc40a025f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 04:25:41 -0800 Subject: [PATCH 26/26] fix(operators): a join puts rows of both token forms together whatever their column is called (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/operators/streaming_joins.py | 21 ++- .../operators/test_keys_only_joins.py | 133 ++++++++++++++++++ 2 files changed, 147 insertions(+), 7 deletions(-) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 6126c3920..5a0cd4d25 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -377,17 +377,24 @@ def close(self) -> None: def _one_form(tables: Sequence[pa.Table]) -> pa.Table: - """``tables`` under one another, a source-info column of several forms as text. + """``tables`` under one another, a token column of several forms as text. + + Every derived column is looked at, whatever its name: a join holds the token column + of a data-tag both inputs have under a name of its own. Args: tables: Rows of one input, at least one table. """ - kinds: dict[str, set[pa.DataType]] = {} - for table in tables: - for field in table.schema: - if field.name.startswith(constants.SOURCE_PREFIX): - kinds.setdefault(field.name, set()).add(field.type) - mixed = {name for name, types in kinds.items() if len(types) > 1} + derived = { + name: table.schema.field(name).type + for table in tables + for name in source_tokens.derived_columns(table.schema) + } + mixed = { + name + for name, kind in derived.items() + if any(table.schema.field(name).type != kind for table in tables) + } return pa.concat_tables([source_tokens.materialize(t, mixed) for t in tables]) diff --git a/tests/test_core/operators/test_keys_only_joins.py b/tests/test_core/operators/test_keys_only_joins.py index 30cca135d..25ff10f51 100644 --- a/tests/test_core/operators/test_keys_only_joins.py +++ b/tests/test_core/operators/test_keys_only_joins.py @@ -11,6 +11,7 @@ import asyncio import functools +import itertools import random import warnings from collections import Counter @@ -1262,3 +1263,135 @@ async def go(*, barrier: bool) -> StreamProtocol: assert _rows(_transport(_bounded(go(barrier=False)))) == _rows( _transport(_bounded(go(barrier=True))) ) + + +def _rejoin(inputs: Sequence[StreamProtocol]) -> StreamingJoinKernel: + return StreamingRejoin(Rejoin(), inputs) + + +def _data_tagged_inputs(kernel: str) -> list[Any]: + """Inputs that share data-tags, with every token of them derived.""" + if kernel == "rejoin": + source = _data_tagged("a", 7) + return [ + source.select_data_columns(["a1", "k", "g"]), + source.select_data_columns(["a2", "k", "g"]), + ] + names = "abc" if kernel == "join3" else "ab" + return [_data_tagged(name, 5 + i) for i, name in enumerate(names)] + + +DATA_TAG_KERNELS: dict[str, tuple[Any, Any]] = { + "join": (_join, Join()), + "join3": (_join, Join()), + "merge_join": (_merge, MergeJoin()), + "semi_join": (_semi, SemiJoin()), + "rejoin": (_rejoin, Rejoin()), +} + + +@pytest.mark.parametrize("blocks", [2, 64]) +@pytest.mark.parametrize("changes", ["one", "every"]) +@pytest.mark.parametrize("first", ["derived", "text"]) +@pytest.mark.parametrize("kernel", sorted(DATA_TAG_KERNELS)) +def test_shared_data_tags_when_a_tokens_form_changes( + spooled: Path, + kernel: str, + first: str, + changes: str, + blocks: int, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Review of #567: a merged data-tag's tokens are held under a name of the join's + own, and rows of both forms could not be put together. Every input changes its form + half way (or one does, each in turn), before and after the others arrive and end.""" + # With blocks of 64 rows, rows of both forms are fetched together. + monkeypatch.setattr(streaming_joins, "PUSH_ROWS", blocks) + monkeypatch.setattr(streaming_joins, "PAIRS_PER_BATCH", blocks) + make, op = DATA_TAG_KERNELS[kernel] + inputs = _data_tagged_inputs(kernel) + expected = _rows(_transport(op.static_process(*inputs))) + assert expected + carried = [_carried(s).combine_chunks() for s in inputs] + assert all(source_tokens.derived_columns(t.schema) for t in carried) + changing = [{i} for i in range(len(inputs))] + if changes == "every": + changing = [set(range(len(inputs)))] + for changed in changing: + parts: list[list[pa.RecordBatch]] = [] + for index, table in enumerate(carried): + half = table.num_rows // 2 + pieces = [table.slice(0, half), table.slice(half)] + if index in changed: + as_text = 1 if first == "derived" else 0 + pieces[as_text] = source_tokens.materialize(pieces[as_text]) + parts.append([b for t in pieces for b in t.combine_chunks().to_batches()]) + for order in itertools.permutations(range(len(inputs))): + # Each input whole in turn, its end now or only after the last one. + for ends_at_once in (True, False): + events: list[tuple[int, pa.RecordBatch | None]] = [] + for index in order: + events += [(index, batch) for batch in parts[index]] + if ends_at_once: + events.append((index, None)) + if not ends_at_once: + events += [(index, None) for index in order] + _check_events(make(inputs), events, expected) + # And the inputs' halves in turn. + events = [ + (index, parts[index][half]) + for half in (0, 1) + for index in range(len(inputs)) + ] + events += [(index, None) for index in range(len(inputs))] + _check_events(make(inputs), events, expected) + assert _files(spooled) == [] + + +def _check_events( + kernel: StreamingJoinKernel, + events: Sequence[tuple[int, pa.RecordBatch | None]], + expected: Any, +) -> None: + """Check the rows a kernel gives for these arrivals, their tokens as text.""" + rows: Any = Counter() + for batch in _run(kernel, events): + rows += _rows(source_tokens.materialize(pa.Table.from_batches([batch]))) + assert rows == expected + assert kernel.held_rows == 0 + + +@pytest.mark.parametrize("first", ["derived", "text"]) +@pytest.mark.parametrize("kernel", sorted(DATA_TAG_KERNELS)) +def test_shared_data_tags_whose_tokens_change_form_over_staged_channels( + spooled: Path, kernel: str, first: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """The same over channels, the join taking each batch before the next is sent.""" + monkeypatch.setattr(streaming_joins, "PUSH_ROWS", 64) + monkeypatch.setattr(streaming_joins, "PAIRS_PER_BATCH", 64) + _, op = DATA_TAG_KERNELS[kernel] + inputs = _data_tagged_inputs(kernel) + expected = _rows(_transport(op.static_process(*inputs))) + tables = [_carried(s).combine_chunks() for s in inputs] + + async def go() -> StreamProtocol: + channels = [OutputChannel(s, retain=False, buffer_size=8) for s in inputs] + output = OutputChannel(op(*inputs)) + readers = [channel.open_reader() for channel in channels] + run = asyncio.create_task(op.async_execute_batches(readers, output)) + for half in (0, 1): + for channel, table in zip(channels, tables): + middle = table.num_rows // 2 + part = table.slice(0, middle) if half == 0 else table.slice(middle) + if (half == 0) == (first == "text"): + part = source_tokens.materialize(part) + for batch in part.combine_chunks().to_batches(): + await channel.send(batch) + await asyncio.sleep(0.01) + for channel in channels: + await channel.close() + await run + return output.result() + + assert _rows(_transport(_bounded(go()))) == expected + assert _files(spooled) == []