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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions docs/dev/specs/itl-1464-joins.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# 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, each until 65,536 rows wait for the join (the
producer's last batch is taken whole, whatever its size). Nothing
waits for one input to end, because both inputs may read one upstream (a diamond).

Not covered: `Rejoin` stays a barrier on this path, because its kernel can differ from the
sync path for repeated origins with three or more inputs. A subclass of an operator runs its
own sync call over its whole inputs.

## 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
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: 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 |
|---|---|
| `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 | 2,733 MiB | 392 MiB | 61.7 s |
| `one_to_one` | 1,000,000 | keys | 1,000,000 | 317 MiB | 64 MiB | 4.7 s |
| `one_to_one` | 8,000,000 | keys | 8,000,000 | 341 MiB | 64 MiB | 39.3 s |
| `one_to_one_late` | 1,000,000 | barrier | 1,000,000 | 2,574 MiB | 1,854 MiB | 4.4 s |
| `one_to_one_late` | 1,000,000 | keys | 1,000,000 | 741 MiB | 176 MiB | 5.1 s |
| `one_to_one_late` | 8,000,000 | keys | 8,000,000 | 2,301 MiB | 453 MiB | 60.0 s |
| `many` (5 per row) | 1,000,000 | barrier | 5,000,000 | 4,835 MiB | 4,111 MiB | 2.4 s |
| `many` | 1,000,000 | keys | 5,000,000 | 445 MiB | 144 MiB | 3.2 s |
| `many` | 8,000,000 | keys | 40,000,000 | 453 MiB | 146 MiB | 26.0 s |
| `many_open` (5 per row) | 1,000,000 | barrier | 5,000,000 | 6,068 MiB | 5,002 MiB | 4.2 s |
| `many_open` | 1,000,000 | keys | 5,000,000 | 992 MiB | 384 MiB | 5.6 s |
| `many_open` | 4,000,000 | keys | 20,000,000 | 1,691 MiB | 633 MiB | 23.5 s |
| `many_open` | 8,000,000 | keys | 40,000,000 | 2,629 MiB | 941 MiB | 57.3 s |
| `semi` | 8,000,000 | keys | 8,000,000 | 252 MiB | 21 MiB | 19.6 s |

`lookup`, `one_to_one` in step, `many` and `semi` do not grow with the rows. The late
cases grow with the keys of the input that arrived first, as the bound says. `many` ends its small
side first, so it measures the bounded output; `many_open` is the worst case, two open inputs
with no certificate, and grows with the keys of both.
233 changes: 233 additions & 0 deletions docs/dev/specs/itl-1464-joins/measure.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
"""One async join over record-batch channels, its time and peak memory (ITL-1464).

Usage: ``measure.py <case> <rows> [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.
- ``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).
"""

from __future__ import annotations

import asyncio
import resource
import sys
import time
import warnings
from collections.abc import Callable, Iterator
from typing import Any

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-0123456789abcdef"


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:
"""Synthetic event rows: tags and data of several types."""
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()),
"burst": pa.array(i // 5, 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 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(
{
"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: 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)

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]:
tags = {"many": "shank", "many_open": "burst"}.get(case, "unit")
big = Input(
"spikes",
spikes,
rows,
["session", tags, "spike"],
["session", "spike"]
if case.startswith("many")
else ["session", "unit", "spike"],
)
if case.startswith("one_to_one"):
other = Input(
"second",
second,
rows,
["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"]
)
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() or 0) / 2**20:8.0f} MiB"
)
9 changes: 8 additions & 1 deletion src/orcapod/core/cached_function_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
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
from orcapod.core.datagrams import Datagram
from orcapod.core.function_pod import (
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -509,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)
Expand Down
Loading
Loading