From f6a76c3bcede579242e319394fce83a4a81fd95e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 00:56:55 -0800 Subject: [PATCH 01/81] perf(spiraldb): build no source-info tokens for a read that returns none (ITL-1464) A SpiralDBTableSource read whose table holds no source-info column and no content hash built one token per row and data column, then dropped them. On 2.2 million rows of 13 columns that was 9.3 GiB of Arrow memory for a 282 MiB table. The read now builds them only when its result shows or hashes them. Adds the memory diagnosis (docs/dev/specs/itl-1464-memory-diagnosis.md) and the scripts it was measured with. Co-Authored-By: Claude Fable 5.2 --- changelog.d/ITL-1464.md | 7 + docs/dev/specs/itl-1464-memory-diagnosis.md | 205 ++++++++ docs/dev/specs/itl-1464/measure.py | 493 ++++++++++++++++++ docs/dev/specs/itl-1464/run_measurements.py | 111 ++++ .../core/sources/spiraldb_table_source.py | 46 +- src/orcapod/core/sources/stream_builder.py | 25 +- .../test_spiraldb_table_source_tokens.py | 215 ++++++++ 7 files changed, 1088 insertions(+), 14 deletions(-) create mode 100644 changelog.d/ITL-1464.md create mode 100644 docs/dev/specs/itl-1464-memory-diagnosis.md create mode 100644 docs/dev/specs/itl-1464/measure.py create mode 100644 docs/dev/specs/itl-1464/run_measurements.py create mode 100644 tests/test_core/sources/test_spiraldb_table_source_tokens.py diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md new file mode 100644 index 000000000..8f42a6b57 --- /dev/null +++ b/changelog.d/ITL-1464.md @@ -0,0 +1,7 @@ +### Changed + +- A `SpiralDBTableSource` read whose table holds no source-info column and no content hash + (`as_table()`, `run()`, `as_polars_df()` with the default columns) no longer builds the + source-info tokens of every row and column only to drop them. The rows and the table are + the same; on a table of 2.2 million rows and 13 columns the read's peak memory falls from + 10.8 GiB to 2.0 GiB (ITL-1464). diff --git a/docs/dev/specs/itl-1464-memory-diagnosis.md b/docs/dev/specs/itl-1464-memory-diagnosis.md new file mode 100644 index 000000000..7a6d629c7 --- /dev/null +++ b/docs/dev/specs/itl-1464-memory-diagnosis.md @@ -0,0 +1,205 @@ +# Where the memory goes (ITL-1464, phase 1: diagnosis) + +Status: measured on `origin/main` 0d1e017c, November 25, 2026. The design that follows from +it is `itl-1464-streaming-design.md`. + +## Summary + +Three causes account for the memory, in this order of size: + +1. **Rows held as `(Tag, Data)` objects cost 18 to 110 KiB each.** A row of the measured + table is 120 bytes of Arrow data. The async orchestrator passes every row between nodes + as a pair of datagram objects, and every operator job node keeps every pair of its + output until the run ends. One async job over 200,000 rows peaks at 19.7 GiB + (102 KiB per row, 877 times the input); the cost is linear in rows, so the full + session (2,177,155 rows) extrapolates to about 210 GiB. This is the workshop + notebook's 145 to 166 GB. +2. **Source-info tokens are 35 times the data.** A source writes one string per row and + data column, `::::`, about 324 bytes each here. With 13 + data columns (every key column is a data-tag, so it has a token too) that is 4.2 KiB + per row against 120 bytes of data. A source builds them on every read, also for a + caller that drops them at once: `source.as_table()` on the full session allocates + 9.3 GiB of Arrow memory to return a 282 MiB table. This is the 18 GB of + `run()` followed by `as_table()` (the live table has longer ids than the synthetic one). +3. **Every sync operator holds its whole input and its whole output at once, tokens + included**, and a job node keeps its output. `drop_nulls` peaks at 2 times the + tokenized table (19.7 GiB), `group_by` at 20.9 GiB, and a join, which adds the other + input's tokens to every output row, passes 24 GiB. + +`run()` returning a view over `as_table()` (the issue's starting point) is real but is the +smallest of these: the view of a bare source holds 60 MiB here. The table it is built +from is not the problem; what is built on the way to it is. + +Nothing was measured live. The synthetic tables reproduce the reported sizes closely +enough that no SpiralDB read was needed. + +## Method + +- Scripts: `docs/dev/specs/itl-1464/measure.py` (one step), `run_measurements.py` (every + step, each in a fresh process, killed above 24 GiB of resident memory). +- Tables: synthetic, with the column names and Arrow types of three tables of a SpiralDB + sample dataset, one session each: + - a gaze time series: 13 columns (5 key columns: two strings, a timestamp, a `uint32`, + a `uint64`; 8 value columns: two short strings, two `float`, three `double`, a + `bool`), 120 bytes per row; + - a spike event table: 8 columns (7 key columns), 79 bytes per row; + - a unit location table: 14 columns (9 key columns), 300 rows. +- They are stored in the test suite's disk-backed fake of the SpiralDB client + (`tests/test_databases/fake_spiral_sdk.py`), so the real `SpiralDBTableSource` reads + them. The fake memory-maps its file, so the rows it hands over are not process memory + until copied. No `where` is applied: the stored table is the one session. +- Per step: Arrow bytes in (`Table.nbytes` of the stored rows), Arrow bytes of the result, + peak resident memory of the process (`ru_maxrss`; 0.14 GiB of it is the import of + Orcapod), peak of the Arrow memory pool, and, in separate runs, Python's own + allocations (`tracemalloc`). +- Machine: macOS, Apple silicon, Python 3.13, pyarrow and polars as locked. +- The synthetic ids are shorter than live ones (a 23-character project id, a + 32-character hash key), so a live token is longer and the live numbers are higher. + +## The sync path, outside a job (2,177,155 rows) + +"Ratio" is peak resident memory, less the import baseline, over the input's Arrow bytes. + +| Step | Input | Result | Peak RSS | Arrow pool peak | Ratio | Why | +|---|---|---|---|---|---|---| +| The rows alone, copied once | 248 MiB | 248 MiB | 0.63 GiB | 0.24 GiB | 2 | the floor | +| `source.as_table()` | 248 MiB | 282 MiB | 10.8 GiB | 9.3 GiB | 44 | tokens for 13 columns built per batch, kept until the batches are joined, then dropped | +| `source.run()` | 248 MiB | (view) | 10.8 GiB | 9.3 GiB | 44 | is `as_table()`; the view keeps 60 MiB | +| `run()` then `as_table()` | 248 MiB | 282 MiB | 12.5 GiB | 9.4 GiB | 51 | the source holds no rows, so the table is read and tokenized twice | +| `source.as_polars_df()` | 248 MiB | 215 MiB | 10.9 GiB | 9.3 GiB | 44 | is `as_table()` | +| `for tag, data in source` | 248 MiB | none | 1.4 GiB | 0.07 GiB | 5 | one batch (8,192 rows) held at a time; the growth is the set of keys seen (below); 88 s | +| `source.map_data(...)` | 248 MiB | 282 MiB | 10.8 GiB | 9.3 GiB | 44 | a rename; the cost is its input | +| `source.drop_nulls(...)` | 248 MiB | 277 MiB | 19.7 GiB | 18.6 GiB | 80 | input with tokens and a filtered copy with tokens, both held | +| `source.polars_filter(...)` | 248 MiB | 141 MiB | 16.6 GiB | 9.3 GiB | 68 | input with tokens, and every column copied into Polars and back | +| `source.group_by(key)` | 248 MiB | 143 MiB | 20.9 GiB | 15.9 GiB | 85 | input with tokens, the sorted copy, and a token list per group and column | +| `spikes.join(locations)` | 164 MiB | - | killed, above 24 GiB | - | above 150 | at 200,000 rows: 2.96 GiB, ratio 191. Each output row carries the tokens of both inputs: 22 columns | +| `drop_nulls`, `group_by`, `map_data` | 248 MiB | - | killed, above 24 GiB | - | above 100 | at 200,000 rows: 2.89 GiB, ratio 123 | +| the same, then a function pod | 248 MiB | - | killed, above 24 GiB | - | above 100 | at 200,000 rows: 3.05 GiB, ratio 131 | +| `source.flow()` | 248 MiB | - | killed, above 24 GiB | - | above 100 | at 200,000 rows: 3.58 GiB, 18 KiB per row | +| `source.as_table(all_info=True)` | 248 MiB | - | killed, above 24 GiB | - | above 100 | at 200,000 rows: 5.33 GiB; the content hash column is computed from one datagram per row | + +Every step scales linearly: the 200,000-row runs give the same ratios (44 to 45 for +`as_table()`, 81 for `drop_nulls`, 89 for `group_by`). + +### What a tokenized table is made of + +`source.as_table(all_info=True)` at 200,000 rows, 911 MiB of Arrow data: + +| Column group | Bytes | Share | +|---|---|---| +| Tag and data columns (the rows) | 26 MiB | 3% | +| Source-info tokens, 13 columns | 805 MiB | 88% | +| System tags (source id, record id), data context, content hash | 81 MiB | 9% | + +A token repeats, for every row and column, the source id (constant over the table) and +the record id (the canonical JSON of the row's key, itself a copy of the key columns with +their names). Everything in a source's token is in the row's two system tags plus the +column name: the 805 MiB are derivable from the 81 MiB. + +### What a held row costs + +`source.flow()` at 200,000 rows: 3.58 GiB, 18 KiB per row. `tracemalloc` sees 1.75 GiB of +Python objects (8.7 KiB per row; the largest part is the per-row split of the table into +one-row tables, `tag_data.py`), and the rest is Arrow's own objects outside its buffer +pool: a one-row table of 26 columns has a schema, fields and array objects of its own. +The Arrow pool holds 80 MiB throughout: the data is not the cost, the per-row structure +is. + +Three places hold every row this way today: + +- `flow()`, and any read that iterates a stream and keeps the pairs; +- `ArrowTableStream.iter_data()`, which keeps every pair it yielded + (`_cached_elements`) for the life of the stream, so iterating an in-memory stream once + costs the same as `flow()`; +- the async path (next section). + +### The keys a source remembers + +`SpiralDBTableSource` keeps the record id of every row it has read during one read, to +refuse a repeated key. At 2,177,155 rows that is a Python set of about 130-character +strings: roughly 0.5 GiB, most of the 1.4 GiB of plain iteration. + +## Inside a job: sync and async + +The same step as the only node of a job, by both orchestrators, at 20,000 rows (2.3 MiB +of input; the join's large input is 1.5 MiB). "Per row" is peak resident memory less the +import baseline, over the rows. + +| Job | Sync peak | Sync per row | Async peak | Async per row | Async over sync | +|---|---|---|---|---|---| +| `map_data` | 0.27 GiB | 6.9 KiB | 1.17 GiB | 54 KiB | 7.8 | +| `drop_nulls` | 0.35 GiB | 11.1 KiB | 1.87 GiB | 90 KiB | 8.1 | +| `polars_filter` | 0.35 GiB | 10.8 KiB | 2.23 GiB | 109 KiB | 10.1 | +| `join` (large with small) | 0.55 GiB | 21.3 KiB | 1.45 GiB | 68 KiB | 3.2 | +| `group_by` | 0.37 GiB | 12.1 KiB | 1.23 GiB | 57 KiB | 4.7 | +| `drop_nulls`, `group_by`, `map_data`, function pod | 0.56 GiB | 21.7 KiB | 2.18 GiB | 107 KiB | 4.9 | + +The last job at larger sizes: + +| Rows | Sync peak | Sync per row | Async peak | Async per row | Async time | +|---|---|---|---|---|---| +| 20,000 | 0.56 GiB | 21.7 KiB | 2.18 GiB | 107 KiB | 13 s | +| 50,000 | 1.09 GiB | 19.8 KiB | 5.05 GiB | 103 KiB | 32 s | +| 100,000 | 1.99 GiB | 19.4 KiB | 9.98 GiB | 103 KiB | 63 s | +| 200,000 | 3.81 GiB | 19.2 KiB | 19.67 GiB | 102 KiB | 127 s | +| 2,177,155 | killed, above 24 GiB (41 GiB extrapolated) | | not run (207 GiB extrapolated) | | (23 min extrapolated) | + +### Does the async path stream today? + +It moves rows one at a time, but it does not bound memory: every node gathers. + +- **Transport.** A channel carries `(Tag, Data)` pairs, one row each, 64 buffered + (`AsyncPipelineOrchestrator(buffer_size=64)`). A source node sends + `async_iter_data()` row by row, so a source does not gather. The record-batch channels + of ITL-1347 exist (`InputChannel`, `OutputChannel`, `async_execute_batches`, the + streaming join kernels) but no node or orchestrator uses them yet. +- **Operators that pass rows on as they arrive**: the column selections, the mappers, + `DropNulls`, `Filter`, `AddTags`, `Pick`, `Index`, `SemiJoin` (after its right + input is read), and `Join` (a symmetric hash join: it keeps the rows of both inputs + until the other closes). +- **Operators that gather their whole input** (`StaticOutputOperatorPod.async_execute`, + the barrier: `ch.collect()` on every input, then the sync `static_process`, then one + row at a time out): `PolarsFilter`, `GroupBy`, `TagBy`, `MergeJoin`, `Rejoin`, `Batch` + without a size. `PolarsFilter` is a row-by-row operation that gathers only because it + has no async form of its own; it is the most expensive single step measured. +- **Every operator job node gathers its whole output**, whatever its operator does: + `OperatorNode.async_execute` appends every pair it forwards to a list (`collected`) + and, when the run ends, rebuilds one table from the list to keep on the node + (`_cached_output_stream`), because a job node shows its current run (ITL-1095). This + is why a pure rename costs 54 KiB per row on the async path: the rows are held twice, + once as objects and once as the rebuilt table. +- **A function job node** computes one row at a time and writes its results to the + database, but it too keeps its run's rows. + +So async is the more expensive path today, by 3 to 10 times, and the slower one (127 s +against 5 s at 200,000 rows). In theory it is the path that can bound memory; in +practice it has the same gathering as sync, at the per-row object price. + +## What each cause is worth + +| Cause | Where | Size at 2.18 million rows | What removes it | +|---|---|---|---| +| Rows as objects, kept by every async node | async transport, `OperatorNode.async_execute`, `iter_data` cache, `flow()` | about 100 KiB per row and node chain: 200 GiB | record batches between nodes (ITL-1347 wiring); a node keeps a reference to stored or spilled rows, not the rows | +| Source-info tokens | every source read, every operator's input and output | 4.2 KiB per row per tokenized copy: 9 GiB per copy, 2 to 3 copies per operator | not building them where nothing reads them (prototype, below); deriving a source's tokens from its system tags until an operator changes them (design) | +| Whole input plus whole output per operator | every sync operator, async barriers | 2 to 3 tokenized copies | batch-wise execution for row-by-row operators; a stated bound for the others (design) | +| A source read twice | `run()` then `as_table()` on a source that holds no rows | one more read | a view that does not need the table (design) | +| Keys remembered by a source | `SpiralDBTableSource` | 0.5 GiB | trusting a key the store enforces (developer's decision, in the design) | + +## The prototype's effect (phase 3) + +A `SpiralDBTableSource` read whose result holds no source-info column and no content hash +(`as_table()`, `run()`, `as_polars_df()` with the default columns) no longer builds +tokens. Same rows, same table, at 2,177,155 rows: + +| Step | Peak RSS before | Peak RSS after | Arrow pool peak before | after | +|---|---|---|---|---| +| `source.as_table()` | 10.8 GiB | 1.96 GiB | 9.3 GiB | 0.96 GiB | +| `source.run()` | 10.8 GiB | 1.96 GiB | 9.3 GiB | 0.96 GiB | +| `run()` then `as_table()` | 12.5 GiB | 2.62 GiB | 9.4 GiB | 1.02 GiB | +| `source.as_polars_df()` | 10.9 GiB | 2.21 GiB | 9.3 GiB | 0.96 GiB | +| `source.drop_nulls(...)` (an operator reads the tokens) | 19.7 GiB | 19.7 GiB | 18.6 GiB | 18.6 GiB | + +It removes the largest cost of the reported case (a) and nothing of case (b): an +operator and a job still read the tokens. What remains of the 1.96 GiB is the system +tags (0.5 GiB of Arrow), the set of keys seen (0.5 GiB of Python strings) and the copy +made when the batches are joined. diff --git a/docs/dev/specs/itl-1464/measure.py b/docs/dev/specs/itl-1464/measure.py new file mode 100644 index 000000000..1b9bb44f3 --- /dev/null +++ b/docs/dev/specs/itl-1464/measure.py @@ -0,0 +1,493 @@ +"""Measure the memory of one step of a workshop-shaped pipeline (ITL-1464). + +One step per process, so that a step's peak is its own:: + + uv run python docs/dev/specs/itl-1464/measure.py setup --rows 2177155 --store + uv run python docs/dev/specs/itl-1464/measure.py --store + +``run_measurements.py`` runs every step under a memory guard and writes the table. + +The tables are synthetic: the column names and Arrow types of three tables of a +SpiralDB sample dataset (a gaze time series, a spike event table and a unit location +table), with generated values. They are stored in the disk-backed fake of the SpiralDB +client that the test suite uses (``tests/test_databases/fake_spiral_sdk.py``), so the +real ``SpiralDBTableSource`` reads them: the code under measurement is the library's, +only the service is replaced. The fake memory-maps the stored file, so the rows it +hands over are not private memory of the process until they are copied. + +Each step prints one JSON line: the rows and Arrow bytes that went in, the Arrow bytes +of the result, the peak resident memory of the process (``ru_maxrss``), the peak of +the Arrow memory pool, and the peak of Python's own allocations when ``--tracemalloc`` +is given. +""" + +from __future__ import annotations + +import argparse +import gc +import json +import resource +import sys +import time +import tracemalloc +import warnings +from collections.abc import Callable +from datetime import datetime +from pathlib import Path +from typing import Any + +import numpy as np +import pyarrow as pa + +REPOSITORY = Path(__file__).resolve().parents[4] +sys.path.insert(0, str(REPOSITORY)) + +from tests.test_databases import fake_spiral_sdk as fake # noqa: E402 + +PROJECT = "synthetic-sample-000000" +GAZE = "experiment_gaze_online_timeseries" +SPIKES = "spike_event" +LOCATIONS = "unit_location" + +SESSION_START = datetime(2026, 1, 1, 12, 0, 0) +SUBJECT = "subject" +HASH = "0123456789abcdef0123456789abcdef" +EXPERIMENTS = 6 +UNITS = 300 + +GAZE_KEYS = [ + "experiment_preprocessing_hash", + "subject_id", + "session_start_datetime", + "experiment_index", + "timestamp", +] +EXPERIMENT_KEY = GAZE_KEYS[:4] +SPIKE_KEYS = [ + "spike_extraction_hash", + "subject_id", + "session_start_datetime", + "recording_index", + "probe_index", + "timestamp", + "unit_id", +] +UNIT_KEY = [ + "spike_extraction_hash", + "subject_id", + "session_start_datetime", + "recording_index", + "probe_index", + "unit_id", +] +LOCATION_KEYS = [ + "spike_extraction_hash", + "localization_hash", + "subject_id", + "session_start_datetime", + "recording_index", + "probe_index", + "unit_id", + "atlas_id", + "atlas_label_region_short", +] + + +def _constant(value: Any, kind: pa.DataType, rows: int) -> pa.Array[Any]: + return pa.repeat(pa.scalar(value, kind), rows) + + +def gaze_table(rows: int) -> pa.Table: + """Return ``rows`` rows shaped like one session of the gaze time series.""" + rng = np.random.default_rng(0) + per_experiment = -(-rows // EXPERIMENTS) + experiment = np.repeat(np.arange(EXPERIMENTS, dtype=np.uint32), per_experiment)[ + :rows + ] + timestamp = np.arange(rows, dtype=np.uint64) * 5_000 + 1_700_000_000_000_000 + x = rng.normal(size=rows) + y = rng.normal(size=rows) + # A few nulls, as blinks leave: ``drop_nulls`` has rows to drop. + missing = rng.random(rows) < 0.02 + return pa.table( + { + "experiment_preprocessing_hash": _constant(HASH, pa.string(), rows), + "subject_id": _constant(SUBJECT, pa.string(), rows), + "session_start_datetime": _constant( + SESSION_START, pa.timestamp("us"), rows + ), + "experiment_index": pa.array(experiment), + "timestamp": pa.array(timestamp), + "eye_tracking_software": _constant("tracker", pa.string(), rows), + "eye_tracking_software_version": _constant("1.2.3", pa.string(), rows), + "eye_x_deg": pa.array(x.astype(np.float32), mask=missing), + "eye_x_px": pa.array(x * 100, mask=missing), + "eye_y_deg": pa.array(y.astype(np.float32), mask=missing), + "eye_y_px": pa.array(y * 100, mask=missing), + "gaze_unreliable": pa.array(missing), + "pupil_size_norm": pa.array(rng.random(rows)), + } + ) + + +def spike_table(rows: int) -> pa.Table: + """Return ``rows`` rows shaped like one session of the spike event table.""" + rng = np.random.default_rng(1) + timestamp = np.arange(rows, dtype=np.uint64) * 400 + 1_700_000_000_000_000 + return pa.table( + { + "spike_extraction_hash": _constant(HASH, pa.string(), rows), + "subject_id": _constant(SUBJECT, pa.string(), rows), + "session_start_datetime": _constant( + SESSION_START, pa.timestamp("us"), rows + ), + "recording_index": _constant(0, pa.uint32(), rows), + "probe_index": _constant(0, pa.uint32(), rows), + "timestamp": pa.array(timestamp), + "unit_id": pa.array(rng.integers(0, UNITS, rows).astype(np.uint32)), + "spike_amplitude_uv": pa.array(rng.normal(size=rows).astype(np.float32)), + } + ) + + +def location_table() -> pa.Table: + """Return one row per unit, shaped like the unit location table.""" + rng = np.random.default_rng(2) + rows = UNITS + return pa.table( + { + "spike_extraction_hash": _constant(HASH, pa.string(), rows), + "localization_hash": _constant(HASH[::-1], pa.string(), rows), + "subject_id": _constant(SUBJECT, pa.string(), rows), + "session_start_datetime": _constant( + SESSION_START, pa.timestamp("us"), rows + ), + "recording_index": _constant(0, pa.uint32(), rows), + "probe_index": _constant(0, pa.uint32(), rows), + "unit_id": pa.array(np.arange(rows, dtype=np.uint32)), + "atlas_id": _constant("atlas", pa.string(), rows), + "atlas_label_region_short": _constant("V1", pa.string(), rows), + "atlas_label_region_full": _constant("area", pa.string(), rows), + "chamber_id": _constant("chamber", pa.string(), rows), + "chamber_x_um": pa.array(rng.normal(size=rows)), + "chamber_y_um": pa.array(rng.normal(size=rows)), + "chamber_z_um": pa.array(rng.normal(size=rows)), + } + ) + + +def setup(rows: int) -> None: + """Write the three tables into the fake store, in key order, and record them.""" + from orcapod.utils import arrow_utils + + store = fake._store() + for name, keys, table in ( + (GAZE, GAZE_KEYS, gaze_table(rows)), + (SPIKES, SPIKE_KEYS, spike_table(rows)), + (LOCATIONS, LOCATION_KEYS, location_table()), + ): + made = fake.ExternalProject(PROJECT).create_table( + f"default.{name}", key_schema=[table.schema.field(k) for k in keys] + ) + # Written as a stored version directly (the rows are generated in key order, + # with unique keys), not through the fake's upsert, which builds a Python + # tuple per key. + ordered = fake._order([f for f in table.schema if f.name not in keys]) + table = table.select([*keys, *(f.name for f in ordered)]) + store.write(made.table_id, table) + # Key columns are recorded as non-nullable, as the dataset declares them. + recorded = arrow_utils.normalize_table_to_large_types(table).schema + recorded = pa.schema([f.with_nullable(f.name not in keys) for f in recorded]) + fake.migrate(PROJECT, {name: recorded}) + + +def _source(name: str) -> Any: + from orcapod.core.sources import SpiralDBTableSource + + return SpiralDBTableSource(PROJECT, name, max_rows=None) + + +def _raw(name: str) -> pa.Table: + store = fake._store() + found = store.find(PROJECT, "default", name) + assert found is not None + return store.read(found["id"], 1) + + +Result = "tuple[pa.Table | None, list[pa.Table], Any]" + + +def step_raw_copy() -> tuple[int, int, Any]: + """The rows alone, copied into process memory: the floor every step stands on.""" + raw = _raw(GAZE) + copy = pa.concat_tables([raw]).combine_chunks() + copy = pa.Table.from_arrays( + [pa.concat_arrays([c.chunk(0), c.chunk(0).slice(0, 0)]) for c in copy.columns], + schema=copy.schema, + ) + return raw.nbytes, copy.nbytes, copy + + +def step_as_table() -> tuple[int, int, Any]: + table = _source(GAZE).as_table() + return _raw(GAZE).nbytes, table.nbytes, table + + +def step_as_table_all_info() -> tuple[int, int, Any]: + table = _source(GAZE).as_table(all_info=True) + groups: dict[str, int] = {"user": 0, "source_info": 0, "system_tags": 0, "other": 0} + for name in table.column_names: + size = table.column(name).nbytes + if name.startswith("_source_"): + groups["source_info"] += size + elif name.startswith("_tag::"): + groups["system_tags"] += size + elif name.startswith("_"): + groups["other"] += size + else: + groups["user"] += size + print(json.dumps({"column_group_bytes": groups}), file=sys.stderr) + return _raw(GAZE).nbytes, table.nbytes, table + + +def step_run() -> tuple[int, int, Any]: + view = _source(GAZE).run() + return _raw(GAZE).nbytes, 0, view + + +def step_run_then_as_table() -> tuple[int, int, Any]: + source = _source(GAZE) + view = source.run() + table = source.as_table() + return _raw(GAZE).nbytes, table.nbytes, (view, table) + + +def step_as_polars_df() -> tuple[int, int, Any]: + frame = _source(GAZE).as_polars_df() + return _raw(GAZE).nbytes, int(frame.estimated_size()), frame + + +def step_iterate() -> tuple[int, int, Any]: + count = 0 + for _tag, _data in _source(GAZE): + count += 1 + return _raw(GAZE).nbytes, 0, count + + +def step_iterate_read_one_value() -> tuple[int, int, Any]: + total = 0.0 + for _tag, data in _source(GAZE): + total += data["pupil_size_norm"] + return _raw(GAZE).nbytes, 0, total + + +def step_flow() -> tuple[int, int, Any]: + pairs = _source(GAZE).flow() + return _raw(GAZE).nbytes, 0, pairs + + +def step_drop_nulls() -> tuple[int, int, Any]: + table = _source(GAZE).drop_nulls(["eye_x_deg", "eye_y_deg"]).as_table() + return _raw(GAZE).nbytes, table.nbytes, table + + +def step_polars_filter() -> tuple[int, int, Any]: + import polars as pl + + table = _source(GAZE).polars_filter(pl.col("pupil_size_norm") > 0.5).as_table() + return _raw(GAZE).nbytes, table.nbytes, table + + +def step_map_data() -> tuple[int, int, Any]: + table = _source(GAZE).map_data({"pupil_size_norm": "pupil"}).as_table() + return _raw(GAZE).nbytes, table.nbytes, table + + +def step_join() -> tuple[int, int, Any]: + table = _source(SPIKES).join(_source(LOCATIONS)).as_table() + return _raw(SPIKES).nbytes + _raw(LOCATIONS).nbytes, table.nbytes, table + + +def _grouped_gaze() -> Any: + return ( + _source(GAZE) + .drop_nulls(["eye_x_deg", "eye_y_deg"]) + .group_by(EXPERIMENT_KEY) + .map_data({"timestamp": "gaze_time"}) + ) + + +def step_group_by() -> tuple[int, int, Any]: + table = _source(GAZE).group_by(EXPERIMENT_KEY).as_table() + return _raw(GAZE).nbytes, table.nbytes, table + + +def step_group_by_chain() -> tuple[int, int, Any]: + table = _grouped_gaze().as_table() + return _raw(GAZE).nbytes, table.nbytes, table + + +def _onsets_pod() -> Any: + from orcapod import function_pod + + @function_pod(output_keys="fixation_onset") + def fixation_onsets( + gaze_time: list[int], eye_x_deg: list[float], eye_y_deg: list[float] + ) -> list[int]: + t, x, y = np.asarray(gaze_time), np.asarray(eye_x_deg), np.asarray(eye_y_deg) + speed = np.hypot(np.diff(x), np.diff(y)) / (np.diff(t) / 1_000_000) + moving = speed > 40 + ends = np.flatnonzero(moving[:-1] & ~moving[1:]) + 1 + return [int(t[i]) for i in ends] + + return fixation_onsets + + +def step_function_pod() -> tuple[int, int, Any]: + table = _onsets_pod().pod(_grouped_gaze()).as_table() + return _raw(GAZE).nbytes, table.nbytes, table + + +def _job(store: Path) -> Any: + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + + database = DeltaTableDatabase(str(store / "results")) + with PipelineJob(name="fixation_response", database=database) as job: + _onsets_pod().pod(_grouped_gaze(), label="onsets") + return job + + +def step_job_run(store: Path) -> tuple[int, int, Any]: + job = _job(store) + job.run() + return _raw(GAZE).nbytes, 0, job + + +def step_job_run_async(store: Path) -> tuple[int, int, Any]: + from orcapod.pipeline import AsyncPipelineOrchestrator + + job = _job(store) + job.run(orchestrator=AsyncPipelineOrchestrator()) + return _raw(GAZE).nbytes, 0, job + + +def _operator_chains() -> dict[str, Callable[[], Any]]: + import polars as pl + + return { + "map_data": lambda: _source(GAZE).map_data({"pupil_size_norm": "pupil"}), + "drop_nulls": lambda: _source(GAZE).drop_nulls(["eye_x_deg", "eye_y_deg"]), + "polars_filter": lambda: _source(GAZE).polars_filter( + pl.col("pupil_size_norm") > 0.5 + ), + "join": lambda: _source(SPIKES).join(_source(LOCATIONS)), + "group_by": lambda: _source(GAZE).group_by(EXPERIMENT_KEY), + } + + +def _operator_job(chain: str, orchestrator: str) -> Callable[[Path], Any]: + """A job of one operator over its sources, run by the named orchestrator.""" + + def step(store: Path) -> tuple[int, int, Any]: + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + from orcapod.pipeline import AsyncPipelineOrchestrator + + database = DeltaTableDatabase(str(store / f"results_{chain}_{orchestrator}")) + with PipelineJob(name=f"only_{chain}", database=database) as job: + _operator_chains()[chain]() + if orchestrator == "async": + job.run(orchestrator=AsyncPipelineOrchestrator()) + else: + job.run() + name = SPIKES if chain == "join" else GAZE + return _raw(name).nbytes, 0, job + + return step + + +STEPS: dict[str, Callable[..., tuple[int, int, Any]]] = { + **{ + f"job_{chain}_{orchestrator}": _operator_job(chain, orchestrator) + for chain in ("map_data", "drop_nulls", "polars_filter", "join", "group_by") + for orchestrator in ("sync", "async") + }, + "raw_copy": step_raw_copy, + "as_table": step_as_table, + "as_table_all_info": step_as_table_all_info, + "run": step_run, + "run_then_as_table": step_run_then_as_table, + "as_polars_df": step_as_polars_df, + "iterate": step_iterate, + "iterate_read_one_value": step_iterate_read_one_value, + "flow": step_flow, + "drop_nulls": step_drop_nulls, + "polars_filter": step_polars_filter, + "map_data": step_map_data, + "join": step_join, + "group_by": step_group_by, + "group_by_chain": step_group_by_chain, + "function_pod": step_function_pod, + "job_run": step_job_run, + "job_run_async": step_job_run_async, +} + + +def _peak_rss_bytes() -> int: + peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + return peak if sys.platform == "darwin" else peak * 1024 + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("step", choices=["setup", *STEPS]) + parser.add_argument("--store", required=True, type=Path) + parser.add_argument("--rows", type=int, default=2_177_155) + parser.add_argument("--tracemalloc", action="store_true") + args = parser.parse_args() + warnings.simplefilter("ignore") + + with fake.install(args.store / "spiral"): + fake.scan_batch_rows = 65_536 + if args.step == "setup": + setup(args.rows) + return + import orcapod # noqa: F401 + + gc.collect() + before = _peak_rss_bytes() + pool = pa.default_memory_pool() + if args.tracemalloc: + tracemalloc.start(1) + started = time.perf_counter() + step = STEPS[args.step] + took_store = args.step.startswith("job_") + in_bytes, out_bytes, kept = step(args.store) if took_store else step() + elapsed = time.perf_counter() - started + record: dict[str, Any] = { + "step": args.step, + "rows": _raw(GAZE).num_rows, + "input_arrow_bytes": in_bytes, + "output_arrow_bytes": out_bytes, + "rss_before_bytes": before, + "peak_rss_bytes": _peak_rss_bytes(), + "arrow_pool_peak_bytes": pool.max_memory(), + "arrow_pool_held_bytes": pool.bytes_allocated(), + "seconds": round(elapsed, 1), + } + if args.tracemalloc: + held, peak = tracemalloc.get_traced_memory() + top = tracemalloc.take_snapshot().statistics("lineno")[:8] + record["python_held_bytes"] = held + record["python_peak_bytes"] = peak + record["python_top_lines"] = [ + f"{Path(s.traceback[0].filename).name}:{s.traceback[0].lineno} {s.size}" + for s in top + ] + del kept + print(json.dumps(record)) + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1464/run_measurements.py b/docs/dev/specs/itl-1464/run_measurements.py new file mode 100644 index 000000000..a6c355a0a --- /dev/null +++ b/docs/dev/specs/itl-1464/run_measurements.py @@ -0,0 +1,111 @@ +"""Run every step of ``measure.py`` in its own process, under a memory guard (ITL-1464). + + uv run python docs/dev/specs/itl-1464/run_measurements.py --store \ + --rows 2177155 --out [--steps as_table run ...] + +A step whose resident memory passes ``--guard-gb`` (24 by default) is killed and +recorded as ``killed``; nothing here may starve the machine it runs on. +""" + +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +import time +from pathlib import Path + +MEASURE = Path(__file__).with_name("measure.py") + +DEFAULT_STEPS = [ + "raw_copy", + "as_table", + "as_table_all_info", + "run", + "run_then_as_table", + "as_polars_df", + "iterate", + "iterate_read_one_value", + "flow", + "map_data", + "drop_nulls", + "polars_filter", + "join", + "group_by", + "group_by_chain", + "function_pod", + "job_run", + "job_run_async", +] + + +def _rss_bytes(pid: int) -> int: + found = subprocess.run( + ["ps", "-o", "rss=", "-p", str(pid)], capture_output=True, text=True + ).stdout.strip() + return int(found) * 1024 if found else 0 + + +def run_step(step: str, store: Path, guard_bytes: int, extra: list[str]) -> dict: + """Run one step; kill it when its resident memory passes the guard.""" + process = subprocess.Popen( + [sys.executable, str(MEASURE), step, "--store", str(store), *extra], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + seen = 0 + while process.poll() is None: + seen = max(seen, _rss_bytes(process.pid)) + if seen > guard_bytes: + process.kill() + process.wait() + return {"step": step, "killed": True, "rss_when_killed_bytes": seen} + time.sleep(0.2) + out, err = process.communicate() + if process.returncode != 0: + return {"step": step, "failed": True, "error": err.strip()[-2000:]} + record = json.loads(out.strip().splitlines()[-1]) + for line in err.splitlines(): + if line.startswith("{"): + record.update(json.loads(line)) + return record + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--store", required=True, type=Path) + parser.add_argument("--rows", type=int, default=2_177_155) + parser.add_argument("--out", required=True, type=Path) + parser.add_argument("--guard-gb", type=float, default=24.0) + parser.add_argument("--steps", nargs="*", default=DEFAULT_STEPS) + parser.add_argument("--tracemalloc", action="store_true") + parser.add_argument("--skip-setup", action="store_true") + args = parser.parse_args() + + if not args.skip_setup: + subprocess.run( + [ + sys.executable, + str(MEASURE), + "setup", + "--store", + str(args.store), + "--rows", + str(args.rows), + ], + check=True, + ) + extra = ["--tracemalloc"] if args.tracemalloc else [] + guard = int(args.guard_gb * 1024**3) + with args.out.open("a") as out: + for step in args.steps: + record = run_step(step, args.store, guard, extra) + print(json.dumps(record), flush=True) + out.write(json.dumps(record) + "\n") + out.flush() + + +if __name__ == "__main__": + main() diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 6312a677f..91ce850bf 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -113,6 +113,23 @@ class _Head(NamedTuple): counted_to: int = 0 +def _reads_source_info(config: ColumnConfig) -> bool: + """Whether a table with the column groups of ``config`` needs source-info tokens. + + The tokens are one string per row and data column, many times the size of the + rows they describe (ITL-1464), so a read builds them only when its result shows + them (``source``) or hashes each row (``content_hash``: a row's hash is computed + from the row as the stream holds it). + + Args: + config: The normalized column configuration of the read. + + Returns: + True when the tokens must be built. + """ + return bool(config.source or config.content_hash) + + def _schema_difference(found: "pa.Schema", expected: "pa.Schema") -> str: """Describe how the table's columns as found differ from the ones the source expects.""" if found.names != expected.names: @@ -825,11 +842,16 @@ def _key_tokens(self, table: "pa.Table") -> list[str]: f"SpiralDB table {self._qualified!r}: {exc}" ) from exc - def _batch_streams(self) -> Generator["ArrowTableStream", None, None]: + def _batch_streams( + self, *, with_source_info: bool = True + ) -> Generator["ArrowTableStream", None, None]: """Scan the table once and yield its rows as streams of at most ``batch_rows`` rows. Each SpiralDB batch is held while its slices are yielded. + Args: + with_source_info: As for ``_read_batches``. + Raises: SourceTooLargeError: If the read would return, or returns, more than ``max_rows`` rows. @@ -839,7 +861,11 @@ def _batch_streams(self) -> Generator["ArrowTableStream", None, None]: asof = self._asof table = self._lookup_table() yield from self._read_batches( - table, asof=asof, limit=self._limit, max_rows=self._max_rows + table, + asof=asof, + limit=self._limit, + max_rows=self._max_rows, + with_source_info=with_source_info, ) def _read_batches( @@ -849,6 +875,7 @@ def _read_batches( asof: int | None, limit: int | None, max_rows: int | None, + with_source_info: bool = True, ) -> Generator["ArrowTableStream", None, None]: """Scan the table once, reading at most ``limit`` rows, in streams of ``batch_rows``. @@ -859,6 +886,9 @@ def _read_batches( asof: The pinned version for both the count and the scan. limit: Read at most this many rows, the first in key order. max_rows: Raise when the read would return more rows; ``None`` for no cap. + with_source_info: Whether each stream holds its rows' source-info tokens. + ``False`` only where the caller returns no source-info column and + hashes no row (``_whole_table``): the streams then hold null tokens. Raises: SourceTooLargeError: If the read would return, or returns, more than @@ -923,6 +953,7 @@ def _read_batches( source_id=self.source_id, row_identifiers=tokens, data_tags=self._data_tags, + with_source_info=with_source_info, ) def iter_data(self) -> Iterator["tuple[TagProtocol, DataProtocol]"]: @@ -959,8 +990,11 @@ def as_table( all_info: bool = False, ) -> "pa.Table": """Scan the table and return its rows as one PyArrow table (all held in memory).""" + config = ColumnConfig.handle_config(columns, all_info=all_info) return self._whole_table( - self._batch_streams(), columns=columns, all_info=all_info + self._batch_streams(with_source_info=_reads_source_info(config)), + columns=columns, + all_info=all_info, ) def _whole_table( @@ -972,8 +1006,10 @@ def _whole_table( ) -> "pa.Table": """Return the rows of ``streams`` (batches of one read) as one table.""" # One stream over all the rows, so that a whole-table option (sorting by - # tags) applies across batches. - enriched = {"source": True, "system_tags": True} + # tags) applies across batches. The source-info tokens are carried only for + # a result that shows or hashes them (ITL-1464). + config = ColumnConfig.handle_config(columns, all_info=all_info) + enriched = {"source": _reads_source_info(config), "system_tags": True} tables = [stream.as_table(columns=enriched) for stream in streams] if not tables: return self._stream.as_table(columns=columns, all_info=all_info) diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 5fbb8eb52..6ece00b22 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -590,6 +590,7 @@ def attach_provenance( source_id: str, row_identifiers: Sequence[str], data_tags: Sequence[str] = (), + with_source_info: bool = True, ) -> ArrowTableStream: """Add source-info and system-tag columns to ``table`` and wrap it as a stream. @@ -611,19 +612,25 @@ def attach_provenance( source. data_tags: The tag columns that are also data columns (data-tags); they get source info like any data column. + with_source_info: Whether to build the source-info tokens. ``False`` only + for a read whose caller keeps no source-info column and hashes no row + (ITL-1464): the tokens are one string per row and data column, many + times the size of the rows. The stream then holds null tokens and + must not be handed on. Returns: The stream over the enriched table. """ - source_info = [ - f"{source_id}{constants.BLOCK_SEPARATOR}{identifier}" - for identifier in row_identifiers - ] - table = arrow_utils.add_source_info( - table, - source_info, - exclude_columns=[c for c in tag_columns if c not in data_tags], - ) + if with_source_info: + source_info = [ + f"{source_id}{constants.BLOCK_SEPARATOR}{identifier}" + for identifier in row_identifiers + ] + table = arrow_utils.add_source_info( + table, + source_info, + exclude_columns=[c for c in tag_columns if c not in data_tags], + ) table = arrow_utils.add_system_tag_columns( table, schema_hash, diff --git a/tests/test_core/sources/test_spiraldb_table_source_tokens.py b/tests/test_core/sources/test_spiraldb_table_source_tokens.py new file mode 100644 index 000000000..658ef73c6 --- /dev/null +++ b/tests/test_core/sources/test_spiraldb_table_source_tokens.py @@ -0,0 +1,215 @@ +"""A SpiralDB read builds source-info tokens only for a result that holds them (ITL-1464). + +The tokens are one string per row and data column, many times the size of the rows. A +read whose table shows no source-info column and no content hash must not build them, +and must return exactly the table the read that builds them returns. + +Runs against the disk-backed fake of the SpiralDB client. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.core.sources import spiraldb_table_source as source_module +from orcapod.sources import SpiralDBTableSource +from orcapod.utils import arrow_utils +from tests.test_databases import fake_spiral_sdk + +_PROJECT = "sample" +_KEYS = pa.schema( + [pa.field("subject_id", pa.string()), pa.field("timestamp", pa.uint64())] +) +_ROWS = 5 + +# Column configurations whose table holds no token and no row hash. +_WITHOUT_TOKENS: list[dict[str, Any]] = [ + {}, + {"system_tags": True}, + {"context": True}, + {"meta": True}, + {"sort_by_tags": True}, + {"system_tags": True, "context": True, "sort_by_tags": True}, +] +# Column configurations whose table holds the tokens or a hash computed from the rows. +_WITH_TOKENS: list[dict[str, Any]] = [ + {"source": True}, + {"content_hash": True}, + {"source": True, "system_tags": True, "sort_by_tags": True}, +] + + +def _rows() -> pa.Table: + """Five rows with two key columns and two value columns, not in key order.""" + timestamps = [4, 1, 5, 2, 3] + table = pa.table( + { + "subject_id": ["m1", "m1", "m2", "m2", "m1"], + "timestamp": pa.array(timestamps, pa.uint64()), + "amplitude": pa.array([t + 0.5 for t in timestamps], pa.float32()), + "quality": pa.array(["a", None, "c", "d", "e"], pa.string()), + } + ) + return table.cast(pa.schema([pa.field(f.name, f.type, True) for f in table.schema])) + + +@pytest.fixture() +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """Provide a fake project holding ``event``, scanned 2 rows per batch.""" + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 2) + with fake_spiral_sdk.install(tmp_path / "spiral"): + made = fake_spiral_sdk.ExternalProject(_PROJECT) + made.create_table("default.event", key_schema=_KEYS).write(_rows()) + yield made + + +@pytest.fixture() +def token_builds(monkeypatch: pytest.MonkeyPatch) -> list[int]: + """Record the row count of every table the source builds tokens for.""" + calls: list[int] = [] + original = arrow_utils.add_source_info + + def recording(table: pa.Table, *given: Any, **options: Any) -> pa.Table: + calls.append(table.num_rows) + return original(table, *given, **options) + + monkeypatch.setattr(arrow_utils, "add_source_info", recording) + return calls + + +def _source(tag_only: bool) -> SpiralDBTableSource: + return SpiralDBTableSource(_PROJECT, "event", tag_only_columns=tag_only) + + +def _with_tokens_always(monkeypatch: pytest.MonkeyPatch) -> None: + """Make every read build the tokens, as every read did before ITL-1464.""" + monkeypatch.setattr(source_module, "_reads_source_info", lambda config: True) + + +@pytest.mark.parametrize("tag_only", [False, True], ids=["data_tags", "tag_only"]) +@pytest.mark.parametrize("columns", _WITHOUT_TOKENS) +def test_a_table_without_tokens_builds_none_and_equals_the_one_that_did( + project: Any, + token_builds: list[int], + monkeypatch: pytest.MonkeyPatch, + tag_only: bool, + columns: dict[str, Any], +) -> None: + source = _source(tag_only) + token_builds.clear() + + table = source.as_table(columns=columns) + + assert token_builds == [] + assert table.num_rows == _ROWS + with monkeypatch.context() as patched: + _with_tokens_always(patched) + expected = _source(tag_only).as_table(columns=columns) + assert sum(token_builds) == _ROWS + assert table.schema.equals(expected.schema, check_metadata=True) + assert table.equals(expected) + + +@pytest.mark.parametrize("tag_only", [False, True], ids=["data_tags", "tag_only"]) +@pytest.mark.parametrize("columns", _WITH_TOKENS) +def test_a_table_with_tokens_or_row_hashes_still_builds_them( + project: Any, + token_builds: list[int], + monkeypatch: pytest.MonkeyPatch, + tag_only: bool, + columns: dict[str, Any], +) -> None: + source = _source(tag_only) + token_builds.clear() + + table = source.as_table(columns=columns) + + assert sum(token_builds) == _ROWS + with monkeypatch.context() as patched: + _with_tokens_always(patched) + expected = _source(tag_only).as_table(columns=columns) + assert table.schema.equals(expected.schema, check_metadata=True) + assert table.equals(expected) + + +@pytest.mark.parametrize("tag_only", [False, True], ids=["data_tags", "tag_only"]) +def test_all_info_holds_every_token( + project: Any, token_builds: list[int], tag_only: bool +) -> None: + source = _source(tag_only) + + table = source.as_table(all_info=True) + + assert sum(token_builds) == _ROWS + tokens = [name for name in table.column_names if name.startswith("_source_")] + # A data-tag has a token; a tag kept tag-only has none. + expected = {"_source_amplitude", "_source_quality"} | ( + set() if tag_only else {"_source_subject_id", "_source_timestamp"} + ) + assert set(tokens) == expected + by_time = dict( + zip( + table.column("timestamp").to_pylist(), + table.column("_source_amplitude").to_pylist(), + strict=True, + ) + ) + assert by_time[4] == ( + f'{source.source_id}::{{"subject_id":"m1","timestamp":4}}::amplitude' + ) + for name in tokens: + assert table.column(name).null_count == 0 + + +def test_run_and_the_data_frame_build_no_tokens( + project: Any, token_builds: list[int] +) -> None: + source = _source(False) + token_builds.clear() + + view = source.run() + frame = source.as_polars_df() + + assert token_builds == [] + assert view.total_rows == _ROWS + assert frame.height == _ROWS + assert frame.columns == source.as_table().column_names + + +@pytest.mark.parametrize("tag_only", [False, True], ids=["data_tags", "tag_only"]) +def test_an_operator_over_the_source_still_reads_its_tokens( + project: Any, monkeypatch: pytest.MonkeyPatch, tag_only: bool +) -> None: + kept = _source(tag_only).drop_nulls(["quality", "amplitude"]) + + table = kept.as_table(all_info=True) + + assert table.num_rows == _ROWS - 1 + assert table.column("_source_quality").null_count == 0 + assert table.column("_source_amplitude").null_count == 0 + with monkeypatch.context() as patched: + _with_tokens_always(patched) + expected = ( + _source(tag_only) + .drop_nulls(["amplitude", "quality"]) + .as_table(all_info=True) + ) + assert table.equals(expected) + + +def test_iteration_still_gives_each_row_its_tokens(project: Any) -> None: + source = _source(False) + + tokens = { + tag.as_dict()["timestamp"]: data.source_info()["quality"] + for tag, data in source.iter_data() + } + + assert tokens[2] == ( + f'{source.source_id}::{{"subject_id":"m2","timestamp":2}}::quality' + ) + assert len(tokens) == _ROWS From 42cb6fe532302fb101e4fbca7c59dd74d53d37a0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 00:59:30 -0800 Subject: [PATCH 02/81] chore(dev): fix type errors in the ITL-1464 measurement scripts Co-Authored-By: Claude Fable 5.2 --- docs/dev/specs/itl-1464/measure.py | 12 +++--------- docs/dev/specs/itl-1464/run_measurements.py | 5 ++++- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/docs/dev/specs/itl-1464/measure.py b/docs/dev/specs/itl-1464/measure.py index 1b9bb44f3..3674b1aa9 100644 --- a/docs/dev/specs/itl-1464/measure.py +++ b/docs/dev/specs/itl-1464/measure.py @@ -94,7 +94,7 @@ def _constant(value: Any, kind: pa.DataType, rows: int) -> pa.Array[Any]: - return pa.repeat(pa.scalar(value, kind), rows) + return pa.array([value] * rows, kind) def gaze_table(rows: int) -> pa.Table: @@ -214,17 +214,11 @@ def _raw(name: str) -> pa.Table: return store.read(found["id"], 1) -Result = "tuple[pa.Table | None, list[pa.Table], Any]" - - def step_raw_copy() -> tuple[int, int, Any]: """The rows alone, copied into process memory: the floor every step stands on.""" raw = _raw(GAZE) - copy = pa.concat_tables([raw]).combine_chunks() - copy = pa.Table.from_arrays( - [pa.concat_arrays([c.chunk(0), c.chunk(0).slice(0, 0)]) for c in copy.columns], - schema=copy.schema, - ) + # ``take`` writes new buffers: the rows as private memory of this process. + copy = raw.take(np.arange(raw.num_rows)) return raw.nbytes, copy.nbytes, copy diff --git a/docs/dev/specs/itl-1464/run_measurements.py b/docs/dev/specs/itl-1464/run_measurements.py index a6c355a0a..fbeb141f9 100644 --- a/docs/dev/specs/itl-1464/run_measurements.py +++ b/docs/dev/specs/itl-1464/run_measurements.py @@ -15,6 +15,7 @@ import sys import time from pathlib import Path +from typing import Any MEASURE = Path(__file__).with_name("measure.py") @@ -47,7 +48,9 @@ def _rss_bytes(pid: int) -> int: return int(found) * 1024 if found else 0 -def run_step(step: str, store: Path, guard_bytes: int, extra: list[str]) -> dict: +def run_step( + step: str, store: Path, guard_bytes: int, extra: list[str] +) -> dict[str, Any]: """Run one step; kill it when its resident memory passes the guard.""" process = subprocess.Popen( [sys.executable, str(MEASURE), step, "--store", str(store), *extra], From 0f9bcd4214ba1afced735c26264dc7d070762879 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:03:30 -0800 Subject: [PATCH 03/81] docs(dev): streaming design for ITL-1464 Co-Authored-By: Claude Fable 5.2 --- docs/dev/specs/itl-1464-streaming-design.md | 534 ++++++++++++++++++++ 1 file changed, 534 insertions(+) create mode 100644 docs/dev/specs/itl-1464-streaming-design.md diff --git a/docs/dev/specs/itl-1464-streaming-design.md b/docs/dev/specs/itl-1464-streaming-design.md new file mode 100644 index 000000000..936109554 --- /dev/null +++ b/docs/dev/specs/itl-1464-streaming-design.md @@ -0,0 +1,534 @@ +# Computation that never holds everything in memory (ITL-1464, phase 2: design) + +Status: draft for approval, November 25, 2026. Written against `origin/main` 0d1e017c. The +measurements it rests on are in `itl-1464-memory-diagnosis.md`. Decisions the developer +has made are marked **Decided**; decisions still open are marked **OPEN** and listed again +at the end. + +LFP tables are out of scope (developer, November 25, 2026): one LFP row holds 384 samples, +and a session of them is a different problem. Nothing here is designed or tested for them. + +## The governing rules + +- **No hash, identity, stored layout or golden value changes.** Everything here is about + what is held in memory and when. If a step turns out to need such a change, it stops + and is asked about. +- **Sync results stay exact and deterministic**: every value, type, row order, stored row + and error of the sync path stays as it is today (the rule of ITL-1347 and ITL-1441). +- **Async results equal the sync results as a set of rows** (each row as often as it + occurs); row order is not a result on the async path (developer, November 22, 2026). +- **The async path is the primary memory-bounded path** (developer, November 25, 2026). + The sync path gets what it can get without giving up its order. +- **Fewest special cases.** One mechanism for rows that are not in memory (the local + cache, below), used by every part that needs one. + +## What the diagnosis found, in one paragraph + +A row of the measured table is 120 bytes. Held as a `(Tag, Data)` pair it costs 18 to +110 KiB; the async path passes rows that way and every operator job node keeps all of +them. Its source-info tokens are 4.2 KiB (35 times the data), built at every source +read. Every sync operator holds its whole input and whole output, tokens included. So the +design has three parts, in this order of worth: rows move and are kept as Arrow record +batches, never as objects; a node does not keep its rows in memory; tokens are not +materialized per row where they can be derived. + +## 1. The `run()` contract + +`run()` is the way to trigger computation (developer, November 24, 2026). It promises: + +- every row of the stream is computed, with every effect and every write a job makes; +- on the sync path, in the deterministic order of today; +- it returns a `StreamView`. + +It promises nothing about how the rows are produced or what is held meanwhile: not one +table, not batches of a given size, not a thread. "Does exactly the work `as_table()` +does" (ITL-1081) is replaced by "computes every row; `as_table()` afterwards does not +compute them again" (section 3 says how). + +`as_table()`, `as_polars_df()` and iteration stay the way to get all rows, and +`as_table()` still returns one Arrow table: asking for it is asking for the rows in +memory. `head()` and the notebook display still never compute. + +## 2. The local cache + +One mechanism holds rows that are computed but not in memory. + +- **What it is.** Arrow IPC files (the file format, uncompressed, so they can be + memory-mapped), one per stream of rows, written a record batch at a time as the rows + are produced, in the form the rows have on a job's edges (ITL-1347's row-built form). + A row is addressed by `(batch number, row number)`. +- **Where.** A directory per process run, `/orcapod--/`. The + cache root is `OrcapodConfig.local_cache_dir`, by default the system's temporary + directory. **OPEN (L1)**: the default location, and whether a job's cache may live + beside the job's database. +- **Reading.** A reader memory-maps the file. Pages of a mapped file are the operating + system's to drop under pressure, so they are not memory the process holds: this is + what makes "fetch the row by reference, emit it, let it go" cheap. Rows are fetched in + batches of references (`take` on the mapped batches), never one by one. +- **Lifetime.** A file belongs to the object that wrote it (an operator's run, a job + node's current run, a stream's computed result) and is deleted when that object lets + go of it: an operator when it finishes or fails (`finally`), a node at + `clear_cache()`, at its next run and when it is collected, a stream when it is + collected. The process directory is removed at exit. A directory whose process no + longer exists is removed at the next start (the directory name holds the process id + and a lock file). +- **Small results skip it.** Rows below a threshold (`OrcapodConfig.keep_in_memory_bytes`, + proposed 64 MiB per stream) stay in memory as one Arrow table, as today; nothing is + written. Tutorial-sized work never touches the disk. **OPEN (L2)**: the threshold. +- **What it never is.** It is not a store: nothing in it is an identity, nothing survives + the process, no result is read from it by a later process, and it holds no hash. + +Without source-info tokens materialized (section 7) a cache file is about the size of the +rows' Arrow data: 248 MiB for the measured 2.18 million row session. + +## 3. What a job node keeps, and the view + +Today a job node keeps its current run's rows in memory (ITL-1095). That is one whole +tokenized table per node, for as long as the job lives. + +**Proposed (OPEN, N1: a public promise changes).** A job node keeps a *reference* to its +current run's rows, not the rows: + +- a function node, and an operator node in `LOG` mode, read them from the database, a + page at a time (their rows are stored there by the run; the node knows which entries + are this run's); +- an operator node in `OFF` mode, and a side-effect node, read them from the local + cache, where the run wrote them; +- below the in-memory threshold, the rows are kept as today. + +Every read keeps its meaning: `node.as_table()` returns the current run's rows (now read +from the reference, memory-mapped where it is the cache), iteration yields them a batch +at a time, a downstream node's read is a batch reader. "A job node shows its current +run" stays true; "holds them in memory" does not. + +**The view** (`StreamView`) follows the same rule and needs no special case: + +- inside a job, it reads pages from the node's reference; +- outside a job, `run()` writes the computed rows to the local cache (or keeps them in + memory below the threshold) and the stream keeps that reference, as a pod's stream + keeps its computed table today. So nothing is computed twice: `as_table()` after + `run()` reads the reference. +- `head(n)` and `tail(n)` read the first and last `n` rows; `total_rows` and the schema + are recorded while the rows are written; +- `sort_by_tags()` on a result in memory sorts as today; on a cached result it sorts an + index of the tags (the same keys-only index a join uses, section 6) and fetches the + rows shown. The view then shows exactly what it shows today. +- The notebook display of a view is its `head` in tag order plus the row count, as + today. + +The issue's alternative, a view that keeps only the first and last rows, the count and +the schema, would make `as_table()` after `run()` compute everything again (calling +every function again outside a job) and would need a rule for every view method beyond +the kept rows. The cache-backed view has neither problem. **OPEN (N2)**: confirm the +cache-backed view over the bounded-window view. + +A source that holds no rows (`SpiralDBTableSource`) is the one case where "keep a +reference" means "read again": its `run()` view may keep a cache file of the read, or +the first and last rows and the count. **OPEN (N3)**; proposed: the cache file, so a +source behaves as every other stream. + +## 4. A bounded preview: `stream.preview(n)` + +`head()` never computes, so it cannot show the first rows of a derived stream that was +never run. `preview(n)` computes only what `n` rows need: + +- the limit is passed down: a source reads at most the rows asked of it (a SpiralDB or + database source as a pushed-down `limit`, a file source by stopping the read); +- row-by-row steps (section 5) are applied to batches until `n` rows have come out; the + batch size doubles when a batch yields too few (a selective filter); +- a step that needs its whole input (`GroupBy`, `Batch`, a join) is **computed in full** + under `preview`, with a note in the view saying so. **OPEN (P1)**: compute in full, or + refuse and point to `run()`. Proposed: refuse by default with + `preview(n, compute_all=True)` to allow it, because a preview that silently reads + 2 million rows is the surprise this method exists to avoid. + +Decisions the issue lists: + +- **OPEN (P2)**: does a preview call user functions? Proposed: yes; it is the point of + the method, and the name says it computes. `head()` stays the method that never does. +- **OPEN (P3)**: are a preview's results stored? Proposed: outside a job nothing is + stored, as for any stream outside a job. A job node's `preview` is not offered in the + first version: `job.run()` and `node.head()` cover it. +- **OPEN (P4)**: is the order defined? Proposed: the preview's rows are the first `n` the + sync path would produce when every source has a defined read order (in-memory, CSV, + Delta: the order given; SpiralDB and database tables: key order). A source without one + (none today) would say "some `n` rows". +- A preview delivers no side effect: a `SideEffectPod` in the chain is refused. + +## 5. Batch-wise execution, per operator kind + +Rows move between job nodes as Arrow record batches (ITL-1347, already designed and +partly built: `InputChannel`, `OutputChannel`, `async_execute_batches`, the streaming +join kernels). This design finishes the wiring and adds what the memory bound needs. + +| Kind | Operators | Holds | +|---|---|---| +| Row by row (`ROW_BY_ROW`) | `Select*`/`Drop*` columns, `MapTags`, `MapData`, `MapColumns`, `DropNulls`, `Filter`, `PolarsFilter`, `AddTags`, `TagBy`, `Pick`, `Index` | the batch in hand | +| Per row, user code | function pods, side-effect pods | the batch in hand; results go to the database as they are computed | +| Probe against one small or indexed side | `SemiJoin` | a keys-only index of the right input (section 6) | +| Joins | `Join`, `MergeJoin`, `Rejoin` | a keys-only index, section 6 | +| Grouping by key | `GroupBy` | a keys-only index of the input and one group at a time (below) | +| Grouping by arrival | `Batch` with a size | one batch of `size` rows | +| Whole input, by definition | `Batch` without a size | one row holding everything: its output is the input | + +Notes: + +- `PolarsFilter` is row by row but has no async form today, so it gathers its input; it + gets `ROW_BY_ROW`. Its predicate is applied per batch; a predicate is an expression + over one row's columns (an expression that reads other rows, such as a window, is + already outside what the sync path's identity describes). **OPEN (B1)**: refuse + expressions that are not row-wise (they exist in Polars), or document. +- `GroupBy` sorts its input by key and member order. Batch-wise: the input goes to the + local cache while a keys-only index is built (the prepared key columns, the + member-order tags, record id and source id, and the row's reference); the index is + sorted exactly as today's sort frame is; groups are emitted one at a time by fetching + their members. It holds the index (the size of the tag columns) and one group. Its + output order is today's, on both paths. A group larger than memory is a row larger + than memory: out of scope. +- A function pod over grouped rows receives one group's lists at a time; that row is as + large as the group, by the user's choice. + +### How sync stays deterministic + +The sync orchestrator runs nodes in topological order, each to completion. Batch-wise it +does the same, with these rules: + +- a row-by-row operator applied to the batches of its input in order, with the results + concatenated in order, gives exactly its result over the whole input, because each + output row comes from one input row; the differential test of ITL-1347 (sync against + pinned `main`, byte for byte) is the gate; +- every other operator runs its one sync body (`static_process`) as today; what changes + is only where its inputs' rows live (the cache instead of memory) and, for `GroupBy` + and the joins, that the body fetches rows by reference. The matching, the order of the + output rows and every value are the present code's: `Join` and `SemiJoin` already + match on key columns and row numbers and take every value from the input by row number + (ITL-1284), and a row number is a reference; +- the order of a sync read is the order the run emitted (ITL-1441): the cache file is + written in that order and read in it. + +So the sync path gets the same bounds as async for row-by-row chains and grouping, and +for joins the bound of "keys-only index plus the output written to the cache". It does +not get the early-release rules of section 6 that depend on arrival order. + +## 6. Joins + +Joins are where rows multiply and where an operator must remember rows. The aim is a +stated bound per case, not a join that is free (developer, November 25, 2026). + +**The target (Decided).** An async join's memory is, in the worst case, linear in the +size of one of its inputs: never the product, never all inputs plus the output at once. +Everything else on the async path is bounded by the batches in flight. + +### What a join holds today + +- Sync `Join`: both inputs whole, as tokenized Arrow tables (about 4 KiB per row here), a + Polars frame of the prepared key columns and row numbers, and the whole output. It is + already a keys-only match: Polars sees keys and row numbers, and the rows are taken + from the tables by row number. +- Async `Join` (today's row form): both inputs as lists of `(Tag, Data)` pairs (tens of + KiB per row) until the other side closes. +- The streaming join kernels of ITL-1362 (built, not wired): each side's rows as Arrow + tables plus a key frame, a side dropped when the other closes. + +### Keys only in memory, rows in the local cache (Decided direction) + +Each input of an async join is written to the local cache as it arrives. In memory the +join keeps, per row that can still match, an index entry: + +- the row's join key in prepared form (`arrow_keys.polars_ready`, the present + preparation), as a Polars frame, so matching stays one vectorized join per arriving + batch with the sync path's own rule (`join._matched_pairs`); and +- the row's reference, `(batch number, row number)`: 8 bytes. + +For each batch of matches the join fetches the matched rows of the other side from the +cache by reference (one `take` per input per batch of pairs), builds the output batch +with the sync path's column work, sends it, and lets the rows go. + +Cost per indexed row: the key's own size plus 8 bytes. For the measured tables the +prepared key is 60 to 90 bytes (two short strings, a timestamp, two integers), against +4.2 KiB for the tokenized row today and 120 bytes for the bare row. **OPEN (J1)**: index +a 128-bit hash of the key instead of the key (24 bytes per row whatever the key's +width); matches are then confirmed on the fetched rows, so a hash collision costs a +fetch, never a wrong row. Proposed: start with the key itself (it is the present code), +measure, and switch only if the index is the limit. + +Compared with today's sync `Join`: the same match, on the same prepared keys, with a +reference where today there is a row number; the difference is that the rows behind the +references are in a mapped file, not in process memory. + +### Uniqueness certificates + +A stream can be certified to have unique tags: each tag tuple occurs at most once. + +**Where a certificate comes from (Decided).** Certificates originate inside Orcapod and +are trusted by every step that derives them; no step re-checks. The one claim that is +verified is a source's own. + +The certificate is a set of *unique keys*: sets of tag names such that no two rows agree +on all of them. A stream has unique tags when one of its unique keys is a subset of its +tags. (**OPEN (C1)**: this form, or a single yes/no. The key form survives dropping a +tag that is not part of the key, and lets a join say more; the yes/no form is simpler +and must be given up whenever a tag is dropped. Proposed: the key form.) + +| Step | Certificate of the output | +|---|---| +| Source with key columns `K` that are all tags | `{K}` (verified or store-guaranteed, below) | +| Source identified by position, or whose key columns are not all tags | none | +| Select/drop data columns, `MapData`, `DropNulls`, `Filter`, `PolarsFilter`, function pod, side-effect pod, `Pick`, `Index` | the input's (rows are removed or data changes; tags stay) | +| `AddTags`, `TagBy` | the input's (a superset of a unique key is unique) | +| Select/drop tag columns | the input's keys that are still tags | +| `MapTags`, `MapColumns` | the input's keys, renamed | +| `SemiJoin` | the left input's | +| `GroupBy(by)` | `{by}`: one row per key | +| `Batch` | none (its tags are lists) | +| `Join`, `MergeJoin` of inputs with keys `Ka`, `Kb`, joined on shared tags `S` | `Ka ∪ Kb`; also `Ka` when `Kb ⊆ S` (each left row matches at most one right row), and `Kb` when `Ka ⊆ S` | +| `Rejoin` | the inputs' common keys (a result row is its origin row) | + +**How it travels (Decided: not in any hash or identity).** It is a read-only member of +the stream's description, beside `condition` and `row_limit`: `StreamProtocol.unique_keys`. +Each operator derives it from its inputs' certificates when the graph is built; no data +is read. It is not Arrow metadata, enters no hash, identity, config, stored path or +stored row, and a loaded job derives it again from its sources. Nothing in the design +requires it in an identity: it never changes a result, only how much a join remembers. + +**Verification as data flows (Decided).** A source that claims a key keeps the keys it +has emitted and checks each batch before it is sent on. On a duplicate it raises, and +the duplicate row never proceeds, so nothing downstream computes on a wrong assumption. + +- *Memory*: keys only. Today `SpiralDBTableSource` already does this with a Python set + of record-id strings (about 250 bytes per row, 0.5 GiB for the measured session). The + proposal keeps 128-bit digests of the record id (16 bytes per row, in a sorted + numeric structure checked per batch): 35 MiB for the measured session. A digest + collision would raise a false duplicate (never a wrong result); at 100 million rows + its probability is below 10^-20. +- *What has happened when a duplicate appears late*: the rows before it were emitted, and + downstream nodes may have computed and stored results for them. Those stored results + are correct for their rows (a function result is kept by its input row's hash), exactly + as after any run that fails part-way. +- *The error*: `RowIdentifierError`, as today, naming the source (its id and label), the + key, and that an earlier row of the read holds it. (Naming the earlier row's position + needs 8 more bytes per key. **OPEN (C2)**; proposed: not kept.) +- *The error policy*: a uniqueness violation is a condition of the whole input, not of a + row, so it is outside the row error policy, as the data-context check is: it stops the + source's node and fails the run under `continue` and `fail_fast` alike. Every node + downstream of the source holds rows computed on a claim that turned out false; a run + that raised defines no rows for the nodes that ran, which is the present rule. +- In-memory sources check their keys when they are built (they hold every row), so their + certificate is verified before the first read; nothing changes for them. + +**Keys the store guarantees (Decided).** Where the source's own system guarantees +uniqueness over the key, Orcapod trusts it without the running check. + +- *How a source states it*: a class-level declaration, never a user flag: + `RootSource.key_enforced_by_store()`, answered by the source class from what it knows + of its table. A user's claim on a file is a claim to verify. +- *The rule*: the key columns the source identifies rows by must be exactly a key the + store enforces, and, for the certificate, the tags must contain them (a superset of a + unique key is unique; a subset is not). +- *Which kinds*: + +| Source | Guaranteed by the store? | +|---|---| +| SQLite, PostgreSQL table, key = the table's primary key | yes: the database enforces it | +| The same, key = columns of a `UNIQUE` constraint, all `NOT NULL` | yes, once the connector reads constraints (not today: running check until then) | +| The same, `record_id_columns` given and not such a key | no: running check | +| `DBTableSource` over a generic connector | only if the connector reports an enforced key; otherwise running check | +| SpiralDB keyed table, key = its key columns, one pinned version | yes, with one reservation (below) | +| CSV, Delta, in-memory (Arrow table, dict, list, data frame) | never: checked at construction (in memory) or as the rows flow (files) | +| `PollingSource` | never trusted; it already refuses a key an earlier batch held | +| `CachedSource` | its wrapped source's answer | +| `DerivedSource` over a job node's stored records | **OPEN (C3)**: the records are kept by record id, which is unique per row of a run, but its tags are the node's output tags, unique only if the node's certificate says so. Proposed: the node's certificate, verified by the running check on read | + + SpiralDB: a keyed table stores at most one row per key; a write of an existing key + replaces that row (upsert), and a repeated key within one write is refused. This was + observed on the service with spiral-sdk 0.16.74 and 0.16.75 (the rules `upsert` and + `dup` of the test fake record it). I did not find a statement of it in documentation + I could cite, so the confidence is "observed, and the meaning of a keyed table", not + "documented guarantee". A source reads one pinned version, so no concurrent write can + show two versions of a row. Proposed: trust it, and keep the conformance test that + would notice a change. + +### The bound for each case + +`n` and `m` are the rows of the two inputs; "index" is the per-row cost above (key plus +8 bytes); rows themselves are in the cache, on disk. + +| Case | What is held in memory | Bound | +|---|---|---| +| Both inputs certified unique on the join key (the tags fully overlap): 1:1 | the index of rows not yet matched; an entry is dropped the moment it matches, and both rows are emitted and let go | index × (unmatched rows). Worst case, one input arriving entirely before the other: index × max(n, m). With both inputs in key order: the out-of-order window only | +| One input certified unique on the join key (a large table against its lookup table) | the unique side's index for the whole join; rows of the other side that arrive before the unique side has closed are indexed until then, after which each arriving row matches at most one row, is emitted and is not kept | index × (unique side) + index × (rows of the other side that arrived early). Worst case index × (n + m): still keys only | +| Neither unique (many to many) | the index of both sides | index × (n + m). The output can be n × m rows; it is sent a batch at a time and never held | +| Any case, a side whose other side has closed | nothing more is kept for it (the kernels' present rule) | | + +In every case the memory is keys only, so it is below the full size of one input by the +ratio of row size to key size (here 120 bytes against 70 to 100, without tokens; 4.2 KiB +against 70 to 100 with today's tokens). The developer's worst case, "linear in the size +of one input", holds with room: the worst case is linear in the *keys* of both. + +**Key-ordered inputs.** Two inputs sorted by their tags can be merged holding only the +rows between the two read positions. That needs a second certificate, "in tag order", +which a source can give (a SpiralDB or database scan in key order) and which few +operators preserve on the async path, where arrival order is not a result. **OPEN (J2)**: +proposed not in the first version; the 1:1 early release already gives the window bound +whenever the inputs happen to arrive in step. + +**Three or more inputs.** `Join` folds pairwise in its canonical order, as today; each +step is one of the cases above, and a step's output goes to the next step as batches, +not to a cache file, unless that next step must index it. + +**Diamonds.** When both inputs come from one upstream through a broadcast, one input +cannot be read to its end while the other waits: the wait would block the upstream. This +is why rows that arrive "early" are indexed and cached rather than refused by +back-pressure, and why the worst case counts both sides. + +### Order and determinism + +- Async: the output is the sync join's rows as a set; batches are sent as matches are + found. +- Sync: `Join.static_process` as today, over references. Its row order is today's (the + order Polars gives the match, kept by ITL-1355's rule), so the stored and returned + tables are identical. + +### Test plan that proves the bound + +- A measurement in `measure.py` style for each case (1:1 in step, 1:1 one side first, + unique side small, many to many), at two sizes a factor of 10 apart, recording peak + resident memory less mapped file pages, and the peak of the Arrow pool: the peak must + grow as the index does (key bytes × rows), not as the rows do, and a 10 times larger + non-indexed side must not move it. +- The differential of ITL-1347 for results: async equals sync as a set of rows, sync + equals pinned `main` byte for byte. +- A violation test per certificate rule: a source that claims a key and repeats it late + raises, the duplicate reaches no downstream node, and the run fails under both error + policies. + +## 7. Source-info tokens that are derived, not stored per row + +A source row's token for column `c` is `::::`, and the row's two +system tags hold the source id and the record id. So the 35-fold cost is a copy of what +the row already carries. + +**Proposed (OPEN, T1).** A stream may hold a column's tokens as a *recipe* instead of a +column: "the token of `c` is built from system-tag columns `S` and `R` and the name +`c0`" (`c0` is the column's name at the source, which a rename does not change). Record +batches then carry no token column for it. The tokens are materialized, by one helper, +exactly where they are read: + +- a table or row that shows them (`as_table(columns={"source": True})`, `all_info`, + `data.source_info()`); +- a function node writing its pipeline records, a database write of an operator's + output: the stored rows hold the same tokens as today, byte for byte; +- an operator that computes with tokens: `MergeJoin` (token pairs), `Batch` and + `GroupBy` (token lists), a function pod's output (new tokens). + +Operators that pass tokens through (select, map, filter, `DropNulls`, `Join`, `SemiJoin`) +pass the recipe; `Join` renames the system-tag columns a recipe names as it renames the +columns. + +This is an in-memory representation only: every stored token, hash and layout is +identical. It touches how every operator treats `_source_` columns, so it is the largest +step and comes after the transport. Its worth, from the measured column groups: a +tokenized table falls from 911 MiB to about 107 MiB per 200,000 rows (8.5 times). + +Second step (**OPEN, T2**): `GroupBy` and `Batch` emit one token list per column, each +with one token per member: the same 35-fold cost inside the lists. A recipe for those +("the tokens of `c` are built from the members' record ids", one hidden list per group +instead of one per column) removes it. Proposed: after T1, measured first. + +## 8. The memory we can promise + +With sections 2 to 7 in place, for a job run by the async orchestrator: + +| Part | Held in memory | +|---|---| +| A source | one batch read (65,536 rows at most), plus 16 bytes per row read if its key is verified as data flows, nothing if the store guarantees it | +| A row-by-row operator, a function pod | the batch in hand | +| A channel between two nodes | its buffered batches (a fixed number) | +| `GroupBy` | its keys-only index, and one group | +| A join | its keys-only index (section 6) | +| A job node after the run | a reference (a file name or a set of stored entries) | +| A view | the rows shown | + +**The bound to state to users**: peak memory of an async job is +`(batches in flight) × (batch bytes) + (key bytes + 8) × (rows indexed by joins and groupings) + 16 × (rows of verified sources) + the largest single row`. +For the measured session (2.18 million rows of 120 bytes, one grouping, one function +pod) that is under 0.5 GiB, against about 210 GiB today. + +**Proposed budget for the workshop** (**OPEN, M1**): a job over every non-LFP table of a +sample dataset peaks below 4 GiB on the async path, checked on synthetic tables of the +dataset's shapes and then once live, read-only. + +The sync path: the same for row-by-row chains, `GroupBy` and joins' inputs; a sync join +additionally holds nothing more than async's worst case. Outside a job, `as_table()` of +a large result returns a memory-mapped table. + +## 9. What changes for users + +- `run()` no longer means "one table in memory". Its view shows the same things. +- A job node no longer holds its rows in memory; every read of it gives the same rows. + Reading a large node with `as_table()` maps a file or reads the database. +- Large results outside a job are written to a temporary directory, which must have + room; small ones are not. A new config value names the directory, another the size + below which rows stay in memory. +- `stream.preview(n)` is new. +- `flow()` and iteration of a large stream yield rows a batch at a time and keep none + (`ArrowTableStream.iter_data` stops keeping every pair it yielded). **OPEN (U1)**: + two iterations of one stream then give equal rows but not the same objects; proposed: + accept. +- A source that repeats a key fails when the repeat is read, as `SpiralDBTableSource` + does today, not always before the first row. +- Async runs get faster as well as smaller: the per-row object work is what makes the + async path 25 times slower than sync today (127 s against 5 s at 200,000 rows). + +## 10. Order of work + +Each step is a draft pull request against `main` with tests and before/after numbers on +the synthetic tables of the diagnosis; none changes a hash, a stored layout or a golden +value. + +1. **Done (PR 558)**: a SpiralDB read that returns no tokens builds none. +2. Rows on the async path as record batches: wire `async_execute_batches` and the + record-batch channels into the nodes and the async orchestrator (ITL-1347's remaining + stages), give `PolarsFilter` `ROW_BY_ROW`. Removes the 18 to 110 KiB per row. +3. The local cache, and job nodes that keep a reference (section 3). Removes "every node + holds its output". +4. The view and `run()` on the cache; `preview(n)`. +5. Certificates and the running check with digests; store-guaranteed keys. +6. Joins on a keys-only index over the cache, with the early-release rules; `GroupBy` + on the index. +7. Derived tokens (T1), then token lists (T2). + +Steps 2 and 3 together give the bound for row-by-row chains and function pods; step 6 +for joins and grouping; step 7 removes the 35-fold factor from everything that still +holds rows (cache files, `as_table()`, the sync path). + +## Open decisions for the developer + +| Id | Decision | Proposed | +|---|---|---| +| N1 | A job node keeps a reference to its run's rows (database or local cache), not the rows in memory: changes the ITL-1095 promise | yes | +| N2 | The view is backed by the cache (keeps every method's meaning, nothing computed twice) rather than a bounded window of first and last rows | cache-backed | +| N3 | A source that holds no rows: its `run()` view keeps a cache file of the read | yes | +| L1 | Where the local cache lives by default | the system temporary directory, configurable | +| L2 | The size below which rows stay in memory | 64 MiB per stream | +| P1 | `preview(n)` over a step that needs its whole input: compute in full or refuse | refuse unless `compute_all=True` | +| P2 | `preview` calls user functions | yes | +| P3 | `preview` results are stored | no; not offered on job nodes at first | +| P4 | `preview` order | the first `n` of the sync order | +| B1 | `PolarsFilter` with an expression that is not row-wise | refuse | +| J1 | The join index holds the key or a 128-bit hash of it | the key first; measure | +| J2 | An "in tag order" certificate for a streaming merge | not in the first version | +| C1 | Certificate as a set of unique keys or as yes/no | set of unique keys | +| C2 | The duplicate-key error names the earlier row's position (8 bytes per key) | no | +| C3 | `DerivedSource` over a node's records: certificate | the node's, verified on read | +| T1 | Source tokens held as a recipe until read | yes, after the transport | +| T2 | Token lists of `GroupBy` and `Batch` as a recipe | after T1, measured first | +| U1 | Iteration keeps no row objects | accept | +| M1 | The workshop budget | 4 GiB peak, async, non-LFP | + +Decided by the developer (November 24 and 25, 2026), recorded above: `run()` promises +computation and nothing about how; async is the primary memory-bounded path; joins keep +keys only, with rows fetched from a local cache; certificates originate in Orcapod and +are trusted by derivation, a source's claim is verified as data flows, and a key the +store enforces is trusted; a certificate enters no hash or identity; an async join's +memory is at worst linear in one input; LFP is out of scope. From 611f72c981cc06ab2663fe131a83e1c7365cefdb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:15:39 -0800 Subject: [PATCH 04/81] docs(dev): views design for ITL-1464 Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-views.md | 120 +++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 docs/dev/specs/itl-1464-views.md diff --git a/docs/dev/specs/itl-1464-views.md b/docs/dev/specs/itl-1464-views.md new file mode 100644 index 000000000..0bc211408 --- /dev/null +++ b/docs/dev/specs/itl-1464-views.md @@ -0,0 +1,120 @@ +# `run()`, its view and `preview(n)` without a full table (ITL-1464, track VIEWS) + +Status: draft for approval, November 25, 2026, against `origin/main` 0d1e017c. Companion of +`itl-1464-streaming-design.md` (sections 1, 3 and 4 of it). Nothing here changes a hash, +identity, stored layout, stored byte or golden value. + +## Scope + +- Now: the bounded view of a plain stream (outside a job). Files: `core/streams/base.py`, + `core/streams/view.py`, with small hooks in `DynamicPodStream` and + `SpiralDBTableSource`. +- With TRANSPORT: a job node's view, which pages from the node's reference to its rows. +- After approval of its decisions: `preview(n)` (designed here, not in the first PR). + +Outside a job, only `SpiralDBTableSource` reads its rows on demand and holds none. Every +other source holds its table, so a table over those rows is not a new cost (a filter's +result over it is, and stays as today). A function pod's stream keeps its results, so +that no function is called twice: it stays as today. So the first step applies to a +**batched chain**: zero or more row-by-row operators (`ROW_BY_ROW`, and `Filter`) over a +source that reads in batches. Joins, `GroupBy`, `Batch`, `PolarsFilter` and function pods +end the chain: they compute as today. + +## The `run()` contract + +`run()` computes every row, with every effect, in the order of `as_table()`, and returns a +`StreamView`. It promises nothing about how rows are produced or held. For a batched chain: + +1. The source's batches are read in order (one scan, its checks unchanged: `max_rows`, + schema, repeated keys). Each batch, shaped as `as_table()` shapes the whole, goes + through each operator's own `static_process`: the one sync body, no second kernel. +2. Result batches are kept whole up to **64 MiB** (all column groups). A result that ends + within it is complete: the view holds it, and an operator stream keeps it, exactly as + today. +3. A larger result drops the kept batches to a **window**: the first and last 1,000 rows + (default columns, copied, so no batch stays alive behind a slice), the row count and + the schema. The operator stream keeps the window, not the rows. + +`as_table()`, iteration and conversion are unchanged and still give every row. After a +large `run()` of a batched chain, `as_table()` reads the source again and applies the +operators again. No user function runs twice: a function pod is never in a batched chain. +An error in any batch propagates and nothing is kept, as today. + +## The view + +A *complete* view holds every row and is today's view, unchanged. A *bounded* view holds +the window. + +| Member | Bounded view | +|---|---| +| `total_rows`, schema, `status`, `header()` | as the complete view: `all 2,177,155 rows` | +| `head(n)`, `tail(n)`, `n` within the window | the same rows and header as the complete view; the result is an ordinary view | +| `head(n)`, `tail(n)`, larger `n` | raise `BoundedViewError`, naming the window and `stream.as_table()` | +| `sort_by_tags()` | raise `BoundedViewError`: sorting needs every row | +| `as_table()`, `as_polars_df()`, `table`, `len()` | `len()` is the row count; the others raise, never a part presented as the whole | +| display | identical to the complete view's: header, legend, shape line, first and last five rows | + +A view that has no cut of its own and is refused tells the caller the one call that does +it. Nothing a view does reads or computes (as today). + +`stream.head(n)` after a large run of an operator stream shows the window's first rows +(`n` within the window, default columns) while the inputs are unchanged. The preview, which +asks for tag order, sorts those and says so: the present rule of a stream that has only +some of its rows. Another column group shows `not_computed`, as before a run. + +### Inside a job + +The same class. The window of a job node's view is filled by one pass over the node's +reference (TRANSPORT's local cache or the stored entries), or, once a reference can be read +by position, `head`, `tail` and `sort_by_tags` page from it and nothing is refused: the +refusals above are the meaning of "rows not held and not addressable". This needs two +operations from TRANSPORT: `row_count` and `read(start, length, columns)`. + +## `preview(n)` + +`stream.preview(n=10)` computes what the first `n` rows need and returns a `StreamView` +with status `PARTIAL` (or `ROWS`, when the stream has at most `n` rows). `head()` still +never computes. + +- A source reads a limit: SpiralDB as a pushed-down scan limit (with its `where`), others a + slice of what they hold. `max_rows` does not apply, as for `head`. +- Row-by-row operators and function pods take batches until `n` rows have passed. The + first batch is `n` rows, or 1,024 when a step can drop rows; it doubles while too few + pass. A pushed-down limit is used only when no step drops rows; otherwise the scan is + read in batches and closed at `n`. +- `Join`, `MergeJoin`, `SemiJoin`, `Rejoin`, `GroupBy`, `Batch`, `TagBy`, `PolarsFilter` + and user operators need a whole input. Refused, naming the step and `run()`; + `preview(n, compute_all=True)` computes that step in full. +- A side-effect pod, or a function that takes the invocation context, is refused: a + preview has no effects. +- A kept result (an already computed stream) is sliced and nothing is computed. + +## Decisions + +| Id | Decision | Recommended | +|---|---|---| +| V1 | Bounded window now, disk-backed later, or wait for the local cache (N2) | window now: no file is written, and paging later only lifts refusals | +| V2 | `as_table()` / `table` / `as_polars_df()` of a bounded view: kept rows, recompute, or refuse | refuse, pointing to the stream (a part must never read as the whole; a view never recomputes) | +| V3 | `head`/`tail` beyond the window, `sort_by_tags` | refuse | +| V4 | Threshold and window | 64 MiB of result (as L2), first and last 1,000 rows; constants, no config yet | +| V5 | `as_table()` after a large run of a batched chain reads and applies operators again | yes (no user function runs again) | +| V6 | Streams in the middle of a chain keep nothing after a run of the last one (today each keeps its result) | yes: keeping one table per step is the cost being removed; each `run()`s by itself | +| V7 | `PolarsFilter` in a batched chain | not until B1 decides expressions that read other rows | +| V8 | `preview` calls user functions | yes, at most on the rows it looks at | +| V9 | `preview` stores or keeps anything | no: not in memory, not in a database. A cached pod reads its stored results and writes none | +| V10 | `preview` order | the first `n` rows of the sync order | +| V11 | Whole-input steps in `preview` | refuse; `compute_all=True` | +| V12 | `preview` on a job node | not offered at first: raises, naming `run()` and `head()` | + +## Tests + +- Differential: for each operator of a batched chain and chains of several, the result + pieces put together equal the unbatched `as_table()` (values, types, nullability, column + order, metadata) with several batch sizes, for every column configuration, with several + tags and data columns, data-tags, zero rows, and all rows dropped. +- Golden display: text and HTML of a bounded view equal those of the complete view of the + same rows, narrow and wide, with large cells, at sizes 11, 12, 1,000 and more; a small + stream's display is unchanged. +- The refusals; `head` after `run`; staleness after the source moves. +- Memory, 2,177,155 rows of the gaze shape, before and after, for the source, a rename, a + `drop_nulls` and a `filter`. From 2818eba7a199658838fdb7c580036f4b8a051c15 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:20:41 -0800 Subject: [PATCH 05/81] 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 06/81] feat(operators): streaming join kernels hold join keys and spooled rows, with bounded output batches (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/operators/streaming_joins.py | 426 ++++++++++++------ 1 file changed, 281 insertions(+), 145 deletions(-) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 8089f0715..39586747c 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -78,10 +78,11 @@ from __future__ import annotations from abc import ABC, abstractmethod -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from typing import Any, ClassVar import numpy as np +import numpy.typing as npt import polars as pl import pyarrow as pa import pyarrow.compute as pc @@ -116,6 +117,7 @@ settle_token_types, tokens_as, ) +from orcapod.core.row_spool import RowSpool from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants @@ -129,6 +131,15 @@ # (keys are tag columns, and a tag never starts with the meta prefix ``__``). _ROW = ("__streaming_left_row", "__streaming_right_row") +# How many rows an output batch holds at most: a row with its source-info tokens is +# several KiB, so a batch is some tens of MiB. +PAIRS_PER_BATCH = 8_192 + +# The pair-count column of a many-to-many match, and how many removed rows a side's key +# frame holds before it is compacted. +_COUNT = "__streaming_count" +_COMPACT_ROWS = 65_536 + def _settled_by_values(schema: pa.Schema) -> pa.Schema: """``schema`` with every system-tag and source-info field nullable. @@ -191,111 +202,180 @@ def _key_frame(table: pa.Table, keys: Sequence[str], row: str) -> pl.DataFrame: ) -def _match( - arriving: pl.DataFrame, held: pl.DataFrame, keys: Sequence[str] -) -> pl.DataFrame: - """Join two key frames by the sync join's rule (``join._matched_pairs``). +def _bounded_pairs( + arriving: pl.DataFrame, + held: pl.DataFrame, + keys: Sequence[str], + *, + at_most_one: bool, + row: str, +) -> Iterator[pl.DataFrame]: + """Join two key frames by the sync join's rule, in pieces of a bounded size. - Both frames hold the constant join key, so inputs that share no tag give every pair - and a top-level null key matches nothing, as on the sync path. + The rule is ``join._matched_pairs``. Both frames hold the constant join key, so + inputs that share no tag give every pair and a top-level null key matches nothing, + as on the sync path. A piece holds at most ``PAIRS_PER_BATCH`` pairs, or the pairs of + one arriving row when it has more: those are at most the rows held. Args: arriving: The arriving batch's key frame. held: The other side's accumulated key frame. keys: The shared tag columns. + at_most_one: Whether an arriving row matches at most one held row (the held + side is unique on the keys), so the pairs need not be counted first. + row: The arriving frame's row-number column. - Returns: - One row per matched pair, holding both row-number columns. + Yields: + One row per matched pair, holding both row-number columns; never empty. """ - return _matched_pairs(arriving, held, [*keys, _COMMON_JOIN_KEY]) + on = [*keys, _COMMON_JOIN_KEY] + if at_most_one: + pieces = [arriving] + else: + # Only the held rows that match, then how many each arriving row has. + held = held.join(arriving, on=on, how="semi") + if not held.height: + return + counts = held.group_by(on).len(name=_COUNT) + counted = arriving.join(counts, on=on, how="inner").sort(row) + pieces = [arriving] + if int(counted.get_column(_COUNT).sum()) > PAIRS_PER_BATCH: + pieces = _pieces(counted) + for piece in pieces: + pairs = _matched_pairs(piece, held, on) + for start in range(0, pairs.height, PAIRS_PER_BATCH): + yield pairs.slice(start, PAIRS_PER_BATCH) -def _joined_by_rows( - left: pa.Table, - right: pa.Table, - keys: Sequence[str], - left_rows: pa.Array[Any], - right_rows: pa.Array[Any], -) -> pa.Table: - """Take matched pairs from two tables, in the layout of ``join._inner_join``. +def _pieces(counted: pl.DataFrame) -> Iterator[pl.DataFrame]: + """Cut arriving rows into runs whose pair counts add up to ``PAIRS_PER_BATCH``. + + Args: + counted: The arriving rows that match, each with its number of pairs. + + Yields: + The runs, without the counts; a row with more pairs is a run of its own. + """ + ends = np.cumsum(counted.get_column(_COUNT).to_numpy().astype(np.int64)) + rows = counted.drop(_COUNT) + start = 0 + while start < rows.height: + before = int(ends[start - 1]) if start else 0 + end = int(np.searchsorted(ends, before + PAIRS_PER_BATCH, side="right")) + end = max(end, start + 1) + yield rows.slice(start, end - start) + start = end + + +def _side_by_side(left: pa.Table, right: pa.Table, keys: Sequence[str]) -> pa.Table: + """Put matched rows of two tables side by side, in the layout of ``join._inner_join``. The left columns (one of each key, the left row's value), then the right columns that are not keys, a name the left table also has taking the suffix ``_right``. Args: - left: The left table. - right: The right table. + left: The left row of each pair. + right: The right row of each pair. keys: The key columns. - left_rows: The left row of each pair. - right_rows: The right row of each pair. Returns: The joined table, fields without the inputs' flags (as ``_inner_join``). """ - names: list[str] = [] - arrays: list[Any] = [] - for name in left.column_names: - names.append(name) - arrays.append(left.column(name).take(left_rows)) + names: list[str] = list(left.column_names) + arrays: list[Any] = list(left.columns) for name in right.column_names: if name in keys: continue names.append(f"{name}_right" if name in left.column_names else name) - arrays.append(right.column(name).take(right_rows)) + arrays.append(right.column(name)) return pa.Table.from_arrays(arrays, names=names) class _Side: - """One side of a binary symmetric hash join: the rows it holds and their key frame. + """One side of a symmetric join: its rows' key frame, the rows themselves spooled. Args: keys: The key columns. row: This side's row-number column. + constant_key: Whether the key frame holds the constant join key. """ - def __init__(self, keys: Sequence[str], row: str) -> None: + def __init__( + self, keys: Sequence[str], row: str, *, constant_key: bool = True + ) -> None: self.keys: list[str] = list(keys) self.row: str = row self.closed: bool = False self.schema: pa.Schema | None = None - self._tables: list[pa.Table] = [] - self._frames: list[pl.DataFrame] = [] - self._table: pa.Table | None = None - self._frame: pl.DataFrame | None = None self.rows: int = 0 + self._constant_key: bool = constant_key + self._frames: list[pl.DataFrame] = [] + self._spool: RowSpool = RowSpool() + # Whether each row is still held, by its number (grown by doubling). + self._alive: npt.NDArray[np.bool_] = np.ones(0, dtype=np.bool_) + self._removed_count: int = 0 def key_frame(self, table: pa.Table) -> pl.DataFrame: """The key frame of ``table``, its rows numbered from 0.""" - return _key_frame(table, self.keys, self.row) + if self._constant_key: + return _key_frame(table, self.keys, self.row) + return polars_key_frame(table, self.keys, self.row) def append(self, table: pa.Table, frame: pl.DataFrame) -> None: """Hold ``table``'s rows, with ``frame`` from ``key_frame``.""" - self._tables.append(table) - # Numbered after the rows already held, as ``table()`` holds them. - self._frames.append( - frame.with_columns(pl.col(self.row) + self.rows) if self.rows else frame - ) - self._table = None - self._frame = None + if not table.num_rows: + return + # Numbered after the rows already held, as the spool numbers them. + self._frames.append(frame.with_columns(pl.col(self.row) + self._spool.size)) + self._spool.append(table) self.rows += table.num_rows + if self._spool.size > len(self._alive): + grown = np.ones(2 * self._spool.size, dtype=np.bool_) + grown[: len(self._alive)] = self._alive + self._alive = grown - def table(self) -> pa.Table: - """Every row held, numbered as in ``frame``.""" - if self._table is None: - self._table = pa.concat_tables(self._tables) - return self._table + def held(self, rows: npt.NDArray[np.int64]) -> npt.NDArray[np.int64]: + """Those of ``rows`` that were not removed.""" + return rows[self._alive[rows]] + + def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: + """The held rows with these numbers, in this order.""" + return self._spool.take(rows) def frame(self) -> pl.DataFrame: - """The key frame of every row held.""" - if self._frame is None: - self._frame = pl.concat(self._frames, rechunk=False) - self._frames = [self._frame] - return self._frame + """The key frame of the rows held and, until compacted, of removed ones. + + A caller whose removed rows can match again asks ``held`` which are held. + """ + if len(self._frames) != 1: + self._frames = [pl.concat(self._frames, rechunk=False)] + return self._frames[0] + + def remove(self, rows: npt.NDArray[np.int64]) -> None: + """Let rows go that can never match again: each is held, each given once.""" + if not len(rows): + return + self._spool.discard(rows) + self.rows -= len(rows) + self._alive[rows] = False + self._removed_count += len(rows) + if self._removed_count >= max(self.rows, _COMPACT_ROWS): + self._compact() + + def _compact(self) -> None: + """Drop the removed rows from the key frame.""" + frame = self.frame() + rows = frame.get_column(self.row).to_numpy() + self._frames = [frame.filter(pl.Series(self._alive[rows]))] + self._removed_count = 0 def clear(self) -> None: - """Drop every row held.""" - self._tables, self._frames = [], [] - self._table, self._frame = None, None + """Drop every row held, and their files.""" + self._frames = [] + self._alive = np.ones(0, dtype=np.bool_) + self._removed_count = 0 + self._spool.close() + self._spool = RowSpool() self.rows = 0 @@ -306,13 +386,18 @@ class _BinaryLink: keys: The key columns. finish: Turns the pairs' joined table (``_joined_by_rows`` layout) into the link's output rows; given the two sides' schemas. + unique: Whether each side is certified unique on the keys: no two of its rows + match one row of the other side. A row is let go once it has matched if, and + only if, the other side is unique: it can match nothing else. """ def __init__( self, keys: Sequence[str], finish: Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table], + unique: tuple[bool, bool] = (False, False), ) -> None: + self.unique: tuple[bool, bool] = unique self.keys: list[str] = list(keys) self.sides: tuple[_Side, _Side] = (_Side(keys, _ROW[0]), _Side(keys, _ROW[1])) self._finish: Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table] = finish @@ -340,48 +425,63 @@ def release(self) -> None: side.closed = True side.clear() - def push(self, side: int, table: pa.Table) -> pa.Table | None: + def push(self, side: int, table: pa.Table) -> Iterator[pa.Table]: """Match ``table``'s rows with the other side's, then hold them if still needed. + The rows are held, and the matched ones let go, once the iterator is read to its + end. + Args: side: 0 for the left side, 1 for the right. table: The arriving rows; every table of one side has one schema. - Returns: - The output rows of the new pairs, or ``None`` when there is none. + Yields: + The output rows of the new pairs, in pieces of at most ``PAIRS_PER_BATCH``. """ this, other = self.sides[side], self.sides[1 - side] if this.schema is None: this.schema = table.schema if other.closed and not other.rows: # Nothing can pair with these rows, and none is held: no key to prepare. - return None + return if self.keys: # A row whose key holds a top-level null matches nothing: never held, so a # closed side holding only such rows is exhausted. table = table.filter(_has_whole_key(table, self.keys)) if not table.num_rows: - return None + return frame = this.key_frame(table) - result = None + this_unique, other_unique = self.unique[side], self.unique[1 - side] + matched = np.zeros(table.num_rows, dtype=np.bool_) + gone: list[npt.NDArray[np.int64]] = [] if other.rows: - pairs = _match(frame, other.frame(), self.keys) - if pairs.height: - rows = ( - pairs.get_column(_ROW[0]).to_arrow(), - pairs.get_column(_ROW[1]).to_arrow(), - ) - tables = (table, other.table()) if side == 0 else (other.table(), table) - joined = _joined_by_rows(*tables, self.keys, *rows) + for pairs in _bounded_pairs( + frame, other.frame(), self.keys, at_most_one=other_unique, row=this.row + ): + mine = pairs.get_column(this.row).to_numpy().astype(np.int64) + theirs = pairs.get_column(other.row).to_numpy().astype(np.int64) + if other_unique: + matched[mine] = True + if this_unique: + gone.append(theirs) + taken = (table.take(pa.array(mine, pa.int64())), other.take(theirs)) + left, right = taken if side == 0 else (taken[1], taken[0]) assert self.sides[0].schema is not None assert self.sides[1].schema is not None - result = self._finish( - joined, self.sides[0].schema, self.sides[1].schema + yield self._finish( + _side_by_side(left, right, self.keys), + self.sides[0].schema, + self.sides[1].schema, ) + if gone: + other.remove(np.concatenate(gone)) # A row is held only for rows still to arrive on the other side. if not other.closed: + if matched.any(): + unmatched = ~matched + table = table.filter(pa.array(unmatched)) + frame = this.key_frame(table) this.append(table, frame) - return result def close(self, side: int) -> None: """Note that ``side`` ends: the other side's rows can never match again.""" @@ -454,11 +554,24 @@ def held_rows(self) -> int: def push(self, input_index: int, batch: pa.RecordBatch) -> list[pa.RecordBatch]: """Take one record batch of an input; return the output rows it decides. + ``iter_push`` with its batches collected: for an output known to be small. + """ + return list(self.iter_push(input_index, batch)) + + def iter_push( + self, input_index: int, batch: pa.RecordBatch + ) -> Iterator[pa.RecordBatch]: + """Take one record batch of an input; yield the output rows it decides. + + The iterator must be read to its end before the kernel is used again: the + batch's own rows are held only then. Reading it piece by piece keeps the output + of a many-to-many match out of memory. + Args: input_index: The input, in call order. batch: The batch, holding the input's transport columns. - Returns: + Yields: The output record batches, possibly none. Raises: @@ -470,9 +583,9 @@ def push(self, input_index: int, batch: pa.RecordBatch) -> list[pa.RecordBatch]: self._require_open(input_index) table = self._as_input_table(input_index, batch) if not table.num_rows: - return [] + return self._received[input_index] = True - return self._emitted(self._push(input_index, table)) + yield from self._emitted(self._push(input_index, table)) def close(self, input_index: int) -> list[pa.RecordBatch]: """Note that an input has ended; return the output rows that decides. @@ -491,7 +604,7 @@ def close(self, input_index: int) -> list[pa.RecordBatch]: """ self._require_open(input_index) self._closed[input_index] = True - emitted = self._emitted(self._close(input_index)) + emitted = list(self._emitted(self._close(input_index))) if all(self._closed): self._check_settled_against_empty_inputs() result = self._check_empty_inputs() @@ -539,8 +652,8 @@ def _check_empty_inputs(self) -> StreamProtocol | None: ) @abstractmethod - def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: - """Take an input's rows; return the output tables they decide. + def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: + """Take an input's rows; give the output tables they decide. Args: input_index: The input, in call order. @@ -643,13 +756,12 @@ def _check_settled_token_types( """ del input_index, token_types - def _emitted(self, tables: list[pa.Table]) -> list[pa.RecordBatch]: + def _emitted(self, tables: Iterable[pa.Table]) -> Iterator[pa.RecordBatch]: """The record batches of the output tables, holding ``output_columns``. Every system-tag and source-info field is declared nullable: the complete table's values decide those flags (``StaticOutputOperatorPod._flag_by_values``). """ - batches: list[pa.RecordBatch] = [] for table in tables: if table.num_rows: self._emitted_any = True @@ -657,8 +769,10 @@ def _emitted(self, tables: list[pa.Table]) -> list[pa.RecordBatch]: table = pa.Table.from_arrays( table.columns, schema=_settled_by_values(table.schema) ) - batches.extend(table.to_batches()) - return batches + yield from table.to_batches() + + def release(self) -> None: + """Let every row held go, with its files: the run has ended or failed.""" def _suffix(self, input_index: int, position: int) -> str: """What an input's system-tag column names gain: ``{pipeline hash}:{position}``.""" @@ -753,7 +867,7 @@ def finish( return finish - def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: + def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: """Feed an input's rows into its step and forward what each step emits. The input at canonical position 0 is the first step's left side, the input at @@ -776,13 +890,19 @@ def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: if rename := self._renames.get(input_index): table = table.rename_columns([rename.get(c, c) for c in table.column_names]) step, side = (0, 0) if position == 0 else (position - 1, 1) - result = self._links[step].push(side, table) - while result is not None and step < len(self._links) - 1: - if step in self._sinks: - return [] - step += 1 - result = self._links[step].push(0, result) - return [] if result is None else [result] + return self._through(step, side, table) + + def _through(self, step: int, side: int, table: pa.Table) -> Iterator[pa.Table]: + """Push rows into a step, and what it emits through the steps after it.""" + for result in self._links[step].push(side, table): + if step == len(self._links) - 1: + yield result + elif step not in self._sinks: + yield from self._through(step + 1, 0, result) + + def release(self) -> None: + for link in self._links: + link.release() def _close(self, input_index: int) -> list[pa.Table]: """End an input's side of its step, and every side that can no longer receive. @@ -1001,7 +1121,7 @@ def _finish( schema=schema, ) - def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: + def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: table = arrow_utils.append_to_system_tags( table, self._suffix(input_index, input_index) ) @@ -1009,8 +1129,10 @@ def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: table = table.rename_columns( [self._rename.get(c, c) for c in table.column_names] ) - result = self._link.push(input_index, table) - return [] if result is None else [result] + return self._link.push(input_index, table) + + def release(self) -> None: + self._link.release() def _close(self, input_index: int) -> list[pa.Table]: self._link.close(input_index) @@ -1037,80 +1159,94 @@ def __init__(self, operator: SemiJoin, inputs: Sequence[StreamProtocol]) -> None super().__init__(operator, inputs) left, right = inputs self._keys = list(SemiJoin._match_keys(left.keys()[0], right.keys()[0])) # pyright: ignore[reportPrivateUsage] # SemiJoin's one rule - # The left rows not decided yet, and the right rows' keys. - self._waiting: pa.Table | None = None + # The left rows not decided yet (keys, the rows spooled), and the distinct keys of + # the right rows. + self._waiting = _Side(self._keys, _ROW[0], constant_key=False) self._right_frames: list[pl.DataFrame] = [] - self._right_frame: pl.DataFrame | None = None + # Whether Polars tells key values apart as its joins do (no nested key). + self._distinct: bool = not any( + pa.types.is_nested(self._layouts[1].field(name).type) for name in self._keys + ) @property def held_rows(self) -> int: - waiting = self._waiting.num_rows if self._waiting is not None else 0 - return waiting + sum(frame.height for frame in self._right_frames) + return self._waiting.rows + sum(frame.height for frame in self._right_frames) + + def release(self) -> None: + self._waiting.clear() + self._right_frames = [] def _right_keys(self) -> pl.DataFrame | None: - """The key frame of every right row held, or ``None`` with none.""" + """The key frame of the right rows held, or ``None`` with none.""" if not self._right_frames: return None - if self._right_frame is None: - self._right_frame = pl.concat(self._right_frames, rechunk=False) - self._right_frames = [self._right_frame] - return self._right_frame - - def _kept(self, left: pa.Table, right_keys: pl.DataFrame) -> pa.Array[Any]: - """Whether each left row's key is among ``right_keys``, as a boolean mask.""" - kept = polars_key_frame(left, self._keys, _ROW[0]).join( - right_keys, on=self._keys, how="semi" - ) - mask = np.zeros(left.num_rows, dtype=np.bool_) - mask[kept.get_column(_ROW[0]).to_numpy()] = True - return pa.array(mask) - - def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: + if len(self._right_frames) > 1: + self._right_frames = [pl.concat(self._right_frames, rechunk=False)] + return self._right_frames[0] + + def _matched( + self, left: pl.DataFrame, right_keys: pl.DataFrame + ) -> npt.NDArray[np.int64]: + """The left rows whose key is among ``right_keys``, by number.""" + kept = left.join(right_keys, on=self._keys, how="semi") + return kept.get_column(_ROW[0]).to_numpy().astype(np.int64) + + def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: if not self._keys: return [table] if input_index == 0 else [] if input_index == 0: - right_keys = self._right_keys() - if right_keys is None: - kept = pa.array(np.zeros(table.num_rows, dtype=np.bool_)) - else: - kept = self._kept(table, right_keys) - if not self._closed[1]: - # A left row whose key holds a top-level null never matches. - undecided = table.filter( - pc.and_(pc.invert(kept), _has_whole_key(table, self._keys)) - ) - if undecided.num_rows: - self._waiting = ( - undecided - if self._waiting is None - else pa.concat_tables([self._waiting, undecided]) - ) - return [table.filter(kept)] - # A right batch: only its keys, and only rows whose keys hold no top-level null - # (the sync path drops those: such a key never matches). + return self._push_left(table) + return self._push_right(table) + + def _push_left(self, table: pa.Table) -> Iterator[pa.Table]: + """Emit the left rows a right row matched already; hold the undecided ones.""" + frame = self._waiting.key_frame(table) + kept = np.zeros(table.num_rows, dtype=np.bool_) + if (right_keys := self._right_keys()) is not None: + kept[self._matched(frame, right_keys)] = True + mask = pa.array(kept) + if not self._closed[1]: + # A left row whose key holds a top-level null never matches. + undecided = table.filter( + pc.and_(pc.invert(mask), _has_whole_key(table, self._keys)) + ) + self._waiting.append(undecided, self._waiting.key_frame(undecided)) + yield table.filter(mask) + + def _push_right(self, table: pa.Table) -> Iterator[pa.Table]: + """Hold the right rows' keys; emit the waiting left rows they decide.""" + # Only rows whose keys hold no top-level null (the sync path drops those: such a + # key never matches). keys = table.select(self._keys) keys = keys.filter(_has_whole_key(keys, self._keys)) if not keys.num_rows: - return [] + return frame = polars_key_frame(keys, self._keys) + if self._distinct: + frame = frame.unique() if not self._closed[0]: - self._right_frames.append(frame) - self._right_frame = None - if self._waiting is None: - return [] - kept = self._kept(self._waiting, frame) - decided = self._waiting.filter(kept) - remaining = self._waiting.filter(pc.invert(kept)) - self._waiting = remaining if remaining.num_rows else None - return [decided] + held = self._right_keys() + if held is not None and self._distinct: + new = frame.join(held, on=self._keys, how="anti") + else: + new = frame + if new.height: + self._right_frames.append(new) + if not self._waiting.rows: + return + decided = self._waiting.held(self._matched(self._waiting.frame(), frame)) + for start in range(0, len(decided), PAIRS_PER_BATCH): + rows = decided[start : start + PAIRS_PER_BATCH] + yield self._waiting.take(rows) + self._waiting.remove(rows) def _close(self, input_index: int) -> list[pa.Table]: if input_index == 0: # No left row will arrive: the right keys can match nothing new. - self._right_frames, self._right_frame = [], None + self._right_frames = [] else: # No right row will arrive: the undecided left rows never match. - self._waiting = None + self._waiting.clear() return [] From b6796d15d08c87bf6e821851fd5467e9fc5f5832 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:24:09 -0800 Subject: [PATCH 07/81] perf(core): carry source-info tokens as a recipe until their text is needed (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/operators/add_tags.py | 2 +- .../core/operators/column_selection.py | 10 +- src/orcapod/core/operators/drop_nulls.py | 2 +- src/orcapod/core/operators/filter.py | 2 +- src/orcapod/core/operators/filters.py | 37 ++- src/orcapod/core/operators/mappers.py | 6 +- src/orcapod/core/operators/meta_columns.py | 2 +- .../core/operators/static_output_pod.py | 10 + src/orcapod/core/operators/tag_by.py | 2 +- src/orcapod/core/sources/base.py | 12 + src/orcapod/core/sources/derived_source.py | 6 + .../core/sources/spiraldb_table_source.py | 37 ++- src/orcapod/core/sources/stream_builder.py | 15 +- .../core/streams/arrow_table_stream.py | 59 +++-- src/orcapod/core/streams/base.py | 12 + .../protocols/core_protocols/streams.py | 11 + src/orcapod/utils/arrow_utils.py | 72 +++--- src/orcapod/utils/source_tokens.py | 234 ++++++++++++++++++ .../unit/test_arrow_data_utils.py | 24 -- tests/test_utils/test_arrow_utils.py | 94 +++---- 20 files changed, 472 insertions(+), 177 deletions(-) create mode 100644 src/orcapod/utils/source_tokens.py diff --git a/src/orcapod/core/operators/add_tags.py b/src/orcapod/core/operators/add_tags.py index 9af218e81..efedd2592 100644 --- a/src/orcapod/core/operators/add_tags.py +++ b/src/orcapod/core/operators/add_tags.py @@ -322,7 +322,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ tag_keys, _ = stream.keys() data_context = stream.data_context # pyright: ignore[reportAttributeAccessIssue] # StreamProtocol omits data_context, which every concrete stream provides (ITL-844) - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index cbc6570b8..9cfd73cbd 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -90,7 +90,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("All tag columns are selected. Returning stream unaltered.") return stream - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -229,7 +229,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("All data columns are selected. Returning stream unaltered.") return stream - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -388,7 +388,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("No tag columns to drop. Returning stream unaltered.") return stream - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -534,7 +534,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: associated_source_columns = [ f"{constants.SOURCE_PREFIX}{c}" for c in columns_to_drop ] - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -774,7 +774,7 @@ def validate_unary_input(self, stream: StreamProtocol) -> None: def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: tag_columns, data_columns = self._user_columns(stream) tags_removed, data_removed = self._removals(tag_columns, data_columns) - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/operators/drop_nulls.py b/src/orcapod/core/operators/drop_nulls.py index 1e7840935..028bcfa8c 100644 --- a/src/orcapod/core/operators/drop_nulls.py +++ b/src/orcapod/core/operators/drop_nulls.py @@ -316,7 +316,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: A stream over the surviving rows, in input order, with the named columns non-nullable. A result with no rows has the same schema. """ - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/operators/filter.py b/src/orcapod/core/operators/filter.py index e5a4fa1a8..b8e3621e1 100644 --- a/src/orcapod/core/operators/filter.py +++ b/src/orcapod/core/operators/filter.py @@ -243,7 +243,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ # Every system column passes through: source info, system tags and each row's # data context (a raw stream may hold several). - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/operators/filters.py b/src/orcapod/core/operators/filters.py index ce01c02b5..2a84592f5 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -10,7 +10,7 @@ from orcapod.core.streams import ArrowTableStream from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import ColumnConfig, Schema -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens if TYPE_CHECKING: import numpy as np @@ -71,9 +71,17 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: return stream # TODO: improve efficiency here... - table = stream.as_table( + whole = stream.as_carried_table( columns={"source": True, "system_tags": True, "sort_by_tags": False} ) + # Polars reads no derived token column: one is left out, and put back for the + # rows kept (its recipe reads the system tags kept with them, ITL-1464), unless + # a predicate could read it. + derived = source_tokens.derived_columns(whole.schema) + others = {c for c in whole.column_names if c not in derived} + if derived and not self._reads_only(others): + whole, derived = source_tokens.materialize(whole), () + table = whole.drop_columns(list(derived)) df = pl.DataFrame(table) filtered_table = df.filter(*self.predicates, **self.constraints).to_arrow() # A filter passes every column through, so each one takes the @@ -96,6 +104,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: filtered_table = arrow_utils.restore_schema_nullability( filtered_table, pa.schema(input_fields) ) + for name in derived: + field = whole.schema.field(name) + recipe = source_tokens.derived_recipe(field.type) + assert recipe is not None + filtered_table = filtered_table.append_column( + field, source_tokens.derived_array(recipe, filtered_table.num_rows) + ) + filtered_table = filtered_table.select(whole.column_names) return ArrowTableStream( filtered_table, @@ -103,6 +119,23 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: data_tags=stream_data_tags(stream), ) + def _reads_only(self, columns: Collection[str]) -> bool: + """Whether every predicate certainly reads columns of ``columns`` only. + + Certain only for expressions that name each column they read: a selector + (``pl.all()``, a regular expression, a type) can read any column, and a predicate + that is not an expression is not looked into. A name that is no column is not + certain either: Polars' error then lists the columns there are. + """ + if not set(self.constraints) <= set(columns): + return False + return all( + isinstance(predicate, pl.Expr) + and not predicate.meta.has_multiple_outputs() + and set(predicate.meta.root_names()) <= set(columns) + for predicate in self.predicates + ) + def validate_unary_input(self, stream: StreamProtocol) -> None: """ This method should be implemented by subclasses to validate the inputs to the operator. diff --git a/src/orcapod/core/operators/mappers.py b/src/orcapod/core/operators/mappers.py index fa89ec4a5..184f66252 100644 --- a/src/orcapod/core/operators/mappers.py +++ b/src/orcapod/core/operators/mappers.py @@ -179,7 +179,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: # nothing to rename in the data, return stream as is return stream - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -457,7 +457,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: # nothing to rename or drop in the tags, return stream as is return stream - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -799,7 +799,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: tag_renames, data_renames, tags_dropped, data_dropped = self._plan( tag_columns, data_columns ) - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/operators/meta_columns.py b/src/orcapod/core/operators/meta_columns.py index 674d55e46..a2312b830 100644 --- a/src/orcapod/core/operators/meta_columns.py +++ b/src/orcapod/core/operators/meta_columns.py @@ -112,7 +112,7 @@ def without_input_meta( """ if not _carries_meta(stream, inputs): return stream - table = stream.as_table( + table = stream.as_carried_table( columns={"source": True, "system_tags": True, "context": True} ) tag_columns = stream.keys()[0] diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f829d44a5..c8f45d059 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -2045,6 +2045,16 @@ def as_table( ) return self._cached_stream.as_table(columns=columns, all_info=all_info) + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The operator's result, derived token columns as they are (ITL-1464).""" + self._refresh() + assert self._cached_stream is not None, ( + "StreamProtocol has not been updated or is empty." + ) + return self._cached_stream.as_carried_table(columns=columns) + def iter_data( self, ) -> Iterator[tuple[TagProtocol, DataProtocol]]: diff --git a/src/orcapod/core/operators/tag_by.py b/src/orcapod/core/operators/tag_by.py index 911fefc36..a7cbe5f7a 100644 --- a/src/orcapod/core/operators/tag_by.py +++ b/src/orcapod/core/operators/tag_by.py @@ -209,7 +209,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ tag_columns, _ = stream.keys() # The context column too, so each row keeps its own data context key. - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 07221924c..780e1c63a 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -537,6 +537,18 @@ def as_table( """Delegate to the underlying stream's as_table.""" return self._stream.as_table(columns=columns, all_info=all_info) + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The underlying stream's table, derived token columns as they are (ITL-1464). + + A source that reads its rows its own way (a subclass, or an object, with its own + ``as_table``) gives that table. + """ + if type(self).as_table is RootSource.as_table and "as_table" not in vars(self): + return self._stream.as_carried_table(columns=columns) + return super().as_carried_table(columns=columns) + # ------------------------------------------------------------------------- # The start-of-run check (ITL-1102) # ------------------------------------------------------------------------- diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1c4a57228..ab1a585b1 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -812,3 +812,9 @@ def as_table( all_info: bool = False, ) -> "pa.Table": return self._get_stream().as_table(columns=columns, all_info=all_info) + + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The source's table, derived token columns as they are (ITL-1464).""" + return self._get_stream().as_carried_table(columns=columns) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 6312a677f..b1dba51bb 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -62,7 +62,7 @@ row_identifiers, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream -from orcapod.core.streams.base import check_head_size +from orcapod.core.streams.base import StreamBase, check_head_size from orcapod.core.streams.view import ViewStatus, StreamView from orcapod.databases.spiraldb_connector import ( SpiralDBConnector, @@ -959,31 +959,32 @@ def as_table( all_info: bool = False, ) -> "pa.Table": """Scan the table and return its rows as one PyArrow table (all held in memory).""" - return self._whole_table( - self._batch_streams(), columns=columns, all_info=all_info + return self._whole_stream(self._batch_streams()).as_table( + columns=columns, all_info=all_info ) - def _whole_table( - self, - streams: Iterator["ArrowTableStream"], - *, - columns: ColumnConfig | dict[str, Any] | None, - all_info: bool, + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None ) -> "pa.Table": - """Return the rows of ``streams`` (batches of one read) as one table.""" + """Scan the table as ``as_table`` does, building no source-info text (ITL-1464).""" + return self._whole_stream(self._batch_streams()).as_carried_table( + columns=columns + ) + + def _whole_stream(self, streams: Iterator["ArrowTableStream"]) -> StreamBase: + """Return the rows of ``streams`` (batches of one read) as one stream.""" # One stream over all the rows, so that a whole-table option (sorting by # tags) applies across batches. enriched = {"source": True, "system_tags": True} - tables = [stream.as_table(columns=enriched) for stream in streams] + tables = [stream.as_carried_table(columns=enriched) for stream in streams] if not tables: - return self._stream.as_table(columns=columns, all_info=all_info) - whole = ArrowTableStream( + return self._stream + return ArrowTableStream( table=pa.concat_tables(tables), tag_columns=self._tag_columns, system_tag_columns=self._system_tag_columns, data_tags=self._data_tags, ) - return whole.as_table(columns=columns, all_info=all_info) def _head( self, @@ -1013,11 +1014,9 @@ def _head( head_limit = n if limit is None else min(n, limit) asof = self._asof table = self._lookup_table() - rows = self._whole_table( - self._read_batches(table, asof=asof, limit=head_limit, max_rows=None), - columns=columns, - all_info=all_info, - ) + rows = self._whole_stream( + self._read_batches(table, asof=asof, limit=head_limit, max_rows=None) + ).as_table(columns=columns, all_info=all_info) if rows.num_rows < head_limit or head_limit == limit: return _Head(rows, True, rows.num_rows, False) bound, total = self._bounded_count(n, table) diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 5fbb8eb52..67eeb2114 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -25,7 +25,6 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import RowIdentifierError from orcapod.logical_types.identifier import LogicalTypeIdentifierError -from orcapod.system_constants import constants from orcapod.types import ContentHash from orcapod.utils import arrow_utils, schema_utils from orcapod.utils.schema_utils import compute_source_schema_hash @@ -597,7 +596,8 @@ def attach_provenance( key's canonical JSON), and its source id is the source's name: the two system-tag columns. Each source-info value is ``::::`` (for example ``_source_amplitude`` - holds ``::row_3::amplitude``). A row keeps its record id wherever + holds ``::row_3::amplitude``), carried as a recipe over the two system + tags until its text is needed (``source_tokens``). A row keeps its record id wherever and however often it is read, as long as its identifier is the same (ITL-1154). @@ -615,13 +615,12 @@ def attach_provenance( Returns: The stream over the enriched table. """ - source_info = [ - f"{source_id}{constants.BLOCK_SEPARATOR}{identifier}" - for identifier in row_identifiers - ] - table = arrow_utils.add_source_info( + # The tokens say nothing the two system tags below and the column names do not: + # each is carried as that recipe, and its text is built when it is needed + # (``source_tokens``, ITL-1464). + table = arrow_utils.add_source_tokens( table, - source_info, + schema_hash, exclude_columns=[c for c in tag_columns if c not in data_tags], ) table = arrow_utils.add_system_tag_columns( diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index df49eaff6..09f1b1d4e 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -20,10 +20,13 @@ from orcapod.protocols.hashing_protocols import PipelineElementProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema, SourceInfoValue -from orcapod.utils import arrow_utils, schema_utils +from orcapod.utils import arrow_utils, schema_utils, source_tokens logger = logging.getLogger(__name__) +ROWS_PER_PART = 8192 +"""The rows whose source-info text ``iter_data`` builds at once (ITL-1464).""" + class ArrowTableStream(StreamBase): """ @@ -351,6 +354,13 @@ def as_table( columns_config = ColumnConfig.handle_config(columns, all_info=all_info) return self._assemble_table(columns_config, limit=None) + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The table with its derived token columns as they are (ITL-1464).""" + config = ColumnConfig.handle_config(columns) + return self._assemble_table(config, limit=None, carried=config.system_tags) + def head( self, n: int = 10, @@ -384,13 +394,19 @@ def _typed_zero_row_table(self) -> "pa.Table": return self._assemble_table(ZERO_ROW_INPUT_COLUMNS, limit=0) def _assemble_table( - self, columns_config: ColumnConfig, limit: int | None + self, + columns_config: ColumnConfig, + limit: int | None, + *, + carried: bool = False, ) -> "pa.Table": """Return the stream's rows with the column groups of ``columns_config``. Args: columns_config: The column groups to include, and whether to sort by tags. limit: Assemble only the first ``limit`` rows; ``None`` for all of them. + carried: Leave a derived token column derived (``as_carried_table``), which + needs the system tags in the table; ``False`` gives its text. """ output_table = self._table data_context_table = self._data_context_table @@ -408,8 +424,8 @@ def hashes() -> pa.Array[Any]: [str(data.content_hash()) for _, data in rows], type=pa.large_string() ) - def shape(carried: "pa.Table") -> "pa.Table": - table_stack = (carried,) + def shape(rows: "pa.Table") -> "pa.Table": + table_stack = (rows,) if columns_config.context: table_stack += (data_context_table,) if columns_config.source: @@ -423,6 +439,8 @@ def shape(carried: "pa.Table") -> "pa.Table": # the system tags are asked for. The system tags stay in the table # through the sort: they break ties between equal tags. table = arrow_utils.sort_by_tag_columns(table, tuple(self._tag_columns)) + if not carried: + table = source_tokens.materialize(table) if not columns_config.system_tags: table = table.drop_columns(list(self._system_tag_columns)) return table @@ -471,21 +489,30 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, Data]]: self._source_info_table.schema.field(name), self._source_info_table.column(name), ) - # The table is prepared once for all of its rows (ITL-1348): building - # ``Tag(row)`` and ``Data(row)`` from one-row slices normalized every row - # three times and split its columns again. - tags = ( - Tag.rows_of(rows.select(tag_columns), self.data_context) - if tag_columns - else None + # Derived tokens become text a part of the rows at a time (ITL-1464); a + # table with none is one part. + size = ( + ROWS_PER_PART + if source_tokens.derived_columns(rows.schema) + else max(rows.num_rows, 1) ) - for data in Data.rows_of(rows.select(data_columns), self.data_context): - # A fresh empty tag per row, so rows never share one object. - tag = next(tags) if tags is not None else Tag({}) + for start in range(0, rows.num_rows, size): + part = source_tokens.materialize(rows.slice(start, size)) + # The part is prepared once for all of its rows (ITL-1348): building + # ``Tag(row)`` and ``Data(row)`` from one-row slices normalized every + # row three times and split its columns again. + tags = ( + Tag.rows_of(part.select(tag_columns), self.data_context) + if tag_columns + else None + ) + for data in Data.rows_of(part.select(data_columns), self.data_context): + # A fresh empty tag per row, so rows never share one object. + tag = next(tags) if tags is not None else Tag({}) - yield tag, data + yield tag, data - cached_elements.append((tag, data)) + cached_elements.append((tag, data)) self._cached_elements = cached_elements else: yield from self._cached_elements diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 9f8b731f7..26fa6713d 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1509,6 +1509,18 @@ def as_table( all_info: bool = False, ) -> "pa.Table": ... + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The table of ``as_table(columns=columns)``, as operators pass it on. + + A source-info column may be derived (``utils/source_tokens.py``): a recipe over + the table's system tags in place of its text, which ``source_tokens.materialize`` + builds. Internal: never stored, hashed or shown (ITL-1464). A stream that holds + none gives ``as_table``. + """ + return self.as_table(columns=columns) + def as_polars_df( self, *, diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index c8c72abd6..b35e38beb 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -255,6 +255,17 @@ def async_iter_data(self) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: """ ... + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The table of ``as_table(columns=columns)``, as operators pass it on. + + A source-info column may be derived (``utils/source_tokens.py``): a recipe over + the table's system tags in place of its text. Internal: never stored, hashed or + shown (ITL-1464). + """ + ... + def as_table( self, *, diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 86ac58283..e51519cbd 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -10,6 +10,7 @@ from orcapod.system_constants import constants from orcapod.types import ColumnConfig, SourceInfoValue +from orcapod.utils import source_tokens if TYPE_CHECKING: from orcapod.logical_types.identifier import LogicalTypeIdentifier @@ -1464,7 +1465,10 @@ def append_to_system_tags(table: "pa.Table", value: str) -> "pa.Table": else c for c in table.column_names } - return table.rename_columns(column_name_map) + # A derived token column keeps reading the columns it read (ITL-1464). + return source_tokens.rename_read_columns( + table.rename_columns(column_name_map), column_name_map + ) def fold_system_tag_values(values: Sequence[Any], *, label: str) -> str: @@ -1712,6 +1716,12 @@ def sort_system_tag_values(table: "pa.Table") -> "pa.Table": if len(positions) <= 1: continue + # The values move between these columns, so a token derived from them is built + # first: it names the row it always named (ITL-1464). + table = source_tokens.materialize_reading( + table, {name for pair in positions.values() for name in pair.values()} + ) + # Sort positions numerically sorted_positions = sorted(positions.keys(), key=int) @@ -1777,50 +1787,38 @@ def sort_system_tag_values(table: "pa.Table") -> "pa.Table": return table -def add_source_info( +def add_source_tokens( table: "pa.Table", - source_info: str | Collection[str] | None, - exclude_prefixes: Collection[str] = ( - constants.META_PREFIX, - constants.DATAGRAM_PREFIX, - ), + schema_hash: str, exclude_columns: Collection[str] = (), ) -> "pa.Table": - """Add source information to an Arrow table.""" - # Create a base list of per-row source tokens; one entry per row. - if source_info is None or isinstance(source_info, str): - base_source = [source_info] * table.num_rows - elif isinstance(source_info, Collection): - if len(source_info) != table.num_rows: - raise ValueError( - "Length of source_info collection must match number of rows in the table." - ) - base_source = list(source_info) - else: - raise TypeError( - f"source_info must be a str, a sized Collection[str], or None; " - f"got {type(source_info).__name__}" - ) + """Add the source-info token column of each data column, as a recipe (ITL-1464). + + Each ``_source_`` column holds no bytes: its type says the token is the row's + source id, its record id and ``col`` (``source_tokens.TokenRecipe``), read from the + two system-tag columns ``add_system_tag_columns`` adds under ``schema_hash``. + + Args: + table: The rows. + schema_hash: The source's schema hash, which names the system-tag columns. + exclude_columns: Columns with no token (the plain tags). Meta and datagram + columns have none either. - # For each data column, build an independent _source_ column from the - # base tokens. We must NOT re-use the array produced for a previous column - # as input for the next one — doing so would accumulate column names - # (e.g. "src::col1::col2" instead of "src::col2"). - for col in table.column_names: - if col.startswith(tuple(exclude_prefixes)) or col in exclude_columns: + Returns: + The table with its token columns, non-nullable: a token is never null. + """ + source_id, record_id = system_tag_column_names(schema_hash) + prefixes = (constants.META_PREFIX, constants.DATAGRAM_PREFIX) + for name in table.column_names: + if name.startswith(prefixes) or name in exclude_columns: continue - col_source = pa.array( - [f"{source_val}::{col}" for source_val in base_source], - type=pa.large_string(), + tokens = source_tokens.derived_array( + source_tokens.TokenRecipe(source_id, record_id, name), table.num_rows ) - # Source info columns are always computed strings, never null. table = table.append_column( - pa.field( - f"{constants.SOURCE_PREFIX}{col}", pa.large_string(), nullable=False - ), - col_source, + pa.field(f"{constants.SOURCE_PREFIX}{name}", tokens.type, nullable=False), + tokens, ) - return table diff --git a/src/orcapod/utils/source_tokens.py b/src/orcapod/utils/source_tokens.py new file mode 100644 index 000000000..9602c5b9f --- /dev/null +++ b/src/orcapod/utils/source_tokens.py @@ -0,0 +1,234 @@ +"""Source-info tokens that are carried as a recipe, not as text (ITL-1464). + +A source row's token is ``::::``: the values of the row's +two system tags and the name the column had at the source. As text it repeats them for +every row and data column, about 35 times the data of a typical table. Inside the library +a token column can instead be **derived**: a column of ``DerivedTokenType`` holds no +bytes, and its type holds the recipe that gives the text from the table's own system-tag +columns. Filtering, taking, slicing, concatenating, selecting and renaming carry such a +column as any other; nothing is computed until the text is needed (``materialize``). + +A derived column is an internal form of a table that operators pass on +(``StreamProtocol.as_carried_table``). It never leaves the library: ``as_table``, rows, +stored tables and everything hashed hold the text. A place that forgets fails loudly: no +value of a derived column can be read, cast to text, hashed, or written to Parquet (its +storage is a struct with no field, which Parquet refuses). +""" + +from __future__ import annotations + +import json +from collections.abc import Collection, Mapping +from dataclasses import dataclass +from typing import Any, NoReturn + +import pyarrow as pa +import pyarrow.compute as pc + +from orcapod.system_constants import constants + +_TEXT = pa.large_string() + +ROWS_PER_CHUNK = 65_536 +"""The most rows whose token text is built in one step.""" + + +@dataclass(frozen=True) +class TokenRecipe: + """How the token of each row is made from the row's system tags. + + Attributes: + source_id: The system-tag column holding the row's source id. + record_id: The system-tag column holding the row's record id. + column: The column name the token ends with: the column's name at the source, + whatever it is called now. + """ + + source_id: str + record_id: str + column: str + + def to_json(self) -> str: + """The recipe as text: what two equal recipes share.""" + return json.dumps([self.source_id, self.record_id, self.column]) + + @classmethod + def from_json(cls, text: str) -> TokenRecipe: + """The recipe ``to_json`` wrote.""" + return cls(*json.loads(text)) + + def renamed(self, names: Mapping[str, str]) -> TokenRecipe: + """The recipe over system-tag columns renamed by ``names``.""" + return TokenRecipe( + names.get(self.source_id, self.source_id), + names.get(self.record_id, self.record_id), + self.column, + ) + + def reads(self, columns: Collection[str]) -> bool: + """Whether the recipe reads one of ``columns``.""" + return self.source_id in columns or self.record_id in columns + + def text(self, batch: pa.RecordBatch) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array + """The tokens of ``batch``'s rows, as ``large_string``.""" + return pc.binary_join_element_wise( + batch.column(self.source_id).cast(_TEXT), + batch.column(self.record_id).cast(_TEXT), + pa.scalar(self.column, _TEXT), + pa.scalar(constants.BLOCK_SEPARATOR, _TEXT), + ) + + +class _DerivedTokenScalar(pa.ExtensionScalar): + """A value of a derived column: it has none to read.""" + + def as_py(self, *args: Any, **kwargs: Any) -> NoReturn: # pyright: ignore[reportExplicitAny, reportIncompatibleMethodOverride] # pyarrow's own signature varies by version + """Refuse to give a value. + + Raises: + TypeError: Always; the text must be built first (``materialize``). + """ + raise TypeError( + "a derived source-info token has no value: build its text first " + "(source_tokens.materialize)" + ) + + +class DerivedTokenType(pa.ExtensionType): + """The Arrow type of a derived token column: no bytes, and the recipe. + + Internal and never registered, so it is in no stored table and no schema Orcapod + presents or hashes. Two derived columns have one type only with one recipe. + """ + + def __init__(self, recipe: TokenRecipe) -> None: + self.recipe = recipe + super().__init__(pa.struct([]), "orcapod.internal.derived_token") + + def __arrow_ext_serialize__(self) -> bytes: + return self.recipe.to_json().encode() + + @classmethod + def __arrow_ext_deserialize__( + cls, storage_type: pa.DataType, serialized: bytes + ) -> DerivedTokenType: + return cls(TokenRecipe.from_json(serialized.decode())) + + def __arrow_ext_scalar_class__(self) -> type[pa.ExtensionScalar]: + return _DerivedTokenScalar + + # pyarrow compares extension types by name and storage only; Arrow asks this. + def __eq__(self, other: object) -> bool: + return isinstance(other, DerivedTokenType) and self.recipe == other.recipe + + def __hash__(self) -> int: + return hash(self.recipe) + + +def derived_array(recipe: TokenRecipe, rows: int) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array + """A derived token column of ``rows`` rows: no row has a byte.""" + storage = pa.Array.from_buffers(pa.struct([]), rows, [None], 0, 0) + return pa.ExtensionArray.from_storage(DerivedTokenType(recipe), storage) + + +def derived_recipe(kind: pa.DataType) -> TokenRecipe | None: + """The recipe of a column of type ``kind``; ``None`` when it is not derived.""" + return kind.recipe if isinstance(kind, DerivedTokenType) else None + + +def derived_columns(schema: pa.Schema) -> tuple[str, ...]: + """The names of the derived token columns of ``schema``.""" + return tuple(f.name for f in schema if derived_recipe(f.type) is not None) + + +def materialize(table: pa.Table, names: Collection[str] | None = None) -> pa.Table: + """Return ``table`` with its derived token columns as text. + + Args: + table: A table holding the system-tag columns its derived columns read. + names: The derived columns to build; ``None`` for all of them. + + Returns: + The table, each such column ``large_string`` with the field's own name and + nullability; ``table`` itself when there is none. + """ + wanted = [ + name for name in derived_columns(table.schema) if names is None or name in names + ] + if not wanted: + return table + schema = table.schema + recipes: dict[str, TokenRecipe] = {} + for name in wanted: + recipe = derived_recipe(schema.field(name).type) + assert recipe is not None + recipes[name] = recipe + read = {c for r in recipes.values() for c in (r.source_id, r.record_id)} + tags = table.select([c for c in table.column_names if c in read]) + chunks: dict[str, list[pa.Array[Any]]] = {name: [] for name in wanted} # pyright: ignore[reportExplicitAny] # Arrow arrays + for batch in tags.to_batches(max_chunksize=ROWS_PER_CHUNK): + for name, recipe in recipes.items(): + chunks[name].append(recipe.text(batch)) + for name in wanted: + index = schema.get_field_index(name) + table = table.set_column( + index, + schema.field(name).with_type(_TEXT), + pa.chunked_array(chunks[name], type=_TEXT), + ) + return table + + +def materialize_reading(table: pa.Table, columns: Collection[str]) -> pa.Table: + """Build the text of the derived columns that read one of ``columns``. + + Called before the values of system-tag columns change, so every token keeps naming + the row it named. + """ + return materialize( + table, + [ + name + for name in derived_columns(table.schema) + if (recipe := derived_recipe(table.schema.field(name).type)) is not None + and recipe.reads(columns) + ], + ) + + +def rename_read_columns(table: pa.Table, names: Mapping[str, str]) -> pa.Table: + """Point the derived columns of ``table`` at system-tag columns renamed by ``names``. + + Args: + table: The table, its system-tag columns already renamed. + names: Old to new column name. + + Returns: + The table with each derived column's recipe reading the new names. + """ + for name in derived_columns(table.schema): + field = table.schema.field(name) + recipe = derived_recipe(field.type) + assert recipe is not None + renamed = recipe.renamed(names) + if renamed == recipe: + continue + table = table.set_column( + table.schema.get_field_index(name), + field.with_type(DerivedTokenType(renamed)), + derived_array(renamed, table.num_rows), + ) + return table + + +def text_schema(schema: pa.Schema) -> pa.Schema: + """``schema`` with each derived token column as the text it stands for.""" + if not derived_columns(schema): + return schema + return pa.schema( + [ + field.with_type(_TEXT) if derived_recipe(field.type) else field + for field in schema + ], + metadata=schema.metadata, + ) diff --git a/test-specification/unit/test_arrow_data_utils.py b/test-specification/unit/test_arrow_data_utils.py index dfc17c7a2..100adcabe 100644 --- a/test-specification/unit/test_arrow_data_utils.py +++ b/test-specification/unit/test_arrow_data_utils.py @@ -13,7 +13,6 @@ from orcapod.system_constants import constants from orcapod.utils.arrow_utils import ( - add_source_info, add_system_tag_columns, append_to_system_tags, drop_columns_with_prefix, @@ -144,29 +143,6 @@ def test_sorts_system_tag_values(self): assert result.num_rows == table_with_tags.num_rows -# --------------------------------------------------------------------------- -# add_source_info -# --------------------------------------------------------------------------- - - -class TestAddSourceInfo: - """Per design, source info columns are prefixed with _source_ and track - provenance tokens per data column.""" - - def test_adds_source_info_columns(self): - table = pa.table({"id": [1, 2], "value": [10, 20]}) - result = add_source_info(table, source_info="src_token") - source_cols = [ - c for c in result.column_names if c.startswith(constants.SOURCE_PREFIX) - ] - assert len(source_cols) > 0 - - def test_source_info_length_mismatch_raises(self): - table = pa.table({"id": [1, 2], "value": [10, 20]}) - with pytest.raises(ValueError): - add_source_info(table, source_info=["a", "b", "c"]) # Wrong count - - # --------------------------------------------------------------------------- # drop_columns_with_prefix # --------------------------------------------------------------------------- diff --git a/tests/test_utils/test_arrow_utils.py b/tests/test_utils/test_arrow_utils.py index 26bbddda1..234b86c34 100644 --- a/tests/test_utils/test_arrow_utils.py +++ b/tests/test_utils/test_arrow_utils.py @@ -4,8 +4,10 @@ import pytest from orcapod.types import ColumnConfig, SourceInfoValue +from orcapod.utils import source_tokens from orcapod.utils.arrow_utils import ( - add_source_info, + add_source_tokens, + add_system_tag_columns, apply_column_config, column_arrow_type, concat_tables_by_name, @@ -243,65 +245,41 @@ def test_none_schema_metadata_stays_none(self): assert not result.metadata -# --------------------------------------------------------------------------- -# add_source_info -# --------------------------------------------------------------------------- - - -class TestAddSourceInfo: - """add_source_info must produce one _source_ column per data column - whose values are exactly '::' for every row.""" - - def test_single_column_produces_correct_source_token(self): - """_source_ value is '::' for every row.""" - table = pa.table({"x": pa.array([10, 20], type=pa.int64())}) - result = add_source_info(table, "mysrc") - - assert result.column("_source_x").to_pylist() == ["mysrc::x", "mysrc::x"] - - def test_multi_column_each_source_column_uses_its_own_name(self): - """Each _source_ value is '::' — columns are independent.""" - table = pa.table( - { - "x": pa.array([1, 2], type=pa.int64()), - "y": pa.array([3, 4], type=pa.int64()), - "z": pa.array([5, 6], type=pa.int64()), - } - ) - result = add_source_info(table, "base") +class TestAddSourceTokens: + """One ``_source_`` column per data column, whose text is + ``::::`` of the row's own system tags.""" - assert result.column("_source_x").to_pylist() == ["base::x", "base::x"] - assert result.column("_source_y").to_pylist() == ["base::y", "base::y"] - assert result.column("_source_z").to_pylist() == ["base::z", "base::z"] - - def test_per_row_source_tokens_combined_with_column_name(self): - """With a per-row source list, each row's token is '::'.""" - table = pa.table( - { - "a": pa.array([10, 20], type=pa.int64()), - "b": pa.array([30, 40], type=pa.int64()), - } + def test_each_column_gets_its_own_token_of_every_row(self): + table = pa.table({"k": [1, 2], "y": ["p", "q"], "x": [3.0, 4.0]}) + carried = add_system_tag_columns( + add_source_tokens(table, "hash", exclude_columns=["k"]), + "hash", + "src", + ["row_0", "row_1"], ) - result = add_source_info(table, ["src0", "src1"]) - - assert result.column("_source_a").to_pylist() == ["src0::a", "src1::a"] - assert result.column("_source_b").to_pylist() == ["src0::b", "src1::b"] - - def test_correct_number_of_source_columns_added(self): - """Exactly one _source_ column is added per non-excluded data column.""" - table = pa.table( - { - "p": pa.array([1], type=pa.int64()), - "q": pa.array([2], type=pa.int64()), - "r": pa.array([3], type=pa.int64()), - } - ) - result = add_source_info(table, "s") - - assert result.num_columns == 6 # 3 data + 3 source - assert "_source_p" in result.column_names - assert "_source_q" in result.column_names - assert "_source_r" in result.column_names + result = source_tokens.materialize(carried) + assert [c for c in result.column_names if c.startswith("_source_")] == [ + "_source_y", + "_source_x", + ] + assert result.column("_source_y").to_pylist() == [ + "src::row_0::y", + "src::row_1::y", + ] + assert result.column("_source_x").to_pylist() == [ + "src::row_0::x", + "src::row_1::x", + ] + field = result.schema.field("_source_x") + assert (field.type, field.nullable) == (pa.large_string(), False) + + def test_meta_columns_get_none(self): + table = pa.table({"x": [1], "__m": [2]}) + assert add_source_tokens(table, "hash").column_names == [ + "x", + "__m", + "_source_x", + ] class TestSystemTagColumnNames: From 3e0794d87c9279010104d7cc7467080c85616b2a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:29:31 -0800 Subject: [PATCH 08/81] 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 09/81] 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 f37442e78f5149d543d3aca919ab8502d7e3f5b5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:33:00 -0800 Subject: [PATCH 10/81] perf(streams): bounded view for run() over an on-demand source (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1464.md | 10 + docs/concepts/streams.md | 28 +- docs/dev/specs/itl-1464-views.md | 38 +- src/orcapod/core/operators/add_tags.py | 1 + .../core/operators/column_selection.py | 8 + src/orcapod/core/operators/drop_nulls.py | 1 + src/orcapod/core/operators/filter.py | 1 + src/orcapod/core/operators/mappers.py | 3 + .../core/operators/static_output_pod.py | 138 +++++ .../core/sources/spiraldb_table_source.py | 37 +- src/orcapod/core/streams/base.py | 64 ++- src/orcapod/core/streams/view.py | 240 ++++++++- src/orcapod/errors.py | 8 + .../protocols/core_protocols/streams.py | 4 +- .../streams/test_bounded_run_view.py | 471 ++++++++++++++++++ 15 files changed, 1025 insertions(+), 27 deletions(-) create mode 100644 changelog.d/ITL-1464.md create mode 100644 tests/test_core/streams/test_bounded_run_view.py diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md new file mode 100644 index 000000000..be50b516d --- /dev/null +++ b/changelog.d/ITL-1464.md @@ -0,0 +1,10 @@ +### Changed + +- `run()` of a `SpiralDBTableSource`, and of column selections, renames, `add_tags`, + `drop_nulls` and `filter` over one, reads the table in batches and no longer holds a result + of more than 50,000 rows (ITL-1464). The view then has the row count and the first and the + last 1,000 rows; it is displayed as before, and its `table`, `as_table()`, + `as_polars_df()`, `sort_by_tags()` and a longer `head` or `tail` raise `BoundedViewError`, + which names the stream's own methods. `stream.as_table()` and iteration are unchanged; after + such a run `as_table()` reads the source again. Smaller results, and every other stream, + are as before. diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index 40c13de07..0ecf17a1b 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -181,9 +181,10 @@ print(months.head(3).header()) ### Computing a stream outside a job: `run()` Every stream, source and node has `run()`, with no arguments: it is the one way to compute -any of them outside a job (developer, November 13, 2026). It does exactly the work -`as_table()` does, through the same cache, and returns a `StreamView` of every row with the -default columns. A stream already computed is not computed a second time; one whose input +any of them outside a job (developer, November 13, 2026). It computes every row, with every +effect, in the order of `as_table()`, and returns a `StreamView` with the default columns. It +promises nothing about how the rows are produced or what is held meanwhile (developer, +November 24, 2026). A stream already computed is not computed a second time; one whose input changed is recomputed. In a notebook, `stream.run()` at the end of a cell computes and displays. The view's own methods choose what is shown. Each returns a new view and never reads or @@ -209,13 +210,30 @@ view does not hold, so it keeps them in the order it has them. The display of a such as the one `run()` returns, shows its first and last five rows when it has more than ten, and its header gives the count. +A view holds every row of the stream, with one exception, the bounded view. A +`SpiralDBTableSource` holds no rows, and `run()` reads it in batches; so are read the +operators that choose or rename columns, add tags or drop rows (`select_*`, `drop_*`, +`map_*`, `add_tags`, `drop_nulls`, `filter`) and the chains of them over such a source. A +result of at most 50,000 rows is held, as everywhere else. A larger one is not: its view has +the row count, the columns, and the first and the last 1,000 rows. It is displayed as any +view, and `head(n)` and `tail(n)` up to 1,000 rows give what any view gives. What needs the +other rows (`table`, `as_table()`, `as_polars_df()`, `sort_by_tags()`, a longer `head` or +`tail`) raises `BoundedViewError`: a part is never given as the whole. Ask the stream itself, +`stream.as_table()`, which reads the source again and applies the operators again (no function +of yours runs a second time). `stream.head(n)` after such a run shows its first rows. Whether +a view is bounded depends only on the kind of stream and on its row count, so equal data +always gives the same kind of view. A `polars_filter`, `pick`, `index`, `tag_by`, join, +`group_by` or `batch`, a function pod, and everything after one, computes its whole result +and holds it, also over a `SpiralDBTableSource`. + A view holds the default column groups only. For system tags, source info, the data context or content hashes, ask the stream after `run()`. A function pod's or operator's output stream, a job node (a job's side-effect node included), an in-memory source and a `CachedSource` keep the rows `run()` gave: their `as_table(columns=...)` and `head(columns=...)` read those rows, compute nothing and deliver no side effect. Other streams do their `as_table()` work again: a side-effect stream outside a job delivers its side effects again (its `head()` shows no rows), -a polling source polls again and a `SpiralDBTableSource` reads its whole table again. A view never asks its stream for more columns, because for those +a polling source polls again and a `SpiralDBTableSource` reads its whole table again (so does +an operator's stream whose `run()` gave a bounded view). A view never asks its stream for more columns, because for those streams asking again is not a read. What `run()` does on each kind of object: @@ -223,7 +241,7 @@ What `run()` does on each kind of object: | Object | `run()` | |---|---| | An in-memory source (`DictSource`, `ArrowTableSource`, ...), a Delta or SQL table source | nothing to compute: a view of the rows it holds | -| A `SpiralDBTableSource` | reads the whole table into memory (`head()` is the bounded read); every call reads again | +| A `SpiralDBTableSource` | reads the whole table in batches (`head()` is the bounded read); every call reads again; a bounded view above 50,000 rows | | A `PollingSource` (provisional, see [Provisional sources](sources.md#provisional-sources)) | polls, as `as_table()` does | | A `CachedSource` | reads its cache and writes the wrapped source's new rows to it | | A function pod's or operator's output stream | computes what is not computed yet | diff --git a/docs/dev/specs/itl-1464-views.md b/docs/dev/specs/itl-1464-views.md index 0bc211408..dd54dd169 100644 --- a/docs/dev/specs/itl-1464-views.md +++ b/docs/dev/specs/itl-1464-views.md @@ -1,6 +1,7 @@ # `run()`, its view and `preview(n)` without a full table (ITL-1464, track VIEWS) -Status: draft for approval, November 25, 2026, against `origin/main` 0d1e017c. Companion of +Status: V1 to V12 approved by the coordinator, November 25, 2026 (V2, V3 and V8 flagged for +the developer); the bounded view is implemented, `preview(n)` is not. Written, against `origin/main` 0d1e017c. Companion of `itl-1464-streaming-design.md` (sections 1, 3 and 4 of it). Nothing here changes a hash, identity, stored layout, stored byte or golden value. @@ -16,8 +17,11 @@ Outside a job, only `SpiralDBTableSource` reads its rows on demand and holds non other source holds its table, so a table over those rows is not a new cost (a filter's result over it is, and stays as today). A function pod's stream keeps its results, so that no function is called twice: it stays as today. So the first step applies to a -**batched chain**: zero or more row-by-row operators (`ROW_BY_ROW`, and `Filter`) over a -source that reads in batches. Joins, `GroupBy`, `Batch`, `PolarsFilter` and function pods +**batched chain**: zero or more operators that declare `BATCHES_GIVE_THE_WHOLE` (the column +selections, the mappers, `AddTags`, `DropNulls`, `Filter`) over a source that reads in +batches. `Pick` and `Index` are row by row but excluded: they build their result from rows, +so its types and nullable flags follow the values of the batch. The flag is read from the +class itself, so a subclass declares it again. Joins, `GroupBy`, `Batch`, `PolarsFilter` and function pods end the chain: they compute as today. ## The `run()` contract @@ -28,7 +32,8 @@ end the chain: they compute as today. 1. The source's batches are read in order (one scan, its checks unchanged: `max_rows`, schema, repeated keys). Each batch, shaped as `as_table()` shapes the whole, goes through each operator's own `static_process`: the one sync body, no second kernel. -2. Result batches are kept whole up to **64 MiB** (all column groups). A result that ends +2. Result batches are kept whole up to **50,000 rows** (all column groups; counted in rows, + not bytes, so equal data is treated alike however its batches are cut). A result that ends within it is complete: the view holds it, and an operator stream keeps it, exactly as today. 3. A larger result drops the kept batches to a **window**: the first and last 1,000 rows @@ -38,7 +43,9 @@ end the chain: they compute as today. `as_table()`, iteration and conversion are unchanged and still give every row. After a large `run()` of a batched chain, `as_table()` reads the source again and applies the operators again. No user function runs twice: a function pod is never in a batched chain. -An error in any batch propagates and nothing is kept, as today. +An error in any batch propagates and nothing is kept, as today. When an operator raises, the +rest of the source is read first: an error of the source, which a whole read raises before +the operator runs, still comes first. ## The view @@ -96,9 +103,9 @@ never computes. | V1 | Bounded window now, disk-backed later, or wait for the local cache (N2) | window now: no file is written, and paging later only lifts refusals | | V2 | `as_table()` / `table` / `as_polars_df()` of a bounded view: kept rows, recompute, or refuse | refuse, pointing to the stream (a part must never read as the whole; a view never recomputes) | | V3 | `head`/`tail` beyond the window, `sort_by_tags` | refuse | -| V4 | Threshold and window | 64 MiB of result (as L2), first and last 1,000 rows; constants, no config yet | +| V4 | Threshold and window | approved at 64 MiB; implemented as 50,000 rows (bytes differ with the batches and with what is already held), first and last 1,000 rows; constants, no config yet | | V5 | `as_table()` after a large run of a batched chain reads and applies operators again | yes (no user function runs again) | -| V6 | Streams in the middle of a chain keep nothing after a run of the last one (today each keeps its result) | yes: keeping one table per step is the cost being removed; each `run()`s by itself | +| V6 | Streams in the middle of a chain keep nothing after a run of the last one (today each keeps its result) | yes, above the threshold (below it each keeps its result, as today): keeping one table per step is the cost being removed; each `run()`s by itself | | V7 | `PolarsFilter` in a batched chain | not until B1 decides expressions that read other rows | | V8 | `preview` calls user functions | yes, at most on the rows it looks at | | V9 | `preview` stores or keeps anything | no: not in memory, not in a database. A cached pod reads its stored results and writes none | @@ -118,3 +125,20 @@ never computes. - The refusals; `head` after `run`; staleness after the source moves. - Memory, 2,177,155 rows of the gaze shape, before and after, for the source, a rename, a `drop_nulls` and a `filter`. + +## Measured + +`run()` of a synthetic SpiralDB table shaped as one session of gaze (2,177,155 rows, 13 +columns, 248 MiB of Arrow data; the diagnosis's table), peak resident memory, one process +per row: + +| Stream | Before | After | Arrow pool peak before | after | Time before | after | +|---|---|---|---|---|---|---| +| the source | 10.8 GiB | 1.24 GiB | 9.3 GiB | 0.07 GiB | 8.9 s | 10.4 s | +| `map_data` | 10.8 GiB | 1.40 GiB | 9.3 GiB | 0.25 GiB | 8.8 s | 10.5 s | +| `drop_nulls` | 19.7 GiB | 1.44 GiB | 18.6 GiB | 0.28 GiB | 9.8 s | 11.1 s | +| `filter` | 15.1 GiB | 1.45 GiB | 14.1 GiB | 0.29 GiB | 9.2 s | 10.2 s | +| `drop_nulls`, `filter`, `map_data` | 20.1 GiB | 1.55 GiB | 18.6 GiB | 0.39 GiB | 10.2 s | 9.9 s | + +The Arrow pool holds nothing large after the run. What remains is mostly the set of keys the +source remembers to refuse a repeat (outside this track), which still grows with the table. diff --git a/src/orcapod/core/operators/add_tags.py b/src/orcapod/core/operators/add_tags.py index 9af218e81..583a51192 100644 --- a/src/orcapod/core/operators/add_tags.py +++ b/src/orcapod/core/operators/add_tags.py @@ -122,6 +122,7 @@ class AddTags(UnaryOperator): # Data-tags pass through as they are; the new tags are plain (ITL-1023). # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__(self, tags: Mapping[str, TagConstant], **kwargs: Any): diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index cbc6570b8..ff312854d 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -60,6 +60,7 @@ class SelectTagColumns(UnaryOperator): # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): @@ -199,6 +200,7 @@ class SelectDataColumns(UnaryOperator): # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): @@ -355,6 +357,7 @@ class DropTagColumns(UnaryOperator): # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): @@ -499,6 +502,7 @@ class DropDataColumns(UnaryOperator): # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): @@ -881,6 +885,8 @@ class DropColumns(_TagAndDataColumnsOperator): be dropped: a stream needs at least one data column. """ + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True + _verb: ClassVar[str] = "drop" def _removed(self, columns: Collection[str]) -> list[str]: @@ -905,6 +911,8 @@ class SelectColumns(_TagAndDataColumnsOperator): named: a stream needs at least one data column. """ + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True + _verb: ClassVar[str] = "select" def _removed(self, columns: Collection[str]) -> list[str]: diff --git a/src/orcapod/core/operators/drop_nulls.py b/src/orcapod/core/operators/drop_nulls.py index 1e7840935..3ad35f7b1 100644 --- a/src/orcapod/core/operators/drop_nulls.py +++ b/src/orcapod/core/operators/drop_nulls.py @@ -93,6 +93,7 @@ class DropNulls(UnaryOperator): # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__( diff --git a/src/orcapod/core/operators/filter.py b/src/orcapod/core/operators/filter.py index e5a4fa1a8..dd341ae58 100644 --- a/src/orcapod/core/operators/filter.py +++ b/src/orcapod/core/operators/filter.py @@ -82,6 +82,7 @@ class Filter(UnaryOperator): # Its head shows the matching rows of its input's head (decision 13, ITL-1374). HEAD_FROM_INPUT_HEAD: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True # Its identity is not frozen with data context v1 (ITL-1374). PROVISIONAL: ClassVar[bool] = True diff --git a/src/orcapod/core/operators/mappers.py b/src/orcapod/core/operators/mappers.py index fa89ec4a5..0a8d684b7 100644 --- a/src/orcapod/core/operators/mappers.py +++ b/src/orcapod/core/operators/mappers.py @@ -94,6 +94,7 @@ class MapData(UnaryOperator): # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__( @@ -371,6 +372,7 @@ class MapTags(UnaryOperator): # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__( @@ -667,6 +669,7 @@ class MapColumns(UnaryOperator): # Provisional: its identity is not frozen with data context v1 (ITL-1279). # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True PROVISIONAL: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f829d44a5..6179a5066 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -5,6 +5,7 @@ import logging from abc import abstractmethod from collections.abc import ( + Generator, AsyncIterator, Collection, Iterable, @@ -12,6 +13,7 @@ Mapping, Sequence, ) +from contextlib import closing from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, cast @@ -43,6 +45,8 @@ from orcapod.utils.provisional import note_provisional_use, provisional_class_name from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( + batch_streams_of, + reads_in_batches, ZERO_ROW_INPUT_COLUMNS, StreamBase, check_head_size, @@ -53,6 +57,8 @@ row_built_columns, ) from orcapod.core.streams.view import ( + RUN_VIEW_COMPLETE_ROWS, + BoundedStreamView, STALE_NOTE, default_note, ViewStatus, @@ -117,6 +123,16 @@ class StaticOutputOperatorPod(TraceableBase): (``async_execute_batches``); every other operator needs all of an input first. """ + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = False + """Whether ``static_process`` over consecutive batches of an input gives, put + together, exactly its result over the whole input: rows, order, types, nullability. + + Stricter than ``ROW_BY_ROW``: no type or nullable flag of the result follows the + values (``Pick`` and ``Index`` build their result from rows, so theirs do). Read + from the class itself, never inherited: a subclass that changes the operator + declares it again. ``run()`` of a stream uses it (ITL-1464). + """ + OUTPUT_SCHEMA_IS_INPUT_SCHEMA: ClassVar[bool] = False """Whether the output has exactly its single input's columns and Arrow types. @@ -1832,6 +1848,9 @@ def __init__( # that this one changed (ITL-1083). self._kept_states: tuple[tuple[str, object], ...] | None = None self._reset_generation: int = 0 + # The window of the last large ``run()`` whose rows were not kept, with what + # its inputs were then (ITL-1464); shown by ``head`` only. + self._run_window: tuple[BoundedStreamView, tuple[object, ...]] | None = None def content_hash(self, hasher=None) -> ContentHash: """The stream's content hash; notes the use of a provisional operator. @@ -1887,6 +1906,7 @@ def clear_cache(self) -> None: self._cached_stream = None self._cached_time = None self._kept_states = None + self._run_window = None self._reset_generation += 1 def _typed_zero_row_table(self) -> pa.Table | None: @@ -2033,6 +2053,96 @@ def _refresh(self) -> None: self._cached_time = datetime.now(timezone.utc) self._kept_states = kept_states + def _reads_in_batches(self) -> bool: + """Whether the operator is applied batch by batch, over an input read so.""" + return ( + reads_as_its_class(self, DynamicPodStream) + and type(self._pod).__dict__.get("BATCHES_GIVE_THE_WHOLE") is True + and len(self._upstreams) == 1 + and reads_in_batches(self._upstreams[0]) + ) + + def _batch_streams_of_rows(self) -> Generator[StreamProtocol, None, None]: + """This stream's rows, in order, as one stream per batch (``run()``, ITL-1464). + + Each batch of the input goes through ``static_process``, the one sync body. A + result of at most ``RUN_VIEW_COMPLETE_ROWS`` rows is kept, as a read keeps it; + a larger one is not. A current kept result is given as it is. + """ + self._pod._note_provisional_identity_use() + self._update_cache_status() + if self._cached_stream is not None and self._cached_time is not None: + if reads_in_batches(self._cached_stream): + # The operator handed its input on: read as that input is. + yield from batch_streams_of(self._cached_stream) + else: + yield self._cached_stream + return + kept_states = _upstream_states(self._upstreams) + kept: list[StreamProtocol] | None = [] + rows = 0 + handed_on = True + with closing(batch_streams_of(self._upstreams[0])) as batches: + for batch in batches: + try: + result = self._pod.static_process(batch) + except Exception: + # A read of the whole input raises before the operator runs: an + # error further on in the input comes first, as it did there. + for _ in batches: + pass + raise + handed_on = handed_on and result is batch + rows += result.as_table().num_rows + if kept is not None: + kept.append(result) + if rows > RUN_VIEW_COMPLETE_ROWS: + kept = None + yield result + if kept: + self._cached_stream = ( + # Its input unchanged, as a read keeps it: reads nothing. + self._pod.static_process(*self._upstreams) + if handed_on + else joined_batches(kept) + ) + self._cached_time = datetime.now(timezone.utc) + self._kept_states = kept_states + self._run_window = None + + def run(self) -> StreamView: + """Compute every row and return a ``StreamView`` (``StreamBase.run``). + + Over a source that reads its rows on demand, through operators applied batch by + batch, a result of more than ``RUN_VIEW_COMPLETE_ROWS`` rows is not held: the + view is bounded (``BoundedStreamView``), ``head`` then shows its first rows, + and ``as_table()`` reads and applies the operators again. + """ + # Noted before the rows are read, so a change made meanwhile is seen. + _ = self.last_modified + state = (*_upstream_states(self._upstreams), self._pod.last_modified) + view = super().run() + if isinstance(view, BoundedStreamView): + self._run_window = (view, state) + return view + + def _window_head(self, n: int, config: ColumnConfig) -> StreamView | None: + """The first rows of the last large ``run()``, or ``None`` when there are none + to show: no such run, changed inputs, more rows or other columns asked for.""" + if self._run_window is None: + return None + view, state = self._run_window + if (*_upstream_states(self._upstreams), self._pod.last_modified) != state: + self._run_window = None + return None + if ( + n > view.window_rows + or dataclasses.replace(config, sort_by_tags=False) != ColumnConfig() + ): + return None + head = view.head(n) + return head.sort_by_tags() if config.sort_by_tags else head + def as_table( self, *, @@ -2089,6 +2199,8 @@ def head( view = head_of( self._cached_stream.head(n, columns=config), self, origin="computed" ) + elif (window := self._window_head(n, config)) is not None: + view = window else: matching = self._matching_head(n, config) # A view of no rows is falsy (``StreamView.__len__``): compared to None. @@ -2156,6 +2268,32 @@ def __repr__(self) -> str: ) +def joined_batches(batches: Sequence[StreamProtocol]) -> StreamProtocol: + """Put the batches of one operator's result together as the result itself. + + Args: + batches: The results of consecutive batches of the input, in order; at least + one, all with the same columns and types. + + Returns: + A stream over all their rows, every column group included. + """ + first = batches[0] + return ArrowTableStream( + pa.concat_tables( + [ + batch.as_table( + columns={"source": True, "system_tags": True, "context": True} + ) + for batch in batches + ] + ), + tag_columns=first.keys()[0], + data_tags=stream_data_tags(first), + data_context=first.data_context_key, + ) + + def _with_explain_line(view: StreamView, stream: StreamProtocol) -> StreamView: """Return ``view`` with the one-line split of ``explain()`` added to its header, for a ``Filter`` directly over a source (ITL-1402); any other view unchanged.""" diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 6312a677f..316ac347d 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -44,6 +44,7 @@ import os from collections.abc import AsyncIterator, Collection, Generator, Iterator, Mapping from concurrent.futures import ThreadPoolExecutor +from contextlib import closing from threading import Lock from types import TracebackType from typing import Any, ClassVar, NamedTuple, TYPE_CHECKING @@ -62,7 +63,7 @@ row_identifiers, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream -from orcapod.core.streams.base import check_head_size +from orcapod.core.streams.base import check_head_size, reads_as_its_class from orcapod.core.streams.view import ViewStatus, StreamView from orcapod.databases.spiraldb_connector import ( SpiralDBConnector, @@ -79,7 +80,11 @@ if TYPE_CHECKING: from orcapod import contexts from orcapod.config import OrcapodConfig - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import ( + DataProtocol, + StreamProtocol, + TagProtocol, + ) DEFAULT_MAX_ROWS = 100_000 DEFAULT_BATCH_ROWS = 8_192 @@ -1122,11 +1127,33 @@ def head( ), ) + @override + def _reads_in_batches(self) -> bool: + return reads_as_its_class(self, SpiralDBTableSource) + + @override + def _batch_streams_of_rows(self) -> Generator[StreamProtocol, None, None]: + """One scan of the table, each batch shaped as ``as_table()`` shapes the whole + (``run()``, ITL-1464).""" + with closing(self._batch_streams()) as streams: + for stream in streams: + yield ArrowTableStream( + self._whole_table( + iter([stream]), + columns={"source": True, "system_tags": True, "context": True}, + all_info=False, + ), + tag_columns=self._tag_columns, + data_tags=self._data_tags, + data_context=self.data_context_key, + ) + def run(self) -> StreamView: - """Read the whole table into memory and return a ``StreamView`` of every row. + """Read every row the source reads and return a ``StreamView`` of them. - Does what ``as_table()`` does: one scan of every row the source reads (``where``, - ``limit``, ``max_rows`` and the pinned version applied), held in memory. The + One scan (``where``, ``limit``, ``max_rows`` and the pinned version applied), + read in batches: a table of more than ``RUN_VIEW_COMPLETE_ROWS`` rows gives a + bounded view (``BoundedStreamView``) and is not held. The source holds no rows, so every call scans again. ``head(n)`` and the notebook preview are the bounded read: they read only the first ``n`` rows. """ diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 9f8b731f7..c3296bec4 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -9,12 +9,13 @@ AsyncIterator, Callable, Collection, + Generator, Iterable, Iterator, Mapping, Sequence, ) -from contextlib import contextmanager +from contextlib import closing, contextmanager from contextvars import ContextVar from datetime import datetime from typing import TYPE_CHECKING, Any, cast @@ -28,8 +29,10 @@ from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, + BoundedStreamView, ViewStatus, StreamView, + WindowOfRows, default_note, preview_html, ) @@ -84,6 +87,22 @@ def reads_as_its_class(obj: object, cls: type) -> bool: return True +def reads_in_batches(stream: object) -> bool: + """Whether ``run()`` reads ``stream``'s rows batch by batch (ITL-1464). + + True for a source that reads its rows on demand and holds none, and for operators + applied batch by batch over one; decided by the kind of stream and its operators, + never by its rows. + """ + check = getattr(stream, "_reads_in_batches", None) + return bool(check()) if callable(check) else False + + +def batch_streams_of(stream: object) -> Generator[StreamProtocol, None, None]: + """The rows of a stream that ``reads_in_batches``, in order, one stream per batch.""" + return cast("StreamBase", stream)._batch_streams_of_rows() # pyright: ignore[reportPrivateUsage] # shared by the stream kinds + + def system_tags_as_rows_give(table: pa.Table) -> bool: """Whether every system-tag column is what the row rebuild gives: non-null text. @@ -1591,11 +1610,16 @@ def run(self) -> StreamView: The one way to compute any stream outside a job (developer, November 13, 2026, ITL-1081): ``head()`` and the notebook preview never compute a row (see - ``head``). ``run()`` does - exactly the work ``as_table()`` does, through the same code path and cache, so - a stream already computed is not computed again, and one whose inputs changed is - computed again. The view holds every row with the default column configuration; - its ``head``, ``tail`` and ``sort_by_tags`` choose what is shown. For other + ``head``). ``run()`` computes every row, in the order of ``as_table()``, with + every effect, and promises nothing about how the rows are produced or held + (developer, November 24, 2026, ITL-1464). A stream that keeps its computed rows + is not computed again, and one whose inputs changed is computed again. The view + has the default column configuration; + its ``head``, ``tail`` and ``sort_by_tags`` choose what is shown. The view holds + every row, except over a source that reads its rows on demand + (``reads_in_batches``): its rows, and those of operators applied batch by batch + over it, are read in batches, and a result of more than + ``RUN_VIEW_COMPLETE_ROWS`` rows gives a ``BoundedStreamView``. For other column groups, use ``as_table(columns=...)`` or ``head(columns=...)`` after ``run()``. On a stream that keeps its rows (a pod's or operator's output stream, a job node, a job's side-effect node included, an in-memory source) they read the @@ -1605,10 +1629,36 @@ def run(self) -> StreamView: Returns: A ``StreamView`` of all the rows ``as_table()`` returns, with status - ``ROWS``. + ``ROWS``; bounded as said above. """ + if self._reads_in_batches(): + view = self._run_in_batches() + if view is not None: + return view return self._view_of_rows(self.as_table(), self._RUN_ORIGIN) + def _reads_in_batches(self) -> bool: + """See ``reads_in_batches``; a stream reads its rows whole unless it says.""" + return False + + def _batch_streams_of_rows(self) -> Generator[StreamProtocol, None, None]: + """See ``batch_streams_of``; asked only when ``_reads_in_batches``.""" + raise NotImplementedError(f"{type(self).__name__} has no rows in batches") + + def _run_in_batches(self) -> StreamView | None: + """The ``run()`` view of rows read batch by batch; ``None`` for no batch.""" + rows = WindowOfRows() + with closing(self._batch_streams_of_rows()) as batches: + for batch in batches: + rows.add(batch.as_table()) + complete = rows.complete + if complete is not None: + return self._view_of_rows(complete, self._RUN_ORIGIN) + if rows.total == 0: + return None + first = self._view_of_rows(rows.first, self._RUN_ORIGIN) + return BoundedStreamView(first, rows.last, rows.total) + def _view_of_rows(self, table: "pa.Table", origin: str) -> StreamView: """Return the ``run()`` view of ``table``, every row of this stream.""" return StreamView.of_rows( diff --git a/src/orcapod/core/streams/view.py b/src/orcapod/core/streams/view.py index 699de9401..373c76216 100644 --- a/src/orcapod/core/streams/view.py +++ b/src/orcapod/core/streams/view.py @@ -20,6 +20,7 @@ import dataclasses import html import importlib +from collections import deque from collections.abc import Iterable, Sequence from dataclasses import dataclass from enum import Enum @@ -31,6 +32,7 @@ import pyarrow.compute as pc from typing_extensions import override +from orcapod.errors import BoundedViewError from orcapod.system_constants import constants @@ -112,6 +114,12 @@ def default_note(status: ViewStatus) -> str: # A view nobody cut to n rows (the view ``run()`` returns, or a sort of it) shows at most # this many rows: the first and the last half, with Polars' ellipsis row between. _DISPLAY_ROWS = 10 +# A ``run()`` that reads its rows batch by batch keeps every row of a result of at most +# ``RUN_VIEW_COMPLETE_ROWS`` rows; of a larger one, the view has the first and the last +# ``RUN_VIEW_WINDOW_ROWS`` rows (ITL-1464). Counted in rows, so equal data is always +# treated alike, however its batches were cut. +RUN_VIEW_COMPLETE_ROWS = 50_000 +RUN_VIEW_WINDOW_ROWS = 1_000 _MAX_TEXT = 80 _TEXT_START = 56 _TEXT_END = 20 @@ -603,6 +611,10 @@ def _display_frame(self, text: bool = False) -> pl.DataFrame: names = list(table.column_names) return pl.DataFrame(pa.table(columns, names=names)) + def _with_row_count(self, rendered: str) -> str: + """Return Polars' rendering of the display frame, which names its row count.""" + return rendered + def _displays_every_row(self) -> bool: """Whether the display shows every row: a view cut to ``n`` rows, or a short one.""" return self.display_all_rows or self.table.num_rows <= _DISPLAY_ROWS @@ -625,7 +637,7 @@ def _repr_html_(self) -> str: if self.table.num_columns: # Polars shortens strings to its own default length; show up to _MAX_TEXT. with pl.Config(fmt_str_lengths=_MAX_TEXT, tbl_rows=self._display_rows()): - frame_html = self._display_frame()._repr_html_() + frame_html = self._with_row_count(self._display_frame()._repr_html_()) columns = self._display_columns() names = _HeaderNames() names.feed(frame_html) @@ -654,7 +666,7 @@ def __str__(self) -> str: if self.table.num_columns: with pl.Config(fmt_str_lengths=_MAX_TEXT, tbl_rows=self._display_rows()): frame = self._display_frame(text=True) - frame_text = str(frame) + frame_text = self._with_row_count(str(frame)) columns = self._display_columns() rendered = _rendered_columns(_text_header_cells(frame_text), frame.columns) if rendered is not None: @@ -679,6 +691,230 @@ def __repr__(self) -> str: ) +@dataclass(frozen=True, repr=False) +class _EndsView(StreamView): + """The first and last rows of a longer view, displayed as that view is. + + ``table`` holds one row more than a long view shows, so Polars renders its ellipsis. + + Attributes: + shown_total: The row count of the whole view, named by the display. + """ + + shown_total: int = 0 + + @override + def _with_row_count(self, rendered: str) -> str: + # Polars names the frame's shape before anything else it renders. + return rendered.replace( + f"shape: ({self.table.num_rows:_}, ", f"shape: ({self.shown_total:_}, ", 1 + ) + + +class BoundedStreamView(StreamView): + """The view of a ``run()`` whose rows are not held (ITL-1464). + + It has the first and the last ``window_rows`` rows, the row count and the columns. + It is displayed as a view holding every row is. ``head(n)`` and ``tail(n)`` within + the window give the same views such a view gives. What needs rows it does not hold + (``table``, ``as_table()``, ``as_polars_df()``, ``sort_by_tags()``, a longer + ``head`` or ``tail``) raises ``BoundedViewError``, which names the stream's own + method: a part is never given as the whole, and a view never reads or computes. + + Attributes: + window_rows: The rows held at each end. + """ + + def __init__( # pyright: ignore[reportMissingSuperCall] # the parent's would set ``table`` + self, first: StreamView, last: pa.Table, total_rows: int + ) -> None: + """Make the view. + + Args: + first: A view of the first rows, named as the stream's view is named. + last: The last rows, as many as ``first`` has. + total_rows: The row count of the whole. + """ + # ``table`` is deliberately not set: reading it reaches ``__getattr__``. + for field in dataclasses.fields(StreamView): + if field.name != "table": + object.__setattr__(self, field.name, getattr(first, field.name)) + object.__setattr__(self, "total_rows", total_rows) + object.__setattr__( + self, "_first", dataclasses.replace(first, total_rows=total_rows) + ) + object.__setattr__(self, "_last", last) + + def __getattr__(self, name: str) -> Any: + if name == "table": + raise self._refused("its table") + raise AttributeError(f"{type(self).__name__!r} has no attribute {name!r}") + + def _refused(self, what: str) -> BoundedViewError: + """Return the error for ``what``, which needs rows the view does not hold.""" + return BoundedViewError( + f"{what} needs every row, and this view of {self._total():,} rows holds only " + f"the first and the last {self.window_rows:,}: run() does not keep a result " + f"of more than {RUN_VIEW_COMPLETE_ROWS:,} rows read in batches. Ask the " + "stream for its rows: stream.as_table(), stream.as_polars_df() or iteration " + "(stream.as_table(columns={'sort_by_tags': True}) sorts them)." + ) + + def _total(self) -> int: + return cast(int, self.total_rows) + + def _held(self) -> tuple[StreamView, pa.Table]: + values = vars(self) + return cast("StreamView", values["_first"]), cast(pa.Table, values["_last"]) + + @property + def window_rows(self) -> int: + """The rows held at each end.""" + return self._held()[1].num_rows + + @override + def __len__(self) -> int: + return self._total() + + @override + def __eq__(self, other: object) -> bool: + return self is other + + @override + def __hash__(self) -> int: + return id(self) + + @override + def as_table(self) -> pa.Table: + raise self._refused("as_table()") + + @override + def as_polars_df(self) -> pl.DataFrame: + raise self._refused("as_polars_df()") + + @override + def sort_by_tags(self) -> StreamView: + # A view with no tag column is returned as it is, as every view is. + if not self.tag_columns: + return self + raise self._refused("sort_by_tags()") + + @override + def head(self, n: int = 10) -> StreamView: + _check_row_count(n) + if n > self.window_rows: + raise self._refused(f"head({n})") + return dataclasses.replace(self._held()[0].head(n), display_all_rows=True) + + @override + def tail(self, n: int = 10) -> StreamView: + _check_row_count(n) + if n > self.window_rows: + raise self._refused(f"tail({n})") + first, last = self._held() + whole = dataclasses.replace( + first, table=last, start=self._total() - last.num_rows + ) + return whole.tail(n) + + @override + def for_stream( + self, stream: Any, *, origin: str | None = None, note: str | None = None + ) -> StreamView: + first, last = self._held() + return BoundedStreamView( + first.for_stream(stream, origin=origin, note=note), last, self._total() + ) + + def _ends(self) -> _EndsView: + """The rows the display shows, worded and counted as the whole.""" + first, last = self._held() + half = _DISPLAY_ROWS // 2 + values = { + f.name: getattr(first, f.name) for f in dataclasses.fields(StreamView) + } + values["table"] = pa.concat_tables( + [first.table.slice(0, half + 1), last.slice(last.num_rows - half)] + ) + values["description"] = first._describe_rows(self._total()) + values["display_all_rows"] = False + return _EndsView(**values, shown_total=self._total()) + + @override + def header(self) -> str: + return self._ends().header() + + @override + def _repr_html_(self) -> str: + return self._ends()._repr_html_() + + @override + def __str__(self) -> str: + return str(self._ends()) + + @override + def __repr__(self) -> str: + return ( + f"StreamView({self.kind}[{self.label}], status={self.status.value}, " + f"rows={self._total()})" + ) + + +class WindowOfRows: + """Collects the tables of a stream's rows, batch by batch: all rows of a result of + at most ``RUN_VIEW_COMPLETE_ROWS`` rows, else the first and the last + ``RUN_VIEW_WINDOW_ROWS``. The window is copied, so no batch stays alive behind it. + """ + + def __init__(self) -> None: + self.total: int = 0 + self._all: list[pa.Table] | None = [] + self._first: list[pa.Table] = [] + self._last: deque[pa.Table] = deque() + + def add(self, table: pa.Table) -> None: + """Take the next rows. + + Args: + table: The rows; every table of a stream has the same schema. + """ + missing = RUN_VIEW_WINDOW_ROWS - min(self.total, RUN_VIEW_WINDOW_ROWS) + if missing and table.num_rows: + self._first.append(_copied(table.slice(0, missing))) + if table.num_rows: + end = max(table.num_rows - RUN_VIEW_WINDOW_ROWS, 0) + self._last.append(_copied(table.slice(end))) + held = sum(part.num_rows for part in self._last) + while held - self._last[0].num_rows >= RUN_VIEW_WINDOW_ROWS: + held -= self._last.popleft().num_rows + self.total += table.num_rows + if self._all is not None: + self._all.append(table) + if self.total > RUN_VIEW_COMPLETE_ROWS: + self._all = None + + @property + def complete(self) -> pa.Table | None: + """Every row, or ``None`` when there are too many (or nothing was taken).""" + return pa.concat_tables(self._all) if self._all else None + + @property + def first(self) -> pa.Table: + """The first rows.""" + return pa.concat_tables(self._first) + + @property + def last(self) -> pa.Table: + """The last rows.""" + rows = pa.concat_tables(list(self._last)) + return rows.slice(max(rows.num_rows - RUN_VIEW_WINDOW_ROWS, 0)) + + +def _copied(table: pa.Table) -> pa.Table: + """Return ``table``'s rows in buffers of their own, every value bit for bit.""" + return table.take(pa.array(range(table.num_rows), pa.int64())) + + def _mark_columns( frame_html: str, columns: Sequence[tuple[str, str]], diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 7720e7980..492f411ad 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -1267,6 +1267,14 @@ def __str__(self) -> str: ) +class BoundedViewError(ValueError): + """What was asked of a view needs rows the view does not hold (ITL-1464). + + Raised by the view of a ``run()`` whose result is too large to be kept; ask the + stream itself for its rows. + """ + + class ProvenanceInconsistencyError(ValueError): """What a job holds and what its databases store disagree about a row's provenance. diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index c8c72abd6..ad079e67e 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -280,7 +280,9 @@ def as_table( def run(self) -> "StreamViewProtocol": """Compute the whole stream and return a view of all its rows. - Does the work ``as_table()`` does, through the same path and cache; a job node + Every row is computed, with every effect; nothing is promised about how the + rows are produced or held (ITL-1464), and the view of a large result may hold + only its ends (``BoundedStreamView``). A job node runs as it does in a job. Every stream has it, with no argument: it is the one way to compute a stream outside a job (ITL-1081). ``head()`` and the notebook preview never compute a row. diff --git a/tests/test_core/streams/test_bounded_run_view.py b/tests/test_core/streams/test_bounded_run_view.py new file mode 100644 index 000000000..c6462d038 --- /dev/null +++ b/tests/test_core/streams/test_bounded_run_view.py @@ -0,0 +1,471 @@ +"""``run()`` over a source read on demand: batches, and a bounded view (ITL-1464). + +The differential compares the batch-wise result with the result of the operators over the +whole input (``as_table()`` of a stream that was never run), for every column group. Runs +against the disk-backed fake of the SpiralDB client. +""" + +from __future__ import annotations + +import pickle +import uuid +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import polars as pl +import pyarrow as pa +import pytest + +from orcapod import col, function_pod +from orcapod.core.operators import DropNulls, MapData +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams import base, view as view_module +from orcapod.core.streams.view import BoundedStreamView, StreamView, WindowOfRows +from orcapod.errors import BoundedViewError, RowIdentifierError, SourceTooLargeError +from orcapod.sources import SpiralDBTableSource +from orcapod.streams import ViewStatus +from tests.test_databases import fake_spiral_sdk + +_PROJECT = "sample" +_KEYS = pa.schema( + [pa.field("subject", pa.string()), pa.field("timestamp", pa.uint64())] +) + + +def _rows(n: int) -> pa.Table: + """``n`` rows: two keys, data with nulls, strings longer than the display shows.""" + return pa.table( + { + "subject": [f"m{i * 3 // max(n, 1)}" for i in range(n)], + "timestamp": pa.array(range(n), pa.uint64()), + "amplitude": pa.array( + [None if i % 7 == 3 else i + 0.5 for i in range(n)], pa.float32() + ), + "note": [f"{i:04d}" + "a" * (200 if i % 5 == 0 else 3) for i in range(n)], + "trace": pa.array( + [[float(i)] * (i % 4) for i in range(n)], pa.list_(pa.float64()) + ), + "flag": [i % 2 == 0 for i in range(n)], + } + ) + + +@pytest.fixture() +def source(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """Make a source of ``n`` rows (default 40), scanned 6 rows per batch.""" + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 6) + with fake_spiral_sdk.install(tmp_path / "spiral"): + + def make(n: int = 40, **kwargs: Any) -> SpiralDBTableSource: + name = f"event_{n}" + project = fake_spiral_sdk.ExternalProject(_PROJECT) + try: + return SpiralDBTableSource(_PROJECT, name, **kwargs) + except Exception: # noqa: BLE001 - not made yet + project.create_table(f"default.{name}", key_schema=_KEYS).write( + _rows(n) + ) + return SpiralDBTableSource(_PROJECT, name, **kwargs) + + yield make + + +@pytest.fixture() +def small_limits(monkeypatch: pytest.MonkeyPatch) -> None: + """A result of more than 20 rows is bounded, with a window of 12 rows.""" + monkeypatch.setattr(view_module, "RUN_VIEW_COMPLETE_ROWS", 20) + monkeypatch.setattr(view_module, "RUN_VIEW_WINDOW_ROWS", 12) + import orcapod.core.operators.static_output_pod as pods + + monkeypatch.setattr(pods, "RUN_VIEW_COMPLETE_ROWS", 20) + + +CHAINS: dict[str, Callable[[Any], Any]] = { + "source": lambda s: s, + "drop_nulls": lambda s: s.drop_nulls(["amplitude", "note"]), + "drop_nulls_all": lambda s: s.drop_nulls(), + "filter": lambda s: s.filter(col("amplitude") >= 5.0, flag=True), + "filter_none_left": lambda s: s.filter(col("amplitude") >= 1e6), + "map_data": lambda s: s.map_data({"note": "text", "amplitude": "uv"}), + "map_tags": lambda s: s.map_tags({"timestamp": "t", "subject": "who"}), + "map_columns": lambda s: s.map_columns({"timestamp": "t", "note": "text"}), + "add_tags": lambda s: s.add_tags(cohort="A", run=3), + "select_tags": lambda s: s.select_tag_columns(["timestamp"]), + "select_data": lambda s: s.select_data_columns(["note", "amplitude"]), + "select_data_pass_through": lambda s: s.select_data_columns(list(s.keys()[1])), + "drop_tags": lambda s: s.drop_tag_columns(["subject", "timestamp"]), + "drop_data": lambda s: s.drop_data_columns(["trace", "note"]), + "select": lambda s: s.select_columns("timestamp", "note", "flag"), + "drop": lambda s: s.drop_columns("subject", "trace"), + "several": lambda s: ( + s.drop_nulls(["amplitude"]) + .filter(flag=True) + .map_data({"note": "text"}) + .add_tags(cohort="A") + .drop_columns("trace") + ), +} + +CONFIGS: list[dict[str, Any]] = [ + {}, + {"source": True, "system_tags": True}, + {"context": True}, + {"content_hash": True}, + {"sort_by_tags": True}, + {"all_info": True}, +] + + +def _same(left: pa.Table, right: pa.Table) -> None: + assert left.schema.equals(right.schema, check_metadata=True) + assert left.equals(right) + + +@pytest.mark.parametrize("tag_only", [True, False, ["timestamp"]]) +@pytest.mark.parametrize("batch_rows", [1, 5, 8192]) +@pytest.mark.parametrize("name", list(CHAINS)) +def test_the_batches_give_the_whole( + source: Any, name: str, batch_rows: int, tag_only: Any +) -> None: + """Rows, order, types, nullability, tokens, record ids and row hashes are those of + the operators over the whole input; the kept result is the one a read keeps.""" + + def stream() -> Any: + if name == "map_columns" and tag_only is not True: + pytest.skip("MapColumns takes no data-tags yet (ITL-1022)") + return CHAINS[name](source(batch_rows=batch_rows, tag_only_columns=tag_only)) + + whole = stream() + ran = stream() + assert base.reads_in_batches(ran) + view = ran.run() + assert type(view) is StreamView + _same(view.as_table(), whole.as_table()) + for config in CONFIGS: + _same(ran.as_table(columns=config), whole.as_table(columns=config)) + assert ran.keys() == whole.keys() + assert ran.content_hash() == whole.content_hash() + assert [(t.as_dict(all_info=True), d.content_hash()) for t, d in ran] == [ + (t.as_dict(all_info=True), d.content_hash()) for t, d in whole + ] + + +@pytest.mark.parametrize("name", list(CHAINS)) +def test_a_small_run_shows_what_the_whole_shows(source: Any, name: str) -> None: + """Header, text and HTML of a small result are those of a view of the whole.""" + ran = CHAINS[name](source(tag_only_columns=True)) + view = ran.run() + whole = CHAINS[name](source(tag_only_columns=True)) + expected = whole._view_of_rows(whole.as_table(), whole._RUN_ORIGIN) # pyright: ignore[reportPrivateUsage] # the view as it was built before + assert view.header() == expected.header() + assert str(view) == str(expected) + assert view._repr_html_() == expected._repr_html_() + assert ran.head(3).header() == whole.head(3).header() + assert ran.head(3).table.equals(whole.head(3).table) + assert ran._repr_html_() == whole._repr_html_() + + +def test_a_run_of_at_most_the_limit_is_kept_and_reads_once(source: Any) -> None: + """A small result is kept at every step of the chain: no second scan.""" + first = source().drop_nulls(["amplitude"]) + out = first.map_data({"note": "text"}) + fake_spiral_sdk.scan_log.clear() + view = out.run() + scans = len(fake_spiral_sdk.scan_log) + assert out.as_table().equals(view.as_table()) + assert out.run().as_table().equals(view.as_table()) + assert first.head(2).status is ViewStatus.ROWS + assert len(first.as_table()) == len(view) + assert len(fake_spiral_sdk.scan_log) == scans + + +# --------------------------------------------------------------------------- +# The bounded view +# --------------------------------------------------------------------------- + + +def _bounded_and_complete(stream: Any) -> tuple[BoundedStreamView, StreamView]: + view = stream.run() + assert isinstance(view, BoundedStreamView) + table = stream.as_table() + return view, stream._view_of_rows(table, stream._RUN_ORIGIN) # the complete view + + +@pytest.mark.usefixtures("small_limits") +@pytest.mark.parametrize("n", [33, 40, 1200]) +@pytest.mark.parametrize("name", ["source", "map_data", "drop_nulls", "several"]) +def test_a_bounded_view_is_displayed_as_the_complete_one( + source: Any, name: str, n: int +) -> None: + """Header, legend, shape line and rows, in text and HTML.""" + chain = CHAINS[name] + if name == "several" and n < 100: + pytest.skip("leaves fewer rows than the limit") + view, complete = _bounded_and_complete(chain(source(n))) + assert view.header() == complete.header() + assert str(view) == str(complete) + assert view._repr_html_() == complete._repr_html_() + assert repr(view) == repr(complete) + assert view.total_rows == complete.total_rows == len(view) == len(complete) + assert view.status is complete.status + assert view.tag_columns == complete.tag_columns + assert view.data_tag_columns == complete.data_tag_columns + + +@pytest.mark.usefixtures("small_limits") +def test_head_and_tail_within_the_window_are_the_complete_views(source: Any) -> None: + """Rows and header; and the cuts and sorts of those.""" + view, complete = _bounded_and_complete(source().map_data({"note": "text"})) + for n in (0, 1, 5, 12): + for cut in ("head", "tail"): + mine, theirs = getattr(view, cut)(n), getattr(complete, cut)(n) + assert type(mine) is StreamView + _same(mine.as_table(), theirs.as_table()) + assert mine.header() == theirs.header() + assert str(mine) == str(theirs) + assert mine.sort_by_tags().header() == theirs.sort_by_tags().header() + assert view.head(8).tail(3).header() == complete.head(8).tail(3).header() + assert view.tail(8).head(3).header() == complete.tail(8).head(3).header() + + +@pytest.mark.usefixtures("small_limits") +@pytest.mark.parametrize( + "ask", + [ + lambda v: v.as_table(), + lambda v: v.as_polars_df(), + lambda v: v.table, + lambda v: v.sort_by_tags(), + lambda v: v.head(13), + lambda v: v.tail(13), + ], + ids=["as_table", "as_polars_df", "table", "sort_by_tags", "head", "tail"], +) +def test_what_needs_rows_not_held_is_refused( + source: Any, ask: Callable[[Any], Any] +) -> None: + """A part is never given as the whole; the error names the stream's method.""" + view = source().run() + with pytest.raises(BoundedViewError, match=r"stream\.as_table\(\)"): + ask(view) + + +@pytest.mark.usefixtures("small_limits") +def test_a_bounded_view_checks_the_number_of_rows(source: Any) -> None: + """As a complete view does, before the window.""" + view = source().run() + with pytest.raises(TypeError): + view.head(True) + with pytest.raises(ValueError, match="negative"): + view.tail(-1) + with pytest.raises(AttributeError): + _ = view.no_such_member + assert len(pickle.loads(pickle.dumps(view))) == len(view) + + +@pytest.mark.usefixtures("small_limits") +@pytest.mark.parametrize("n", [19, 20, 21]) +def test_the_limit_is_counted_in_rows_whatever_the_batches(source: Any, n: int) -> None: + """Equal data gives the same kind of view: however cut, run again, or already read.""" + for batch_rows in (1, 7, 8192): + stream = source(n, batch_rows=batch_rows).map_data({"note": "text"}) + bounded = n > 20 + assert isinstance(stream.run(), BoundedStreamView) is bounded + assert isinstance(stream.run(), BoundedStreamView) is bounded + _ = stream.as_table() # the stream now holds every row + assert isinstance(stream.run(), BoundedStreamView) is bounded + assert ( + isinstance(source(n, batch_rows=batch_rows).run(), BoundedStreamView) + is bounded + ) + + +@pytest.mark.usefixtures("small_limits") +def test_head_after_a_large_run_shows_the_window(source: Any) -> None: + """Default columns, within the window, while the inputs are unchanged.""" + stream = source().drop_nulls(["amplitude"]) + view = stream.run() + fake_spiral_sdk.scan_log.clear() + assert stream.head(3).table.equals(view.head(3).table) + assert stream.head(3).header() == view.head(3).header() + assert "first 10 of 34 computed rows, then sorted by tags" in stream._repr_html_() + assert stream.head(3, columns={"source": True}).status is ViewStatus.NOT_COMPUTED + assert stream.head(13).status is ViewStatus.NOT_COMPUTED + assert fake_spiral_sdk.scan_log == [] + stream.clear_cache() + assert stream.head(3).status is ViewStatus.NOT_COMPUTED + + +@pytest.mark.usefixtures("small_limits") +def test_head_after_the_source_moved_shows_no_old_rows(source: Any) -> None: + """The window is not shown once an input changed.""" + root = source() + stream = root.map_data({"note": "text"}) + _ = stream.run() + fake_spiral_sdk.ExternalProject(_PROJECT).table("default.event_40").write( + _rows(41).slice(40) + ) + assert root.check_for_new_data() + assert stream.head(3).status is ViewStatus.NOT_COMPUTED + assert len(stream.run()) == 41 + + +@pytest.mark.usefixtures("small_limits") +def test_reads_after_a_large_run_give_every_row(source: Any) -> None: + """``as_table()`` and iteration read again; a bounded run keeps no rows.""" + stream = CHAINS["several"](source(200)) + assert isinstance(stream.run(), BoundedStreamView) + whole = CHAINS["several"](source(200)) + _same(stream.as_table(), whole.as_table()) + assert len(list(stream)) == whole.as_table().num_rows + + +# --------------------------------------------------------------------------- +# Errors +# --------------------------------------------------------------------------- + + +class _Refusing(DropNulls): + """Reads its input, then raises when there are rows.""" + + BATCHES_GIVE_THE_WHOLE = True + + def unary_static_process(self, stream: Any) -> Any: + if stream.as_table().num_rows: + raise RuntimeError("the operator refused") + return super().unary_static_process(stream) + + +def test_max_rows_holds_for_the_whole_read(source: Any) -> None: + """The read is refused as ``as_table()`` refuses it; no view is returned.""" + for make in ( + lambda: source(max_rows=30), + lambda: source(max_rows=30, where={"flag": True}, limit=25), + ): + stream = make().map_data({"note": "text"}) + try: + expected: object = len(make().as_table()) + except SourceTooLargeError as error: + expected = str(error) + try: + found: object = len(stream.run()) + except SourceTooLargeError as error: + found = str(error) + assert found == expected + late = source(max_rows=10, where={"flag": True}) + with pytest.raises(SourceTooLargeError): + _ = late.drop_nulls().run() + assert len(late.drop_nulls().head()) == 0 + + +def test_a_late_source_error_is_raised_as_a_whole_read_raises_it( + source: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """Also before an operator's own error on an earlier batch.""" + root = source(batch_rows=6) + original = SpiralDBTableSource._key_tokens # pyright: ignore[reportPrivateUsage] # a failing row, late + + def failing(self: Any, table: pa.Table) -> list[str]: + if 30 in table.column("timestamp").to_pylist(): + raise RowIdentifierError("a null key, late") + return original(self, table) + + monkeypatch.setattr(SpiralDBTableSource, "_key_tokens", failing) + for stream in (root.map_data({"note": "text"}), _Refusing(["amplitude"])(root)): + with pytest.raises(RowIdentifierError, match="late"): + _ = stream.as_table() + with pytest.raises(RowIdentifierError, match="late"): + _ = stream.run() + assert stream.head().status is ViewStatus.NOT_COMPUTED + + +def test_an_operator_error_keeps_nothing(source: Any) -> None: + """The operator's error is raised, and nothing is shown after it.""" + stream = _Refusing(["amplitude"])(source()) + with pytest.raises(RuntimeError, match="refused"): + _ = stream.run() + assert stream.head().status is ViewStatus.NOT_COMPUTED + + +# --------------------------------------------------------------------------- +# What is not read in batches +# --------------------------------------------------------------------------- + + +class _Subclass(MapData): + """A subclass may change what an operator does: it declares batches itself.""" + + +def test_only_declared_operators_over_an_on_demand_source_are_batched( + source: Any, +) -> None: + """Everything else computes as before, and its view holds every row.""" + + @function_pod(output_keys="double") + def double(amplitude: float) -> float: + return 2 * amplitude + + root = source() + held = ArrowTableSource(_rows(40), tag_columns=["subject"]) + clean = root.drop_nulls(["amplitude"]) + for stream in ( + held, + held.drop_nulls(), + _Subclass({"note": "text"})(root), + clean.polars_filter(pl.col("flag")), + clean.group_by("subject"), + clean.batch(4), + clean.join(held.select_data_columns(["flag"]).map_data({"flag": "f"})), + double.pod(clean), + MapData({"double": "d"})(double.pod(clean)), + ): + assert not base.reads_in_batches(stream) + assert not isinstance(stream, SpiralDBTableSource) + assert "BATCHES_GIVE_THE_WHOLE" not in vars(_Subclass) + assert StaticOutputOperatorPod.BATCHES_GIVE_THE_WHOLE is False + + +# --------------------------------------------------------------------------- +# The window +# --------------------------------------------------------------------------- + + +def _column(kind: pa.DataType, rows: int) -> pa.Array[Any]: + if kind == pa.uuid(): + storage = pa.array([uuid.UUID(int=i).bytes for i in range(rows)], pa.binary(16)) + return pa.ExtensionArray.from_storage(pa.uuid(), storage) + return pa.array([None if i % 5 == 4 else i for i in range(rows)], pa.int64()).cast( + kind + ) + + +@pytest.mark.parametrize("cut", [1, 3, 8, 50]) +def test_the_window_is_the_first_and_last_rows( + monkeypatch: pytest.MonkeyPatch, cut: int +) -> None: + """Whatever the batches, for every kind of column; and it holds no batch.""" + monkeypatch.setattr(view_module, "RUN_VIEW_COMPLETE_ROWS", 20) + monkeypatch.setattr(view_module, "RUN_VIEW_WINDOW_ROWS", 8) + table = pa.table( + { + "i": _column(pa.int64(), 50), + "half": _column(pa.float32(), 50).cast(pa.float16()), + "text": _column(pa.large_string(), 50), + "uuid": _column(pa.uuid(), 50), + "decimal": _column(pa.decimal256(30, 2), 50), + "lists": pa.array([[i] * (i % 3) for i in range(50)]), + "structs": pa.array([{"a": i, "b": [str(i)]} for i in range(50)]), + "maps": pa.array( + [[(i, "x")] for i in range(50)], pa.map_(pa.int64(), pa.string()) + ), + } + ) + window = WindowOfRows() + for start in range(0, 50, cut): + window.add(table.slice(start, cut)) + assert window.total == 50 + assert window.complete is None + _same(window.first, table.slice(0, 8)) + _same(window.last, table.slice(42)) From a6027682cfb7575b6d8e0bd33d5fe5905e891482 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:33:12 -0800 Subject: [PATCH 11/81] 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 614e5f762ba57d0c63123b1297514ed78945e0e5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:36:31 -0800 Subject: [PATCH 12/81] perf(pipeline): keep async rows as Arrow chunks, not object pairs (ITL-1464) An async job kept every row three times as (Tag, Data) pairs: in the orchestrator's result collectors (never read by a job), in each operator job node's output list, and in each barrier operator's gathered input, plus the pairs an ArrowTableStream caches while a barrier sends its result. Rows are now kept as Arrow tables of at most 8,192 rows (RowChunks), which build exactly the table the row list built. Co-Authored-By: Claude Fable 5.2 --- changelog.d/ITL-1464.md | 7 + docs/dev/specs/itl-1464/measure.py | 14 +- src/orcapod/core/nodes/operator_node.py | 10 +- src/orcapod/core/operators/base.py | 24 +- src/orcapod/core/operators/batch.py | 10 +- .../core/operators/static_output_pod.py | 175 +++++++++++- .../core/streams/arrow_table_stream.py | 84 ++++-- src/orcapod/pipeline/async_orchestrator.py | 13 +- src/orcapod/pipeline/job.py | 10 +- tests/test_core/operators/test_row_chunks.py | 268 ++++++++++++++++++ 10 files changed, 557 insertions(+), 58 deletions(-) create mode 100644 tests/test_core/operators/test_row_chunks.py diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md index 8f42a6b57..ee40b64d5 100644 --- a/changelog.d/ITL-1464.md +++ b/changelog.d/ITL-1464.md @@ -5,3 +5,10 @@ source-info tokens of every row and column only to drop them. The rows and the table are the same; on a table of 2.2 million rows and 13 columns the read's peak memory falls from 10.8 GiB to 2.0 GiB (ITL-1464). +- An async job run keeps the rows a node passes on as Arrow tables of at most 8,192 rows, + not as one pair of objects per row: in an operator job node's output, in the input of an + operator that reads all of its input first (`PolarsFilter`, `GroupBy`, `MergeJoin`, + `Rejoin`, `Batch` without a size), and no longer at all in the orchestrator for a job + (which never read them). Results are unchanged. An async job of `drop_nulls`, `group_by`, + `map_data` and a function pod over 200,000 rows peaks at 4.8 GiB instead of 19.7 GiB + (ITL-1464). diff --git a/docs/dev/specs/itl-1464/measure.py b/docs/dev/specs/itl-1464/measure.py index 3674b1aa9..c5967bfd0 100644 --- a/docs/dev/specs/itl-1464/measure.py +++ b/docs/dev/specs/itl-1464/measure.py @@ -358,6 +358,14 @@ def step_job_run(store: Path) -> tuple[int, int, Any]: return _raw(GAZE).nbytes, 0, job +def step_job_run_async_unkept(store: Path) -> tuple[int, int, Any]: + from orcapod.pipeline import AsyncPipelineOrchestrator + + job = _job(store) + job.run(orchestrator=AsyncPipelineOrchestrator(), materialize_results=False) + return _raw(GAZE).nbytes, 0, job + + def step_job_run_async(store: Path) -> tuple[int, int, Any]: from orcapod.pipeline import AsyncPipelineOrchestrator @@ -393,6 +401,9 @@ def step(store: Path) -> tuple[int, int, Any]: _operator_chains()[chain]() if orchestrator == "async": job.run(orchestrator=AsyncPipelineOrchestrator()) + elif orchestrator == "async_unkept": + # The orchestrator keeps no node's rows for its result. + job.run(orchestrator=AsyncPipelineOrchestrator(), materialize_results=False) else: job.run() name = SPIKES if chain == "join" else GAZE @@ -405,7 +416,7 @@ def step(store: Path) -> tuple[int, int, Any]: **{ f"job_{chain}_{orchestrator}": _operator_job(chain, orchestrator) for chain in ("map_data", "drop_nulls", "polars_filter", "join", "group_by") - for orchestrator in ("sync", "async") + for orchestrator in ("sync", "async", "async_unkept") }, "raw_copy": step_raw_copy, "as_table": step_as_table, @@ -425,6 +436,7 @@ def step(store: Path) -> tuple[int, int, Any]: "function_pod": step_function_pod, "job_run": step_job_run, "job_run_async": step_job_run_async, + "job_run_async_unkept": step_job_run_async_unkept, } diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index b2134184a..9590c52cf 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -41,6 +41,7 @@ from orcapod.config import OrcapodConfig from orcapod.core.operators.static_output_pod import ( RowBuiltFormUnavailable, + RowChunks, StaticOutputOperatorPod, produced_stream, rows_on_read, @@ -2311,11 +2312,12 @@ async def async_execute( require_same_data_context( input_stream.data_context_key, self.data_context_key ) - collected: list[tuple[TagProtocol, DataProtocol]] = [] + # Kept as Arrow tables, not as a list of every pair (ITL-1464). + collected = RowChunks() async def forward() -> None: async for item in intermediate.reader: - collected.append(item) + collected.add(*item) await output.send(item) hashes = [s.pipeline_hash() for s in self._input_streams] @@ -2341,8 +2343,8 @@ async def forward() -> None: # does, and store it in LOG mode (sync DB write, post-hoc). A run # with no rows replaces an earlier run's output too: the node then # reads as a zero-row table. - if collected: - stream = StaticOutputOperatorPod._materialize_to_stream(collected) + if collected.num_rows: + stream = collected.output_stream() self._cached_output_stream = stream if should_store: self._store_output_stream(stream) diff --git a/src/orcapod/core/operators/base.py b/src/orcapod/core/operators/base.py index c0fd0c320..96b97ade3 100644 --- a/src/orcapod/core/operators/base.py +++ b/src/orcapod/core/operators/base.py @@ -12,7 +12,11 @@ from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.data_tags import data_tags_first from orcapod.core.operators.arrow_keys import part_without_rule -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.operators.static_output_pod import ( + StaticOutputOperatorPod, + collect_row_chunks, + rows_once, +) from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import ( ArgumentGroup, @@ -228,15 +232,15 @@ async def async_execute( f"input_pipeline_hashes length ({len(input_pipeline_hashes)}) " f"must match inputs length ({len(inputs)})" ) - rows = await inputs[0].collect() - if not rows: + rows = await collect_row_chunks(inputs[0]) + if not rows.num_rows: # No rows in, no rows out: an operator never synthesizes a row. # The typed empty stream the sync path returns needs a schema the # channel does not carry (ITL-858), so nothing is emitted (ITL-865). return - stream = self._materialize_input_stream(rows, input_pipeline_hashes[0]) + stream = rows.input_stream(input_pipeline_hashes[0]) result = self.static_process(stream) - for tag, data in result.iter_data(): + for tag, data in rows_once(result): await output.send((tag, data)) finally: await output.close() @@ -344,18 +348,18 @@ async def async_execute( ) left_hash, right_hash = input_pipeline_hashes left_rows, right_rows = await asyncio.gather( - inputs[0].collect(), inputs[1].collect() + collect_row_chunks(inputs[0]), collect_row_chunks(inputs[1]) ) - if not left_rows or not right_rows: + if not left_rows.num_rows or not right_rows.num_rows: # The one barrier binary operator, MergeJoin, is an inner join: an # input with no rows gives no rows, as on the sync path. The typed # empty stream needs a schema the channels do not carry (ITL-858), # so nothing is emitted (ITL-865). return - left_stream = self._materialize_input_stream(left_rows, left_hash) - right_stream = self._materialize_input_stream(right_rows, right_hash) + left_stream = left_rows.input_stream(left_hash) + right_stream = right_rows.input_stream(right_hash) result = self.static_process(left_stream, right_stream) - for tag, data in result.iter_data(): + for tag, data in rows_once(result): await output.send((tag, data)) finally: await output.close() diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index e7a1969f8..180892846 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -18,8 +18,10 @@ from orcapod.core.operators.base import UnaryOperator from orcapod.core.operators.static_output_pod import ( close_inputs, + collect_row_chunks, concatenate_batches, finish_operator, + rows_once, ) from orcapod.core.data_tags import stream_data_tags from orcapod.core.streams import ArrowTableStream @@ -278,11 +280,11 @@ async def async_execute( pipeline_hash = input_pipeline_hashes[0] if self.batch_size == 0: # Must collect all rows — barrier fallback - rows = await inputs[0].collect() - if rows: - stream = self._materialize_input_stream(rows, pipeline_hash) + rows = await collect_row_chunks(inputs[0]) + if rows.num_rows: + stream = rows.input_stream(pipeline_hash) result = self.unary_static_process(stream) - for tag, data in result.iter_data(): + for tag, data in rows_once(result): await output.send((tag, data)) return diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f829d44a5..e750afe03 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1078,18 +1078,18 @@ async def async_execute( f"input_pipeline_hashes length ({len(input_pipeline_hashes)}) " f"must match inputs length ({len(inputs)})" ) - all_rows = await asyncio.gather(*(ch.collect() for ch in inputs)) - if not all(all_rows): + all_rows = await asyncio.gather(*(collect_row_chunks(ch) for ch in inputs)) + if not all(rows.num_rows for rows in all_rows): # Every barrier operator that exists gives no rows when an input has # none. The typed empty stream the sync path returns needs a schema # the channels do not carry (ITL-858), so nothing is emitted (ITL-865). return streams = [ - self._materialize_input_stream(rows, pipeline_hash) + rows.input_stream(pipeline_hash) for rows, pipeline_hash in zip(all_rows, input_pipeline_hashes) ] result = self.static_process(*streams) - for tag, data in result.iter_data(): + for tag, data in rows_once(result): await output.send((tag, data)) finally: await output.close() @@ -1289,6 +1289,173 @@ async def _streams_of(inputs: Sequence[RecordBatchInput]) -> list[StreamProtocol # --------------------------------------------------------------------------- +ROW_CHUNK_ROWS = 8_192 +"""Rows per Arrow table that ``RowChunks`` keeps: arriving rows are held as objects only +until this many have arrived.""" + + +class RowChunks: + """Rows received one at a time, kept as Arrow tables, not as ``(Tag, Data)`` pairs. + + The async path hands rows on one by one, and a node that must keep what passed + (an operator job node its output, a barrier operator its input) kept every pair: + 18 to 110 KiB per row against a few KiB as Arrow data (ITL-1464). This keeps at most + ``ROW_CHUNK_ROWS`` pairs; every full chunk is built into two Arrow tables (tags + with system tags, data with source info) and the pairs are let go. + + What it builds is exactly what the row list built: ``row_table()`` equals + ``StaticOutputOperatorPod._rows_to_table(rows)`` over all the rows added, in + order (same columns, types, field flags and values; only the arrays' chunking + differs), because that table is a concatenation of one table per row, matched by + name to the first row's column order, and concatenation chunk by chunk gives the + same table. Rows whose columns disagree raise ``pyarrow.ArrowInvalid`` as there, + when their chunk is built or the chunks are joined; the message's table index is + then the row's place in its chunk, or the chunk's place. + + A chunk is the record batch an ITL-1347 channel carries, before the last step of + its row-built form (the source-info field flags, which need every row); a node + wired to record-batch channels receives such batches and needs no ``RowChunks``. + """ + + def __init__(self) -> None: + self._tag_chunks: list[pa.Table] = [] + self._data_chunks: list[pa.Table] = [] + self._context_chunks: list[pa.Array[Any]] = [] # pyright: ignore[reportExplicitAny] # any array + self._pending: list[tuple[TagProtocol, DataProtocol]] = [] + self._tag_keys: tuple[str, ...] = () + self._data_tags: tuple[str, ...] = () + self._first_context_key: str | None = None + self.num_rows: int = 0 + + def add(self, tag: TagProtocol, data: DataProtocol) -> None: + """Keep one row, after every row added before it.""" + if self.num_rows == 0: + self._tag_keys = tuple(tag.keys()) + self._data_tags = data_tag_names(tag.keys(), data.keys()) + self._first_context_key = data.data_context_key + self._pending.append((tag, data)) + self.num_rows += 1 + if len(self._pending) >= ROW_CHUNK_ROWS: + self._seal() + + def _seal(self) -> None: + """Build the pending rows into Arrow tables and let the pairs go.""" + from orcapod.utils import arrow_utils + + rows = self._pending + if not rows: + return + tag_tables = [tag.as_table(columns={"system_tags": True}) for tag, _ in rows] + data_tables = [data.as_table(columns={"source": True}) for _, data in rows] + if self._data_tags: + data_tables = [t.drop_columns(list(self._data_tags)) for t in data_tables] + # One chunk per column instead of one per row: the per-row arrays are what + # costs memory, the values are the same. + self._tag_chunks.append( + arrow_utils.concat_tables_by_name(tag_tables).combine_chunks() + ) + self._data_chunks.append( + arrow_utils.concat_tables_by_name(data_tables).combine_chunks() + ) + self._context_chunks.append( + pa.array([data.data_context_key for _, data in rows], pa.large_string()) + ) + self._pending = [] + + def row_table(self) -> tuple[pa.Table, tuple[str, ...], tuple[str, ...]]: + """Return what ``_rows_to_table`` returns for the rows added, in order. + + Returns: + The concatenated table, the user tag column names and the data-tags. + + Raises: + ValueError: If no row was added. + """ + from orcapod.utils import arrow_utils + + if self.num_rows == 0: + raise ValueError("Cannot materialize an empty list of rows into a stream") + self._seal() + combined_tags = arrow_utils.concat_tables_by_name(self._tag_chunks) + combined_data = StaticOutputOperatorPod._flag_source_info_nullability( # pyright: ignore[reportPrivateUsage] # the one rule for these flags + arrow_utils.concat_tables_by_name(self._data_chunks) + ) + return ( + arrow_utils.hstack_tables(combined_tags, combined_data), + self._tag_keys, + self._data_tags, + ) + + def output_stream(self) -> StreamProtocol: + """Return the stream ``_materialize_to_stream`` builds from the rows added.""" + return StaticOutputOperatorPod._stream_over_row_table(self.row_table()) # pyright: ignore[reportPrivateUsage] # the one builder of that stream + + def input_stream(self, pipeline_hash: ContentHash) -> StreamProtocol: + """Return the stream ``_materialize_input_stream`` builds from the rows added. + + Args: + pipeline_hash: The pipeline hash of the stream the rows came from. + + Returns: + A stream over the rows, in order, each with its own data context. + + Raises: + ValueError: If no row was added. + """ + table, tag_keys, data_tags = self.row_table() + table = table.append_column( + pa.field(constants.CONTEXT_KEY, pa.large_string(), nullable=False), + pa.chunked_array(self._context_chunks, pa.large_string()), + ) + return _RowsOfStream( + table, + tag_columns=tag_keys, + pipeline_hash=pipeline_hash, + data_tags=data_tags, + data_context=contexts.resolve_context(self._first_context_key), + ) + + +def rows_once( + result: StreamProtocol, +) -> Iterator[tuple[TagProtocol, DataProtocol]]: + """Return ``result``'s rows for a reader that passes each on once. + + An ``ArrowTableStream`` keeps every pair ``iter_data`` yields; an operator that + sends its result downstream and then drops it would hold the whole result as + objects while it sends (ITL-1464), so it reads such a stream without keeping. + + Args: + result: An operator's result stream. + + Returns: + The rows of ``result.iter_data()``, in its order. + """ + if isinstance(result, ArrowTableStream): + return result.iter_data_unkept() + return result.iter_data() + + +async def collect_row_chunks( + channel: ReadableChannel[tuple[TagProtocol, DataProtocol]], +) -> RowChunks: + """Read ``channel`` to its end, keeping its rows as ``RowChunks``. + + What a barrier operator does instead of ``channel.collect()``: the same rows in + the same order, without holding every row as a pair of objects (ITL-1464). + + Args: + channel: The input channel. + + Returns: + The rows; ``num_rows`` is 0 when the channel delivered none. + """ + chunks = RowChunks() + async for tag, data in channel: + chunks.add(tag, data) + return chunks + + ROW_BUILT_OUTPUT = "_orcapod_row_built_output" """The attribute that marks a complete node output in the row-built form (ITL-1347). diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index df49eaff6..3c6e2045a 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -454,42 +454,64 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, Data]]: # TODO: make it work with table batch stream if self._cached_elements is None: cached_elements = [] - tag_columns = list(self._all_tag_columns) - # Each row's source info goes to ``Data`` as Arrow columns, so it - # keeps the type it has here: re-typing it from Python values - # (``to_pylist``) would infer a type the stream already knows. - source_columns = list(self._source_info_table.column_names) - data_columns = list(self._data_columns) + source_columns - - # The source-info columns go beside the data columns they describe: the - # rows of this one table are read together, however each column is - # chunked (``rows_of`` reads batch by batch, cut at every column's chunk - # boundaries, so no row is dropped or paired with another's). - rows = self._table - for name in source_columns: - rows = rows.append_column( - self._source_info_table.schema.field(name), - self._source_info_table.column(name), - ) - # The table is prepared once for all of its rows (ITL-1348): building - # ``Tag(row)`` and ``Data(row)`` from one-row slices normalized every row - # three times and split its columns again. - tags = ( - Tag.rows_of(rows.select(tag_columns), self.data_context) - if tag_columns - else None - ) - for data in Data.rows_of(rows.select(data_columns), self.data_context): - # A fresh empty tag per row, so rows never share one object. - tag = next(tags) if tags is not None else Tag({}) - - yield tag, data + for pair in self._build_rows(): + yield pair - cached_elements.append((tag, data)) + cached_elements.append(pair) self._cached_elements = cached_elements else: yield from self._cached_elements + def iter_data_unkept(self) -> Iterator[tuple[TagProtocol, Data]]: + """Iterate the rows as ``iter_data`` does, without keeping the pairs built. + + ``iter_data`` keeps every pair it yields for the stream's life, so a second + iteration returns the same objects. A reader that passes each row on once + (an operator sending its result downstream) has no second iteration, and the + kept pairs are the whole result held as objects (ITL-1464). Pairs an earlier + ``iter_data`` kept are yielded as they are. + + Yields: + A ``(Tag, Data)`` tuple for each row, in table order. + """ + if self._cached_elements is not None: + yield from self._cached_elements + else: + yield from self._build_rows() + + def _build_rows(self) -> Iterator[tuple[TagProtocol, Data]]: + """Build and yield each row's ``(Tag, Data)`` pair, in table order.""" + tag_columns = list(self._all_tag_columns) + # Each row's source info goes to ``Data`` as Arrow columns, so it + # keeps the type it has here: re-typing it from Python values + # (``to_pylist``) would infer a type the stream already knows. + source_columns = list(self._source_info_table.column_names) + data_columns = list(self._data_columns) + source_columns + + # The source-info columns go beside the data columns they describe: the + # rows of this one table are read together, however each column is + # chunked (``rows_of`` reads batch by batch, cut at every column's chunk + # boundaries, so no row is dropped or paired with another's). + rows = self._table + for name in source_columns: + rows = rows.append_column( + self._source_info_table.schema.field(name), + self._source_info_table.column(name), + ) + # The table is prepared once for all of its rows (ITL-1348): building + # ``Tag(row)`` and ``Data(row)`` from one-row slices normalized every row + # three times and split its columns again. + tags = ( + Tag.rows_of(rows.select(tag_columns), self.data_context) + if tag_columns + else None + ) + for data in Data.rows_of(rows.select(data_columns), self.data_context): + # A fresh empty tag per row, so rows never share one object. + tag = next(tags) if tags is not None else Tag({}) + + yield tag, data + def __repr__(self) -> str: refs = f", data_tags={self._data_tags}" if self._data_tags else "" return ( diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 9edd1614e..d299ca106 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -361,9 +361,12 @@ async def _run_async( f"Unknown node type: {getattr(node, 'node_type', None)!r}" ) - # Drain terminal channels concurrently + # Drain terminal channels concurrently. The rows are let go as they + # are read: nothing reads this task's result, and a list of every + # row a terminal node sent is the whole output held as objects + # (ITL-1464). for ch in terminal_channels: - tg.create_task(ch.reader.collect()) + tg.create_task(_drain(ch.reader)) return OrchestratorResult( node_outputs=( @@ -811,6 +814,12 @@ def _leaves(group: BaseExceptionGroup) -> list[BaseException]: return found +async def _drain(reader: Any) -> None: + """Read a channel to its end, keeping no row.""" + async for _ in reader: + pass + + class _CollectingWriter: """Wrapper that collects items while forwarding to real writer.""" diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 2f80d1fa0..4f5231cd4 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1009,6 +1009,8 @@ def run( execution. When ``True`` (the default) the buffer is kept for the duration of the run. When ``False`` each node's buffer is released as soon as the node completes, reducing peak memory. + The async orchestrator never keeps that buffer for a job, which + does not read it (ITL-1464). This setting does not affect database persistence or post-run result access: DB records are written regardless, and ``job.nodes["label"]`` returns the same rows from @@ -1099,7 +1101,10 @@ def run( observer=_with_counter(observer, counter), run_id=prepared.run_id, pipeline_uri=prepared.pipeline_uri, - materialize_results=materialize_results, + # The job reads nothing from the orchestrator's result (every + # node keeps its own run), so the async orchestrator is never + # asked to collect every row of every node for it (ITL-1464). + materialize_results=False, load_only=load_only, held_rows=plan.held_rows, ) @@ -1171,7 +1176,8 @@ async def run_async( observer=_with_counter(observer, counter), run_id=prepared.run_id, pipeline_uri=prepared.pipeline_uri, - materialize_results=materialize_results, + # As in ``run``: the job reads nothing from the result (ITL-1464). + materialize_results=False, load_only=load_only, held_rows=plan.held_rows, ) diff --git a/tests/test_core/operators/test_row_chunks.py b/tests/test_core/operators/test_row_chunks.py new file mode 100644 index 000000000..7c6ea5045 --- /dev/null +++ b/tests/test_core/operators/test_row_chunks.py @@ -0,0 +1,268 @@ +"""Rows kept as Arrow tables build exactly what the row list built (ITL-1464). + +The async path kept every row a node passed on, or a barrier operator gathered, as a +``(Tag, Data)`` pair. ``RowChunks`` keeps them as Arrow tables instead; these tests hold +it to the table and streams the row list gave, over several chunks. +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.channels import Channel +from orcapod.core.operators import static_output_pod +from orcapod.core.operators.static_output_pod import ( + RowChunks, + StaticOutputOperatorPod, + collect_row_chunks, + rows_once, +) +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import DeltaTableDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.sources import ArrowTableSource + +_ROWS = 11 + + +def _table() -> pa.Table: + """Eleven rows: two tags, two data columns (one with nulls), a list column.""" + numbers = list(range(_ROWS)) + return pa.table( + { + "subject": pa.array([f"s{n % 3}" for n in numbers], pa.large_string()), + "trial": pa.array(numbers, pa.int32()), + "value": pa.array([n + 0.5 for n in numbers], pa.float32()), + "note": pa.array( + [None if n % 4 == 0 else f"n{n}" for n in numbers], pa.large_string() + ), + "samples": pa.array( + [[n, n + 1] for n in numbers], pa.large_list(pa.int8()) + ), + } + ) + + +def _source(tag_only: bool) -> ArrowTableSource: + return ArrowTableSource( + _table(), + tag_columns=["subject", "trial"], + tag_only_columns=tag_only, + record_id_columns=["trial"], + source_id="rows", + ) + + +def _rows(tag_only: bool) -> list[tuple[Any, Any]]: + return list(_source(tag_only).iter_data()) + + +def _chunks(rows: list[tuple[Any, Any]]) -> RowChunks: + chunks = RowChunks() + for tag, data in rows: + chunks.add(tag, data) + return chunks + + +@pytest.fixture(params=[1, 3, 4, 11, 8192], ids=lambda n: f"chunk{n}") +def chunk_rows(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> int: + """Every chunk size: one row, several chunks with and without a rest, one chunk.""" + monkeypatch.setattr(static_output_pod, "ROW_CHUNK_ROWS", request.param) + return request.param + + +@pytest.mark.parametrize("tag_only", [False, True], ids=["data_tags", "tag_only"]) +def test_the_row_table_is_the_one_built_from_the_row_list( + chunk_rows: int, tag_only: bool +) -> None: + rows = _rows(tag_only) + expected, tag_keys, data_tags = StaticOutputOperatorPod._rows_to_table(rows) # pyright: ignore[reportPrivateUsage] # the rule RowChunks must equal + + table, got_keys, got_data_tags = _chunks(rows).row_table() + + assert (got_keys, got_data_tags) == (tag_keys, data_tags) + assert table.schema.equals(expected.schema, check_metadata=True) + assert table.column_names == expected.column_names + assert table.equals(expected) + # A token column with no null is declared non-nullable, as from the row list. + assert not table.schema.field("_source_value").nullable + + +@pytest.mark.parametrize("tag_only", [False, True], ids=["data_tags", "tag_only"]) +def test_the_streams_are_the_ones_built_from_the_row_list( + chunk_rows: int, tag_only: bool +) -> None: + rows = _rows(tag_only) + pipeline_hash = _source(tag_only).pipeline_hash() + chunks = _chunks(rows) + everything = {"system_tags": True, "source": True, "context": True} + + output = chunks.output_stream() + expected_output = StaticOutputOperatorPod._materialize_to_stream(rows) # pyright: ignore[reportPrivateUsage] # the builder RowChunks must equal + assert output.keys() == expected_output.keys() + assert output.as_table(columns=everything).equals( + expected_output.as_table(columns=everything) + ) + assert output.content_hash() == expected_output.content_hash() + + given = chunks.input_stream(pipeline_hash) + expected_input = StaticOutputOperatorPod._materialize_input_stream( # pyright: ignore[reportPrivateUsage] # the builder RowChunks must equal + rows, pipeline_hash + ) + assert given.keys() == expected_input.keys() + assert given.pipeline_hash() == expected_input.pipeline_hash() == pipeline_hash + assert given.data_context_key == expected_input.data_context_key + assert given.as_table(columns=everything).equals( + expected_input.as_table(columns=everything) + ) + + +def test_rows_with_a_missing_token_keep_their_field_nullable(chunk_rows: int) -> None: + rows = _rows(False) + tag, data = rows[5] + # One row whose token for ``value`` is None, in the middle of a chunk. + rows[5] = (tag, data.with_source_info(value=None)) + expected = StaticOutputOperatorPod._rows_to_table(rows)[0] # pyright: ignore[reportPrivateUsage] # the rule RowChunks must equal + + table = _chunks(rows).row_table()[0] + + assert table.schema.field("_source_value").nullable + assert not table.schema.field("_source_note").nullable + assert table.schema.equals(expected.schema, check_metadata=True) + assert table.equals(expected) + + +def test_no_rows_is_refused_as_an_empty_row_list_is() -> None: + chunks = RowChunks() + assert chunks.num_rows == 0 + with pytest.raises(ValueError, match="empty list of rows"): + chunks.row_table() + + +def test_at_most_one_chunk_of_rows_is_held_as_objects( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(static_output_pod, "ROW_CHUNK_ROWS", 4) + chunks = _chunks(_rows(False)) + + assert chunks.num_rows == _ROWS + assert len(chunks._pending) == _ROWS % 4 # pyright: ignore[reportPrivateUsage] # the bound this class exists for + assert [t.num_rows for t in chunks._tag_chunks] == [4, 4] # pyright: ignore[reportPrivateUsage] # the bound this class exists for + + +def test_collecting_a_channel_keeps_its_rows_in_order(chunk_rows: int) -> None: + rows = _rows(False) + + async def read() -> RowChunks: + channel: Channel[tuple[Any, Any]] = Channel(buffer_size=2) + + async def send() -> None: + for row in rows: + await channel.writer.send(row) + await channel.writer.close() + + async with asyncio.TaskGroup() as group: + _ = group.create_task(send()) + collected = group.create_task(collect_row_chunks(channel.reader)) + return collected.result() + + chunks = asyncio.run(read()) + + assert chunks.num_rows == _ROWS + assert chunks.row_table()[0].equals( + StaticOutputOperatorPod._rows_to_table(rows)[0] # pyright: ignore[reportPrivateUsage] # the rule RowChunks must equal + ) + + +def test_rows_read_once_are_not_kept_by_the_stream() -> None: + stream = _source(False).map_data({"value": "amplitude"}) + result = ArrowTableStream( + stream.as_table(columns={"system_tags": True, "source": True}), + tag_columns=["subject", "trial"], + data_tags=["subject", "trial"], + ) + + once = [(t.as_dict(), d.as_dict(), d.source_info()) for t, d in rows_once(result)] + + assert result._cached_elements is None # pyright: ignore[reportPrivateUsage] # what rows_once must not fill + kept = [(t.as_dict(), d.as_dict(), d.source_info()) for t, d in result.iter_data()] + assert once == kept + assert len(once) == _ROWS + # Pairs an earlier iteration kept are the ones a later single read gives. + assert [id(d) for _, d in rows_once(result)] == [ + id(d) for _, d in result.iter_data() + ] + + +def _job(tmp_path: Path, name: str, chain: str, tag_only: bool) -> PipelineJob: + database = DeltaTableDatabase(str(tmp_path / name)) + with PipelineJob(name="chunks", database=database) as job: + source = _source(tag_only) + if chain == "map": + _ = source.map_data({"value": "amplitude"}, label="out") + elif chain == "group": + _ = source.group_by(["subject"], label="out") + else: + _ = source.drop_nulls(["note"]).batch(4, label="out") + return job + + +def _sorted_rows(table: pa.Table) -> list[dict[str, Any]]: + names = sorted(table.column_names) + return sorted(table.select(names).to_pylist(), key=repr) + + +@pytest.mark.parametrize("tag_only", [False, True], ids=["data_tags", "tag_only"]) +@pytest.mark.parametrize("chain", ["map", "group", "batch"]) +def test_an_async_job_over_several_chunks_gives_the_sync_rows( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, chain: str, tag_only: bool +) -> None: + monkeypatch.setattr(static_output_pod, "ROW_CHUNK_ROWS", 3) + sync_job = _job(tmp_path, "sync", chain, tag_only) + _ = sync_job.run() + async_job = _job(tmp_path, "async", chain, tag_only) + _ = async_job.run(orchestrator=AsyncPipelineOrchestrator()) + + expected = sync_job.nodes["out"].as_table(all_info=True) + found = async_job.nodes["out"].as_table(all_info=True) + + assert found.num_rows == expected.num_rows > 0 + assert sorted(found.column_names) == sorted(expected.column_names) + assert {n: found.schema.field(n) for n in found.column_names} == { + n: expected.schema.field(n) for n in expected.column_names + } + if chain == "batch": + # ``Batch`` groups by arrival on the async path: the rows in order, as sync. + assert found.select(expected.column_names).equals(expected) + else: + assert _sorted_rows(found) == _sorted_rows(expected) + assert async_job.nodes["out"].content_hash() == sync_job.nodes["out"].content_hash() + + +def test_an_async_job_run_asks_the_orchestrator_to_keep_no_rows( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + asked: list[bool] = [] + original = AsyncPipelineOrchestrator._run_async # pyright: ignore[reportPrivateUsage] # the one place the rows are collected + + async def recording(self: Any, graph: Any, materialize_results: bool, **kw: Any): + asked.append(materialize_results) + return await original(self, graph, materialize_results, **kw) + + monkeypatch.setattr(AsyncPipelineOrchestrator, "_run_async", recording) + job = _job(tmp_path, "kept", "map", False) + + _ = job.run(orchestrator=AsyncPipelineOrchestrator()) + assert asked == [False] + assert job.nodes["out"].as_table().num_rows == _ROWS + + again = _job(tmp_path, "kept2", "map", False) + _ = asyncio.run(again.run_async()) + assert asked == [False, False] + assert again.nodes["out"].as_table().num_rows == _ROWS From 9f8f0b509f64442ca84fc74bd8d56e8d7ce1c492 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:37:14 -0800 Subject: [PATCH 13/81] docs(dev): record the first transport step's numbers and decisions (ITL-1464) Co-Authored-By: Claude Fable 5.2 --- docs/dev/specs/itl-1464-memory-diagnosis.md | 20 ++++++++++++++++++++ docs/dev/specs/itl-1464-streaming-design.md | 12 +++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/docs/dev/specs/itl-1464-memory-diagnosis.md b/docs/dev/specs/itl-1464-memory-diagnosis.md index 7a6d629c7..4615724c6 100644 --- a/docs/dev/specs/itl-1464-memory-diagnosis.md +++ b/docs/dev/specs/itl-1464-memory-diagnosis.md @@ -203,3 +203,23 @@ It removes the largest cost of the reported case (a) and nothing of case (b): an operator and a job still read the tokens. What remains of the 1.96 GiB is the system tags (0.5 GiB of Arrow), the set of keys seen (0.5 GiB of Python strings) and the copy made when the batches are joined. + +## The first transport step's effect + +Async rows kept as Arrow tables of at most 8,192 rows instead of one pair of objects per +row (the orchestrator's collectors and drain, an operator job node's kept output, a +barrier operator's gathered input and its result while sent). Async job, peak resident +memory less the import, per row; before at 20,000 rows, after at 200,000: + +| Job | Before | After | +|---|---|---| +| `map_data` | 54 KiB | 7.7 KiB | +| `drop_nulls` | 90 KiB | 8.6 KiB | +| `polars_filter` | 109 KiB | 12.5 KiB | +| `join` (large with small) | 68 KiB | 21 KiB | +| `group_by` | 57 KiB | 15 KiB | +| `drop_nulls`, `group_by`, `map_data`, function pod | 102 KiB (19.7 GiB at 200,000 rows) | 24 KiB (4.8 GiB) | + +The async path now costs about what the sync path does. What remains is cause 2 and +cause 3: each node keeps its tokenized table (about 4.5 KiB per row per copy), and +`Join` buffers both inputs in the row form. diff --git a/docs/dev/specs/itl-1464-streaming-design.md b/docs/dev/specs/itl-1464-streaming-design.md index 936109554..bf00c5bdb 100644 --- a/docs/dev/specs/itl-1464-streaming-design.md +++ b/docs/dev/specs/itl-1464-streaming-design.md @@ -487,7 +487,9 @@ the synthetic tables of the diagnosis; none changes a hash, a stored layout or a value. 1. **Done (PR 558)**: a SpiralDB read that returns no tokens builds none. -2. Rows on the async path as record batches: wire `async_execute_batches` and the +2. **First part done (PR 562)**: rows kept on the async path as Arrow tables of at most + 8,192 rows, never as a list of pairs (async now costs about what sync does). Remaining: + rows on the async path as record batches: wire `async_execute_batches` and the record-batch channels into the nodes and the async orchestrator (ITL-1347's remaining stages), give `PolarsFilter` `ROW_BY_ROW`. Removes the 18 to 110 KiB per row. 3. The local cache, and job nodes that keep a reference (section 3). Removes "every node @@ -526,6 +528,14 @@ holds rows (cache files, `as_table()`, the sync path). | U1 | Iteration keeps no row objects | accept | | M1 | The workshop budget | 4 GiB peak, async, non-LFP | +Approved by the coordinator on the developer's delegation (November 25, 2026), each for +the developer's review: N1 (a job node reads its run's rows from storage or a local +spill file, a page at a time; spill files under a temporary directory per job run, +removed with the job or the process, never part of a stored path or hash; same rows, +same order on sync), T1 as a direction (design first, implemented after the transport), +and the interim transport step of PR 562. The local cache of section 2 is one shared +module, `core/row_spool.py` (PR 559), used by joins, views and job nodes alike. + Decided by the developer (November 24 and 25, 2026), recorded above: `run()` promises computation and nothing about how; async is the primary memory-bounded path; joins keep keys only, with rows fetched from a local cache; certificates originate in Orcapod and From b03a944e7b5edcaae39df36c9f2cbb0b614ce93b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:37:57 -0800 Subject: [PATCH 14/81] perf(core): recipes through F, predicates and spills; design and tests (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1464.md | 7 + docs/dev/specs/itl-1464-tokens.md | 111 +++++ src/orcapod/core/nodes/source_node.py | 6 + src/orcapod/core/operators/filters.py | 5 +- .../core/operators/static_output_pod.py | 4 + src/orcapod/core/sources/base.py | 3 +- src/orcapod/core/streams/base.py | 9 +- src/orcapod/utils/source_tokens.py | 44 +- tests/test_core/streams/test_source_tokens.py | 449 ++++++++++++++++++ 9 files changed, 612 insertions(+), 26 deletions(-) create mode 100644 changelog.d/ITL-1464.md create mode 100644 docs/dev/specs/itl-1464-tokens.md create mode 100644 tests/test_core/streams/test_source_tokens.py diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md new file mode 100644 index 000000000..c9b7b4402 --- /dev/null +++ b/changelog.d/ITL-1464.md @@ -0,0 +1,7 @@ +### Changed + +- Reading a source and applying an operator that selects, renames, filters or tags rows + no longer builds the source-info text of every row and column. The text is built when + it is shown, stored or handed to a function, a part of the rows at a time, so these + steps take a few times the memory of their data instead of tens of times (ITL-1464). + Values, hashes and stored tables are unchanged. diff --git a/docs/dev/specs/itl-1464-tokens.md b/docs/dev/specs/itl-1464-tokens.md new file mode 100644 index 000000000..7473d3954 --- /dev/null +++ b/docs/dev/specs/itl-1464-tokens.md @@ -0,0 +1,111 @@ +# Source-info tokens carried as a recipe (ITL-1464, track TOKENS) + +Status: direction approved November 25, 2026. Step 1 (sources and row-wise operators) +implemented with this document; step 2 (joins) is a separate pull request. + +## The cost + +A source row's token is `::::`, one per row and data +column: about 300 bytes each on the measured synthetic tables, 35 times the data +(`itl-1464-memory-diagnosis.md`). Everything in it is in the row's two system tags and +the column's name at the source. + +## The representation + +A `_source_x` column is **derived** while no one needs its text: a column of +`DerivedTokenType` (`src/orcapod/utils/source_tokens.py`), an internal Arrow extension +type. Its storage is a struct with no field, so a row has no byte, whatever the number of +rows. Its parameter is a recipe, `TokenRecipe(source_id, record_id, column)`: two +system-tag column names of the same table, and the column's name at the source. + +- `filter`, `take`, `slice`, `concat_tables`, `select` and `rename_columns` carry the + column with no special code, since it is one column like any other. The rows of the + table and their system tags move together, so the recipe stays right. +- Two columns have one Arrow type only with one recipe (`__eq__`), so Arrow itself refuses + to concatenate two that would read different columns. +- The system-tag names of a join change (`append_to_system_tags`): the recipes follow + there (`rename_read_columns`). The values of the system tags move between columns only + in `sort_system_tag_values` (inputs of one pipeline hash): the tokens that read them + become text first (`materialize_reading`). +- Text is made in one function, `materialize`, at most 65,536 rows at a time. + +A derived column is loud where it does not belong: reading a value, casting to text, +hashing, pickling and writing Parquet (so Delta) each raise. + +## Where a derived table can go + +`StreamProtocol.as_carried_table(columns=)` is the internal read: the table of `as_table` +with derived columns left as they are. Only library operators call it. The default is +`as_table` (text), so a user's operator, source or stream, and every job node today, is +given and gives text. `ArrowTableStream`, `DynamicPodStream`, and the sources over a held +or scanned table answer it without text. `as_table` with any columns, `iter_data`, `head`, +`run`, the data frame methods and the identity table give text, as before. A read without +the system tags gives text (the recipe would have nothing to read). + +## Producers of `_source_` columns + +| Producer | Form | +|---|---| +| `SourceStreamBuilder.attach_provenance` (every source's rows) | derived | +| `ArrowTableStream(source_info=...)` and a raw table's own `_source_` columns | as given (text) | +| `prepare_prefixed_columns` for a data column with no token | null text | +| `CachedSource`, `DerivedSource` over stored records | text, read from storage | +| `DerivedSource(tags_as_data=)` | derived (a new root, through the builder) | +| `PollingSource` | derived per batch; its combined stream is text (its batches are combined through `as_table`) | +| A function pod's outputs (`data_function.py`) | text: an output's token names the computation, not a source row | +| `Pick` (`with_source_info`) | text: the token is extended | +| `Index` | per row, text (the element's token) | +| `Batch`, `GroupBy` | text lists, one element per member | +| `Join`, `MergeJoin` merged or colliding columns | text | + +## Consumers + +| Consumer | What it needs | Step 1 | +|---|---|---| +| Column selections, `MapData`, `MapTags`, `MapColumns`, `TagBy`, `AddTags`, `DropNulls`, `Filter` | none of the values | derived in, derived out | +| `PolarsFilter` | none, unless a predicate reads a token | the columns stay out of the Polars frame and are put back for the kept rows; a predicate that could read one (a selector, a regular expression, a non-expression, a name that is no column) gets text, as before | +| `without_input_meta` | names only | derived | +| `SemiJoin` (left input) | none | step 2 | +| `Join`, `Rejoin`, `MergeJoin`: columns of one input | none | step 2 | +| `Join`: a shared data-tag | both tokens, folded (`join_v1`) | step 2: a fold recipe; until then text | +| `MergeJoin`: a colliding column | both tokens, in a list | text of that column | +| `GroupBy`, `Batch` | the members' tokens, in a list | text (below) | +| `iter_data` (rows: function pods, side effects, async rows) | one string per column of each row | built for 8,192 rows at a time | +| `F` (`_row_built_form`, `row_built_provenance`) | types and null flags | passes a derived column through (a token is one string and never null) | +| Job nodes (`core/nodes/*`) | the stored text; the kept table | text until the transport calls `as_carried_table` | +| Function node pipeline table, result table, operator and source caches | stored text | unchanged: they read rows or `as_table` | +| Record-batch channels, streaming joins | types, values | unchanged (text) | +| Provenance trace (`pipeline/provenance.py`) | text | unchanged | +| Identity of a raw stream (`_identity_table`), record hashes | text | unchanged | + +## After each operator + +| Operator | Derivable after it? | +|---|---| +| filter, drop nulls, select, drop, rename, add tags, tag by | yes, all columns | +| semi join | yes, all left columns | +| join, rejoin | yes: each input's columns through its renamed system tags; a shared data-tag through a fold of two recipes. Not for inputs of one pipeline hash in `Join`, whose system-tag values are sorted per row | +| merge join | yes for columns only one input has; a colliding column is a list of two tokens | +| group by, batch | no: the system tags are folded to one digest, the members' ids are gone. The lists must be text (or carry the members' ids, a later step) | +| function pod | an output: no. Inputs' tokens are not in its output | + +## Aggregations + +`GroupBy` and `Batch` keep one token per member and column, so their output needs the +members' record ids: text lists are about 300 bytes per member and column. A derived list +(the members' record ids once, in one hidden list column, and recipes over it) is possible +but adds a column operators would have to carry; it is not done here. + +## Measured + +A synthetic time series table, about 2.2 million rows, 13 columns, about 250 MiB of Arrow data, read through +`SpiralDBTableSource` (`measure.py` of the diagnosis, one process per step). + +| Step | Peak RSS before | after | Arrow pool peak before | after | +|---|---|---|---|---| +| `as_table()`, `run()` | 10.8 GiB | 2.0 GiB | 9.3 GiB | 0.75 GiB | +| `map_data` | 10.8 GiB | 2.0 GiB | 9.3 GiB | 0.75 GiB | +| `drop_nulls` | 19.7 GiB | 2.4 GiB | 18.6 GiB | 1.7 GiB | +| `polars_filter` | 16.6 GiB | 2.5 GiB | 9.3 GiB | 0.75 GiB | +| `join` (8 and 14 columns) | above 24 GiB | above 24 GiB (step 2) | | | +| `group_by` | 20.9 GiB | 20.7 GiB (its lists are text) | 15.9 GiB | 15.9 GiB | diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b6b8bc0f6..2fc8678fd 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1271,6 +1271,12 @@ def run(self) -> StreamView: display_all_rows=False, ) + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The table of ``as_table(columns=columns)``; see ``StreamProtocol`` (ITL-1464).""" + return self.as_table(columns=columns) + def open_channel(self) -> RecordBatchInput: """Open an input channel on this node's rows, for async computation (ITL-1347). diff --git a/src/orcapod/core/operators/filters.py b/src/orcapod/core/operators/filters.py index 2a84592f5..491fa79b9 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -133,7 +133,10 @@ def _reads_only(self, columns: Collection[str]) -> bool: isinstance(predicate, pl.Expr) and not predicate.meta.has_multiple_outputs() and set(predicate.meta.root_names()) <= set(columns) - for predicate in self.predicates + for predicate in ( + *self.predicates, + *(v for v in self.constraints.values() if isinstance(v, pl.Expr)), + ) ) def validate_unary_input(self, stream: StreamProtocol) -> None: diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index c8f45d059..845a7d6a7 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -40,6 +40,7 @@ provisional_operator_name, warn_provisional_operator, ) +from orcapod.utils import source_tokens from orcapod.utils.provisional import note_provisional_use, provisional_class_name from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( @@ -579,6 +580,9 @@ def _type_source_info_by_values(table: pa.Table) -> pa.Table: continue if pa.types.is_large_string(field.type): continue + if source_tokens.derived_recipe(field.type) is not None: + # Every token of a derived column is one string. + continue values = table.column(index).to_pylist() kinds = {arrow_utils.source_info_arrow_type(value) for value in values} if len(kinds) != 1: diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 780e1c63a..100d67285 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -546,7 +546,8 @@ def as_carried_table( ``as_table``) gives that table. """ if type(self).as_table is RootSource.as_table and "as_table" not in vars(self): - return self._stream.as_carried_table(columns=columns) + stream: StreamBase = getattr(self, "_stream") # noqa: B009 # set by each subclass + return stream.as_carried_table(columns=columns) return super().as_carried_table(columns=columns) # ------------------------------------------------------------------------- diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 26fa6713d..833a17347 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -42,7 +42,7 @@ from orcapod.protocols.core_protocols.streams import RecordBatchInput from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Condition, Schema -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens if TYPE_CHECKING: from orcapod.types.explanation import Explanation @@ -340,7 +340,12 @@ def row_built_provenance(table: pa.Table) -> pa.Table: changed = False for field, column in zip(table.schema, table.columns, strict=True): if field.name.startswith(constants.SOURCE_PREFIX): - kind = _source_info_value_type(field.type) + # A derived token column stays derived: its text is what the rows give. + kind = ( + field.type + if source_tokens.derived_recipe(field.type) is not None + else _source_info_value_type(field.type) + ) if kind != field.type: column = column.cast(kind) new_field = pa.field(field.name, kind, nullable=field.nullable) diff --git a/src/orcapod/utils/source_tokens.py b/src/orcapod/utils/source_tokens.py index 9602c5b9f..0fd59bcfc 100644 --- a/src/orcapod/utils/source_tokens.py +++ b/src/orcapod/utils/source_tokens.py @@ -11,8 +11,8 @@ A derived column is an internal form of a table that operators pass on (``StreamProtocol.as_carried_table``). It never leaves the library: ``as_table``, rows, stored tables and everything hashed hold the text. A place that forgets fails loudly: no -value of a derived column can be read, cast to text, hashed, or written to Parquet (its -storage is a struct with no field, which Parquet refuses). +value of a derived column can be read, cast to text, hashed, pickled, or written to +Parquet (its storage is a struct with no field, which Parquet refuses). """ from __future__ import annotations @@ -20,7 +20,7 @@ import json from collections.abc import Collection, Mapping from dataclasses import dataclass -from typing import Any, NoReturn +from typing import Any, NoReturn, cast import pyarrow as pa import pyarrow.compute as pc @@ -71,11 +71,11 @@ def reads(self, columns: Collection[str]) -> bool: def text(self, batch: pa.RecordBatch) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array """The tokens of ``batch``'s rows, as ``large_string``.""" - return pc.binary_join_element_wise( + return pc.binary_join_element_wise( # pyright: ignore[reportCallIssue, reportUnknownVariableType] # the stubs leave out scalar arguments batch.column(self.source_id).cast(_TEXT), batch.column(self.record_id).cast(_TEXT), - pa.scalar(self.column, _TEXT), - pa.scalar(constants.BLOCK_SEPARATOR, _TEXT), + pa.scalar(self.column, _TEXT), # pyright: ignore[reportArgumentType] # as above + pa.scalar(constants.BLOCK_SEPARATOR, _TEXT), # pyright: ignore[reportArgumentType] # as above ) @@ -97,8 +97,9 @@ def as_py(self, *args: Any, **kwargs: Any) -> NoReturn: # pyright: ignore[repor class DerivedTokenType(pa.ExtensionType): """The Arrow type of a derived token column: no bytes, and the recipe. - Internal and never registered, so it is in no stored table and no schema Orcapod - presents or hashes. Two derived columns have one type only with one recipe. + Internal: in no stored table and no schema Orcapod presents or hashes. Not + registered with Arrow: a spilled table is written as its storage (no bytes) and + wrapped in its type again. Two derived columns have one type only with one recipe. """ def __init__(self, recipe: TokenRecipe) -> None: @@ -117,17 +118,29 @@ def __arrow_ext_deserialize__( def __arrow_ext_scalar_class__(self) -> type[pa.ExtensionScalar]: return _DerivedTokenScalar + def __reduce__(self) -> NoReturn: + """Refuse to be pickled: a table another process reads holds the text. + + Raises: + TypeError: Always. + """ + raise TypeError("a derived source-info token column is not pickled") + # pyarrow compares extension types by name and storage only; Arrow asks this. def __eq__(self, other: object) -> bool: return isinstance(other, DerivedTokenType) and self.recipe == other.recipe + def __ne__(self, other: object) -> bool: + return not self == other + def __hash__(self) -> int: return hash(self.recipe) def derived_array(recipe: TokenRecipe, rows: int) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array """A derived token column of ``rows`` rows: no row has a byte.""" - storage = pa.Array.from_buffers(pa.struct([]), rows, [None], 0, 0) + # No validity bitmap: no row is null. (The stubs do not allow the absent buffer.) + storage = pa.Array.from_buffers(pa.struct([]), rows, cast(Any, [None]), 0, 0) return pa.ExtensionArray.from_storage(DerivedTokenType(recipe), storage) @@ -219,16 +232,3 @@ def rename_read_columns(table: pa.Table, names: Mapping[str, str]) -> pa.Table: derived_array(renamed, table.num_rows), ) return table - - -def text_schema(schema: pa.Schema) -> pa.Schema: - """``schema`` with each derived token column as the text it stands for.""" - if not derived_columns(schema): - return schema - return pa.schema( - [ - field.with_type(_TEXT) if derived_recipe(field.type) else field - for field in schema - ], - metadata=schema.metadata, - ) diff --git a/tests/test_core/streams/test_source_tokens.py b/tests/test_core/streams/test_source_tokens.py new file mode 100644 index 000000000..40eb740ea --- /dev/null +++ b/tests/test_core/streams/test_source_tokens.py @@ -0,0 +1,449 @@ +"""Source-info tokens carried as a recipe until their text is needed (ITL-1464). + +The oracle is the same operation with every source's tokens built as text at once, as +sources did before: values, types, nullability, row order and hashes are equal, and no +derived column reaches a user, a user's operator, a stored table, a hash or a pickle. +""" + +from __future__ import annotations + +import pickle +from collections.abc import Callable +from typing import Any + +import polars as pl +import pyarrow as pa +import pyarrow.compute as pc +import pyarrow.parquet as pq +import pytest + +from orcapod import contexts +from orcapod.core.data_tags import stream_data_tags +from orcapod.core.operators.base import UnaryOperator +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS +from orcapod.databases import InMemoryArrowDatabase +from orcapod.operators import ( + AddTags, + DropColumns, + DropNulls, + DropTagColumns, + MapColumns, + MapData, + MapTags, + PolarsFilter, + SelectDataColumns, + TagBy, +) +from orcapod.sources import ArrowTableSource, CachedSource +from orcapod.system_constants import constants +from orcapod.utils import arrow_utils, source_tokens +from tests.test_core.operators.test_async_sync_equivalence import ( + AFTER_OPERATOR_CASES, + CASES, + Case, +) +from tests.test_core.operators.test_row_built_form import assert_same_values + +CARRIED = {"source": True, "system_tags": True, "context": True} + + +@pytest.fixture +def text_sources(monkeypatch: pytest.MonkeyPatch) -> Callable[[], None]: + """Make every source built from now on hold its tokens as text.""" + add = arrow_utils.add_system_tag_columns + + def switch() -> None: + monkeypatch.setattr( + arrow_utils, + "add_system_tag_columns", + lambda *args: source_tokens.materialize(add(*args)), + ) + + return switch + + +def _table() -> pa.Table: + """Chunked, two tags (one a data-tag), two data columns, nulls.""" + whole = pa.table( + { + "k": pa.array(range(10), pa.int32()), + "j": pa.array([f"j{i % 3}" for i in range(10)]), + "x": pa.array([None if i % 4 == 0 else float(i) for i in range(10)]), + "y": pa.array([f"y{i}" for i in range(10)]), + } + ) + return pa.concat_tables([whole.slice(0, 3), whole.slice(3, 4), whole.slice(7)]) + + +def _source(**kwargs: Any) -> ArrowTableSource: + return ArrowTableSource( + _table(), + tag_columns=["k", "j"], + tag_only_columns=["j"], + record_id_columns=["k"], + **kwargs, + ) + + +def _plain_source() -> ArrowTableSource: + return ArrowTableSource( + _table(), tag_columns=["k", "j"], tag_only_columns=True, record_id_columns=["k"] + ) + + +def _derived(table: pa.Table) -> tuple[str, ...]: + return source_tokens.derived_columns(table.schema) + + +ROW_WISE: dict[str, Callable[[], Any]] = { + "drop_nulls": lambda: DropNulls(["x"])(_source()), + "drop_nulls_all": lambda: DropNulls()(_source()), + "polars_filter": lambda: PolarsFilter([pl.col("x") > 2, pl.col("j") == "j1"])( + _source() + ), + "polars_constraint": lambda: PolarsFilter([], {"j": "j1", "y": "y4"})(_source()), + "filter": lambda: _source().filter({"j": "j1", "y": "y4"}), + "map_data": lambda: MapData({"x": "y", "y": "x"})(_source()), + "map_data_tag": lambda: MapData({"k": "kk", "x": "z"})(_source()), + "map_tags": lambda: MapTags({"k": "kk", "j": "jj"})(_source()), + "map_tags_only": lambda: MapTags({"k": "kk", "j": "jj"}, tag_only=True)(_source()), + "map_columns": lambda: MapColumns({"j": "jj", "x": "z", "k": "kk"})( + _plain_source() + ), + "select_data": lambda: SelectDataColumns(["y"])(_source()), + "drop_tags": lambda: DropTagColumns(["k"])(_source()), + "drop_columns": lambda: DropColumns(["k", "x"])(_source()), + "add_tags": lambda: AddTags({"b": 1, "a": "q"})(_source()), + "tag_by": lambda: TagBy(["x"])(DropNulls(["x"])(_plain_source())), + "chain": lambda: ( + _source() + .drop_nulls(["x"]) + .map_data({"x": "y", "y": "x"}) + .polars_filter(pl.col("y") > 2) + .add_tags(c=1) + ), +} + + +@pytest.mark.parametrize("name", ROW_WISE) +def test_a_row_wise_operator_carries_the_tokens_and_gives_the_same_rows( + name: str, text_sources: Callable[[], None] +) -> None: + result = ROW_WISE[name]() + carried = result.as_carried_table(columns=CARRIED) + tokens = [c for c in carried.column_names if c.startswith(constants.SOURCE_PREFIX)] + assert tokens and set(_derived(carried)) == set(tokens) + table = result.as_table(all_info=True) + rows = [(t.as_dict(all_info=True), d.as_dict(all_info=True)) for t, d in result] + digest = result.content_hash() + text_sources() + oracle = ROW_WISE[name]() + expected = oracle.as_table(all_info=True) + assert not _derived(oracle.as_carried_table(columns=CARRIED)) + assert table.schema.equals(expected.schema, check_metadata=True) + assert_same_values(table, expected) + assert rows == [ + (t.as_dict(all_info=True), d.as_dict(all_info=True)) for t, d in oracle + ] + assert digest == oracle.content_hash() + + +@pytest.mark.parametrize( + "case", [*[pytest.param(c, id=c.label) for c in CASES], *AFTER_OPERATOR_CASES] +) +def test_every_operator_gives_what_text_sources_give( + case: Case, text_sources: Callable[[], None] +) -> None: + """Every operator of the equivalence corpus: the whole table, its carried form, and + F (the table a job node hands on) of the carried form.""" + result = case.make_op()(*case.make_sources()) + table = result.as_table(all_info=True) + carried = result.as_carried_table(columns=ZERO_ROW_INPUT_COLUMNS) + plain = result.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + built = source_tokens.materialize(carried) + assert built.schema.equals(plain.schema, check_metadata=True) + assert_same_values(built, plain) + if plain.num_rows: + formed = StaticOutputOperatorPod._row_built_form(carried, result.keys()) + from_text = StaticOutputOperatorPod._row_built_form(plain, result.keys()) + assert _derived(formed) or not _derived(carried) + formed = source_tokens.materialize(formed) + assert formed.schema.equals(from_text.schema, check_metadata=True) + assert_same_values(formed, from_text) + text_sources() + expected = case.make_op()(*case.make_sources()).as_table(all_info=True) + assert table.schema.equals(expected.schema, check_metadata=True) + assert_same_values(table, expected) + + +def _column_configs() -> list[dict[str, bool]]: + groups = ("source", "system_tags", "context", "content_hash", "sort_by_tags") + return [ + {g: bool(bits >> i & 1) for i, g in enumerate(groups)} + for bits in range(2 ** len(groups)) + ] + + +@pytest.mark.parametrize("make", [_source, ROW_WISE["chain"]], ids=["source", "chain"]) +def test_no_public_read_gives_a_derived_column(make: Callable[[], Any]) -> None: + stream = make() + tables: list[pa.Table] = [stream.as_table(columns=c) for c in _column_configs()] + tables += [stream.head(3, columns=c).table for c in _column_configs()] + tables += [stream.as_table(all_info=True), stream.head(3, all_info=True).table] + tables += [stream.run().table] + for tag, data in stream.flow(): + tables += [tag.as_table(all_info=True), data.as_table(all_info=True)] + assert all(isinstance(t, str) for t in data.source_info().values()) + tables.append(stream.as_polars_df(columns=CARRIED).to_arrow()) + tables.append(pa.Table.from_pandas(stream.as_pandas_df(columns=CARRIED))) + assert not stream.as_lazy_frame(columns=CARRIED).collect().is_empty() + for table in tables: + assert not _derived(table) + assert pa.struct([]) not in table.schema.types + _ = table.to_pylist() + for schema in (stream.arrow_schema(), *stream.output_schema(all_info=True)): + assert "derived" not in str(schema) + assert "derived_token" not in stream.run()._repr_html_() + repr(stream.run()) + + +def test_a_table_without_its_system_tags_holds_text() -> None: + """The recipe reads the system tags, so a table without them is never carried.""" + for config in ({"source": True}, {"source": True, "context": True}): + table = _source().as_carried_table(columns=config) + assert not _derived(table) + assert table.column("_source_x").type == pa.large_string() + + +class _ReadsEverything(UnaryOperator): + """A user's operator: reads every column of its input table.""" + + DATA_TAGS_ISSUE = None + seen: list[pa.Table] = [] + + def validate_unary_input(self, stream: Any) -> None: + pass + + def unary_output_schema(self, stream: Any, **kwargs: Any) -> Any: + return stream.output_schema(**kwargs) + + def identity_structure(self) -> Any: + return "ReadsEverything" + + def unary_static_process(self, stream: Any) -> Any: + table = stream.as_table(columns={"source": True, "system_tags": True}) + self.seen.append(table) + assert all(len(v) == len(table) for v in table.to_pydict().values()) + return ArrowTableStream( + table, tag_columns=stream.keys()[0], data_tags=stream_data_tags(stream) + ) + + +def test_a_users_operator_reads_text() -> None: + _ReadsEverything.seen = [] + result = _ReadsEverything()(_source()) + after = result.drop_nulls(["x"]) + table = after.as_table(columns=CARRIED) + (seen,) = _ReadsEverything.seen + assert not _derived(seen) + assert str(seen.column("_source_x")[1]).endswith('::{"k":1}::x') + assert table.column("_source_x").to_pylist() == [ + t for i, t in enumerate(seen.column("_source_x").to_pylist()) if i % 4 + ] + + +@pytest.mark.parametrize( + "predicate", + [ + pl.col("_source_x").str.ends_with("::x"), + pl.any_horizontal(pl.all().is_not_null()), + pl.any_horizontal(pl.col("^_source_.*$").str.contains("::")), + pl.concat_str(["_source_x", "_source_y"]).str.contains("::x"), + "x_is_big", + [True] * 5 + [False] * 5, + ], + ids=["named", "all", "regex", "concat", "name", "mask"], +) +def test_a_predicate_that_may_read_tokens_reads_text( + predicate: Any, text_sources: Callable[[], None] +) -> None: + def make() -> Any: + table = _table().append_column("x_is_big", pa.array([True, False] * 5)) + return PolarsFilter([predicate])(ArrowTableSource(table, tag_columns=["k"])) + + table = make().as_table(all_info=True) + text_sources() + expected = make().as_table(all_info=True) + assert table.num_rows > 0 + assert table.equals(expected) + + +def test_an_unknown_column_is_reported_as_with_text( + text_sources: Callable[[], None], +) -> None: + def message() -> str: + with pytest.raises(pl.exceptions.ColumnNotFoundError) as error: + _ = PolarsFilter([pl.col("nope") > 1])(_source()).as_table() + return str(error.value) + + got = message() + text_sources() + assert got == message() + + +def test_a_constraint_expression_may_read_tokens() -> None: + """``filter(x=)``: the value is looked into as a predicate is.""" + kept = PolarsFilter([], {"y": pl.col("_source_y").str.slice(0, 2)})(_source()) + assert kept.as_table().num_rows == 0 + + +def test_stored_rows_hold_text(text_sources: Callable[[], None]) -> None: + """A cached source stores every column, tokens and record hashes included.""" + + def stored() -> pa.Table: + database = InMemoryArrowDatabase() + cached = CachedSource(_source(), cache_database=database) + _ = cached.as_table() + table = cached.get_all_records() + assert table is not None + return table.drop_columns( + [c for c in table.column_names if "time" in c or c.endswith("_ts")] + ) + + table = stored() + assert not _derived(table) + text_sources() + expected = stored() + assert table.schema.equals(expected.schema, check_metadata=True) + assert table.equals(expected) + + +def test_a_derived_column_that_leaks_is_an_error() -> None: + carried = _source().as_carried_table(columns=CARRIED) + tokens = carried.column("_source_x") + with pytest.raises(TypeError, match="no value"): + _ = tokens.to_pylist() + with pytest.raises(pa.ArrowNotImplementedError): + _ = tokens.cast(pa.large_string()) + with pytest.raises(TypeError, match="not pickled"): + _ = pickle.dumps(carried) + with pytest.raises(pa.ArrowNotImplementedError): + pq.write_table(carried, pa.BufferOutputStream()) + with pytest.raises(Exception, match="no value|derived"): + _ = contexts.get_default_context().arrow_hasher.hash_table(carried) + + +def test_a_spilled_table_keeps_its_recipes() -> None: + """As the row spool writes it: an extension column's storage, wrapped when read.""" + carried: Any = _source().as_carried_table(columns=CARRIED).combine_chunks() + arrow: Any = pa + batch: Any = carried.to_batches()[0] + storage = arrow.RecordBatch.from_arrays( + [getattr(c, "storage", c) for c in batch.columns], names=batch.schema.names + ) + sink = pa.BufferOutputStream() + with pa.ipc.new_file(sink, storage.schema) as writer: + writer.write_batch(storage) + read = pa.ipc.open_file(sink.getvalue()).get_batch(0) + wrapped = arrow.Table.from_arrays( + [ + arrow.ExtensionArray.from_storage(f.type, c) + if isinstance(f.type, pa.BaseExtensionType) + else c + for f, c in zip(carried.schema, read.columns, strict=True) + ], + schema=carried.schema, + ) + order = pa.array([7, 2, 2, 9]) + assert _derived(wrapped) == _derived(carried) + assert source_tokens.materialize(wrapped.take(order)).equals( + source_tokens.materialize(carried).take(order) + ) + + +def test_a_carried_column_has_no_bytes_and_is_not_null() -> None: + carried = _source().as_carried_table(columns=CARRIED) + taken = carried.take(pa.array([1, 5])).filter(pc.field("k") > 1) + for table in (carried, taken, pa.concat_tables([carried, taken]).combine_chunks()): + for name in _derived(table): + assert table.column(name).nbytes == 0 + assert table.column(name).null_count == 0 + assert not table.schema.field(name).nullable + + +def test_recipes_tell_types_apart() -> None: + one, two = ( + source_tokens.derived_array(source_tokens.TokenRecipe("s", "r", c), 2) + for c in ("a", "b") + ) + assert one.type != two.type + assert pa.schema([("c", one.type)]) != pa.schema([("c", two.type)]) + with pytest.raises(pa.ArrowInvalid): + _ = pa.concat_tables([pa.table({"c": one}), pa.table({"c": two})]) + + +def test_extended_system_tag_names_are_followed_and_sorting_builds_the_text() -> None: + """A join's system-tag rename keeps the tokens derived; sorting the values of two + inputs with one pipeline hash builds them first, so each names its own row.""" + left, right = ( + _source(source_id=name).map_data( + {"x": f"x{name}", "y": f"y{name}", "k": f"k{name}"} + ) + for name in ("b", "a") + ) + tables = [ + arrow_utils.append_to_system_tags( + s.as_carried_table(columns={"source": True, "system_tags": True}), f"h:{i}" + ) + for i, s in enumerate((left, right)) + ] + plain = [source_tokens.materialize(t) for t in tables] + assert plain[0].column("_source_xb")[1].as_py().startswith("arrow_table_v1:b::") + joined = arrow_utils.hstack_tables(tables[0], tables[1].drop_columns(["k", "j"])) + assert _derived(joined) + done = arrow_utils.sort_system_tag_values(joined) + assert not _derived(done) + for table in plain: + for name in table.column_names: + if name.startswith(constants.SOURCE_PREFIX): + assert done.column(name).equals(table.column(name)) + + +def test_rows_are_built_a_part_at_a_time(monkeypatch: pytest.MonkeyPatch) -> None: + """Iteration builds text per part of the rows, whatever their chunks.""" + from orcapod.core.streams import arrow_table_stream + + expected = _source().as_table(columns=CARRIED) + sizes: list[int] = [] + build = source_tokens.materialize + + def record(table: pa.Table, names: Any = None) -> pa.Table: + sizes.append(table.num_rows) + return build(table, names) + + monkeypatch.setattr(arrow_table_stream, "ROWS_PER_PART", 4) + monkeypatch.setattr(source_tokens, "materialize", record) + rows = list(_source()) + assert sizes == [4, 4, 2] + assert [d.source_info()["x"] for _, d in rows] == expected.column( + "_source_x" + ).to_pylist() + + +def test_no_rows_hold_text_types() -> None: + table = _source().polars_filter(pl.col("k") > 100).as_table(all_info=True) + assert table.num_rows == 0 + assert table.schema.field("_source_x").type == pa.large_string() + assert table.schema.equals(_source().as_table(all_info=True).schema) + + +def test_a_source_with_its_own_read_gives_its_own_table() -> None: + """A subclass, or an object, with its own ``as_table`` is read through it.""" + + class Own(ArrowTableSource): + def as_table(self, **kwargs: Any) -> pa.Table: + return super().as_table(**kwargs).slice(0, 2) + + own = Own(_table(), tag_columns=["k"]) + assert own.drop_columns(["x"]).as_table().num_rows == 2 From bea13ee8885b43b28375ce0ef6f69ca28daae461 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:38:07 -0800 Subject: [PATCH 15/81] docs(dev): generic table and column names, rounded sizes in the ITL-1464 material Co-Authored-By: Claude Fable 5.2 --- docs/dev/specs/itl-1464-memory-diagnosis.md | 21 +- docs/dev/specs/itl-1464-streaming-design.md | 14 +- docs/dev/specs/itl-1464/measure.py | 263 ++++++++++---------- docs/dev/specs/itl-1464/run_measurements.py | 4 +- 4 files changed, 145 insertions(+), 157 deletions(-) diff --git a/docs/dev/specs/itl-1464-memory-diagnosis.md b/docs/dev/specs/itl-1464-memory-diagnosis.md index 4615724c6..4bf2c9276 100644 --- a/docs/dev/specs/itl-1464-memory-diagnosis.md +++ b/docs/dev/specs/itl-1464-memory-diagnosis.md @@ -12,8 +12,7 @@ Three causes account for the memory, in this order of size: as a pair of datagram objects, and every operator job node keeps every pair of its output until the run ends. One async job over 200,000 rows peaks at 19.7 GiB (102 KiB per row, 877 times the input); the cost is linear in rows, so the full - session (2,177,155 rows) extrapolates to about 210 GiB. This is the workshop - notebook's 145 to 166 GB. + session (about 2.2 million rows) extrapolates to about 210 GiB. This is the size of the reported notebook run. 2. **Source-info tokens are 35 times the data.** A source writes one string per row and data column, `::::`, about 324 bytes each here. With 13 data columns (every key column is a data-tag, so it has a token too) that is 4.2 KiB @@ -39,11 +38,11 @@ enough that no SpiralDB read was needed. step, each in a fresh process, killed above 24 GiB of resident memory). - Tables: synthetic, with the column names and Arrow types of three tables of a SpiralDB sample dataset, one session each: - - a gaze time series: 13 columns (5 key columns: two strings, a timestamp, a `uint32`, + - a time series: 13 columns (5 key columns: two strings, a timestamp, a `uint32`, a `uint64`; 8 value columns: two short strings, two `float`, three `double`, a `bool`), 120 bytes per row; - - a spike event table: 8 columns (7 key columns), 79 bytes per row; - - a unit location table: 14 columns (9 key columns), 300 rows. + - an event table: 8 columns (7 key columns), 79 bytes per row; + - a small lookup table: 14 columns (9 key columns), a few hundred rows. - They are stored in the test suite's disk-backed fake of the SpiralDB client (`tests/test_databases/fake_spiral_sdk.py`), so the real `SpiralDBTableSource` reads them. The fake memory-maps its file, so the rows it hands over are not process memory @@ -56,7 +55,7 @@ enough that no SpiralDB read was needed. - The synthetic ids are shorter than live ones (a 23-character project id, a 32-character hash key), so a live token is longer and the live numbers are higher. -## The sync path, outside a job (2,177,155 rows) +## The sync path, outside a job (about 2.2 million rows) "Ratio" is peak resident memory, less the import baseline, over the input's Arrow bytes. @@ -72,7 +71,7 @@ enough that no SpiralDB read was needed. | `source.drop_nulls(...)` | 248 MiB | 277 MiB | 19.7 GiB | 18.6 GiB | 80 | input with tokens and a filtered copy with tokens, both held | | `source.polars_filter(...)` | 248 MiB | 141 MiB | 16.6 GiB | 9.3 GiB | 68 | input with tokens, and every column copied into Polars and back | | `source.group_by(key)` | 248 MiB | 143 MiB | 20.9 GiB | 15.9 GiB | 85 | input with tokens, the sorted copy, and a token list per group and column | -| `spikes.join(locations)` | 164 MiB | - | killed, above 24 GiB | - | above 150 | at 200,000 rows: 2.96 GiB, ratio 191. Each output row carries the tokens of both inputs: 22 columns | +| `events.join(lookup)` | 164 MiB | - | killed, above 24 GiB | - | above 150 | at 200,000 rows: 2.96 GiB, ratio 191. Each output row carries the tokens of both inputs: 22 columns | | `drop_nulls`, `group_by`, `map_data` | 248 MiB | - | killed, above 24 GiB | - | above 100 | at 200,000 rows: 2.89 GiB, ratio 123 | | the same, then a function pod | 248 MiB | - | killed, above 24 GiB | - | above 100 | at 200,000 rows: 3.05 GiB, ratio 131 | | `source.flow()` | 248 MiB | - | killed, above 24 GiB | - | above 100 | at 200,000 rows: 3.58 GiB, 18 KiB per row | @@ -116,7 +115,7 @@ Three places hold every row this way today: ### The keys a source remembers `SpiralDBTableSource` keeps the record id of every row it has read during one read, to -refuse a repeated key. At 2,177,155 rows that is a Python set of about 130-character +refuse a repeated key. At about 2.2 million rows that is a Python set of about 130-character strings: roughly 0.5 GiB, most of the 1.4 GiB of plain iteration. ## Inside a job: sync and async @@ -142,7 +141,7 @@ The last job at larger sizes: | 50,000 | 1.09 GiB | 19.8 KiB | 5.05 GiB | 103 KiB | 32 s | | 100,000 | 1.99 GiB | 19.4 KiB | 9.98 GiB | 103 KiB | 63 s | | 200,000 | 3.81 GiB | 19.2 KiB | 19.67 GiB | 102 KiB | 127 s | -| 2,177,155 | killed, above 24 GiB (41 GiB extrapolated) | | not run (207 GiB extrapolated) | | (23 min extrapolated) | +| about 2.2 million | killed, above 24 GiB (41 GiB extrapolated) | | not run (207 GiB extrapolated) | | (23 min extrapolated) | ### Does the async path stream today? @@ -177,7 +176,7 @@ practice it has the same gathering as sync, at the per-row object price. ## What each cause is worth -| Cause | Where | Size at 2.18 million rows | What removes it | +| Cause | Where | Size at 2.2 million rows | What removes it | |---|---|---|---| | Rows as objects, kept by every async node | async transport, `OperatorNode.async_execute`, `iter_data` cache, `flow()` | about 100 KiB per row and node chain: 200 GiB | record batches between nodes (ITL-1347 wiring); a node keeps a reference to stored or spilled rows, not the rows | | Source-info tokens | every source read, every operator's input and output | 4.2 KiB per row per tokenized copy: 9 GiB per copy, 2 to 3 copies per operator | not building them where nothing reads them (prototype, below); deriving a source's tokens from its system tags until an operator changes them (design) | @@ -189,7 +188,7 @@ practice it has the same gathering as sync, at the per-row object price. A `SpiralDBTableSource` read whose result holds no source-info column and no content hash (`as_table()`, `run()`, `as_polars_df()` with the default columns) no longer builds -tokens. Same rows, same table, at 2,177,155 rows: +tokens. Same rows, same table, at about 2.2 million rows: | Step | Peak RSS before | Peak RSS after | Arrow pool peak before | after | |---|---|---|---|---| diff --git a/docs/dev/specs/itl-1464-streaming-design.md b/docs/dev/specs/itl-1464-streaming-design.md index bf00c5bdb..16ff3c515 100644 --- a/docs/dev/specs/itl-1464-streaming-design.md +++ b/docs/dev/specs/itl-1464-streaming-design.md @@ -5,8 +5,8 @@ measurements it rests on are in `itl-1464-memory-diagnosis.md`. Decisions the de has made are marked **Decided**; decisions still open are marked **OPEN** and listed again at the end. -LFP tables are out of scope (developer, November 25, 2026): one LFP row holds 384 samples, -and a session of them is a different problem. Nothing here is designed or tested for them. +Tables whose rows hold long sample arrays are out of scope (developer, November 25, 2026): +a session of them is a different problem. Nothing here is designed or tested for them. ## The governing rules @@ -79,7 +79,7 @@ One mechanism holds rows that are computed but not in memory. the process, no result is read from it by a later process, and it holds no hash. Without source-info tokens materialized (section 7) a cache file is about the size of the -rows' Arrow data: 248 MiB for the measured 2.18 million row session. +rows' Arrow data: 248 MiB for the measured 2.2 million row session. ## 3. What a job node keeps, and the view @@ -451,10 +451,10 @@ With sections 2 to 7 in place, for a job run by the async orchestrator: **The bound to state to users**: peak memory of an async job is `(batches in flight) × (batch bytes) + (key bytes + 8) × (rows indexed by joins and groupings) + 16 × (rows of verified sources) + the largest single row`. -For the measured session (2.18 million rows of 120 bytes, one grouping, one function +For the measured session (2.2 million rows of 120 bytes, one grouping, one function pod) that is under 0.5 GiB, against about 210 GiB today. -**Proposed budget for the workshop** (**OPEN, M1**): a job over every non-LFP table of a +**Proposed budget for the workshop** (**OPEN, M1**): a job over every table in scope of a sample dataset peaks below 4 GiB on the async path, checked on synthetic tables of the dataset's shapes and then once live, read-only. @@ -526,7 +526,7 @@ holds rows (cache files, `as_table()`, the sync path). | T1 | Source tokens held as a recipe until read | yes, after the transport | | T2 | Token lists of `GroupBy` and `Batch` as a recipe | after T1, measured first | | U1 | Iteration keeps no row objects | accept | -| M1 | The workshop budget | 4 GiB peak, async, non-LFP | +| M1 | The workshop budget | 4 GiB peak, async, tables in scope | Approved by the coordinator on the developer's delegation (November 25, 2026), each for the developer's review: N1 (a job node reads its run's rows from storage or a local @@ -541,4 +541,4 @@ computation and nothing about how; async is the primary memory-bounded path; joi keys only, with rows fetched from a local cache; certificates originate in Orcapod and are trusted by derivation, a source's claim is verified as data flows, and a key the store enforces is trusted; a certificate enters no hash or identity; an async join's -memory is at worst linear in one input; LFP is out of scope. +memory is at worst linear in one input; tables of long sample arrays are out of scope. diff --git a/docs/dev/specs/itl-1464/measure.py b/docs/dev/specs/itl-1464/measure.py index c5967bfd0..629f2d549 100644 --- a/docs/dev/specs/itl-1464/measure.py +++ b/docs/dev/specs/itl-1464/measure.py @@ -1,15 +1,14 @@ -"""Measure the memory of one step of a workshop-shaped pipeline (ITL-1464). +"""Measure the memory of one step of an analysis-shaped pipeline (ITL-1464). One step per process, so that a step's peak is its own:: - uv run python docs/dev/specs/itl-1464/measure.py setup --rows 2177155 --store + uv run python docs/dev/specs/itl-1464/measure.py setup --rows 2200000 --store uv run python docs/dev/specs/itl-1464/measure.py --store ``run_measurements.py`` runs every step under a memory guard and writes the table. The tables are synthetic: the column names and Arrow types of three tables of a -SpiralDB sample dataset (a gaze time series, a spike event table and a unit location -table), with generated values. They are stored in the disk-backed fake of the SpiralDB +SpiralDB sample dataset (a time series, an event table and a small lookup table), with generated values. They are stored in the disk-backed fake of the SpiralDB client that the test suite uses (``tests/test_databases/fake_spiral_sdk.py``), so the real ``SpiralDBTableSource`` reads them: the code under measurement is the library's, only the service is replaced. The fake memory-maps the stored file, so the rows it @@ -45,51 +44,51 @@ from tests.test_databases import fake_spiral_sdk as fake # noqa: E402 PROJECT = "synthetic-sample-000000" -GAZE = "experiment_gaze_online_timeseries" -SPIKES = "spike_event" -LOCATIONS = "unit_location" +SERIES = "time_series" +EVENTS = "event" +LOCATIONS = "lookup" SESSION_START = datetime(2026, 1, 1, 12, 0, 0) SUBJECT = "subject" HASH = "0123456789abcdef0123456789abcdef" -EXPERIMENTS = 6 -UNITS = 300 +BLOCKS = 6 +ITEMS = 300 -GAZE_KEYS = [ - "experiment_preprocessing_hash", +SERIES_KEYS = [ + "processing_hash", "subject_id", - "session_start_datetime", - "experiment_index", + "session_start", + "block_index", "timestamp", ] -EXPERIMENT_KEY = GAZE_KEYS[:4] -SPIKE_KEYS = [ - "spike_extraction_hash", +BLOCK_KEY = SERIES_KEYS[:4] +EVENT_KEYS = [ + "extraction_hash", "subject_id", - "session_start_datetime", + "session_start", "recording_index", - "probe_index", + "device_index", "timestamp", - "unit_id", + "item_id", ] -UNIT_KEY = [ - "spike_extraction_hash", +ITEM_KEY = [ + "extraction_hash", "subject_id", - "session_start_datetime", + "session_start", "recording_index", - "probe_index", - "unit_id", + "device_index", + "item_id", ] LOCATION_KEYS = [ - "spike_extraction_hash", - "localization_hash", + "extraction_hash", + "placement_hash", "subject_id", - "session_start_datetime", + "session_start", "recording_index", - "probe_index", - "unit_id", - "atlas_id", - "atlas_label_region_short", + "device_index", + "item_id", + "map_id", + "region_short", ] @@ -97,81 +96,73 @@ def _constant(value: Any, kind: pa.DataType, rows: int) -> pa.Array[Any]: return pa.array([value] * rows, kind) -def gaze_table(rows: int) -> pa.Table: - """Return ``rows`` rows shaped like one session of the gaze time series.""" +def time_series_table(rows: int) -> pa.Table: + """Return ``rows`` rows shaped like one session of the time series.""" rng = np.random.default_rng(0) - per_experiment = -(-rows // EXPERIMENTS) - experiment = np.repeat(np.arange(EXPERIMENTS, dtype=np.uint32), per_experiment)[ - :rows - ] + per_block = -(-rows // BLOCKS) + block = np.repeat(np.arange(BLOCKS, dtype=np.uint32), per_block)[:rows] timestamp = np.arange(rows, dtype=np.uint64) * 5_000 + 1_700_000_000_000_000 x = rng.normal(size=rows) y = rng.normal(size=rows) - # A few nulls, as blinks leave: ``drop_nulls`` has rows to drop. + # A few nulls: ``drop_nulls`` has rows to drop. missing = rng.random(rows) < 0.02 return pa.table( { - "experiment_preprocessing_hash": _constant(HASH, pa.string(), rows), + "processing_hash": _constant(HASH, pa.string(), rows), "subject_id": _constant(SUBJECT, pa.string(), rows), - "session_start_datetime": _constant( - SESSION_START, pa.timestamp("us"), rows - ), - "experiment_index": pa.array(experiment), + "session_start": _constant(SESSION_START, pa.timestamp("us"), rows), + "block_index": pa.array(block), "timestamp": pa.array(timestamp), - "eye_tracking_software": _constant("tracker", pa.string(), rows), - "eye_tracking_software_version": _constant("1.2.3", pa.string(), rows), - "eye_x_deg": pa.array(x.astype(np.float32), mask=missing), - "eye_x_px": pa.array(x * 100, mask=missing), - "eye_y_deg": pa.array(y.astype(np.float32), mask=missing), - "eye_y_px": pa.array(y * 100, mask=missing), - "gaze_unreliable": pa.array(missing), - "pupil_size_norm": pa.array(rng.random(rows)), + "software": _constant("reader", pa.string(), rows), + "software_version": _constant("1.2.3", pa.string(), rows), + "x_small": pa.array(x.astype(np.float32), mask=missing), + "x_wide": pa.array(x * 100, mask=missing), + "y_small": pa.array(y.astype(np.float32), mask=missing), + "y_wide": pa.array(y * 100, mask=missing), + "unreliable": pa.array(missing), + "level": pa.array(rng.random(rows)), } ) -def spike_table(rows: int) -> pa.Table: - """Return ``rows`` rows shaped like one session of the spike event table.""" +def event_table(rows: int) -> pa.Table: + """Return ``rows`` rows shaped like one session of the event table.""" rng = np.random.default_rng(1) timestamp = np.arange(rows, dtype=np.uint64) * 400 + 1_700_000_000_000_000 return pa.table( { - "spike_extraction_hash": _constant(HASH, pa.string(), rows), + "extraction_hash": _constant(HASH, pa.string(), rows), "subject_id": _constant(SUBJECT, pa.string(), rows), - "session_start_datetime": _constant( - SESSION_START, pa.timestamp("us"), rows - ), + "session_start": _constant(SESSION_START, pa.timestamp("us"), rows), "recording_index": _constant(0, pa.uint32(), rows), - "probe_index": _constant(0, pa.uint32(), rows), + "device_index": _constant(0, pa.uint32(), rows), "timestamp": pa.array(timestamp), - "unit_id": pa.array(rng.integers(0, UNITS, rows).astype(np.uint32)), - "spike_amplitude_uv": pa.array(rng.normal(size=rows).astype(np.float32)), + "item_id": pa.array(rng.integers(0, ITEMS, rows).astype(np.uint32)), + "amplitude": pa.array(rng.normal(size=rows).astype(np.float32)), } ) -def location_table() -> pa.Table: - """Return one row per unit, shaped like the unit location table.""" +def lookup_table() -> pa.Table: + """Return one row per item, shaped like the lookup table.""" rng = np.random.default_rng(2) - rows = UNITS + rows = ITEMS return pa.table( { - "spike_extraction_hash": _constant(HASH, pa.string(), rows), - "localization_hash": _constant(HASH[::-1], pa.string(), rows), + "extraction_hash": _constant(HASH, pa.string(), rows), + "placement_hash": _constant(HASH[::-1], pa.string(), rows), "subject_id": _constant(SUBJECT, pa.string(), rows), - "session_start_datetime": _constant( - SESSION_START, pa.timestamp("us"), rows - ), + "session_start": _constant(SESSION_START, pa.timestamp("us"), rows), "recording_index": _constant(0, pa.uint32(), rows), - "probe_index": _constant(0, pa.uint32(), rows), - "unit_id": pa.array(np.arange(rows, dtype=np.uint32)), - "atlas_id": _constant("atlas", pa.string(), rows), - "atlas_label_region_short": _constant("V1", pa.string(), rows), - "atlas_label_region_full": _constant("area", pa.string(), rows), - "chamber_id": _constant("chamber", pa.string(), rows), - "chamber_x_um": pa.array(rng.normal(size=rows)), - "chamber_y_um": pa.array(rng.normal(size=rows)), - "chamber_z_um": pa.array(rng.normal(size=rows)), + "device_index": _constant(0, pa.uint32(), rows), + "item_id": pa.array(np.arange(rows, dtype=np.uint32)), + "map_id": _constant("map", pa.string(), rows), + "region_short": _constant("r1", pa.string(), rows), + "region_full": _constant("area", pa.string(), rows), + "frame_id": _constant("frame", pa.string(), rows), + "x_um": pa.array(rng.normal(size=rows)), + "y_um": pa.array(rng.normal(size=rows)), + "z_um": pa.array(rng.normal(size=rows)), } ) @@ -182,9 +173,9 @@ def setup(rows: int) -> None: store = fake._store() for name, keys, table in ( - (GAZE, GAZE_KEYS, gaze_table(rows)), - (SPIKES, SPIKE_KEYS, spike_table(rows)), - (LOCATIONS, LOCATION_KEYS, location_table()), + (SERIES, SERIES_KEYS, time_series_table(rows)), + (EVENTS, EVENT_KEYS, event_table(rows)), + (LOCATIONS, LOCATION_KEYS, lookup_table()), ): made = fake.ExternalProject(PROJECT).create_table( f"default.{name}", key_schema=[table.schema.field(k) for k in keys] @@ -216,19 +207,19 @@ def _raw(name: str) -> pa.Table: def step_raw_copy() -> tuple[int, int, Any]: """The rows alone, copied into process memory: the floor every step stands on.""" - raw = _raw(GAZE) + raw = _raw(SERIES) # ``take`` writes new buffers: the rows as private memory of this process. copy = raw.take(np.arange(raw.num_rows)) return raw.nbytes, copy.nbytes, copy def step_as_table() -> tuple[int, int, Any]: - table = _source(GAZE).as_table() - return _raw(GAZE).nbytes, table.nbytes, table + table = _source(SERIES).as_table() + return _raw(SERIES).nbytes, table.nbytes, table def step_as_table_all_info() -> tuple[int, int, Any]: - table = _source(GAZE).as_table(all_info=True) + table = _source(SERIES).as_table(all_info=True) groups: dict[str, int] = {"user": 0, "source_info": 0, "system_tags": 0, "other": 0} for name in table.column_names: size = table.column(name).nbytes @@ -241,105 +232,105 @@ def step_as_table_all_info() -> tuple[int, int, Any]: else: groups["user"] += size print(json.dumps({"column_group_bytes": groups}), file=sys.stderr) - return _raw(GAZE).nbytes, table.nbytes, table + return _raw(SERIES).nbytes, table.nbytes, table def step_run() -> tuple[int, int, Any]: - view = _source(GAZE).run() - return _raw(GAZE).nbytes, 0, view + view = _source(SERIES).run() + return _raw(SERIES).nbytes, 0, view def step_run_then_as_table() -> tuple[int, int, Any]: - source = _source(GAZE) + source = _source(SERIES) view = source.run() table = source.as_table() - return _raw(GAZE).nbytes, table.nbytes, (view, table) + return _raw(SERIES).nbytes, table.nbytes, (view, table) def step_as_polars_df() -> tuple[int, int, Any]: - frame = _source(GAZE).as_polars_df() - return _raw(GAZE).nbytes, int(frame.estimated_size()), frame + frame = _source(SERIES).as_polars_df() + return _raw(SERIES).nbytes, int(frame.estimated_size()), frame def step_iterate() -> tuple[int, int, Any]: count = 0 - for _tag, _data in _source(GAZE): + for _tag, _data in _source(SERIES): count += 1 - return _raw(GAZE).nbytes, 0, count + return _raw(SERIES).nbytes, 0, count def step_iterate_read_one_value() -> tuple[int, int, Any]: total = 0.0 - for _tag, data in _source(GAZE): - total += data["pupil_size_norm"] - return _raw(GAZE).nbytes, 0, total + for _tag, data in _source(SERIES): + total += data["level"] + return _raw(SERIES).nbytes, 0, total def step_flow() -> tuple[int, int, Any]: - pairs = _source(GAZE).flow() - return _raw(GAZE).nbytes, 0, pairs + pairs = _source(SERIES).flow() + return _raw(SERIES).nbytes, 0, pairs def step_drop_nulls() -> tuple[int, int, Any]: - table = _source(GAZE).drop_nulls(["eye_x_deg", "eye_y_deg"]).as_table() - return _raw(GAZE).nbytes, table.nbytes, table + table = _source(SERIES).drop_nulls(["x_small", "y_small"]).as_table() + return _raw(SERIES).nbytes, table.nbytes, table def step_polars_filter() -> tuple[int, int, Any]: import polars as pl - table = _source(GAZE).polars_filter(pl.col("pupil_size_norm") > 0.5).as_table() - return _raw(GAZE).nbytes, table.nbytes, table + table = _source(SERIES).polars_filter(pl.col("level") > 0.5).as_table() + return _raw(SERIES).nbytes, table.nbytes, table def step_map_data() -> tuple[int, int, Any]: - table = _source(GAZE).map_data({"pupil_size_norm": "pupil"}).as_table() - return _raw(GAZE).nbytes, table.nbytes, table + table = _source(SERIES).map_data({"level": "pupil"}).as_table() + return _raw(SERIES).nbytes, table.nbytes, table def step_join() -> tuple[int, int, Any]: - table = _source(SPIKES).join(_source(LOCATIONS)).as_table() - return _raw(SPIKES).nbytes + _raw(LOCATIONS).nbytes, table.nbytes, table + table = _source(EVENTS).join(_source(LOCATIONS)).as_table() + return _raw(EVENTS).nbytes + _raw(LOCATIONS).nbytes, table.nbytes, table -def _grouped_gaze() -> Any: +def _grouped_series() -> Any: return ( - _source(GAZE) - .drop_nulls(["eye_x_deg", "eye_y_deg"]) - .group_by(EXPERIMENT_KEY) - .map_data({"timestamp": "gaze_time"}) + _source(SERIES) + .drop_nulls(["x_small", "y_small"]) + .group_by(BLOCK_KEY) + .map_data({"timestamp": "sample_time"}) ) def step_group_by() -> tuple[int, int, Any]: - table = _source(GAZE).group_by(EXPERIMENT_KEY).as_table() - return _raw(GAZE).nbytes, table.nbytes, table + table = _source(SERIES).group_by(BLOCK_KEY).as_table() + return _raw(SERIES).nbytes, table.nbytes, table def step_group_by_chain() -> tuple[int, int, Any]: - table = _grouped_gaze().as_table() - return _raw(GAZE).nbytes, table.nbytes, table + table = _grouped_series().as_table() + return _raw(SERIES).nbytes, table.nbytes, table def _onsets_pod() -> Any: from orcapod import function_pod - @function_pod(output_keys="fixation_onset") - def fixation_onsets( - gaze_time: list[int], eye_x_deg: list[float], eye_y_deg: list[float] + @function_pod(output_keys="onset") + def onsets( + sample_time: list[int], x_small: list[float], y_small: list[float] ) -> list[int]: - t, x, y = np.asarray(gaze_time), np.asarray(eye_x_deg), np.asarray(eye_y_deg) + t, x, y = np.asarray(sample_time), np.asarray(x_small), np.asarray(y_small) speed = np.hypot(np.diff(x), np.diff(y)) / (np.diff(t) / 1_000_000) moving = speed > 40 ends = np.flatnonzero(moving[:-1] & ~moving[1:]) + 1 return [int(t[i]) for i in ends] - return fixation_onsets + return onsets def step_function_pod() -> tuple[int, int, Any]: - table = _onsets_pod().pod(_grouped_gaze()).as_table() - return _raw(GAZE).nbytes, table.nbytes, table + table = _onsets_pod().pod(_grouped_series()).as_table() + return _raw(SERIES).nbytes, table.nbytes, table def _job(store: Path) -> Any: @@ -347,15 +338,15 @@ def _job(store: Path) -> Any: from orcapod.databases import DeltaTableDatabase database = DeltaTableDatabase(str(store / "results")) - with PipelineJob(name="fixation_response", database=database) as job: - _onsets_pod().pod(_grouped_gaze(), label="onsets") + with PipelineJob(name="chain", database=database) as job: + _onsets_pod().pod(_grouped_series(), label="onsets") return job def step_job_run(store: Path) -> tuple[int, int, Any]: job = _job(store) job.run() - return _raw(GAZE).nbytes, 0, job + return _raw(SERIES).nbytes, 0, job def step_job_run_async_unkept(store: Path) -> tuple[int, int, Any]: @@ -363,7 +354,7 @@ def step_job_run_async_unkept(store: Path) -> tuple[int, int, Any]: job = _job(store) job.run(orchestrator=AsyncPipelineOrchestrator(), materialize_results=False) - return _raw(GAZE).nbytes, 0, job + return _raw(SERIES).nbytes, 0, job def step_job_run_async(store: Path) -> tuple[int, int, Any]: @@ -371,20 +362,18 @@ def step_job_run_async(store: Path) -> tuple[int, int, Any]: job = _job(store) job.run(orchestrator=AsyncPipelineOrchestrator()) - return _raw(GAZE).nbytes, 0, job + return _raw(SERIES).nbytes, 0, job def _operator_chains() -> dict[str, Callable[[], Any]]: import polars as pl return { - "map_data": lambda: _source(GAZE).map_data({"pupil_size_norm": "pupil"}), - "drop_nulls": lambda: _source(GAZE).drop_nulls(["eye_x_deg", "eye_y_deg"]), - "polars_filter": lambda: _source(GAZE).polars_filter( - pl.col("pupil_size_norm") > 0.5 - ), - "join": lambda: _source(SPIKES).join(_source(LOCATIONS)), - "group_by": lambda: _source(GAZE).group_by(EXPERIMENT_KEY), + "map_data": lambda: _source(SERIES).map_data({"level": "pupil"}), + "drop_nulls": lambda: _source(SERIES).drop_nulls(["x_small", "y_small"]), + "polars_filter": lambda: _source(SERIES).polars_filter(pl.col("level") > 0.5), + "join": lambda: _source(EVENTS).join(_source(LOCATIONS)), + "group_by": lambda: _source(SERIES).group_by(BLOCK_KEY), } @@ -406,7 +395,7 @@ def step(store: Path) -> tuple[int, int, Any]: job.run(orchestrator=AsyncPipelineOrchestrator(), materialize_results=False) else: job.run() - name = SPIKES if chain == "join" else GAZE + name = EVENTS if chain == "join" else SERIES return _raw(name).nbytes, 0, job return step @@ -449,7 +438,7 @@ def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("step", choices=["setup", *STEPS]) parser.add_argument("--store", required=True, type=Path) - parser.add_argument("--rows", type=int, default=2_177_155) + parser.add_argument("--rows", type=int, default=2_200_000) parser.add_argument("--tracemalloc", action="store_true") args = parser.parse_args() warnings.simplefilter("ignore") @@ -473,7 +462,7 @@ def main() -> None: elapsed = time.perf_counter() - started record: dict[str, Any] = { "step": args.step, - "rows": _raw(GAZE).num_rows, + "rows": _raw(SERIES).num_rows, "input_arrow_bytes": in_bytes, "output_arrow_bytes": out_bytes, "rss_before_bytes": before, diff --git a/docs/dev/specs/itl-1464/run_measurements.py b/docs/dev/specs/itl-1464/run_measurements.py index fbeb141f9..ac72ac539 100644 --- a/docs/dev/specs/itl-1464/run_measurements.py +++ b/docs/dev/specs/itl-1464/run_measurements.py @@ -1,7 +1,7 @@ """Run every step of ``measure.py`` in its own process, under a memory guard (ITL-1464). uv run python docs/dev/specs/itl-1464/run_measurements.py --store \ - --rows 2177155 --out [--steps as_table run ...] + --rows 2200000 --out [--steps as_table run ...] A step whose resident memory passes ``--guard-gb`` (24 by default) is killed and recorded as ``killed``; nothing here may starve the machine it runs on. @@ -79,7 +79,7 @@ def run_step( def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--store", required=True, type=Path) - parser.add_argument("--rows", type=int, default=2_177_155) + parser.add_argument("--rows", type=int, default=2_200_000) parser.add_argument("--out", required=True, type=Path) parser.add_argument("--guard-gb", type=float, default=24.0) parser.add_argument("--steps", nargs="*", default=DEFAULT_STEPS) From 65392680f2ea8b9b0ea9d618841cd7ceef6fa9a0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:38:09 -0800 Subject: [PATCH 16/81] docs(dev): generic table and column names, rounded sizes in the ITL-1464 material Co-Authored-By: Claude Fable 5.2 --- docs/dev/specs/itl-1464-memory-diagnosis.md | 41 ++- docs/dev/specs/itl-1464-streaming-design.md | 26 +- docs/dev/specs/itl-1464/measure.py | 275 ++++++++++---------- docs/dev/specs/itl-1464/run_measurements.py | 4 +- 4 files changed, 188 insertions(+), 158 deletions(-) diff --git a/docs/dev/specs/itl-1464-memory-diagnosis.md b/docs/dev/specs/itl-1464-memory-diagnosis.md index 7a6d629c7..4bf2c9276 100644 --- a/docs/dev/specs/itl-1464-memory-diagnosis.md +++ b/docs/dev/specs/itl-1464-memory-diagnosis.md @@ -12,8 +12,7 @@ Three causes account for the memory, in this order of size: as a pair of datagram objects, and every operator job node keeps every pair of its output until the run ends. One async job over 200,000 rows peaks at 19.7 GiB (102 KiB per row, 877 times the input); the cost is linear in rows, so the full - session (2,177,155 rows) extrapolates to about 210 GiB. This is the workshop - notebook's 145 to 166 GB. + session (about 2.2 million rows) extrapolates to about 210 GiB. This is the size of the reported notebook run. 2. **Source-info tokens are 35 times the data.** A source writes one string per row and data column, `::::`, about 324 bytes each here. With 13 data columns (every key column is a data-tag, so it has a token too) that is 4.2 KiB @@ -39,11 +38,11 @@ enough that no SpiralDB read was needed. step, each in a fresh process, killed above 24 GiB of resident memory). - Tables: synthetic, with the column names and Arrow types of three tables of a SpiralDB sample dataset, one session each: - - a gaze time series: 13 columns (5 key columns: two strings, a timestamp, a `uint32`, + - a time series: 13 columns (5 key columns: two strings, a timestamp, a `uint32`, a `uint64`; 8 value columns: two short strings, two `float`, three `double`, a `bool`), 120 bytes per row; - - a spike event table: 8 columns (7 key columns), 79 bytes per row; - - a unit location table: 14 columns (9 key columns), 300 rows. + - an event table: 8 columns (7 key columns), 79 bytes per row; + - a small lookup table: 14 columns (9 key columns), a few hundred rows. - They are stored in the test suite's disk-backed fake of the SpiralDB client (`tests/test_databases/fake_spiral_sdk.py`), so the real `SpiralDBTableSource` reads them. The fake memory-maps its file, so the rows it hands over are not process memory @@ -56,7 +55,7 @@ enough that no SpiralDB read was needed. - The synthetic ids are shorter than live ones (a 23-character project id, a 32-character hash key), so a live token is longer and the live numbers are higher. -## The sync path, outside a job (2,177,155 rows) +## The sync path, outside a job (about 2.2 million rows) "Ratio" is peak resident memory, less the import baseline, over the input's Arrow bytes. @@ -72,7 +71,7 @@ enough that no SpiralDB read was needed. | `source.drop_nulls(...)` | 248 MiB | 277 MiB | 19.7 GiB | 18.6 GiB | 80 | input with tokens and a filtered copy with tokens, both held | | `source.polars_filter(...)` | 248 MiB | 141 MiB | 16.6 GiB | 9.3 GiB | 68 | input with tokens, and every column copied into Polars and back | | `source.group_by(key)` | 248 MiB | 143 MiB | 20.9 GiB | 15.9 GiB | 85 | input with tokens, the sorted copy, and a token list per group and column | -| `spikes.join(locations)` | 164 MiB | - | killed, above 24 GiB | - | above 150 | at 200,000 rows: 2.96 GiB, ratio 191. Each output row carries the tokens of both inputs: 22 columns | +| `events.join(lookup)` | 164 MiB | - | killed, above 24 GiB | - | above 150 | at 200,000 rows: 2.96 GiB, ratio 191. Each output row carries the tokens of both inputs: 22 columns | | `drop_nulls`, `group_by`, `map_data` | 248 MiB | - | killed, above 24 GiB | - | above 100 | at 200,000 rows: 2.89 GiB, ratio 123 | | the same, then a function pod | 248 MiB | - | killed, above 24 GiB | - | above 100 | at 200,000 rows: 3.05 GiB, ratio 131 | | `source.flow()` | 248 MiB | - | killed, above 24 GiB | - | above 100 | at 200,000 rows: 3.58 GiB, 18 KiB per row | @@ -116,7 +115,7 @@ Three places hold every row this way today: ### The keys a source remembers `SpiralDBTableSource` keeps the record id of every row it has read during one read, to -refuse a repeated key. At 2,177,155 rows that is a Python set of about 130-character +refuse a repeated key. At about 2.2 million rows that is a Python set of about 130-character strings: roughly 0.5 GiB, most of the 1.4 GiB of plain iteration. ## Inside a job: sync and async @@ -142,7 +141,7 @@ The last job at larger sizes: | 50,000 | 1.09 GiB | 19.8 KiB | 5.05 GiB | 103 KiB | 32 s | | 100,000 | 1.99 GiB | 19.4 KiB | 9.98 GiB | 103 KiB | 63 s | | 200,000 | 3.81 GiB | 19.2 KiB | 19.67 GiB | 102 KiB | 127 s | -| 2,177,155 | killed, above 24 GiB (41 GiB extrapolated) | | not run (207 GiB extrapolated) | | (23 min extrapolated) | +| about 2.2 million | killed, above 24 GiB (41 GiB extrapolated) | | not run (207 GiB extrapolated) | | (23 min extrapolated) | ### Does the async path stream today? @@ -177,7 +176,7 @@ practice it has the same gathering as sync, at the per-row object price. ## What each cause is worth -| Cause | Where | Size at 2.18 million rows | What removes it | +| Cause | Where | Size at 2.2 million rows | What removes it | |---|---|---|---| | Rows as objects, kept by every async node | async transport, `OperatorNode.async_execute`, `iter_data` cache, `flow()` | about 100 KiB per row and node chain: 200 GiB | record batches between nodes (ITL-1347 wiring); a node keeps a reference to stored or spilled rows, not the rows | | Source-info tokens | every source read, every operator's input and output | 4.2 KiB per row per tokenized copy: 9 GiB per copy, 2 to 3 copies per operator | not building them where nothing reads them (prototype, below); deriving a source's tokens from its system tags until an operator changes them (design) | @@ -189,7 +188,7 @@ practice it has the same gathering as sync, at the per-row object price. A `SpiralDBTableSource` read whose result holds no source-info column and no content hash (`as_table()`, `run()`, `as_polars_df()` with the default columns) no longer builds -tokens. Same rows, same table, at 2,177,155 rows: +tokens. Same rows, same table, at about 2.2 million rows: | Step | Peak RSS before | Peak RSS after | Arrow pool peak before | after | |---|---|---|---|---| @@ -203,3 +202,23 @@ It removes the largest cost of the reported case (a) and nothing of case (b): an operator and a job still read the tokens. What remains of the 1.96 GiB is the system tags (0.5 GiB of Arrow), the set of keys seen (0.5 GiB of Python strings) and the copy made when the batches are joined. + +## The first transport step's effect + +Async rows kept as Arrow tables of at most 8,192 rows instead of one pair of objects per +row (the orchestrator's collectors and drain, an operator job node's kept output, a +barrier operator's gathered input and its result while sent). Async job, peak resident +memory less the import, per row; before at 20,000 rows, after at 200,000: + +| Job | Before | After | +|---|---|---| +| `map_data` | 54 KiB | 7.7 KiB | +| `drop_nulls` | 90 KiB | 8.6 KiB | +| `polars_filter` | 109 KiB | 12.5 KiB | +| `join` (large with small) | 68 KiB | 21 KiB | +| `group_by` | 57 KiB | 15 KiB | +| `drop_nulls`, `group_by`, `map_data`, function pod | 102 KiB (19.7 GiB at 200,000 rows) | 24 KiB (4.8 GiB) | + +The async path now costs about what the sync path does. What remains is cause 2 and +cause 3: each node keeps its tokenized table (about 4.5 KiB per row per copy), and +`Join` buffers both inputs in the row form. diff --git a/docs/dev/specs/itl-1464-streaming-design.md b/docs/dev/specs/itl-1464-streaming-design.md index 936109554..16ff3c515 100644 --- a/docs/dev/specs/itl-1464-streaming-design.md +++ b/docs/dev/specs/itl-1464-streaming-design.md @@ -5,8 +5,8 @@ measurements it rests on are in `itl-1464-memory-diagnosis.md`. Decisions the de has made are marked **Decided**; decisions still open are marked **OPEN** and listed again at the end. -LFP tables are out of scope (developer, November 25, 2026): one LFP row holds 384 samples, -and a session of them is a different problem. Nothing here is designed or tested for them. +Tables whose rows hold long sample arrays are out of scope (developer, November 25, 2026): +a session of them is a different problem. Nothing here is designed or tested for them. ## The governing rules @@ -79,7 +79,7 @@ One mechanism holds rows that are computed but not in memory. the process, no result is read from it by a later process, and it holds no hash. Without source-info tokens materialized (section 7) a cache file is about the size of the -rows' Arrow data: 248 MiB for the measured 2.18 million row session. +rows' Arrow data: 248 MiB for the measured 2.2 million row session. ## 3. What a job node keeps, and the view @@ -451,10 +451,10 @@ With sections 2 to 7 in place, for a job run by the async orchestrator: **The bound to state to users**: peak memory of an async job is `(batches in flight) × (batch bytes) + (key bytes + 8) × (rows indexed by joins and groupings) + 16 × (rows of verified sources) + the largest single row`. -For the measured session (2.18 million rows of 120 bytes, one grouping, one function +For the measured session (2.2 million rows of 120 bytes, one grouping, one function pod) that is under 0.5 GiB, against about 210 GiB today. -**Proposed budget for the workshop** (**OPEN, M1**): a job over every non-LFP table of a +**Proposed budget for the workshop** (**OPEN, M1**): a job over every table in scope of a sample dataset peaks below 4 GiB on the async path, checked on synthetic tables of the dataset's shapes and then once live, read-only. @@ -487,7 +487,9 @@ the synthetic tables of the diagnosis; none changes a hash, a stored layout or a value. 1. **Done (PR 558)**: a SpiralDB read that returns no tokens builds none. -2. Rows on the async path as record batches: wire `async_execute_batches` and the +2. **First part done (PR 562)**: rows kept on the async path as Arrow tables of at most + 8,192 rows, never as a list of pairs (async now costs about what sync does). Remaining: + rows on the async path as record batches: wire `async_execute_batches` and the record-batch channels into the nodes and the async orchestrator (ITL-1347's remaining stages), give `PolarsFilter` `ROW_BY_ROW`. Removes the 18 to 110 KiB per row. 3. The local cache, and job nodes that keep a reference (section 3). Removes "every node @@ -524,11 +526,19 @@ holds rows (cache files, `as_table()`, the sync path). | T1 | Source tokens held as a recipe until read | yes, after the transport | | T2 | Token lists of `GroupBy` and `Batch` as a recipe | after T1, measured first | | U1 | Iteration keeps no row objects | accept | -| M1 | The workshop budget | 4 GiB peak, async, non-LFP | +| M1 | The workshop budget | 4 GiB peak, async, tables in scope | + +Approved by the coordinator on the developer's delegation (November 25, 2026), each for +the developer's review: N1 (a job node reads its run's rows from storage or a local +spill file, a page at a time; spill files under a temporary directory per job run, +removed with the job or the process, never part of a stored path or hash; same rows, +same order on sync), T1 as a direction (design first, implemented after the transport), +and the interim transport step of PR 562. The local cache of section 2 is one shared +module, `core/row_spool.py` (PR 559), used by joins, views and job nodes alike. Decided by the developer (November 24 and 25, 2026), recorded above: `run()` promises computation and nothing about how; async is the primary memory-bounded path; joins keep keys only, with rows fetched from a local cache; certificates originate in Orcapod and are trusted by derivation, a source's claim is verified as data flows, and a key the store enforces is trusted; a certificate enters no hash or identity; an async join's -memory is at worst linear in one input; LFP is out of scope. +memory is at worst linear in one input; tables of long sample arrays are out of scope. diff --git a/docs/dev/specs/itl-1464/measure.py b/docs/dev/specs/itl-1464/measure.py index 3674b1aa9..629f2d549 100644 --- a/docs/dev/specs/itl-1464/measure.py +++ b/docs/dev/specs/itl-1464/measure.py @@ -1,15 +1,14 @@ -"""Measure the memory of one step of a workshop-shaped pipeline (ITL-1464). +"""Measure the memory of one step of an analysis-shaped pipeline (ITL-1464). One step per process, so that a step's peak is its own:: - uv run python docs/dev/specs/itl-1464/measure.py setup --rows 2177155 --store + uv run python docs/dev/specs/itl-1464/measure.py setup --rows 2200000 --store uv run python docs/dev/specs/itl-1464/measure.py --store ``run_measurements.py`` runs every step under a memory guard and writes the table. The tables are synthetic: the column names and Arrow types of three tables of a -SpiralDB sample dataset (a gaze time series, a spike event table and a unit location -table), with generated values. They are stored in the disk-backed fake of the SpiralDB +SpiralDB sample dataset (a time series, an event table and a small lookup table), with generated values. They are stored in the disk-backed fake of the SpiralDB client that the test suite uses (``tests/test_databases/fake_spiral_sdk.py``), so the real ``SpiralDBTableSource`` reads them: the code under measurement is the library's, only the service is replaced. The fake memory-maps the stored file, so the rows it @@ -45,51 +44,51 @@ from tests.test_databases import fake_spiral_sdk as fake # noqa: E402 PROJECT = "synthetic-sample-000000" -GAZE = "experiment_gaze_online_timeseries" -SPIKES = "spike_event" -LOCATIONS = "unit_location" +SERIES = "time_series" +EVENTS = "event" +LOCATIONS = "lookup" SESSION_START = datetime(2026, 1, 1, 12, 0, 0) SUBJECT = "subject" HASH = "0123456789abcdef0123456789abcdef" -EXPERIMENTS = 6 -UNITS = 300 +BLOCKS = 6 +ITEMS = 300 -GAZE_KEYS = [ - "experiment_preprocessing_hash", +SERIES_KEYS = [ + "processing_hash", "subject_id", - "session_start_datetime", - "experiment_index", + "session_start", + "block_index", "timestamp", ] -EXPERIMENT_KEY = GAZE_KEYS[:4] -SPIKE_KEYS = [ - "spike_extraction_hash", +BLOCK_KEY = SERIES_KEYS[:4] +EVENT_KEYS = [ + "extraction_hash", "subject_id", - "session_start_datetime", + "session_start", "recording_index", - "probe_index", + "device_index", "timestamp", - "unit_id", + "item_id", ] -UNIT_KEY = [ - "spike_extraction_hash", +ITEM_KEY = [ + "extraction_hash", "subject_id", - "session_start_datetime", + "session_start", "recording_index", - "probe_index", - "unit_id", + "device_index", + "item_id", ] LOCATION_KEYS = [ - "spike_extraction_hash", - "localization_hash", + "extraction_hash", + "placement_hash", "subject_id", - "session_start_datetime", + "session_start", "recording_index", - "probe_index", - "unit_id", - "atlas_id", - "atlas_label_region_short", + "device_index", + "item_id", + "map_id", + "region_short", ] @@ -97,81 +96,73 @@ def _constant(value: Any, kind: pa.DataType, rows: int) -> pa.Array[Any]: return pa.array([value] * rows, kind) -def gaze_table(rows: int) -> pa.Table: - """Return ``rows`` rows shaped like one session of the gaze time series.""" +def time_series_table(rows: int) -> pa.Table: + """Return ``rows`` rows shaped like one session of the time series.""" rng = np.random.default_rng(0) - per_experiment = -(-rows // EXPERIMENTS) - experiment = np.repeat(np.arange(EXPERIMENTS, dtype=np.uint32), per_experiment)[ - :rows - ] + per_block = -(-rows // BLOCKS) + block = np.repeat(np.arange(BLOCKS, dtype=np.uint32), per_block)[:rows] timestamp = np.arange(rows, dtype=np.uint64) * 5_000 + 1_700_000_000_000_000 x = rng.normal(size=rows) y = rng.normal(size=rows) - # A few nulls, as blinks leave: ``drop_nulls`` has rows to drop. + # A few nulls: ``drop_nulls`` has rows to drop. missing = rng.random(rows) < 0.02 return pa.table( { - "experiment_preprocessing_hash": _constant(HASH, pa.string(), rows), + "processing_hash": _constant(HASH, pa.string(), rows), "subject_id": _constant(SUBJECT, pa.string(), rows), - "session_start_datetime": _constant( - SESSION_START, pa.timestamp("us"), rows - ), - "experiment_index": pa.array(experiment), + "session_start": _constant(SESSION_START, pa.timestamp("us"), rows), + "block_index": pa.array(block), "timestamp": pa.array(timestamp), - "eye_tracking_software": _constant("tracker", pa.string(), rows), - "eye_tracking_software_version": _constant("1.2.3", pa.string(), rows), - "eye_x_deg": pa.array(x.astype(np.float32), mask=missing), - "eye_x_px": pa.array(x * 100, mask=missing), - "eye_y_deg": pa.array(y.astype(np.float32), mask=missing), - "eye_y_px": pa.array(y * 100, mask=missing), - "gaze_unreliable": pa.array(missing), - "pupil_size_norm": pa.array(rng.random(rows)), + "software": _constant("reader", pa.string(), rows), + "software_version": _constant("1.2.3", pa.string(), rows), + "x_small": pa.array(x.astype(np.float32), mask=missing), + "x_wide": pa.array(x * 100, mask=missing), + "y_small": pa.array(y.astype(np.float32), mask=missing), + "y_wide": pa.array(y * 100, mask=missing), + "unreliable": pa.array(missing), + "level": pa.array(rng.random(rows)), } ) -def spike_table(rows: int) -> pa.Table: - """Return ``rows`` rows shaped like one session of the spike event table.""" +def event_table(rows: int) -> pa.Table: + """Return ``rows`` rows shaped like one session of the event table.""" rng = np.random.default_rng(1) timestamp = np.arange(rows, dtype=np.uint64) * 400 + 1_700_000_000_000_000 return pa.table( { - "spike_extraction_hash": _constant(HASH, pa.string(), rows), + "extraction_hash": _constant(HASH, pa.string(), rows), "subject_id": _constant(SUBJECT, pa.string(), rows), - "session_start_datetime": _constant( - SESSION_START, pa.timestamp("us"), rows - ), + "session_start": _constant(SESSION_START, pa.timestamp("us"), rows), "recording_index": _constant(0, pa.uint32(), rows), - "probe_index": _constant(0, pa.uint32(), rows), + "device_index": _constant(0, pa.uint32(), rows), "timestamp": pa.array(timestamp), - "unit_id": pa.array(rng.integers(0, UNITS, rows).astype(np.uint32)), - "spike_amplitude_uv": pa.array(rng.normal(size=rows).astype(np.float32)), + "item_id": pa.array(rng.integers(0, ITEMS, rows).astype(np.uint32)), + "amplitude": pa.array(rng.normal(size=rows).astype(np.float32)), } ) -def location_table() -> pa.Table: - """Return one row per unit, shaped like the unit location table.""" +def lookup_table() -> pa.Table: + """Return one row per item, shaped like the lookup table.""" rng = np.random.default_rng(2) - rows = UNITS + rows = ITEMS return pa.table( { - "spike_extraction_hash": _constant(HASH, pa.string(), rows), - "localization_hash": _constant(HASH[::-1], pa.string(), rows), + "extraction_hash": _constant(HASH, pa.string(), rows), + "placement_hash": _constant(HASH[::-1], pa.string(), rows), "subject_id": _constant(SUBJECT, pa.string(), rows), - "session_start_datetime": _constant( - SESSION_START, pa.timestamp("us"), rows - ), + "session_start": _constant(SESSION_START, pa.timestamp("us"), rows), "recording_index": _constant(0, pa.uint32(), rows), - "probe_index": _constant(0, pa.uint32(), rows), - "unit_id": pa.array(np.arange(rows, dtype=np.uint32)), - "atlas_id": _constant("atlas", pa.string(), rows), - "atlas_label_region_short": _constant("V1", pa.string(), rows), - "atlas_label_region_full": _constant("area", pa.string(), rows), - "chamber_id": _constant("chamber", pa.string(), rows), - "chamber_x_um": pa.array(rng.normal(size=rows)), - "chamber_y_um": pa.array(rng.normal(size=rows)), - "chamber_z_um": pa.array(rng.normal(size=rows)), + "device_index": _constant(0, pa.uint32(), rows), + "item_id": pa.array(np.arange(rows, dtype=np.uint32)), + "map_id": _constant("map", pa.string(), rows), + "region_short": _constant("r1", pa.string(), rows), + "region_full": _constant("area", pa.string(), rows), + "frame_id": _constant("frame", pa.string(), rows), + "x_um": pa.array(rng.normal(size=rows)), + "y_um": pa.array(rng.normal(size=rows)), + "z_um": pa.array(rng.normal(size=rows)), } ) @@ -182,9 +173,9 @@ def setup(rows: int) -> None: store = fake._store() for name, keys, table in ( - (GAZE, GAZE_KEYS, gaze_table(rows)), - (SPIKES, SPIKE_KEYS, spike_table(rows)), - (LOCATIONS, LOCATION_KEYS, location_table()), + (SERIES, SERIES_KEYS, time_series_table(rows)), + (EVENTS, EVENT_KEYS, event_table(rows)), + (LOCATIONS, LOCATION_KEYS, lookup_table()), ): made = fake.ExternalProject(PROJECT).create_table( f"default.{name}", key_schema=[table.schema.field(k) for k in keys] @@ -216,19 +207,19 @@ def _raw(name: str) -> pa.Table: def step_raw_copy() -> tuple[int, int, Any]: """The rows alone, copied into process memory: the floor every step stands on.""" - raw = _raw(GAZE) + raw = _raw(SERIES) # ``take`` writes new buffers: the rows as private memory of this process. copy = raw.take(np.arange(raw.num_rows)) return raw.nbytes, copy.nbytes, copy def step_as_table() -> tuple[int, int, Any]: - table = _source(GAZE).as_table() - return _raw(GAZE).nbytes, table.nbytes, table + table = _source(SERIES).as_table() + return _raw(SERIES).nbytes, table.nbytes, table def step_as_table_all_info() -> tuple[int, int, Any]: - table = _source(GAZE).as_table(all_info=True) + table = _source(SERIES).as_table(all_info=True) groups: dict[str, int] = {"user": 0, "source_info": 0, "system_tags": 0, "other": 0} for name in table.column_names: size = table.column(name).nbytes @@ -241,105 +232,105 @@ def step_as_table_all_info() -> tuple[int, int, Any]: else: groups["user"] += size print(json.dumps({"column_group_bytes": groups}), file=sys.stderr) - return _raw(GAZE).nbytes, table.nbytes, table + return _raw(SERIES).nbytes, table.nbytes, table def step_run() -> tuple[int, int, Any]: - view = _source(GAZE).run() - return _raw(GAZE).nbytes, 0, view + view = _source(SERIES).run() + return _raw(SERIES).nbytes, 0, view def step_run_then_as_table() -> tuple[int, int, Any]: - source = _source(GAZE) + source = _source(SERIES) view = source.run() table = source.as_table() - return _raw(GAZE).nbytes, table.nbytes, (view, table) + return _raw(SERIES).nbytes, table.nbytes, (view, table) def step_as_polars_df() -> tuple[int, int, Any]: - frame = _source(GAZE).as_polars_df() - return _raw(GAZE).nbytes, int(frame.estimated_size()), frame + frame = _source(SERIES).as_polars_df() + return _raw(SERIES).nbytes, int(frame.estimated_size()), frame def step_iterate() -> tuple[int, int, Any]: count = 0 - for _tag, _data in _source(GAZE): + for _tag, _data in _source(SERIES): count += 1 - return _raw(GAZE).nbytes, 0, count + return _raw(SERIES).nbytes, 0, count def step_iterate_read_one_value() -> tuple[int, int, Any]: total = 0.0 - for _tag, data in _source(GAZE): - total += data["pupil_size_norm"] - return _raw(GAZE).nbytes, 0, total + for _tag, data in _source(SERIES): + total += data["level"] + return _raw(SERIES).nbytes, 0, total def step_flow() -> tuple[int, int, Any]: - pairs = _source(GAZE).flow() - return _raw(GAZE).nbytes, 0, pairs + pairs = _source(SERIES).flow() + return _raw(SERIES).nbytes, 0, pairs def step_drop_nulls() -> tuple[int, int, Any]: - table = _source(GAZE).drop_nulls(["eye_x_deg", "eye_y_deg"]).as_table() - return _raw(GAZE).nbytes, table.nbytes, table + table = _source(SERIES).drop_nulls(["x_small", "y_small"]).as_table() + return _raw(SERIES).nbytes, table.nbytes, table def step_polars_filter() -> tuple[int, int, Any]: import polars as pl - table = _source(GAZE).polars_filter(pl.col("pupil_size_norm") > 0.5).as_table() - return _raw(GAZE).nbytes, table.nbytes, table + table = _source(SERIES).polars_filter(pl.col("level") > 0.5).as_table() + return _raw(SERIES).nbytes, table.nbytes, table def step_map_data() -> tuple[int, int, Any]: - table = _source(GAZE).map_data({"pupil_size_norm": "pupil"}).as_table() - return _raw(GAZE).nbytes, table.nbytes, table + table = _source(SERIES).map_data({"level": "pupil"}).as_table() + return _raw(SERIES).nbytes, table.nbytes, table def step_join() -> tuple[int, int, Any]: - table = _source(SPIKES).join(_source(LOCATIONS)).as_table() - return _raw(SPIKES).nbytes + _raw(LOCATIONS).nbytes, table.nbytes, table + table = _source(EVENTS).join(_source(LOCATIONS)).as_table() + return _raw(EVENTS).nbytes + _raw(LOCATIONS).nbytes, table.nbytes, table -def _grouped_gaze() -> Any: +def _grouped_series() -> Any: return ( - _source(GAZE) - .drop_nulls(["eye_x_deg", "eye_y_deg"]) - .group_by(EXPERIMENT_KEY) - .map_data({"timestamp": "gaze_time"}) + _source(SERIES) + .drop_nulls(["x_small", "y_small"]) + .group_by(BLOCK_KEY) + .map_data({"timestamp": "sample_time"}) ) def step_group_by() -> tuple[int, int, Any]: - table = _source(GAZE).group_by(EXPERIMENT_KEY).as_table() - return _raw(GAZE).nbytes, table.nbytes, table + table = _source(SERIES).group_by(BLOCK_KEY).as_table() + return _raw(SERIES).nbytes, table.nbytes, table def step_group_by_chain() -> tuple[int, int, Any]: - table = _grouped_gaze().as_table() - return _raw(GAZE).nbytes, table.nbytes, table + table = _grouped_series().as_table() + return _raw(SERIES).nbytes, table.nbytes, table def _onsets_pod() -> Any: from orcapod import function_pod - @function_pod(output_keys="fixation_onset") - def fixation_onsets( - gaze_time: list[int], eye_x_deg: list[float], eye_y_deg: list[float] + @function_pod(output_keys="onset") + def onsets( + sample_time: list[int], x_small: list[float], y_small: list[float] ) -> list[int]: - t, x, y = np.asarray(gaze_time), np.asarray(eye_x_deg), np.asarray(eye_y_deg) + t, x, y = np.asarray(sample_time), np.asarray(x_small), np.asarray(y_small) speed = np.hypot(np.diff(x), np.diff(y)) / (np.diff(t) / 1_000_000) moving = speed > 40 ends = np.flatnonzero(moving[:-1] & ~moving[1:]) + 1 return [int(t[i]) for i in ends] - return fixation_onsets + return onsets def step_function_pod() -> tuple[int, int, Any]: - table = _onsets_pod().pod(_grouped_gaze()).as_table() - return _raw(GAZE).nbytes, table.nbytes, table + table = _onsets_pod().pod(_grouped_series()).as_table() + return _raw(SERIES).nbytes, table.nbytes, table def _job(store: Path) -> Any: @@ -347,15 +338,23 @@ def _job(store: Path) -> Any: from orcapod.databases import DeltaTableDatabase database = DeltaTableDatabase(str(store / "results")) - with PipelineJob(name="fixation_response", database=database) as job: - _onsets_pod().pod(_grouped_gaze(), label="onsets") + with PipelineJob(name="chain", database=database) as job: + _onsets_pod().pod(_grouped_series(), label="onsets") return job def step_job_run(store: Path) -> tuple[int, int, Any]: job = _job(store) job.run() - return _raw(GAZE).nbytes, 0, job + return _raw(SERIES).nbytes, 0, job + + +def step_job_run_async_unkept(store: Path) -> tuple[int, int, Any]: + from orcapod.pipeline import AsyncPipelineOrchestrator + + job = _job(store) + job.run(orchestrator=AsyncPipelineOrchestrator(), materialize_results=False) + return _raw(SERIES).nbytes, 0, job def step_job_run_async(store: Path) -> tuple[int, int, Any]: @@ -363,20 +362,18 @@ def step_job_run_async(store: Path) -> tuple[int, int, Any]: job = _job(store) job.run(orchestrator=AsyncPipelineOrchestrator()) - return _raw(GAZE).nbytes, 0, job + return _raw(SERIES).nbytes, 0, job def _operator_chains() -> dict[str, Callable[[], Any]]: import polars as pl return { - "map_data": lambda: _source(GAZE).map_data({"pupil_size_norm": "pupil"}), - "drop_nulls": lambda: _source(GAZE).drop_nulls(["eye_x_deg", "eye_y_deg"]), - "polars_filter": lambda: _source(GAZE).polars_filter( - pl.col("pupil_size_norm") > 0.5 - ), - "join": lambda: _source(SPIKES).join(_source(LOCATIONS)), - "group_by": lambda: _source(GAZE).group_by(EXPERIMENT_KEY), + "map_data": lambda: _source(SERIES).map_data({"level": "pupil"}), + "drop_nulls": lambda: _source(SERIES).drop_nulls(["x_small", "y_small"]), + "polars_filter": lambda: _source(SERIES).polars_filter(pl.col("level") > 0.5), + "join": lambda: _source(EVENTS).join(_source(LOCATIONS)), + "group_by": lambda: _source(SERIES).group_by(BLOCK_KEY), } @@ -393,9 +390,12 @@ def step(store: Path) -> tuple[int, int, Any]: _operator_chains()[chain]() if orchestrator == "async": job.run(orchestrator=AsyncPipelineOrchestrator()) + elif orchestrator == "async_unkept": + # The orchestrator keeps no node's rows for its result. + job.run(orchestrator=AsyncPipelineOrchestrator(), materialize_results=False) else: job.run() - name = SPIKES if chain == "join" else GAZE + name = EVENTS if chain == "join" else SERIES return _raw(name).nbytes, 0, job return step @@ -405,7 +405,7 @@ def step(store: Path) -> tuple[int, int, Any]: **{ f"job_{chain}_{orchestrator}": _operator_job(chain, orchestrator) for chain in ("map_data", "drop_nulls", "polars_filter", "join", "group_by") - for orchestrator in ("sync", "async") + for orchestrator in ("sync", "async", "async_unkept") }, "raw_copy": step_raw_copy, "as_table": step_as_table, @@ -425,6 +425,7 @@ def step(store: Path) -> tuple[int, int, Any]: "function_pod": step_function_pod, "job_run": step_job_run, "job_run_async": step_job_run_async, + "job_run_async_unkept": step_job_run_async_unkept, } @@ -437,7 +438,7 @@ def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("step", choices=["setup", *STEPS]) parser.add_argument("--store", required=True, type=Path) - parser.add_argument("--rows", type=int, default=2_177_155) + parser.add_argument("--rows", type=int, default=2_200_000) parser.add_argument("--tracemalloc", action="store_true") args = parser.parse_args() warnings.simplefilter("ignore") @@ -461,7 +462,7 @@ def main() -> None: elapsed = time.perf_counter() - started record: dict[str, Any] = { "step": args.step, - "rows": _raw(GAZE).num_rows, + "rows": _raw(SERIES).num_rows, "input_arrow_bytes": in_bytes, "output_arrow_bytes": out_bytes, "rss_before_bytes": before, diff --git a/docs/dev/specs/itl-1464/run_measurements.py b/docs/dev/specs/itl-1464/run_measurements.py index fbeb141f9..ac72ac539 100644 --- a/docs/dev/specs/itl-1464/run_measurements.py +++ b/docs/dev/specs/itl-1464/run_measurements.py @@ -1,7 +1,7 @@ """Run every step of ``measure.py`` in its own process, under a memory guard (ITL-1464). uv run python docs/dev/specs/itl-1464/run_measurements.py --store \ - --rows 2177155 --out [--steps as_table run ...] + --rows 2200000 --out [--steps as_table run ...] A step whose resident memory passes ``--guard-gb`` (24 by default) is killed and recorded as ``killed``; nothing here may starve the machine it runs on. @@ -79,7 +79,7 @@ def run_step( def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--store", required=True, type=Path) - parser.add_argument("--rows", type=int, default=2_177_155) + parser.add_argument("--rows", type=int, default=2_200_000) parser.add_argument("--out", required=True, type=Path) parser.add_argument("--guard-gb", type=float, default=24.0) parser.add_argument("--steps", nargs="*", default=DEFAULT_STEPS) From ffb51d31ccb10348eb5b200edd78e918eee88cdc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:39:14 -0800 Subject: [PATCH 17/81] test(pipeline): a job's nodes read the same whatever materialize_results says (ITL-1464) Co-Authored-By: Claude Fable 5.2 --- tests/test_core/operators/test_row_chunks.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/test_core/operators/test_row_chunks.py b/tests/test_core/operators/test_row_chunks.py index 7c6ea5045..f2e4c200c 100644 --- a/tests/test_core/operators/test_row_chunks.py +++ b/tests/test_core/operators/test_row_chunks.py @@ -266,3 +266,23 @@ async def recording(self: Any, graph: Any, materialize_results: bool, **kw: Any) _ = asyncio.run(again.run_async()) assert asked == [False, False] assert again.nodes["out"].as_table().num_rows == _ROWS + + +@pytest.mark.parametrize("chain", ["map", "group", "batch"]) +def test_a_jobs_nodes_read_the_same_whatever_materialize_results_says( + tmp_path: Path, chain: str +) -> None: + """Decision T-1: the async orchestrator keeps no rows for a job, flag or not.""" + tables = [] + for flag in (True, False): + job = _job(tmp_path, f"flag_{flag}", chain, False) + _ = job.run(orchestrator=AsyncPipelineOrchestrator(), materialize_results=flag) + node = job.nodes["out"] + rows = [(t.as_dict(), d.as_dict()) for t, d in node.iter_data()] + tables.append((node.as_table(all_info=True), rows, node.content_hash())) + (kept, kept_rows, kept_hash), (unkept, unkept_rows, unkept_hash) = tables + + assert kept.num_rows > 0 + assert _sorted_rows(kept) == _sorted_rows(unkept) + assert sorted(kept_rows, key=repr) == sorted(unkept_rows, key=repr) + assert kept_hash == unkept_hash From 35fe2572918ba2cae3edb21c7c951edf4b7e65cc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:41:15 -0800 Subject: [PATCH 18/81] 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 d57d26e9cb997318785490b45c072fc87f5679b7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:43:20 -0800 Subject: [PATCH 19/81] docs(dev): round the measured sizes in the views spec Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-views.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/dev/specs/itl-1464-views.md b/docs/dev/specs/itl-1464-views.md index dd54dd169..19301738d 100644 --- a/docs/dev/specs/itl-1464-views.md +++ b/docs/dev/specs/itl-1464-views.md @@ -54,7 +54,7 @@ the window. | Member | Bounded view | |---|---| -| `total_rows`, schema, `status`, `header()` | as the complete view: `all 2,177,155 rows` | +| `total_rows`, schema, `status`, `header()` | as the complete view: `all 1,234,567 rows` | | `head(n)`, `tail(n)`, `n` within the window | the same rows and header as the complete view; the result is an ordinary view | | `head(n)`, `tail(n)`, larger `n` | raise `BoundedViewError`, naming the window and `stream.as_table()` | | `sort_by_tags()` | raise `BoundedViewError`: sorting needs every row | @@ -123,13 +123,13 @@ never computes. same rows, narrow and wide, with large cells, at sizes 11, 12, 1,000 and more; a small stream's display is unchanged. - The refusals; `head` after `run`; staleness after the source moves. -- Memory, 2,177,155 rows of the gaze shape, before and after, for the source, a rename, a +- Memory, about 2.2 million rows of a time series, before and after, for the source, a rename, a `drop_nulls` and a `filter`. ## Measured -`run()` of a synthetic SpiralDB table shaped as one session of gaze (2,177,155 rows, 13 -columns, 248 MiB of Arrow data; the diagnosis's table), peak resident memory, one process +`run()` of a synthetic SpiralDB table, a time series (about 2.2 million rows, 13 +columns, about 250 MiB of Arrow data), peak resident memory, one process per row: | Stream | Before | After | Arrow pool peak before | after | Time before | after | From 8f81324561c203ebf8924cace47387a8253324b0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:46:41 -0800 Subject: [PATCH 20/81] wip: node rows kept in the row spool (ITL-1464) --- docs/dev/specs/itl-1464/measure.py | 24 ++ .../core/operators/static_output_pod.py | 56 +++-- src/orcapod/core/row_spool.py | 205 +++++++++++++++--- tests/test_core/operators/test_row_chunks.py | 111 +++++++++- 4 files changed, 347 insertions(+), 49 deletions(-) diff --git a/docs/dev/specs/itl-1464/measure.py b/docs/dev/specs/itl-1464/measure.py index 629f2d549..9a1650417 100644 --- a/docs/dev/specs/itl-1464/measure.py +++ b/docs/dev/specs/itl-1464/measure.py @@ -434,6 +434,29 @@ def _peak_rss_bytes() -> int: return peak if sys.platform == "darwin" else peak * 1024 +def _peak_footprint_bytes() -> int | None: + """Peak physical footprint of this process (macOS), or ``None``. + + Resident memory counts the pages of a memory-mapped file that happen to be in + memory, which the system drops when it needs them; the footprint counts only + memory the process itself holds (what the system charges it with). + """ + if sys.platform != "darwin": + return None + import ctypes + import os + + fields = (ctypes.c_uint64 * 64)() + libproc = ctypes.CDLL("/usr/lib/libproc.dylib") + # RUSAGE_INFO_V4: a 16-byte uuid, then 64-bit counters; the 29th is + # ``ri_lifetime_max_phys_footprint``. + buffer = (ctypes.c_uint8 * (16 + 8 * 64))() + if libproc.proc_pid_rusage(os.getpid(), 4, ctypes.byref(buffer)) != 0: + return None + ctypes.memmove(fields, ctypes.byref(buffer, 16), 8 * 64) + return int(fields[28]) + + def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("step", choices=["setup", *STEPS]) @@ -467,6 +490,7 @@ def main() -> None: "output_arrow_bytes": out_bytes, "rss_before_bytes": before, "peak_rss_bytes": _peak_rss_bytes(), + "peak_footprint_bytes": _peak_footprint_bytes(), "arrow_pool_peak_bytes": pool.max_memory(), "arrow_pool_held_bytes": pool.bytes_allocated(), "seconds": round(elapsed, 1), diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index e750afe03..683806ccd 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -36,6 +36,7 @@ stream_data_tags, ) from orcapod.core.function_pod import FunctionPodStream +from orcapod.core.row_spool import SPOOL_MEMORY_BYTES, RowSpool from orcapod.core.operators.provisional import ( provisional_operator_name, warn_provisional_operator, @@ -1294,6 +1295,11 @@ async def _streams_of(inputs: Sequence[RecordBatchInput]) -> list[StreamProtocol until this many have arrived.""" +KEPT_ROWS_MEMORY_BYTES = SPOOL_MEMORY_BYTES +"""Bytes of kept rows that stay in memory; beyond them the rows go to local disk and +are read back memory-mapped (``RowSpool``).""" + + class RowChunks: """Rows received one at a time, kept as Arrow tables, not as ``(Tag, Data)`` pairs. @@ -1312,14 +1318,23 @@ class RowChunks: when their chunk is built or the chunks are joined; the message's table index is then the row's place in its chunk, or the chunk's place. + Sealed chunks are held by a ``RowSpool``: in memory up to + ``KEPT_ROWS_MEMORY_BYTES``, beyond that in a private temporary file read back + memory-mapped. The table and streams built here then refer to the mapping, which + lives as long as they do: also after this object, its node or its job are gone, and + after the file is deleted. + A chunk is the record batch an ITL-1347 channel carries, before the last step of its row-built form (the source-info field flags, which need every row); a node wired to record-batch channels receives such batches and needs no ``RowChunks``. """ def __init__(self) -> None: - self._tag_chunks: list[pa.Table] = [] - self._data_chunks: list[pa.Table] = [] + # Sealed chunks: in memory up to the spool's limit, then on local disk, read + # back memory-mapped (``kept_rows``), so a large output is not process memory. + self._spool = RowSpool(memory_bytes=KEPT_ROWS_MEMORY_BYTES) + self._names: list[str] | None = None + self._schema: pa.Schema | None = None self._context_chunks: list[pa.Array[Any]] = [] # pyright: ignore[reportExplicitAny] # any array self._pending: list[tuple[TagProtocol, DataProtocol]] = [] self._tag_keys: tuple[str, ...] = () @@ -1351,12 +1366,25 @@ def _seal(self) -> None: data_tables = [t.drop_columns(list(self._data_tags)) for t in data_tables] # One chunk per column instead of one per row: the per-row arrays are what # costs memory, the values are the same. - self._tag_chunks.append( - arrow_utils.concat_tables_by_name(tag_tables).combine_chunks() - ) - self._data_chunks.append( - arrow_utils.concat_tables_by_name(data_tables).combine_chunks() + chunk = arrow_utils.hstack_tables( + arrow_utils.concat_tables_by_name(tag_tables).combine_chunks(), + arrow_utils.concat_tables_by_name(data_tables).combine_chunks(), ) + if self._names is None: + self._names = chunk.column_names + elif chunk.column_names != self._names and set(chunk.column_names) == set( + self._names + ): + # Columns are matched by name, as ``concat_tables_by_name`` matches them. + chunk = chunk.select(self._names) + first = self._schema + if first is None: + self._schema = chunk.schema + elif not chunk.schema.equals(first, check_metadata=True): + # What joining it with the earlier chunks gives: their schema, or the + # error a table built from rows of differing columns raises. + chunk = pa.concat_tables([first.empty_table(), chunk]).combine_chunks() + self._spool.append(chunk) self._context_chunks.append( pa.array([data.data_context_key for _, data in rows], pa.large_string()) ) @@ -1371,20 +1399,14 @@ def row_table(self) -> tuple[pa.Table, tuple[str, ...], tuple[str, ...]]: Raises: ValueError: If no row was added. """ - from orcapod.utils import arrow_utils - if self.num_rows == 0: raise ValueError("Cannot materialize an empty list of rows into a stream") self._seal() - combined_tags = arrow_utils.concat_tables_by_name(self._tag_chunks) - combined_data = StaticOutputOperatorPod._flag_source_info_nullability( # pyright: ignore[reportPrivateUsage] # the one rule for these flags - arrow_utils.concat_tables_by_name(self._data_chunks) - ) - return ( - arrow_utils.hstack_tables(combined_tags, combined_data), - self._tag_keys, - self._data_tags, + # Only the ``_source_*`` fields are flagged; the arrays are the spool's. + table = StaticOutputOperatorPod._flag_source_info_nullability( # pyright: ignore[reportPrivateUsage] # the one rule for these flags + self._spool.table() ) + return table, self._tag_keys, self._data_tags def output_stream(self) -> StreamProtocol: """Return the stream ``_materialize_to_stream`` builds from the rows added.""" 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/operators/test_row_chunks.py b/tests/test_core/operators/test_row_chunks.py index f2e4c200c..e0523546a 100644 --- a/tests/test_core/operators/test_row_chunks.py +++ b/tests/test_core/operators/test_row_chunks.py @@ -153,7 +153,7 @@ def test_at_most_one_chunk_of_rows_is_held_as_objects( assert chunks.num_rows == _ROWS assert len(chunks._pending) == _ROWS % 4 # pyright: ignore[reportPrivateUsage] # the bound this class exists for - assert [t.num_rows for t in chunks._tag_chunks] == [4, 4] # pyright: ignore[reportPrivateUsage] # the bound this class exists for + assert chunks._spool.size == 8 # pyright: ignore[reportPrivateUsage] # the bound this class exists for def test_collecting_a_channel_keeps_its_rows_in_order(chunk_rows: int) -> None: @@ -286,3 +286,112 @@ def test_a_jobs_nodes_read_the_same_whatever_materialize_results_says( assert _sorted_rows(kept) == _sorted_rows(unkept) assert sorted(kept_rows, key=repr) == sorted(unkept_rows, key=repr) assert kept_hash == unkept_hash + + +@pytest.fixture() +def spilled(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path: + """Every sealed chunk goes to disk at once, three rows a chunk.""" + monkeypatch.setattr(static_output_pod, "ROW_CHUNK_ROWS", 3) + monkeypatch.setattr(static_output_pod, "KEPT_ROWS_MEMORY_BYTES", 0) + monkeypatch.setattr("tempfile.tempdir", str(tmp_path)) + return tmp_path + + +def _spool_files(root: Path) -> list[Path]: + return [p for p in root.rglob("*") if p.is_file() and not p.name.endswith("lock")] + + +@pytest.mark.parametrize("tag_only", [False, True], ids=["data_tags", "tag_only"]) +def test_rows_spilled_to_disk_build_the_same_table( + spilled: Path, tag_only: bool +) -> None: + rows = _rows(tag_only) + expected = StaticOutputOperatorPod._rows_to_table(rows)[0] # pyright: ignore[reportPrivateUsage] # the rule RowChunks must equal + + chunks = _chunks(rows) + table = chunks.row_table()[0] + + assert _spool_files(spilled), "the chunks were not written to disk" + assert table.schema.equals(expected.schema, check_metadata=True) + assert table.equals(expected) + + +def test_a_table_read_from_spilled_rows_outlives_what_wrote_it(spilled: Path) -> None: + import gc + + rows = _rows(False) + expected = StaticOutputOperatorPod._rows_to_table(rows)[0] # pyright: ignore[reportPrivateUsage] # the rule RowChunks must equal + chunks = _chunks(rows) + stream = chunks.output_stream() + table = stream.as_table(columns={"system_tags": True, "source": True}) + wanted = expected.select(table.column_names) + + del chunks, stream + _ = gc.collect() + + # The spool is gone and its files deleted; the table still reads every value. + assert not _spool_files(spilled) + assert table.equals(wanted) + assert table.to_pylist() == wanted.to_pylist() + + +@pytest.mark.parametrize("chain", ["map", "group", "batch"]) +def test_a_job_node_over_spilled_rows_reads_as_one_in_memory( + spilled: Path, tmp_path: Path, chain: str +) -> None: + import gc + + job = _job(tmp_path, "spilled", chain, False) + _ = job.run(orchestrator=AsyncPipelineOrchestrator()) + node = job.nodes["out"] + table = node.as_table(all_info=True) + rows = [(t.as_dict(), d.as_dict()) for t, d in node.iter_data()] + content_hash = node.content_hash() + values = table.to_pylist() + + with pytest.MonkeyPatch.context() as patched: + patched.setattr(static_output_pod, "KEPT_ROWS_MEMORY_BYTES", 1 << 40) + in_memory = _job(tmp_path, "in_memory", chain, False) + _ = in_memory.run(orchestrator=AsyncPipelineOrchestrator()) + expected = in_memory.nodes["out"] + + assert _sorted_rows(table) == _sorted_rows(expected.as_table(all_info=True)) + assert sorted(rows, key=repr) == sorted( + [(t.as_dict(), d.as_dict()) for t, d in expected.iter_data()], key=repr + ) + assert content_hash == expected.content_hash() + + # A table a user holds stays valid after the node lets its run go and the job + # is gone. + node.clear_cache() + del node, job + _ = gc.collect() + assert table.to_pylist() == values + + +def test_a_table_of_spilled_rows_survives_interpreter_shutdown(tmp_path: Path) -> None: + """A table held at exit, when the spool directory is removed, raises nothing.""" + import subprocess + import sys + import textwrap + + script = textwrap.dedent( + """ + import sys, tempfile + tempfile.tempdir = sys.argv[1] + import pyarrow as pa + from orcapod.core.row_spool import RowSpool + spool = RowSpool(memory_bytes=0) + spool.append(pa.table({"a": list(range(1000))})) + held = spool.table() + import atexit + atexit.register(lambda: print("sum", sum(held.column("a").to_pylist()))) + """ + ) + done = subprocess.run( + [sys.executable, "-c", script, str(tmp_path)], capture_output=True, text=True + ) + assert done.returncode == 0, done.stderr + assert done.stdout.strip() == "sum 499500" + assert done.stderr == "" + assert not _spool_files(tmp_path) From 6a6bea4559e3a9a0fe854fd33dbffcda954932a8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:49:15 -0800 Subject: [PATCH 21/81] docs(dev): keys-only joins and uniqueness certificates, with measurements (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-joins.md | 121 ++++++++++++++++++ docs/dev/specs/itl-1464-joins/measure.py | 20 ++- src/orcapod/core/operators/streaming_joins.py | 10 +- src/orcapod/core/unique_keys.py | 10 +- tests/test_core/test_unique_keys.py | 2 +- 5 files changed, 150 insertions(+), 13 deletions(-) create mode 100644 docs/dev/specs/itl-1464-joins.md diff --git a/docs/dev/specs/itl-1464-joins.md b/docs/dev/specs/itl-1464-joins.md new file mode 100644 index 000000000..26c6da6ee --- /dev/null +++ b/docs/dev/specs/itl-1464-joins.md @@ -0,0 +1,121 @@ +# Joins that hold keys, and certificates of unique tags (ITL-1464) + +Status: implemented with this document, November 25, 2026; design decisions approved by the +coordinator under the developer's delegation. It covers `Join`, `MergeJoin` and +`SemiJoin` over record-batch channels (`async_execute_batches`). No job node calls that +form yet: the transport work of ITL-1464 wires it, and until then a job's memory is as +before. The sync path is unchanged, and no hash, identity, stored row or golden value moves. + +## What an async join holds + +Each side of a binary join step keeps, per row that can still match, its prepared join keys +and its row number (a Polars frame, `streaming_joins._Side`); the rows are in a row spool +(`core/row_spool.py`). Matching is the sync path's (`join._matched_pairs` on +`arrow_keys.polars_key_frame`), one vectorized join per arriving batch, and every value is +taken from the rows by number, so it is the input's, bit for bit. + +| Case | Held | Let go | +|---|---|---| +| both sides unique on the shared tags (1:1) | keys of the rows not matched yet | both rows of a pair, when they match | +| one side unique (a lookup) | keys of the unique side; of the other side, rows that arrived and have not matched | a row of the other side, when it matches | +| neither (many to many) | keys of both sides | nothing while both inputs are open | +| any | | a side's rows, when the other side ends | +| `SemiJoin` | distinct right keys; undecided left rows' keys | a left row, when a right row matches it | + +One rule covers the first three: **a row is let go once it has matched if and only if the +other side is unique on the join keys.** A join of three or more inputs is a chain of such +steps in canonical order; each step's left side has the certificate of the rows joined so +far (`unique_keys.joined_keys`). + +Memory, per held row: the prepared key (16 bytes per string, plus its length when above 12 +bytes; 8 per integer, timestamp or float; 1 for the constant key), 8 for the row number, 1 +for the removal mask. Beside it: at most 64 MiB of rows per side before they go to disk, the +batches in flight, and one output piece of at most 8,192 pairs. Worst case, with no +certificate and neither input ended, the keys of both inputs. A many-to-many output is never +held: the pairs are counted first, then made in pieces; one arriving row with more pairs +than a piece has its pairs listed (16 bytes each, at most the held rows) and is sent in +pieces. + +Every input is read at once and to its end, at most 65,536 rows ahead of the join. Nothing +waits for one input to end, because both inputs may read one upstream (a diamond). + +Not covered: `Rejoin` stays a barrier on this path, because its kernel can differ from the +sync path for repeated origins with three or more inputs. A subclass of an operator runs its +own sync call over its whole inputs. + +## The row spool + +Rows past the memory limit become a file each: an uncompressed Arrow IPC file of one record +batch, read memory-mapped, under a directory of this process in the system's temporary +directory. A file is deleted when its last row is discarded; the rest at a normal end, a +failure, a cancellation, collection and exit. A killed process leaves its directory; the +next process to spill there removes it (it holds no lock any more). A spool belongs to one +thread of one process; a forked child's copy refuses every use. + +## Certificates + +`StreamProtocol.unique_keys` is a set of tag sets on which no two rows agree, under the +joins' equality. It is derived when asked and stored nowhere: in no hash, identity, config, +stored row or equality. A wrong certificate would lose rows, so only what is certain is +certified, and a rule is read from the exact class: a subclass certifies nothing unless it +declares a rule. + +| Stream | Certificate | +|---|---| +| `ArrowTableSource`, `DictSource`, `ListSource`, `DataFrameSource`, SQLite and PostgreSQL tables | the key columns, when all are tags | +| every other source; a raw `ArrowTableStream`, also with a producer | none | +| `DropNulls`, `Filter`, `PolarsFilter`, `AddTags`, `TagBy`, `Pick`, `Index`, `MapData`, the data column selections, function pods (`FunctionPod`, `CachedFunctionPod`), `SideEffectPod` | the input's | +| the tag selections and drops | the input's keys whose tags all stay | +| `MapTags`, `MapColumns` | the input's keys renamed, without those that lose a tag | +| `GroupBy` | its keys | +| `Batch` | none | +| `SemiJoin` | the left input's | +| `Join`, `MergeJoin` on shared tags S | unions of one key of each side; a side's own keys when the other side is unique on S | +| `Rejoin` | every input's (a row is in at most one result row) | +| a source slot | its bound source's | +| an operator job node in `REPLAY` mode | none: it replays every logged run | + +Why a source's key columns are certain: those source kinds build every row through +`SourceStreamBuilder`, which names a row by its key columns and refuses a null or repeated +key, on every read. The record id is a function of the key values and a key is a string, an +integer, a boolean, a timestamp or a date (never a float), so two rows whose keys are equal +to a join have one record id and are refused. + +That direction is the safe one for a database: a store whose equality is coarser than the +join's (a case-insensitive collation, padded `CHAR`) never holds two keys the join takes as +equal; one whose equality is finer (a float key, a timestamp read at a coarser unit) could. +No store is trusted here: the SQL sources are checked as read. A later step may trust a +store's key instead of checking it, only under those conditions and only for a key without +nulls. + +CSV and Delta (a running check is a later step), `CachedSource` (rows of earlier reads), +`DerivedSource` and `PollingSource` certify nothing. + +## Measured + +`docs/dev/specs/itl-1464-joins/measure.py`, each case in a fresh process, synthetic rows +with their source-info tokens, sent and read through bounded +channels. Peak RSS includes 143 MiB of imports and the mapped pages a join reads. "Barrier" +is the form before this change. It is the operator alone, not a job. + +| Case | Rows | Form | Output rows | Peak RSS | Arrow pool peak | Time | +|---|---|---|---|---|---|---| +| `lookup` | 1,000,000 | barrier | 1,000,000 | 1,793 MiB | 1,323 MiB | 2.3 s | +| `lookup` | 1,000,000 | keys | 1,000,000 | 259 MiB | 26 MiB | 2.4 s | +| `lookup` | 8,000,000 | keys | 8,000,000 | 257 MiB | 26 MiB | 19.9 s | +| `lookup_late` | 1,000,000 | keys | 1,000,000 | 756 MiB | 169 MiB | 5.4 s | +| `lookup_late` | 8,000,000 | keys | 8,000,000 | 2733 MiB | 392 MiB | 61.7 s | +| `one_to_one` | 1,000,000 | keys | 1,000,000 | 317 MiB | 64 MiB | 4.7 s | +| `one_to_one` | 8,000,000 | keys | 8,000,000 | 341 MiB | 64 MiB | 39.3 s | +| `one_to_one_late` | 1,000,000 | barrier | 1,000,000 | 2,574 MiB | 1,854 MiB | 4.4 s | +| `one_to_one_late` | 1,000,000 | keys | 1,000,000 | 741 MiB | 176 MiB | 5.1 s | +| `one_to_one_late` | 8,000,000 | keys | 8,000,000 | 2,301 MiB | 453 MiB | 60.0 s | +| `many` (5 per row) | 1,000,000 | barrier | 5,000,000 | 4,835 MiB | 4,111 MiB | 2.4 s | +| `many` | 1,000,000 | keys | 5,000,000 | 445 MiB | 144 MiB | 3.2 s | +| `many` | 8,000,000 | keys | 40,000,000 | 453 MiB | 146 MiB | 26.0 s | +| `semi` | 8,000,000 | keys | 8,000,000 | 252 MiB | 21 MiB | 19.6 s | + +`lookup`, `one_to_one` in step, `many` and `semi` do not grow with the rows. The late +cases grow with the keys of the input that arrived first, as the bound says. In `many` the +small side arrives first and ends, so it measures the bounded output and not the worst case +of two open inputs, which is the sum of both sides' keys. diff --git a/docs/dev/specs/itl-1464-joins/measure.py b/docs/dev/specs/itl-1464-joins/measure.py index 128054893..57954b458 100644 --- a/docs/dev/specs/itl-1464-joins/measure.py +++ b/docs/dev/specs/itl-1464-joins/measure.py @@ -21,7 +21,8 @@ import sys import time import warnings -from collections.abc import Iterator +from collections.abc import Callable, Iterator +from typing import Any import numpy as np import pyarrow as pa @@ -33,15 +34,15 @@ from orcapod.protocols.core_protocols import StreamProtocol BATCH = 8_192 -SESSION = "session-2026-01-01-000000-abcdef" +SESSION = "session-0123456789abcdef" -def _text(values: np.ndarray, pattern: str) -> pa.Array: +def _text(values: np.ndarray[Any, Any], pattern: str) -> pa.Array[Any]: return pa.array([pattern % v for v in values.tolist()], pa.large_string()) def spikes(start: int, n: int) -> pa.Table: - """Event rows: seven tags and data, as the measured spike table.""" + """Synthetic event rows: tags and data of several types.""" i = np.arange(start, start + n) return pa.table( { @@ -97,7 +98,14 @@ def events(start: int, n: int) -> pa.Table: class Input: """An input: a small source of its kind describes it, its rows are made as sent.""" - def __init__(self, name: str, make, rows: int, tags: list[str], key: list[str]): + def __init__( + self, + name: str, + make: Callable[[int, int], pa.Table], + rows: int, + tags: list[str], + key: list[str], + ): self.make, self.rows, self.key, self.name = make, rows, key, name self.tags = tags self.stream = self.source(0, 4) @@ -199,5 +207,5 @@ async def consume() -> None: f"{case:16} rows={rows:>9,} {'barrier' if barrier else 'keys':8}" + f" out={count:>11,} {seconds:7.1f} s" + f" peak={peak / unit:8.0f} MiB (import {base / unit:.0f})" - + f" arrow_peak={pa.default_memory_pool().max_memory() / 2**20:8.0f} MiB" + + f" arrow_peak={(pa.default_memory_pool().max_memory() or 0) / 2**20:8.0f} MiB" ) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 2af444484..ce57e52e5 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -2,7 +2,8 @@ The async path of ``Join``, ``MergeJoin``, ``SemiJoin`` and ``Rejoin`` (ITL-1347, stage 5) is to read its inputs as Arrow record batches, in whatever order they arrive; these -kernels are that computation, not yet wired into ``async_execute``. A kernel gives the +kernels are that computation (``run_kernel``, for the operators' +``async_execute_batches``; no job node calls that form yet). A kernel gives the rows of the operator's sync ``static_process`` over the same inputs as a multiset (row order is not a result on the async path; developer, November 22, 2026), within the limits each kernel's docstring states (``StreamingRejoin``: repeated origins with three @@ -49,8 +50,8 @@ no rows that shares a tag with the others empties the result (an inner join), so no row was emitted before it can refuse. ``SemiJoin`` with no shared tag passes every left row whatever its right input holds, and has no shared column to refuse. -- **Matching is the sync join's.** Each input keeps the rows it needs as Arrow tables and - a Polars frame of their prepared keys and row numbers (``arrow_keys.polars_key_frame``), +- **Matching is the sync join's.** Each input keeps the rows it needs in a row spool + (memory, then local disk; ``core/row_spool``) and a Polars frame of their prepared keys and row numbers (``arrow_keys.polars_key_frame``), with the constant key every join adds (``join._with_common_key``). An arriving batch's key frame is joined with the other side's accumulated key frame by the sync path's own rule (``join._matched_pairs``), in one vectorized join, never per row: a top-level @@ -67,7 +68,8 @@ the last step of F), so a kernel declares every such field nullable and the stream made from its batches settles them. -A kernel holds only what can still match: a side's rows are dropped when the other side +A kernel holds only what can still match: a row is let go once it has matched when the +other side is certified unique on the keys (``core/unique_keys``); a side's rows are dropped when the other side closes (nothing can arrive to match them), and an arriving row is not kept once the other side has closed. A row whose key holds a top-level null is never kept (it matches nothing). A step of a ``Join`` chain that can never emit again (a side closed holding no diff --git a/src/orcapod/core/unique_keys.py b/src/orcapod/core/unique_keys.py index a55e2191f..61875b0c4 100644 --- a/src/orcapod/core/unique_keys.py +++ b/src/orcapod/core/unique_keys.py @@ -18,7 +18,7 @@ class declares, at the time it is asked: nothing is stored on a stream, and noth from collections.abc import Iterable, Mapping, Sequence from contextvars import ContextVar -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Protocol if TYPE_CHECKING: from orcapod.protocols.core_protocols import StreamProtocol @@ -95,8 +95,14 @@ def joined_keys( return certificate(keys) +class _HasKeys(Protocol): + """What the certificate needs of the stream it is of.""" + + def keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: ... + + def derived_keys( - pod: object, upstreams: Sequence[StreamProtocol], stream: StreamProtocol + pod: object, upstreams: Sequence[StreamProtocol], stream: _HasKeys ) -> UniqueKeys: """The certificate of ``stream``, the result of ``pod`` over ``upstreams``. diff --git a/tests/test_core/test_unique_keys.py b/tests/test_core/test_unique_keys.py index a13396894..3d78ca5de 100644 --- a/tests/test_core/test_unique_keys.py +++ b/tests/test_core/test_unique_keys.py @@ -183,7 +183,7 @@ def test_joins_derive_their_certificate() -> None: assert lookup.join(left).unique_keys == _keys(KEY) assert left.join(both).unique_keys == _keys((*KEY, "depth")) assert left.join(none).unique_keys == frozenset() - assert left.join(lookup, _wide()).unique_keys == _keys(KEY) + assert Join()(left, lookup, _wide()).unique_keys == _keys(KEY) assert left.semi_join(none).unique_keys == _keys(KEY) assert none.semi_join(left).unique_keys == frozenset() renamed = left.select_data_columns(["x"]) From 9176ee76d8744bd481d6779f020404b6acda2f03 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:49:28 -0800 Subject: [PATCH 22/81] perf(operators): joins carry source-info tokens as recipes (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-tokens.md | 11 +- src/orcapod/core/operators/join.py | 38 +++- src/orcapod/core/operators/merge_join.py | 16 +- src/orcapod/core/operators/rejoin.py | 43 ++++- src/orcapod/core/operators/semijoin.py | 2 +- src/orcapod/utils/source_tokens.py | 111 +++++++++--- tests/test_core/streams/test_source_tokens.py | 168 ++++++++++++++++++ 7 files changed, 347 insertions(+), 42 deletions(-) diff --git a/docs/dev/specs/itl-1464-tokens.md b/docs/dev/specs/itl-1464-tokens.md index 7473d3954..77000c2f8 100644 --- a/docs/dev/specs/itl-1464-tokens.md +++ b/docs/dev/specs/itl-1464-tokens.md @@ -1,7 +1,7 @@ # Source-info tokens carried as a recipe (ITL-1464, track TOKENS) Status: direction approved November 25, 2026. Step 1 (sources and row-wise operators) -implemented with this document; step 2 (joins) is a separate pull request. +implemented with this document; step 2 (joins) is stacked on it. ## The cost @@ -65,9 +65,10 @@ the system tags gives text (the recipe would have nothing to read). | Column selections, `MapData`, `MapTags`, `MapColumns`, `TagBy`, `AddTags`, `DropNulls`, `Filter` | none of the values | derived in, derived out | | `PolarsFilter` | none, unless a predicate reads a token | the columns stay out of the Polars frame and are put back for the kept rows; a predicate that could read one (a selector, a regular expression, a non-expression, a name that is no column) gets text, as before | | `without_input_meta` | names only | derived | -| `SemiJoin` (left input) | none | step 2 | -| `Join`, `Rejoin`, `MergeJoin`: columns of one input | none | step 2 | -| `Join`: a shared data-tag | both tokens, folded (`join_v1`) | step 2: a fold recipe; until then text | +| `SemiJoin` (left input) | none | derived (step 2) | +| `Join`, `Rejoin`, `MergeJoin`: columns of one input | none | derived (step 2) | +| `Rejoin`: a shared data-tag | equality of the tokens | one recipe in every input: equal wherever the system tags are, so not compared; otherwise text (step 2) | +| `Join`: a shared data-tag | both tokens, folded (`join_v1`) | a fold recipe (`FoldRecipe`), the same fold run when the text is made; text when a member is text (step 2) | | `MergeJoin`: a colliding column | both tokens, in a list | text of that column | | `GroupBy`, `Batch` | the members' tokens, in a list | text (below) | | `iter_data` (rows: function pods, side effects, async rows) | one string per column of each row | built for 8,192 rows at a time | @@ -107,5 +108,5 @@ A synthetic time series table, about 2.2 million rows, 13 columns, about 250 MiB | `map_data` | 10.8 GiB | 2.0 GiB | 9.3 GiB | 0.75 GiB | | `drop_nulls` | 19.7 GiB | 2.4 GiB | 18.6 GiB | 1.7 GiB | | `polars_filter` | 16.6 GiB | 2.5 GiB | 9.3 GiB | 0.75 GiB | -| `join` (8 and 14 columns) | above 24 GiB | above 24 GiB (step 2) | | | +| `join` (8 and 14 columns) | above 24 GiB | 3.6 GiB (step 2) | | 2.6 GiB | | `group_by` | 20.9 GiB | 20.7 GiB (its lists are text) | 15.9 GiB | 15.9 GiB | diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 430957232..8ccfc80ce 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -45,7 +45,7 @@ ) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, DataValue, Schema -from orcapod.utils import arrow_utils, schema_utils +from orcapod.utils import arrow_utils, schema_utils, source_tokens # The row-number columns of the frames Polars joins (``_inner_join``); a tag, so a # key, never starts with the meta prefix ``__``. @@ -179,6 +179,20 @@ def _fold_members(tokens: Sequence[str | None]) -> str: return arrow_utils.fold_system_tag_values(ordered, label=JOIN_FOLD_LABEL) +# The two steps of the merge, for tokens carried as recipes (``source_tokens``, ITL-1464): +# the members met so far, and the fold the join ends with. +_PENDING_FOLD = "join pending" +source_tokens.register_fold(_PENDING_FOLD, _pending) +source_tokens.register_fold(JOIN_FOLD_LABEL, _fold_members) + + +def _pending_members(recipe: source_tokens.Recipe) -> tuple[source_tokens.Recipe, ...]: + """The member recipes a merged column holds so far (itself, if not pending).""" + if isinstance(recipe, source_tokens.FoldRecipe) and recipe.fold == _PENDING_FOLD: + return recipe.members + return (recipe,) + + def _fold_pending(value: Any) -> Any: """Replace every pending token position of ``value`` by its merged token.""" if isinstance(value, list): @@ -464,7 +478,8 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: # Source-info columns of merged data-tag columns, folded once at the end. merged_source: set[str] = set() table = without_meta_columns( - stream.as_table(columns={"source": True, "system_tags": True}), tag_keys + stream.as_carried_table(columns={"source": True, "system_tags": True}), + tag_keys, ) # trick to get cartesian product; use int8 explicitly so that zero-row # tables don't produce a null-typed column that Polars rejects on join @@ -477,7 +492,9 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: for idx, next_stream in enumerate(ordered_streams[1:], start=1): next_tag_keys, _ = next_stream.keys() next_table = without_meta_columns( - next_stream.as_table(columns={"source": True, "system_tags": True}), + next_stream.as_carried_table( + columns={"source": True, "system_tags": True} + ), next_tag_keys, ) next_table = arrow_utils.append_to_system_tags( @@ -580,6 +597,17 @@ def _merge_source_columns( The table with ``left_name`` holding both sides' members, pending until the join folds them (``_fold_source_column``). """ + left_recipe, right_recipe = ( + source_tokens.derived_recipe(table.schema.field(name).type) + for name in (left_name, right_name) + ) + if left_recipe is not None and right_recipe is not None: + members = (*_pending_members(left_recipe), *_pending_members(right_recipe)) + recipe = source_tokens.FoldRecipe(_PENDING_FOLD, members) + return source_tokens.with_recipe(table, left_name, recipe).drop_columns( + [right_name] + ) + table = source_tokens.materialize(table, (left_name, right_name)) field = table.schema.field(left_name) merged = pa.array( [ @@ -606,6 +634,10 @@ def _fold_source_column(table: "pa.Table", name: str) -> "pa.Table": Returns: The table with one merged token at every token position of ``name``. """ + recipe = source_tokens.derived_recipe(table.schema.field(name).type) + if recipe is not None: + fold = source_tokens.FoldRecipe(JOIN_FOLD_LABEL, _pending_members(recipe)) + return source_tokens.with_recipe(table, name, fold) field = table.schema.field(name) folded = pa.array( [_fold_pending(value) for value in table.column(name).to_pylist()], diff --git a/src/orcapod/core/operators/merge_join.py b/src/orcapod/core/operators/merge_join.py index 88abafc5a..f3729bb3e 100644 --- a/src/orcapod/core/operators/merge_join.py +++ b/src/orcapod/core/operators/merge_join.py @@ -32,7 +32,7 @@ from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema -from orcapod.utils import arrow_utils, schema_utils +from orcapod.utils import arrow_utils, schema_utils, source_tokens def _output_types( @@ -397,11 +397,13 @@ def binary_static_process( # Tables with source info and system tags, each input's system-tag # column names extended with its pipeline hash and argument index. left_table = arrow_utils.append_to_system_tags( - left_stream.as_table(columns={"source": True, "system_tags": True}), + left_stream.as_carried_table(columns={"source": True, "system_tags": True}), self._system_tag_suffix(left_stream, 0), ) right_table = arrow_utils.append_to_system_tags( - right_stream.as_table(columns={"source": True, "system_tags": True}), + right_stream.as_carried_table( + columns={"source": True, "system_tags": True} + ), self._system_tag_suffix(right_stream, 1), ) @@ -429,6 +431,12 @@ def binary_static_process( [right_source.get(c, c) for c in right_table.column_names] ) + # A source-info column both inputs have becomes a list of both tokens: text + # (ITL-1464). Any other is carried as it is. + both = set(left_table.column_names) & set(right_table.column_names) + left_table = source_tokens.materialize(left_table, both) + right_table = source_tokens.materialize(right_table, both) + # Find colliding data columns (a merged data-tag column is not one) colliding_keys = (set(left_data_keys) & set(right_data_keys)) - merged @@ -496,6 +504,8 @@ def binary_static_process( for left_name, right_name in right_source.items(): joined = Join._merge_source_columns(joined, left_name, right_name) # pyright: ignore[reportPrivateUsage] # Join's one rule joined = Join._fold_source_column(joined, left_name) # pyright: ignore[reportPrivateUsage] # Join's one rule + # A merge of derived tokens has a recipe, so a type, of its own (ITL-1464). + output_types[left_name] = joined.schema.field(left_name).type # Use the left stream's type converter — not the default context — so that a # MergeJoin over streams built with a non-default DataContext reconstructs the diff --git a/src/orcapod/core/operators/rejoin.py b/src/orcapod/core/operators/rejoin.py index d760f5865..a80921d0e 100644 --- a/src/orcapod/core/operators/rejoin.py +++ b/src/orcapod/core/operators/rejoin.py @@ -48,7 +48,7 @@ ) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, Schema -from orcapod.utils import arrow_utils, schema_utils +from orcapod.utils import arrow_utils, schema_utils, source_tokens from orcapod.utils.warning_utils import outside_orcapod_stacklevel # Row-number columns of the frames Polars matches, and the column of a row's occurrence @@ -66,6 +66,38 @@ def _system_tag_names(stream: StreamProtocol) -> list[str]: ) +def _with_comparable_tokens(tables: Sequence["pa.Table"]) -> "list[pa.Table]": + """Give each shared source-info column one form: one recipe, or text (ITL-1464). + + Rejoin compares a shared column's values. When every input that has a token column + derives it by one recipe, it is equal wherever the system tags are, which the rows + already match on, so it stays derived and is not compared (``_agrees_by_recipe``). + Otherwise its text is built in every input. + + Args: + tables: The inputs' rows. + + Returns: + The same tables; a derived column several of them have has one recipe. + """ + types: dict[str, list[pa.DataType]] = {} + for table in tables: + for field in table.schema: + types.setdefault(field.name, []).append(field.type) + differing = { + name + for name, kinds in types.items() + if any(source_tokens.derived_recipe(kind) is not None for kind in kinds) + and any(kind != kinds[0] for kind in kinds) + } + return [source_tokens.materialize(table, differing) for table in tables] + + +def _agrees_by_recipe(table: "pa.Table", name: str) -> bool: + """Whether column ``name`` is derived, so rows with equal system tags agree on it.""" + return source_tokens.derived_recipe(table.schema.field(name).type) is not None + + def _agreeing( pairs: "pl.DataFrame", left: "pa.Table", @@ -207,7 +239,7 @@ def _differing_columns(tables: Sequence["pa.Table"], keys: Sequence[str]) -> lis holders: dict[str, list[int]] = {} for index, table in enumerate(tables): for name in table.column_names: - if name not in keys: + if name not in keys and not _agrees_by_recipe(table, name): holders.setdefault(name, []).append(index) # The columns several inputs have, by the inputs that have them. shared: dict[tuple[int, ...], list[str]] = {} @@ -421,12 +453,13 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: tag_keys, _ = stream.keys() tables.append( without_meta_columns( - stream.as_table( + stream.as_carried_table( columns={"source": True, "system_tags": True, "context": True} ), tag_keys, ) ) + tables = _with_comparable_tokens(tables) # The rule on the tables themselves, in call order: an input whose schema # states no system tag (``_require_rejoinable``) is checked here. by_call = {id(stream): table for stream, table in zip(ordered_streams, tables)} @@ -572,7 +605,9 @@ def _rejoin_pair( others = [ name for name in right.column_names - if name in left.column_names and name not in keys + if name in left.column_names + and name not in keys + and not _agrees_by_recipe(left, name) ] for name in sorted(others): shared_type = require_shared_arrow_type( diff --git a/src/orcapod/core/operators/semijoin.py b/src/orcapod/core/operators/semijoin.py index d2a379f50..1d59f8a91 100644 --- a/src/orcapod/core/operators/semijoin.py +++ b/src/orcapod/core/operators/semijoin.py @@ -224,7 +224,7 @@ def binary_static_process( if not common_keys: return left_stream - left_table = left_stream.as_table( + left_table = left_stream.as_carried_table( columns={"source": True, "system_tags": True, "context": True} ) # Only the right side's keys are read, never its data columns. diff --git a/src/orcapod/utils/source_tokens.py b/src/orcapod/utils/source_tokens.py index 0fd59bcfc..c68537e77 100644 --- a/src/orcapod/utils/source_tokens.py +++ b/src/orcapod/utils/source_tokens.py @@ -18,9 +18,9 @@ from __future__ import annotations import json -from collections.abc import Collection, Mapping +from collections.abc import Callable, Collection, Mapping, Sequence from dataclasses import dataclass -from typing import Any, NoReturn, cast +from typing import Any, NoReturn, TypeAlias, cast import pyarrow as pa import pyarrow.compute as pc @@ -33,6 +33,20 @@ """The most rows whose token text is built in one step.""" +_folds: dict[str, Callable[[Sequence[str | None]], str]] = {} + + +def register_fold(name: str, fold: Callable[[Sequence[str | None]], str]) -> None: + """Say how a ``FoldRecipe`` named ``name`` makes one token of several. + + Args: + name: The fold's name; for a fold with an algorithm label, the label. + fold: One token from the members' tokens. Called once per row, with the members + in the recipe's order. + """ + _folds[name] = fold + + @dataclass(frozen=True) class TokenRecipe: """How the token of each row is made from the row's system tags. @@ -48,14 +62,14 @@ class TokenRecipe: record_id: str column: str - def to_json(self) -> str: - """The recipe as text: what two equal recipes share.""" - return json.dumps([self.source_id, self.record_id, self.column]) + def to_json(self) -> Any: # pyright: ignore[reportExplicitAny] # JSON + """The recipe as a JSON value: what two equal recipes share.""" + return [self.source_id, self.record_id, self.column] - @classmethod - def from_json(cls, text: str) -> TokenRecipe: - """The recipe ``to_json`` wrote.""" - return cls(*json.loads(text)) + @property + def read_columns(self) -> frozenset[str]: + """The system-tag columns the recipe reads.""" + return frozenset((self.source_id, self.record_id)) def renamed(self, names: Mapping[str, str]) -> TokenRecipe: """The recipe over system-tag columns renamed by ``names``.""" @@ -65,10 +79,6 @@ def renamed(self, names: Mapping[str, str]) -> TokenRecipe: self.column, ) - def reads(self, columns: Collection[str]) -> bool: - """Whether the recipe reads one of ``columns``.""" - return self.source_id in columns or self.record_id in columns - def text(self, batch: pa.RecordBatch) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array """The tokens of ``batch``'s rows, as ``large_string``.""" return pc.binary_join_element_wise( # pyright: ignore[reportCallIssue, reportUnknownVariableType] # the stubs leave out scalar arguments @@ -79,6 +89,52 @@ def text(self, batch: pa.RecordBatch) -> pa.Array[Any]: # pyright: ignore[repor ) +@dataclass(frozen=True) +class FoldRecipe: + """How one token is made of the tokens of several merged columns, row by row. + + Attributes: + fold: The registered fold (``register_fold``). + members: The merged columns' recipes, in the order they were met. + """ + + fold: str + members: tuple[Recipe, ...] + + def to_json(self) -> Any: # pyright: ignore[reportExplicitAny] # JSON + """The recipe as a JSON value: what two equal recipes share.""" + return {"fold": self.fold, "members": [m.to_json() for m in self.members]} + + @property + def read_columns(self) -> frozenset[str]: + """The system-tag columns the members read.""" + return frozenset[str]().union(*(m.read_columns for m in self.members)) + + def renamed(self, names: Mapping[str, str]) -> FoldRecipe: + """The recipe over system-tag columns renamed by ``names``.""" + return FoldRecipe(self.fold, tuple(m.renamed(names) for m in self.members)) + + def text(self, batch: pa.RecordBatch) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array + """The tokens of ``batch``'s rows, as ``large_string``.""" + fold = _folds[self.fold] + members = [member.text(batch).to_pylist() for member in self.members] + return pa.array( + [fold(tokens) for tokens in zip(*members, strict=True)], type=_TEXT + ) + + +Recipe: TypeAlias = TokenRecipe | FoldRecipe + + +def recipe_from_json(value: Any) -> Recipe: # pyright: ignore[reportExplicitAny, reportAny] # JSON + """The recipe whose ``to_json`` is ``value``.""" + if isinstance(value, dict): + return FoldRecipe( + value["fold"], tuple(recipe_from_json(m) for m in value["members"]) + ) + return TokenRecipe(*value) + + class _DerivedTokenScalar(pa.ExtensionScalar): """A value of a derived column: it has none to read.""" @@ -102,18 +158,18 @@ class DerivedTokenType(pa.ExtensionType): wrapped in its type again. Two derived columns have one type only with one recipe. """ - def __init__(self, recipe: TokenRecipe) -> None: + def __init__(self, recipe: Recipe) -> None: self.recipe = recipe super().__init__(pa.struct([]), "orcapod.internal.derived_token") def __arrow_ext_serialize__(self) -> bytes: - return self.recipe.to_json().encode() + return json.dumps(self.recipe.to_json()).encode() @classmethod def __arrow_ext_deserialize__( cls, storage_type: pa.DataType, serialized: bytes ) -> DerivedTokenType: - return cls(TokenRecipe.from_json(serialized.decode())) + return cls(recipe_from_json(json.loads(serialized))) def __arrow_ext_scalar_class__(self) -> type[pa.ExtensionScalar]: return _DerivedTokenScalar @@ -137,14 +193,14 @@ def __hash__(self) -> int: return hash(self.recipe) -def derived_array(recipe: TokenRecipe, rows: int) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array +def derived_array(recipe: Recipe, rows: int) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array """A derived token column of ``rows`` rows: no row has a byte.""" # No validity bitmap: no row is null. (The stubs do not allow the absent buffer.) storage = pa.Array.from_buffers(pa.struct([]), rows, cast(Any, [None]), 0, 0) return pa.ExtensionArray.from_storage(DerivedTokenType(recipe), storage) -def derived_recipe(kind: pa.DataType) -> TokenRecipe | None: +def derived_recipe(kind: pa.DataType) -> Recipe | None: """The recipe of a column of type ``kind``; ``None`` when it is not derived.""" return kind.recipe if isinstance(kind, DerivedTokenType) else None @@ -154,6 +210,13 @@ def derived_columns(schema: pa.Schema) -> tuple[str, ...]: return tuple(f.name for f in schema if derived_recipe(f.type) is not None) +def with_recipe(table: pa.Table, name: str, recipe: Recipe) -> pa.Table: + """``table`` with its token column ``name`` derived by ``recipe``, its field kept.""" + tokens = derived_array(recipe, table.num_rows) + field = table.schema.field(name).with_type(tokens.type) + return table.set_column(table.schema.get_field_index(name), field, tokens) + + def materialize(table: pa.Table, names: Collection[str] | None = None) -> pa.Table: """Return ``table`` with its derived token columns as text. @@ -171,12 +234,12 @@ def materialize(table: pa.Table, names: Collection[str] | None = None) -> pa.Tab if not wanted: return table schema = table.schema - recipes: dict[str, TokenRecipe] = {} + recipes: dict[str, Recipe] = {} for name in wanted: recipe = derived_recipe(schema.field(name).type) assert recipe is not None recipes[name] = recipe - read = {c for r in recipes.values() for c in (r.source_id, r.record_id)} + read = {c for recipe in recipes.values() for c in recipe.read_columns} tags = table.select([c for c in table.column_names if c in read]) chunks: dict[str, list[pa.Array[Any]]] = {name: [] for name in wanted} # pyright: ignore[reportExplicitAny] # Arrow arrays for batch in tags.to_batches(max_chunksize=ROWS_PER_CHUNK): @@ -204,7 +267,7 @@ def materialize_reading(table: pa.Table, columns: Collection[str]) -> pa.Table: name for name in derived_columns(table.schema) if (recipe := derived_recipe(table.schema.field(name).type)) is not None - and recipe.reads(columns) + and not recipe.read_columns.isdisjoint(columns) ], ) @@ -226,9 +289,5 @@ def rename_read_columns(table: pa.Table, names: Mapping[str, str]) -> pa.Table: renamed = recipe.renamed(names) if renamed == recipe: continue - table = table.set_column( - table.schema.get_field_index(name), - field.with_type(DerivedTokenType(renamed)), - derived_array(renamed, table.num_rows), - ) + table = with_recipe(table, name, renamed) return table diff --git a/tests/test_core/streams/test_source_tokens.py b/tests/test_core/streams/test_source_tokens.py index 40eb740ea..0480d5744 100644 --- a/tests/test_core/streams/test_source_tokens.py +++ b/tests/test_core/streams/test_source_tokens.py @@ -20,6 +20,7 @@ from orcapod import contexts from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.base import UnaryOperator +from orcapod.core.operators.join import JOIN_FOLD_LABEL from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.streams import ArrowTableStream from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS @@ -29,10 +30,13 @@ DropColumns, DropNulls, DropTagColumns, + Join, MapColumns, MapData, MapTags, + MergeJoin, PolarsFilter, + Rejoin, SelectDataColumns, TagBy, ) @@ -178,6 +182,170 @@ def test_every_operator_gives_what_text_sources_give( assert_same_values(table, expected) +def _other(name: str, **kwargs: Any) -> ArrowTableSource: + """A source sharing the data-tags ``k`` and ``j``, of its own schema (``name``).""" + table = pa.table( + { + f"{name}1": pa.array([float(i) for i in range(12)]), + "j": pa.array([f"j{i % 3}" for i in range(12)]), + "k": pa.array(reversed(range(12)), pa.int32()), + f"{name}2": pa.array([f"v{i}" for i in range(12)]), + } + ) + return ArrowTableSource(table, tag_columns=["j", "k"], **kwargs) + + +def _text_other(name: str) -> ArrowTableStream: + """``_other`` as a raw stream whose tokens are text already.""" + source = _other(name) + return ArrowTableStream( + source.as_table(columns={"source": True, "system_tags": True}), + tag_columns=["j", "k"], + data_tags=["j", "k"], + ) + + +MATCHES: dict[str, tuple[Callable[[], Any], set[str]]] = { + # The columns whose tokens may be text after it, by name; every other is derived. + "join_2": (lambda: _other("a").join(_other("b")), set()), + "join_2_swapped": (lambda: _other("b").join(_other("a")), set()), + "join_3": (lambda: Join()(_other("c"), _other("a"), _other("b")), set()), + "join_chain": (lambda: _other("a").join(_other("b")).join(_other("c")), set()), + "join_then_row_wise": ( + lambda: ( + _other("a") + .join(_other("b")) + .map_data({"a1": "x", "b2": "y"}) + .drop_nulls() + .polars_filter(pl.col("x") > 3) + ), + set(), + ), + "join_tag_only": ( + lambda: _source().join(_other("a", tag_only_columns=["j"])), + set(), + ), + "join_text_member": ( + lambda: Join()(_other("a"), _text_other("b"), _other("c")), + {"j", "k", "b1", "b2"}, + ), + "join_one_schema": ( + lambda: ( + _other("a", source_id="s2") + .map_data({"a1": "p", "a2": "q"}) + .join(_other("a", source_id="s1").map_data({"a1": "p2", "a2": "q2"})) + ), + set(), + ), + "semi_join": (lambda: _source().semi_join(_plain_source()), set()), + "merge_join": ( + lambda: MergeJoin()( + _other("a").map_data({"a2": "same"}), _other("b").map_data({"b2": "same"}) + ), + {"same"}, + ), + "rejoin": ( + lambda: Rejoin()( + _other("a").select_data_columns(["a1", "j", "k"]), + _other("a").select_data_columns(["a2", "j", "k"]), + ), + set(), + ), + "rejoin_filtered": ( + lambda: Rejoin()( + _other("a").select_data_columns(["a1", "j", "k"]), + _other("a").polars_filter(pl.col("a1") > 3).drop_data_columns(["a1"]), + ), + set(), + ), +} + + +@pytest.mark.parametrize("name", MATCHES) +def test_a_match_carries_the_tokens_and_gives_the_same_rows( + name: str, text_sources: Callable[[], None] +) -> None: + make, text = MATCHES[name] + result = make() + carried = result.as_carried_table(columns={"source": True, "system_tags": True}) + tokens = { + c.removeprefix("_source_") + for c in carried.column_names + if c.startswith(constants.SOURCE_PREFIX) + } + derived = {c.removeprefix("_source_") for c in _derived(carried)} + assert tokens - derived == text & tokens + table = result.as_table(all_info=True) + rows = [(t.as_dict(all_info=True), d.as_dict(all_info=True)) for t, d in result] + assert table.num_rows > 0 + text_sources() + oracle = make() + expected = oracle.as_table(all_info=True) + assert table.schema.equals(expected.schema, check_metadata=True) + assert_same_values(table, expected) + assert rows == [ + (t.as_dict(all_info=True), d.as_dict(all_info=True)) for t, d in oracle + ] + + +@pytest.mark.parametrize("order", [("s1", "s2"), ("s2", "s1")]) +def test_inputs_of_one_pipeline_hash_keep_their_own_tokens( + order: tuple[str, str], text_sources: Callable[[], None] +) -> None: + """Two sources of one schema, every column a data-tag: the join sorts their + system-tag values per row, so the tokens that read them are text first.""" + + def make() -> Any: + streams = [ + ArrowTableSource( + _table().select(["k", "j"]).slice(i), + tag_columns=["k", "j"], + source_id=s, + ) + for i, s in enumerate(order) + ] + assert streams[0].pipeline_hash() == streams[1].pipeline_hash() + return streams[0].join(streams[1]) + + result = make() + assert not _derived(result.as_carried_table(columns=CARRIED)) + table = result.as_table(all_info=True) + text_sources() + expected = make().as_table(all_info=True) + assert table.num_rows == 9 + assert table.schema.equals(expected.schema, check_metadata=True) + assert_same_values(table, expected) + + +def test_a_join_fold_is_the_fold_of_its_members() -> None: + """The merged token is ``join_v1`` of the inputs' own tokens, whatever the order.""" + a, b = _other("a"), _other("b") + table = a.join(b).as_table(columns={"source": True}) + own = [ + dict(zip(t["k"].to_pylist(), t["_source_k"].to_pylist(), strict=True)) + for t in (s.as_table(columns={"source": True}) for s in (a, b)) + ] + for key, token in zip( + table["k"].to_pylist(), table["_source_k"].to_pylist(), strict=True + ): + assert token == arrow_utils.fold_system_tag_values( + sorted(tokens[key] for tokens in own), label=JOIN_FOLD_LABEL + ) + + +def test_a_recipe_survives_its_json() -> None: + leaf = source_tokens.TokenRecipe("s", "r", "c") + fold = source_tokens.FoldRecipe( + JOIN_FOLD_LABEL, (leaf, source_tokens.FoldRecipe(JOIN_FOLD_LABEL, (leaf, leaf))) + ) + for recipe in (leaf, fold): + kind = source_tokens.DerivedTokenType(recipe) + again = source_tokens.DerivedTokenType.__arrow_ext_deserialize__( + pa.struct([]), kind.__arrow_ext_serialize__() + ) + assert again == kind and again.recipe == recipe + + def _column_configs() -> list[dict[str, bool]]: groups = ("source", "system_tags", "context", "content_hash", "sort_by_tags") return [ From 1ce55338027e8b5efde79213d570e779af9975de Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:50:17 -0800 Subject: [PATCH 23/81] 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 24/81] 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 e846289f3f7e21ef407b8619e5727bb70985980d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:55:13 -0800 Subject: [PATCH 25/81] wip: sync operator node output kept on disk when large (ITL-1464) --- src/orcapod/core/nodes/operator_node.py | 3 ++ .../core/operators/static_output_pod.py | 34 ++++++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 9590c52cf..9c1cacc08 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -43,6 +43,7 @@ RowBuiltFormUnavailable, RowChunks, StaticOutputOperatorPod, + kept_table as spilled_when_large, produced_stream, rows_on_read, ) @@ -1759,6 +1760,8 @@ def execute( StaticOutputOperatorPod._raise_as_rows_do( produced.iter_data(), error ) + # On local disk when large, read back memory-mapped (ITL-1464). + kept_table = spilled_when_large(kept_table) self._cached_output_stream = ArrowTableStream( kept_table, tag_columns=tag_keys, data_tags=data_tags ) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 683806ccd..76fb7a9bc 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -513,7 +513,12 @@ def _kept_output( A stream over the rows, in row order. """ if rows: - return StaticOutputOperatorPod._materialize_to_stream(rows) + # Kept as Arrow chunks, on local disk when large (ITL-1464): the table + # ``_materialize_to_stream`` builds. + chunks = RowChunks() + for tag, data in rows: + chunks.add(tag, data) + return chunks.output_stream() return StaticOutputOperatorPod._zero_rows_in_row_order(result) @staticmethod @@ -1458,6 +1463,33 @@ def rows_once( return result.iter_data() +SPILL_SLICE_ROWS = 65_536 +"""Rows handed to the spool at a time by ``kept_table``: the copy the spool makes of +what it is given is then one slice, not the table.""" + + +def kept_table(table: pa.Table) -> pa.Table: + """Return ``table`` as a node keeps it: on local disk when it is large (ITL-1464). + + A table of at most ``KEPT_ROWS_MEMORY_BYTES`` is returned as it is. A larger one + is written to a ``RowSpool`` and returned read back memory-mapped: the same + schema and values (only the arrays' chunking differs), not process memory. The + mapping lives as long as a table that refers to it. + + Args: + table: The rows a node is about to keep. + + Returns: + The table to keep. + """ + if table.nbytes <= KEPT_ROWS_MEMORY_BYTES or not table.num_rows: + return table + spool = RowSpool(memory_bytes=KEPT_ROWS_MEMORY_BYTES) + for start in range(0, table.num_rows, SPILL_SLICE_ROWS): + spool.append(table.slice(start, SPILL_SLICE_ROWS)) + return spool.table() + + async def collect_row_chunks( channel: ReadableChannel[tuple[TagProtocol, DataProtocol]], ) -> RowChunks: From b7bd6e7d4ff6ae9f464f15f13c9cc5a683dc2528 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:57:30 -0800 Subject: [PATCH 26/81] fix(pipeline): never bypass a result stream's own iterator; defer a chunk's error to the read (ITL-1464) Review of PR 562: rows_once took the unkept path for any ArrowTableStream subclass or shadowed iter_data, and a full chunk that cannot make one table raised while a barrier was still collecting, leaving the other input's reader behind and raising where main returned no rows for an empty other input. Co-Authored-By: Claude Fable 5.2 --- .../core/operators/static_output_pod.py | 21 +++-- tests/test_core/operators/test_row_chunks.py | 89 ++++++++++++++++++- 2 files changed, 104 insertions(+), 6 deletions(-) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index e750afe03..a4ec5d410 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1309,8 +1309,9 @@ class RowChunks: differs), because that table is a concatenation of one table per row, matched by name to the first row's column order, and concatenation chunk by chunk gives the same table. Rows whose columns disagree raise ``pyarrow.ArrowInvalid`` as there, - when their chunk is built or the chunks are joined; the message's table index is - then the row's place in its chunk, or the chunk's place. + and as there only when the table is asked for (``row_table``), never when a row + is added; the message's table index is then the row's place in its chunk, or the + chunk's place. A chunk is the record batch an ITL-1347 channel carries, before the last step of its row-built form (the source-info field flags, which need every row); a node @@ -1326,6 +1327,7 @@ def __init__(self) -> None: self._data_tags: tuple[str, ...] = () self._first_context_key: str | None = None self.num_rows: int = 0 + self._unsealable: bool = False def add(self, tag: TagProtocol, data: DataProtocol) -> None: """Keep one row, after every row added before it.""" @@ -1335,8 +1337,15 @@ def add(self, tag: TagProtocol, data: DataProtocol) -> None: self._first_context_key = data.data_context_key self._pending.append((tag, data)) self.num_rows += 1 - if len(self._pending) >= ROW_CHUNK_ROWS: - self._seal() + if len(self._pending) >= ROW_CHUNK_ROWS and not self._unsealable: + try: + self._seal() + except Exception: + # Rows that cannot make one table (columns that disagree). Receiving + # a row never raised: the error belongs to the read of the table + # (``row_table``), which a barrier whose other input is empty never + # makes. The rows wait as they came, and nothing more is sealed. + self._unsealable = True def _seal(self) -> None: """Build the pending rows into Arrow tables and let the pairs go.""" @@ -1431,7 +1440,9 @@ def rows_once( Returns: The rows of ``result.iter_data()``, in its order. """ - if isinstance(result, ArrowTableStream): + # Exactly an ``ArrowTableStream`` with its own iterator: a subclass's ``iter_data``, + # or one set on the instance, is what yields its rows, and is never bypassed. + if type(result) is ArrowTableStream and "iter_data" not in vars(result): return result.iter_data_unkept() return result.iter_data() diff --git a/tests/test_core/operators/test_row_chunks.py b/tests/test_core/operators/test_row_chunks.py index f2e4c200c..1368d4c4b 100644 --- a/tests/test_core/operators/test_row_chunks.py +++ b/tests/test_core/operators/test_row_chunks.py @@ -9,7 +9,7 @@ import asyncio from pathlib import Path -from typing import Any +from typing import Any, cast import pyarrow as pa import pytest @@ -286,3 +286,90 @@ def test_a_jobs_nodes_read_the_same_whatever_materialize_results_says( assert _sorted_rows(kept) == _sorted_rows(unkept) assert sorted(kept_rows, key=repr) == sorted(unkept_rows, key=repr) assert kept_hash == unkept_hash + + +def _other_rows() -> list[tuple[Any, Any]]: + """Rows whose data columns are not those of ``_rows``: no table holds both.""" + source = ArrowTableSource( + pa.table({"subject": ["x", "y"], "trial": [100, 101], "other": [1.0, 2.0]}), + tag_columns=["subject", "trial"], + source_id="other", + ) + return list(source.iter_data()) + + +def test_rows_that_cannot_make_one_table_raise_when_it_is_read_not_when_added( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Review of PR 562: receiving a row never raised before the table was built.""" + import pyarrow.lib + + monkeypatch.setattr(static_output_pod, "ROW_CHUNK_ROWS", 3) + rows = _rows(False)[:4] + _other_rows() + _rows(False)[4:] + + chunks = _chunks(rows) + + assert chunks.num_rows == len(rows) + with pytest.raises(pyarrow.lib.ArrowInvalid): + chunks.row_table() + with pytest.raises(pyarrow.lib.ArrowInvalid): + StaticOutputOperatorPod._rows_to_table(rows) # pyright: ignore[reportPrivateUsage] # the rule RowChunks must equal + + +async def _closed(rows: list[tuple[Any, Any]]) -> Any: + channel: Channel[tuple[Any, Any]] = Channel(buffer_size=len(rows) + 1) + for row in rows: + await channel.writer.send(row) + await channel.writer.close() + return channel.reader + + +def test_a_barrier_with_an_empty_input_never_reads_the_other_as_a_table( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Review of PR 562: rows no table can hold, beside an empty input, give no rows + and no error, and no reader task is left behind.""" + from orcapod.operators import MergeJoin + + monkeypatch.setattr(static_output_pod, "ROW_CHUNK_ROWS", 3) + rows = _rows(False)[:4] + _other_rows() + _rows(False)[4:] + pipeline_hash = _source(False).pipeline_hash() + + async def run() -> tuple[list[Any], int]: + output: Channel[tuple[Any, Any]] = Channel(buffer_size=4) + before = len(asyncio.all_tasks()) + await MergeJoin().async_execute( + [await _closed(rows), await _closed([])], + output.writer, + input_pipeline_hashes=[pipeline_hash, pipeline_hash], + ) + sent = await output.reader.collect() + return sent, len(asyncio.all_tasks()) - before + + sent, left_behind = asyncio.run(run()) + + assert sent == [] + assert left_behind == 0 + + +def test_a_result_streams_own_iterator_is_never_bypassed() -> None: + """Review of PR 562: a subclass's, or an instance's, ``iter_data`` yields the rows.""" + table = _source(False).as_table(columns={"system_tags": True, "source": True}) + + class Odd(ArrowTableStream): + def iter_data(self): # pyright: ignore[reportIncompatibleMethodOverride] # a narrower iterator on purpose + for tag, data in super().iter_data(): + if cast("int", tag.as_dict()["trial"]) % 2: + yield tag, data + + keys: dict[str, Any] = { + "tag_columns": ["subject", "trial"], + "data_tags": ["subject", "trial"], + } + subclassed = Odd(table, **keys) + assert [t.as_dict()["trial"] for t, _ in rows_once(subclassed)] == [1, 3, 5, 7, 9] + + shadowed = ArrowTableStream(table, **keys) + first = next(iter(shadowed.iter_data())) + shadowed.iter_data = lambda: iter([first]) # pyright: ignore[reportAttributeAccessIssue] # an instance's own iterator + assert [t.as_dict()["trial"] for t, _ in rows_once(shadowed)] == [0] From a5e72b733d08e7c3a9631d5985a3929c5edd4aa0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:01:44 -0800 Subject: [PATCH 27/81] 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 ade241e2c0a91307d079289dea4bf67e4d557a74 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:07:09 -0800 Subject: [PATCH 28/81] perf(operators): GroupBy and Batch carry token lists as recipes (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/operators/batch.py | 29 +- src/orcapod/core/operators/filters.py | 22 +- src/orcapod/core/operators/group_by.py | 36 ++- src/orcapod/core/operators/rejoin.py | 8 +- .../core/operators/static_output_pod.py | 5 +- .../core/streams/arrow_table_stream.py | 41 ++- src/orcapod/core/streams/base.py | 17 +- src/orcapod/utils/arrow_utils.py | 35 +- src/orcapod/utils/source_tokens.py | 305 +++++++++++++++--- tests/test_core/streams/test_source_tokens.py | 269 ++++++++++++++- 10 files changed, 664 insertions(+), 103 deletions(-) diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index e7a1969f8..6d6a541e7 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -26,7 +26,7 @@ from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens from orcapod.types import Schema @@ -150,7 +150,13 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: Returns: A stream with one row per batch. """ - table = stream.as_table(columns={"source": True, "system_tags": True}) + table = stream.as_carried_table(columns={"source": True, "system_tags": True}) + # A list of tokens is aggregated as text (ITL-1464). + table = source_tokens.materialize( + table, + set(source_tokens.derived_columns(table.schema)) + - set(source_tokens.recipe_columns(table.schema)), + ) tag_columns, _ = stream.keys() @@ -162,25 +168,36 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: ), ) kept = table.slice(0, int(offsets[-1].as_py())) - bounds = cast(list[int], offsets.to_pylist()) # Every stream has a data context; StreamProtocol does not declare it. type_converter = stream.data_context.type_converter # pyright: ignore[reportAttributeAccessIssue] + # The source-info lists of tokens carried as recipes (ITL-1464). + recipes = source_tokens.recipe_columns(table.schema) + order = pa.array(np.arange(kept.num_rows), pa.int64()) + token_lists = source_tokens.MemberTokens(kept, order, offsets) + fields: list[pa.Field[Any]] = [] arrays: list[pa.Array[Any]] = [] for field in table.schema: + if field.name in recipes: + tokens = token_lists.column( + recipes[field.name], pa.large_list(pa.large_string()) + ) + fields.append(pa.field(field.name, tokens.type, nullable=False)) + arrays.append(tokens) + continue column = kept.column(field.name) if field.name.startswith(constants.SYSTEM_TAG_PREFIX): # Text values, folded per batch; text loses nothing in Python. - values = cast(list[Any], column.to_pylist()) + members = source_tokens.member_texts(kept, field.name, order, offsets) fields.append(field) arrays.append( pa.array( [ arrow_utils.fold_system_tag_values( - values[start:end], label=BATCH_FOLD_LABEL + values, label=BATCH_FOLD_LABEL ) - for start, end in zip(bounds[:-1], bounds[1:]) + for values in members ], field.type, ) diff --git a/src/orcapod/core/operators/filters.py b/src/orcapod/core/operators/filters.py index 491fa79b9..8fc269a7b 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -82,8 +82,17 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: if derived and not self._reads_only(others): whole, derived = source_tokens.materialize(whole), () table = whole.drop_columns(list(derived)) + recipes = source_tokens.recipe_columns(whole.schema) + # A list of tokens holds its members' ids, so its kept rows are taken by number. + lists = [name for name in derived if name not in recipes] + row = arrow_utils.unused_column_name(whole, "__row") df = pl.DataFrame(table) + if lists: + df = df.with_columns(pl.int_range(pl.len()).alias(row)) filtered_table = df.filter(*self.predicates, **self.constraints).to_arrow() + kept = filtered_table.column(row) if lists else None + if lists: + filtered_table = filtered_table.drop_columns([row]) # A filter passes every column through, so each one takes the # large-normalized form of its input Arrow type (string -> # large_string, list -> large_list, recursively; hash-identical). @@ -106,11 +115,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: ) for name in derived: field = whole.schema.field(name) - recipe = source_tokens.derived_recipe(field.type) - assert recipe is not None - filtered_table = filtered_table.append_column( - field, source_tokens.derived_array(recipe, filtered_table.num_rows) - ) + if name in recipes: + column = source_tokens.derived_array( + recipes[name], filtered_table.num_rows + ) + else: + assert kept is not None + column = whole.column(name).take(kept) + filtered_table = filtered_table.append_column(field, column) filtered_table = filtered_table.select(whole.column_names) return ArrowTableStream( diff --git a/src/orcapod/core/operators/group_by.py b/src/orcapod/core/operators/group_by.py index acce7333c..e268679fe 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -24,7 +24,7 @@ from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens from orcapod.utils.schema_utils import column_names # GroupBy decides which rows form a group, and in what order, with Polars, and builds @@ -448,7 +448,13 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: InputValidationError: If a key is a list of any kind, or a user tag's type has no order (``arrow_keys.part_without_rule``). """ - table = stream.as_table(columns={"source": True, "system_tags": True}) + table = stream.as_carried_table(columns={"source": True, "system_tags": True}) + # A list of tokens is aggregated as text (ITL-1464). + table = source_tokens.materialize( + table, + set(source_tokens.derived_columns(table.schema)) + - set(source_tokens.recipe_columns(table.schema)), + ) tag_columns, _ = stream.keys() # The async path reaches here without ``validate_unary_input``. _refuse_unorderable_tags( @@ -512,21 +518,23 @@ def emitted(c: str) -> pa.Array[Any]: return table.column(c).take(rows).combine_chunks() def folded(c: str) -> pa.Array[Any]: - """The fold of system-tag column ``c`` per group, over the members in order.""" + """The fold of text column ``c`` per group, over the members in order.""" # The members' text values in member order, folded per group; text loses # nothing in Python. - values = cast(list[Any], table.column(c).take(order).to_pylist()) - bounds = cast(list[int], offsets.to_pylist()) return pa.array( [ arrow_utils.fold_system_tag_values( - values[start:end], label=GROUP_BY_FOLD_LABEL + members, label=GROUP_BY_FOLD_LABEL ) - for start, end in zip(bounds[:-1], bounds[1:]) + for members in source_tokens.member_texts(table, c, order, offsets) ], - table.schema.field(c).type, + pa.large_string(), ) + # The source-info lists of tokens carried as recipes (ITL-1464). + recipes = source_tokens.recipe_columns(table.schema) + token_lists = source_tokens.MemberTokens(table, order, offsets) + # Every stream has a data context; StreamProtocol does not declare it. type_converter = stream.data_context.type_converter # pyright: ignore[reportAttributeAccessIssue] fields: list[pa.Field[Any]] = [] @@ -535,7 +543,12 @@ def folded(c: str) -> pa.Array[Any]: # folded column keep their field, a member column becomes a list. for field in table.drop_columns(list(dropped_columns)).schema: c = field.name - if c in member_columns: + if c in member_columns and c in recipes: + list_type = pa.large_list(pa.large_string()) + column = token_lists.column(recipes[c], list_type) + fields.append(pa.field(c, column.type, nullable=False)) + arrays.append(column) + elif c in member_columns: list_type = arrow_utils.aggregated_list_type( field.type, type_converter, column=c ) @@ -546,7 +559,10 @@ def folded(c: str) -> pa.Array[Any]: ) ) else: - fields.append(field) + # A key's source info is one fold, text whatever its members were. + fields.append( + field.with_type(pa.large_string()) if c in recipes else field + ) arrays.append(emitted(c) if c in self.by else folded(c)) grouped_table = pa.Table.from_arrays(arrays, schema=pa.schema(fields)) diff --git a/src/orcapod/core/operators/rejoin.py b/src/orcapod/core/operators/rejoin.py index a80921d0e..ba65070e5 100644 --- a/src/orcapod/core/operators/rejoin.py +++ b/src/orcapod/core/operators/rejoin.py @@ -87,8 +87,12 @@ def _with_comparable_tokens(tables: Sequence["pa.Table"]) -> "list[pa.Table]": differing = { name for name, kinds in types.items() - if any(source_tokens.derived_recipe(kind) is not None for kind in kinds) - and any(kind != kinds[0] for kind in kinds) + if len(kinds) > 1 + and any(source_tokens.is_derived(kind) for kind in kinds) + and not all( + source_tokens.derived_recipe(kind) is not None and kind == kinds[0] + for kind in kinds + ) } return [source_tokens.materialize(table, differing) for table in tables] diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 845a7d6a7..7d46a1136 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -580,8 +580,9 @@ def _type_source_info_by_values(table: pa.Table) -> pa.Table: continue if pa.types.is_large_string(field.type): continue - if source_tokens.derived_recipe(field.type) is not None: - # Every token of a derived column is one string. + if source_tokens.is_derived(field.type): + # A token is one string, and a list of them is never empty: the type + # the column declares is the one its tokens give. continue values = table.column(index).to_pylist() kinds = {arrow_utils.source_info_arrow_type(value) for value in values} diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 09f1b1d4e..c4dc42682 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -28,6 +28,30 @@ """The rows whose source-info text ``iter_data`` builds at once (ITL-1464).""" +def _parts(rows: "pa.Table") -> Iterator[tuple[int, int]]: + """The row ranges ``iter_data`` builds at once: all rows, or bounded ones (ITL-1464). + + A table with derived tokens is cut so that a part holds at most ``ROWS_PER_PART`` + rows and, beyond one row, at most eight times as many tokens in a column of lists. + """ + if not rows.num_rows: + return + if not source_tokens.derived_columns(rows.schema): + yield 0, rows.num_rows + return + members = source_tokens.members_per_row(rows) + ends = None if members is None else members.cumsum() + start = 0 + while start < rows.num_rows: + end = min(start + ROWS_PER_PART, rows.num_rows) + if ends is not None: + before = int(ends[start - 1]) if start else 0 + fit = int(ends.searchsorted(before + 8 * ROWS_PER_PART, side="right")) + end = min(end, max(fit, start + 1)) + yield start, end + start = end + + class ArrowTableStream(StreamBase): """ An immutable stream based on a PyArrow Table. @@ -93,14 +117,18 @@ def __init__( # Dictionary-encoded columns are not currently supported (ITL-1264, # ITL-1277): every source and operator result becomes a stream here, so this # refuses them all, tags and data alike. - if found := schema_utils.dictionary_columns(table.schema): + # A derived token column is no column of these types: it is text to every reader. + shown = pa.schema( + [f for f in table.schema if not source_tokens.is_derived(f.type)] + ) + if found := schema_utils.dictionary_columns(shown): raise schema_utils.dictionary_columns_error( found, tag_columns, data_tags, system_tag_columns ) # Nor are columns of a type the schema hash rejects (a union, a list view, a # run-end-encoded type; developer, November 21, 2026, ITL-640): a stream's # identity is its Arrow schema hash, which cannot hold them. - if found := schema_utils.schema_hash_rejected_columns(table.schema): + if found := schema_utils.schema_hash_rejected_columns(shown): raise schema_utils.schema_hash_rejected_columns_error( found, tag_columns, data_tags, system_tag_columns ) @@ -491,13 +519,8 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, Data]]: ) # Derived tokens become text a part of the rows at a time (ITL-1464); a # table with none is one part. - size = ( - ROWS_PER_PART - if source_tokens.derived_columns(rows.schema) - else max(rows.num_rows, 1) - ) - for start in range(0, rows.num_rows, size): - part = source_tokens.materialize(rows.slice(start, size)) + for start, end in _parts(rows): + part = source_tokens.materialize(rows.slice(start, end - start)) # The part is prepared once for all of its rows (ITL-1348): building # ``Tag(row)`` and ``Data(row)`` from one-row slices normalized every # row three times and split its columns again. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 833a17347..3dfdad15d 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -341,12 +341,17 @@ def row_built_provenance(table: pa.Table) -> pa.Table: for field, column in zip(table.schema, table.columns, strict=True): if field.name.startswith(constants.SOURCE_PREFIX): # A derived token column stays derived: its text is what the rows give. - kind = ( - field.type - if source_tokens.derived_recipe(field.type) is not None - else _source_info_value_type(field.type) - ) - if kind != field.type: + if isinstance(field.type, source_tokens.MemberTokenType): + kind = field.type.with_list_type( + _source_info_value_type(field.type.list_type) + ) + if kind != field.type: + column = source_tokens.retyped(column, kind) + elif source_tokens.is_derived(field.type): + kind = field.type + else: + kind = _source_info_value_type(field.type) + if kind != column.type: column = column.cast(kind) new_field = pa.field(field.name, kind, nullable=field.nullable) elif field.name.startswith(constants.SYSTEM_TAG_PREFIX): diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index e51519cbd..f017b3190 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -1,9 +1,17 @@ from __future__ import annotations import hashlib +import itertools import json from collections import defaultdict -from collections.abc import Callable, Iterator, Mapping, Collection, Sequence +from collections.abc import ( + Callable, + Collection, + Iterable, + Iterator, + Mapping, + Sequence, +) from typing import Any, TYPE_CHECKING, cast import pyarrow as pa @@ -1471,7 +1479,11 @@ def append_to_system_tags(table: "pa.Table", value: str) -> "pa.Table": ) -def fold_system_tag_values(values: Sequence[Any], *, label: str) -> str: +_FOLD_PART = 4096 +"""How many members ``fold_system_tag_values`` digests at once.""" + + +def fold_system_tag_values(values: Iterable[Any], *, label: str) -> str: """Fold a group's system-tag values into one scalar: ``"