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/12] 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/12] 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 3e0794d87c9279010104d7cc7467080c85616b2a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:29:31 -0800 Subject: [PATCH 03/12] 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 04/12] 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 05/12] 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 35fe2572918ba2cae3edb21c7c951edf4b7e65cc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:41:15 -0800 Subject: [PATCH 06/12] 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 07/12] 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 1ce55338027e8b5efde79213d570e779af9975de Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:50:17 -0800 Subject: [PATCH 08/12] 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 09/12] 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 10/12] 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 37826edcc8d15caa557821e49051da74f8a327b9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:15:19 -0800 Subject: [PATCH 11/12] 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 7f2635f0f80b4cdfbe50fb8ca3befec78f4b463d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 03:18:38 -0800 Subject: [PATCH 12/12] 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