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/26] 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/26] 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/26] 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 2818eba7a199658838fdb7c580036f4b8a051c15 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:20:41 -0800 Subject: [PATCH 04/26] feat(core): row spool, rows fetched by number from memory and local disk (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/row_spool.py | 359 ++++++++++++++++++++++++++++++ tests/test_core/test_row_spool.py | 238 ++++++++++++++++++++ 2 files changed, 597 insertions(+) create mode 100644 src/orcapod/core/row_spool.py create mode 100644 tests/test_core/test_row_spool.py diff --git a/src/orcapod/core/row_spool.py b/src/orcapod/core/row_spool.py new file mode 100644 index 000000000..e56b5c8d7 --- /dev/null +++ b/src/orcapod/core/row_spool.py @@ -0,0 +1,359 @@ +"""Rows held for a later fetch by row number: some in memory, the rest on local disk. + +A join on the async path keeps its inputs' join keys in memory and the rows behind them +here (ITL-1464). ``RowSpool.append`` numbers rows in the order they come; ``take`` fetches +rows by those numbers; ``discard`` says that rows are never fetched again. + +Format: rows wait in memory until they exceed a byte limit, then become one segment: an +Arrow IPC file of one record batch, uncompressed, read memory-mapped (a mapped page is +the operating system's to drop, not memory this process holds). An extension column is +written as its storage and wrapped again when read, so reading needs no registered type. + +Lifetime: a segment is deleted once every row of it is discarded; a spool's files are +removed by ``close`` (a spool is a context manager: normal end, exception and +cancellation alike) and when it is collected. A process keeps its spools in one directory +of its own, removed at interpreter exit. A killed process leaves its directory behind; the +next process to spill there removes it: every directory holds a lock file its process +keeps locked, so a directory whose lock is free has no owner. (Without ``fcntl``, as on +Windows, nothing is swept.) A spool is not a store: nothing in it outlives the run, is +found by a later process as rows, or enters a hash. +""" + +from __future__ import annotations + +import atexit +import os +import shutil +import tempfile +import threading +import weakref +from typing import IO, Any, Self + +import numpy as np +import numpy.typing as npt +import pyarrow as pa + +try: + import fcntl +except ImportError: # no such module on Windows + fcntl = None + +SPOOL_MEMORY_BYTES = 64 * 1024 * 1024 +"""How many bytes of rows a spool keeps in memory before they become a segment.""" + +_PREFIX = "orcapod-spool-" +_LOCK_NAME = "lock" + + +class _ProcessDirectories: + """The directory of this process under each root, made and swept on first use.""" + + def __init__(self) -> None: + self._guard = threading.Lock() + self._pid: int = os.getpid() + self._held: dict[str, tuple[str, IO[str]]] = {} + + def get(self, root: str) -> str: + """This process's directory under ``root``.""" + with self._guard: + if self._pid != os.getpid(): + # A forked child: the directories held are its parent's. + self._pid, self._held = os.getpid(), {} + if root not in self._held or not os.path.isdir(self._held[root][0]): + self._held[root] = _make_process_directory(root) + return self._held[root][0] + + def remove(self) -> None: + """Remove this process's directories (at exit).""" + if self._pid != os.getpid(): + return # a forked child holds none of its own + for directory, lock in self._held.values(): + shutil.rmtree(directory, ignore_errors=True) + lock.close() + self._held = {} + + +def _make_process_directory(root: str) -> tuple[str, IO[str]]: + """Make this process's directory under ``root``, locked, and sweep abandoned ones. + + Both happen under one lock of the root, so a sweep never sees a directory that is + made but not yet locked. + """ + os.makedirs(root, exist_ok=True) + if fcntl is None: + directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) + return directory, open(os.path.join(directory, _LOCK_NAME), "w") + name = os.path.join(root, f".{_PREFIX}{os.getuid()}.lock") + flags = os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC + with os.fdopen(os.open(name, flags, 0o600), "w") as root_lock: + fcntl.flock(root_lock, fcntl.LOCK_EX) + _sweep(root) + directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) + lock = open(os.path.join(directory, _LOCK_NAME), "w") + fcntl.flock(lock, fcntl.LOCK_EX) + return directory, lock + + +def _sweep(root: str) -> None: + """Remove this user's spool directories under ``root`` that no process holds.""" + assert fcntl is not None + with os.scandir(root) as entries: + candidates = [ + entry.path + for entry in entries + if entry.name.startswith(_PREFIX) and entry.is_dir(follow_symlinks=False) + ] + for directory in candidates: + try: + if os.stat(directory).st_uid != os.getuid(): + continue + with open(os.path.join(directory, _LOCK_NAME)) as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + shutil.rmtree(directory, ignore_errors=True) + except OSError: + continue # held by a live process, being removed, or not a spool's + + +_directories = _ProcessDirectories() +_ = atexit.register(_directories.remove) + + +def _remove_directory(directory: str, owner: int) -> None: + """Remove a spool's directory, in the process that made it only.""" + if os.getpid() == owner: + shutil.rmtree(directory, ignore_errors=True) + + +class _Segment: + """Rows of one run of row numbers, in memory (``table``) or in a file (``path``).""" + + def __init__(self, start: int, table: pa.Table) -> None: + self.start: int = start + self.rows: int = table.num_rows + self.live: int = table.num_rows + self.table: pa.Table | None = table + self.path: str | None = None + + def drop(self) -> None: + """Let the rows go, and delete their file.""" + self.table = None + if self.path is not None: + os.unlink(self.path) + self.path = None + + +class RowSpool: + """Rows numbered from 0 in the order appended, fetched by number. + + Args: + memory_bytes: How many bytes of rows stay in memory; beyond that the rows in + memory are written to a file. + root: The directory to keep files under; by default the system's temporary + directory. Nothing is made there until rows are written. + """ + + def __init__( + self, memory_bytes: int = SPOOL_MEMORY_BYTES, root: str | None = None + ) -> None: + self._memory_bytes: int = memory_bytes + self._root: str | None = root + self._closed: bool = False + self._schema: pa.Schema | None = None + self._segments: list[_Segment] = [] + self._starts: npt.NDArray[np.int64] | None = None + self._in_memory: int = 0 + self._directory: str | None = None + self._cleanup: weakref.finalize[..., Any] | None = None # pyright: ignore[reportExplicitAny] # any finalizer + self.size: int = 0 + """How many rows were appended: the next row's number.""" + + @property + def memory_bytes(self) -> int: + """How many bytes of rows are in memory now.""" + return self._in_memory + + def append(self, table: pa.Table) -> None: + """Hold ``table``'s rows, numbered from ``size`` on. + + Args: + table: The rows; every table appended has one schema. + + Raises: + ValueError: If the spool is closed. + OSError: If the rows in memory cannot be written to the local disk. + """ + if self._closed: + raise ValueError("the row spool is closed") + if not table.num_rows: + return + if self._schema is None: + self._schema = table.schema + # One chunk that owns its rows: a slice would keep its whole parent alive. + self._add(_Segment(self.size, _owned(table))) + self.size += table.num_rows + if self._in_memory > self._memory_bytes: + self._spill() + + def _add(self, segment: _Segment) -> None: + self._segments.append(segment) + self._starts = None + if segment.table is not None: + self._in_memory += segment.table.nbytes + + def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: + """The rows with these numbers, in this order, as one chunk per column. + + Only the segments that hold a wanted row are read, each once. + + Args: + rows: Row numbers, at least one, none of them discarded. + """ + if self._starts is None: + self._starts = np.fromiter( + (s.start for s in self._segments), np.int64, len(self._segments) + ) + held_in = np.searchsorted(self._starts, rows, side="right") - 1 + order = np.argsort(held_in, kind="stable") + sorted_rows, sorted_in = rows[order], held_in[order] + edges = np.flatnonzero(np.diff(sorted_in)) + 1 + parts: list[pa.Table] = [] + for group in np.split(np.arange(len(rows)), edges): + segment = self._segments[int(sorted_in[group[0]])] + local = pa.array(sorted_rows[group] - segment.start, pa.int64()) + parts.append(self._take_from(segment, local)) + if len(parts) == 1: + # One segment: the stable sort changed nothing. + return parts[0].combine_chunks() + taken = pa.concat_tables(parts).combine_chunks() + back = np.empty(len(order), np.int64) + back[order] = np.arange(len(order)) + return taken.take(pa.array(back, pa.int64())).combine_chunks() + + def _take_from(self, segment: _Segment, local: pa.Array[Any]) -> pa.Table: # pyright: ignore[reportExplicitAny] # row numbers + """Rows of one segment, by their numbers in it.""" + if segment.table is not None: + return segment.table.take(local) + assert segment.path is not None and self._schema is not None + with pa.memory_map(segment.path) as mapped: + stored = pa.ipc.open_file(mapped).read_all() + return _wrapped(stored.take(local), self._schema) + + def discard(self, rows: npt.NDArray[np.int64]) -> None: + """Say that these rows are never fetched again. + + A segment whose rows are all discarded is let go, and its file deleted. + + Args: + rows: Row numbers, each discarded once only. + """ + if not len(rows): + return + starts = np.fromiter( + (s.start for s in self._segments), np.int64, len(self._segments) + ) + held_in = np.searchsorted(starts, rows, side="right") - 1 + counts = np.bincount(held_in, minlength=len(self._segments)) + emptied = False + for index in np.flatnonzero(counts): + segment = self._segments[int(index)] + segment.live -= int(counts[index]) + if not segment.live: + if segment.table is not None: + self._in_memory -= segment.table.nbytes + segment.drop() + emptied = True + if emptied: + self._segments = [s for s in self._segments if s.live] + self._starts = None + + def _spill(self) -> None: + """Write the segments in memory to one file, as one segment.""" + waiting = [s for s in self._segments if s.table is not None] + assert self._schema is not None + # Neighbours only: a segment's rows have consecutive numbers. + runs: list[list[_Segment]] = [] + for segment in waiting: + if runs and runs[-1][-1].start + runs[-1][-1].rows == segment.start: + runs[-1].append(segment) + else: + runs.append([segment]) + for run in runs: + tables = [s.table for s in run if s.table is not None] + table = pa.concat_tables(tables).combine_chunks() + merged = _Segment(run[0].start, table) + merged.live = sum(s.live for s in run) + merged.path = self._write(merged) + merged.table = None + replaced = set(map(id, run)) + position = self._segments.index(run[0]) + self._segments = [s for s in self._segments if id(s) not in replaced] + self._segments.insert(position, merged) + self._in_memory -= sum(t.nbytes for t in tables) + self._starts = None + + def _write(self, segment: _Segment) -> str: + """Write a segment's rows to a file of their own; return its path.""" + assert segment.table is not None + if self._directory is None: + process_directory = _directories.get(self._root or tempfile.gettempdir()) + self._directory = tempfile.mkdtemp(dir=process_directory) + self._cleanup = weakref.finalize( + self, _remove_directory, self._directory, os.getpid() + ) + path = os.path.join(self._directory, f"{segment.start}.arrow") + table = _as_storage(segment.table) + with ( + pa.OSFile(path, "wb") as sink, + pa.ipc.new_file(sink, table.schema) as writer, + ): + writer.write_table(table) + return path + + def close(self) -> None: + """Let every row go and remove the files. Calling it again does nothing.""" + self._closed = True + self._segments = [] + self._starts = None + self._in_memory = 0 + if self._cleanup is not None: + _ = self._cleanup() + self._directory = self._cleanup = None + + def __enter__(self) -> Self: + return self + + def __exit__(self, *exc: object) -> None: + self.close() + + +def _owned(table: pa.Table) -> pa.Table: + """``table`` as one chunk over buffers of its own size, copied only if needed.""" + table = table.combine_chunks() + if table.get_total_buffer_size() > 2 * table.nbytes: + table = table.take(pa.array(np.arange(table.num_rows), pa.int64())) + return table + + +def _as_storage(table: pa.Table) -> pa.Table: + """``table`` with each extension column as its storage, no field metadata. + + Flags are dropped too: a field declared non-nullable may hold a null (a column not + settled yet), and ``_wrapped`` puts the schema back. + """ + columns: list[Any] = [] # pyright: ignore[reportExplicitAny] # any column + for column in table.combine_chunks().columns: + array: Any = column.chunk(0) # pyright: ignore[reportExplicitAny] # any column + is_extension = isinstance(column.type, pa.BaseExtensionType) + columns.append(array.storage if is_extension else array) + return pa.Table.from_arrays(columns, names=table.column_names) + + +def _wrapped(table: pa.Table, schema: pa.Schema) -> pa.Table: + """Undo ``_as_storage``: the columns of ``table``, one chunk each, under ``schema``.""" + columns: list[Any] = [] # pyright: ignore[reportExplicitAny] # any column + for column, field in zip(table.combine_chunks().columns, schema): + array = column.chunk(0) + if isinstance(field.type, pa.BaseExtensionType): + array = pa.ExtensionArray.from_storage(field.type, array) + columns.append(array) + return pa.Table.from_arrays(columns, schema=schema) diff --git a/tests/test_core/test_row_spool.py b/tests/test_core/test_row_spool.py new file mode 100644 index 000000000..848fcb94a --- /dev/null +++ b/tests/test_core/test_row_spool.py @@ -0,0 +1,238 @@ +"""Rows held by number, in memory and on local disk (``core/row_spool``, ITL-1464).""" + +from __future__ import annotations + +import asyncio +import gc +import os +import subprocess +import sys +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import pyarrow as pa +import pytest + +from orcapod.core import row_spool +from orcapod.core.row_spool import RowSpool + + +def _table(start: int, rows: int) -> pa.Table: + """Rows with two tags and two data columns, a list and an extension among them.""" + numbers = list(range(start, start + rows)) + return pa.table( + { + "session": pa.array([f"s{n % 3}" for n in numbers], pa.large_string()), + "at": pa.array( + [datetime.fromtimestamp(n, timezone.utc) for n in numbers], + pa.timestamp("us", "UTC"), + ), + "values": pa.array( + [None if n % 5 == 0 else [n, None] for n in numbers], + pa.large_list(pa.int64()), + ), + "id": pa.ExtensionArray.from_storage( + pa.uuid(), + pa.array([n.to_bytes(16, "big") for n in numbers], pa.binary(16)), + ), + } + ) + + +def _filled( + root: Path, sizes: list[int], memory_bytes: int +) -> tuple[RowSpool, pa.Table]: + spool = RowSpool(memory_bytes, str(root)) + tables, start = [], 0 + for size in sizes: + tables.append(_table(start, size)) + spool.append(tables[-1]) + start += size + return spool, pa.concat_tables(tables) + + +def _files(root: Path) -> list[Path]: + return sorted(root.rglob("*.arrow")) + + +@pytest.mark.parametrize("memory_bytes", [0, 3_000, 10**9]) +def test_rows_come_back_by_number_in_the_order_asked( + tmp_path: Path, memory_bytes: int +) -> None: + spool, rows = _filled(tmp_path, [1, 50, 0, 7, 120, 3], memory_bytes) + assert spool.size == rows.num_rows + assert bool(_files(tmp_path)) == (memory_bytes < 10**9) + assert spool.memory_bytes <= max(memory_bytes, 0) + rng = np.random.default_rng(0) + for count in (1, 5, 400): # 400: every row several times + wanted = rng.integers(0, rows.num_rows, count) + taken = spool.take(wanted) + assert taken.schema.equals(rows.schema, check_metadata=True) + assert taken.equals(rows.take(pa.array(wanted, pa.int64()))) + spool.close() + + +def test_a_field_flagged_non_nullable_keeps_the_null_it_holds(tmp_path: Path) -> None: + schema = pa.schema([pa.field("a", pa.int64(), nullable=False, metadata={"k": "v"})]) + table = pa.Table.from_arrays([pa.array([1, None])], schema=schema) + with RowSpool(0, str(tmp_path)) as spool: + spool.append(table) + taken = spool.take(np.array([1, 0])) + assert taken.schema.equals(schema, check_metadata=True) + assert taken.column("a").to_pylist() == [None, 1] + + +def test_a_slice_does_not_keep_its_parent(tmp_path: Path) -> None: + spool = RowSpool(10**9, str(tmp_path)) + spool.append(_table(0, 10_000).slice(5, 2)) + held = spool._segments[0].table # pyright: ignore[reportPrivateUsage] # what it keeps alive + assert held is not None and held.get_total_buffer_size() < 2_000 + assert spool.memory_bytes < 1_000 + assert spool.take(np.array([1])).equals(_table(6, 1)) + + +@pytest.mark.parametrize("memory_bytes", [0, 3_000, 10**9]) +def test_discarded_rows_free_their_segment_and_the_rest_stay( + tmp_path: Path, memory_bytes: int +) -> None: + spool, rows = _filled(tmp_path, [40, 40, 40], memory_bytes) + spool.discard(np.arange(0, 120, 2)) + spool.discard(np.array([], dtype=np.int64)) + odd = np.arange(1, 120, 2) + assert spool.take(odd).equals(rows.take(pa.array(odd, pa.int64()))) + spool.append(_table(120, 40)) # numbered after the discarded rows + assert spool.take(np.array([159, 1])).equals( + pa.concat_tables([_table(159, 1), _table(1, 1)]).combine_chunks() + ) + spool.discard(odd) + spool.discard(np.arange(120, 160)) + assert spool.memory_bytes == 0 + assert _files(tmp_path) == [] + + +def test_rows_spilled_after_a_segment_between_them_was_freed(tmp_path: Path) -> None: + spool = RowSpool(1 << 16, str(tmp_path)) + for start in (0, 10, 20): + spool.append(_table(start, 10)) + spool.discard(np.arange(10, 20)) + spool.append(_table(30, 5_000)) # past the limit: what is in memory is written + assert spool.memory_bytes == 0 + wanted = np.array([0, 25, 30, 5_029, 9]) + expected = pa.concat_tables([_table(0, 30), _table(30, 5_000)]) + assert spool.take(wanted).equals(expected.take(pa.array(wanted, pa.int64()))) + spool.close() + + +def test_nothing_is_written_below_the_limit(tmp_path: Path) -> None: + spool, _ = _filled(tmp_path, [10, 10], 10**9) + assert list(tmp_path.iterdir()) == [] + spool.close() + + +def _spool_directories(root: Path) -> list[Path]: + return [p for d in root.glob("orcapod-spool-*") for p in d.iterdir() if p.is_dir()] + + +def test_close_removes_the_files_and_refuses_more_rows(tmp_path: Path) -> None: + spool, _ = _filled(tmp_path, [10], 0) + assert _files(tmp_path) + spool.close() + spool.close() + assert _spool_directories(tmp_path) == [] + with pytest.raises(ValueError, match="closed"): + spool.append(_table(0, 1)) + + +def test_an_exception_removes_the_files(tmp_path: Path) -> None: + with pytest.raises(RuntimeError, match="stop"), RowSpool(0, str(tmp_path)) as spool: + spool.append(_table(0, 10)) + raise RuntimeError("stop") + assert _spool_directories(tmp_path) == [] + + +@pytest.mark.asyncio +async def test_a_cancellation_removes_the_files(tmp_path: Path) -> None: + async def hold() -> None: + with RowSpool(0, str(tmp_path)) as spool: + spool.append(_table(0, 10)) + await asyncio.Event().wait() + + task = asyncio.create_task(hold()) + await asyncio.sleep(0) + assert _files(tmp_path) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert _spool_directories(tmp_path) == [] + + +def test_a_collected_spool_removes_its_files(tmp_path: Path) -> None: + spool, _ = _filled(tmp_path, [10], 0) + assert _files(tmp_path) + del spool + gc.collect() + assert _spool_directories(tmp_path) == [] + + +_CHILD = """ +import os, sys +import pyarrow as pa +from orcapod.core.row_spool import RowSpool +spool = RowSpool(0, sys.argv[1]) +spool.append(pa.table({"a": [1]})) +print("ready", flush=True) +if sys.argv[2] == "kill": + os.kill(os.getpid(), 9) +if sys.argv[2] == "wait": + sys.stdin.read() +""" + + +def _child(root: Path, end: str) -> subprocess.Popen[str]: + return subprocess.Popen( + [sys.executable, "-c", _CHILD, str(root), end], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True, + ) + + +def test_a_process_that_ends_normally_leaves_nothing(tmp_path: Path) -> None: + child = _child(tmp_path, "exit") + _ = child.communicate() + assert child.returncode == 0 + assert list(tmp_path.glob("orcapod-spool-*")) == [] + + +@pytest.mark.skipif(sys.platform == "win32", reason="swept through fcntl locks") +def test_a_killed_process_is_swept_and_a_live_one_is_not(tmp_path: Path) -> None: + killed = _child(tmp_path, "kill") + _ = killed.communicate() + (left,) = tmp_path.glob("orcapod-spool-*") + assert _files(left) + live = _child(tmp_path, "wait") + assert live.stdout is not None + assert live.stdout.readline() == "ready\n" + try: + assert not left.exists() # the second process swept it + (held,) = tmp_path.glob("orcapod-spool-*") + other = tmp_path / "orcapod-spool-not-ours" # no lock file: left alone + other.mkdir() + spool, _ = _filled(tmp_path, [10], 0) + assert held.exists() and _files(held) + assert other.exists() + spool.close() + finally: + _ = live.communicate() + assert not held.exists() + + +def test_a_forked_child_never_removes_its_parents_files(tmp_path: Path) -> None: + # A child inherits its parent's finalizers; the owner check is what stops them. + directory = tmp_path / "spool" + directory.mkdir() + row_spool._remove_directory(str(directory), os.getpid() + 1) # pyright: ignore[reportPrivateUsage] # the owner check itself + assert directory.exists() + row_spool._remove_directory(str(directory), os.getpid()) # pyright: ignore[reportPrivateUsage] # the owner check itself + assert not directory.exists() From 614e5f762ba57d0c63123b1297514ed78945e0e5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:36:31 -0800 Subject: [PATCH 05/26] 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 06/26] 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 bea13ee8885b43b28375ce0ef6f69ca28daae461 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:38:07 -0800 Subject: [PATCH 07/26] 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 08/26] 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 09/26] 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 10/26] fix(core): row spool survives forks and failed spills; whole tables and slices without copying (ITL-1464) A forked child neither waits for a lock of its parent's threads nor touches its parent's files; a failed spill leaves the spool as it was; an unlocked or partly removed directory is swept. table() and slice() give rows through their mappings and outlive the spool. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/row_spool.py | 205 ++++++++++++++++++---- tests/test_core/test_row_spool.py | 283 +++++++++++++++++++++++++++++- 2 files changed, 448 insertions(+), 40 deletions(-) diff --git a/src/orcapod/core/row_spool.py b/src/orcapod/core/row_spool.py index e56b5c8d7..2ac0de2e2 100644 --- a/src/orcapod/core/row_spool.py +++ b/src/orcapod/core/row_spool.py @@ -15,13 +15,24 @@ of its own, removed at interpreter exit. A killed process leaves its directory behind; the next process to spill there removes it: every directory holds a lock file its process keeps locked, so a directory whose lock is free has no owner. (Without ``fcntl``, as on -Windows, nothing is swept.) A spool is not a store: nothing in it outlives the run, is +Windows, nothing is swept.) + +Ownership: a spool belongs to one thread (or one event loop) of the process that made it: +it has no lock of its own, and a forked child's copy refuses every use, so a child never +touches its parent's files. Different spools may be used from different threads. + +Rows: tables of one schema with at least one column, in Orcapod's normalized types (large +variants, no views). The byte limit bounds what the spool keeps; a ``take`` holds the rows +asked for, twice while it puts them in order, so a caller bounds what it asks for. + +A spool is not a store: nothing in it outlives the run, is found by a later process as rows, or enters a hash. """ from __future__ import annotations import atexit +import contextlib import os import shutil import tempfile @@ -50,28 +61,39 @@ class _ProcessDirectories: def __init__(self) -> None: self._guard = threading.Lock() - self._pid: int = os.getpid() self._held: dict[str, tuple[str, IO[str]]] = {} + self.root_lock: IO[str] | None = None + """The root's lock file while a directory is made.""" def get(self, root: str) -> str: """This process's directory under ``root``.""" with self._guard: - if self._pid != os.getpid(): - # A forked child: the directories held are its parent's. - self._pid, self._held = os.getpid(), {} if root not in self._held or not os.path.isdir(self._held[root][0]): self._held[root] = _make_process_directory(root) return self._held[root][0] def remove(self) -> None: """Remove this process's directories (at exit).""" - if self._pid != os.getpid(): - return # a forked child holds none of its own for directory, lock in self._held.values(): - shutil.rmtree(directory, ignore_errors=True) + _remove_process_directory(directory) lock.close() self._held = {} + def after_fork_in_child(self) -> None: + """Start empty: the directories are the parent's, and so are the locks. + + The guard may be held by a thread that does not exist in the child. The lock + files are closed, never unlocked: the parent's open files keep them locked, and + the child keeps none of them locked after the parent is gone. + """ + self._guard = threading.Lock() + inherited = [lock for _, lock in self._held.values()] + if self.root_lock is not None: + inherited.append(self.root_lock) + self._held, self.root_lock = {}, None + for lock in inherited: + lock.close() + def _make_process_directory(root: str) -> tuple[str, IO[str]]: """Make this process's directory under ``root``, locked, and sweep abandoned ones. @@ -86,14 +108,31 @@ def _make_process_directory(root: str) -> tuple[str, IO[str]]: name = os.path.join(root, f".{_PREFIX}{os.getuid()}.lock") flags = os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC with os.fdopen(os.open(name, flags, 0o600), "w") as root_lock: - fcntl.flock(root_lock, fcntl.LOCK_EX) - _sweep(root) - directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) - lock = open(os.path.join(directory, _LOCK_NAME), "w") - fcntl.flock(lock, fcntl.LOCK_EX) + _directories.root_lock = root_lock + try: + fcntl.flock(root_lock, fcntl.LOCK_EX) + _sweep(root) + directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) + lock = open(os.path.join(directory, _LOCK_NAME), "w") + fcntl.flock(lock, fcntl.LOCK_EX) + finally: + _directories.root_lock = None return directory, lock +def _remove_process_directory(directory: str) -> None: + """Remove a process's directory, its lock file last. + + Stopped part way, it leaves a directory a later sweep still recognizes. + """ + with contextlib.suppress(OSError): + for name in os.listdir(directory): + if name != _LOCK_NAME: + shutil.rmtree(os.path.join(directory, name), ignore_errors=True) + os.unlink(os.path.join(directory, _LOCK_NAME)) + os.rmdir(directory) + + def _sweep(root: str) -> None: """Remove this user's spool directories under ``root`` that no process holds.""" assert fcntl is not None @@ -104,18 +143,24 @@ def _sweep(root: str) -> None: if entry.name.startswith(_PREFIX) and entry.is_dir(follow_symlinks=False) ] for directory in candidates: - try: + # A directory held by a live process, being removed, or not a spool's is left. + with contextlib.suppress(OSError): if os.stat(directory).st_uid != os.getuid(): continue - with open(os.path.join(directory, _LOCK_NAME)) as lock: - fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) - shutil.rmtree(directory, ignore_errors=True) - except OSError: - continue # held by a live process, being removed, or not a spool's + try: + with open(os.path.join(directory, _LOCK_NAME)) as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + _remove_process_directory(directory) + except FileNotFoundError: + # Its process was killed before it made the lock file (the root's lock + # is held here, so none is being made): then it is empty. + os.rmdir(directory) _directories = _ProcessDirectories() _ = atexit.register(_directories.remove) +if hasattr(os, "register_at_fork"): + os.register_at_fork(after_in_child=_directories.after_fork_in_child) def _remove_directory(directory: str, owner: int) -> None: @@ -158,10 +203,12 @@ def __init__( self._memory_bytes: int = memory_bytes self._root: str | None = root self._closed: bool = False + self._owner: int = os.getpid() self._schema: pa.Schema | None = None self._segments: list[_Segment] = [] self._starts: npt.NDArray[np.int64] | None = None self._in_memory: int = 0 + self._discarded: bool = False self._directory: str | None = None self._cleanup: weakref.finalize[..., Any] | None = None # pyright: ignore[reportExplicitAny] # any finalizer self.size: int = 0 @@ -180,19 +227,41 @@ def append(self, table: pa.Table) -> None: Raises: ValueError: If the spool is closed. - OSError: If the rows in memory cannot be written to the local disk. + RuntimeError: In a process other than the one that made the spool. + OSError: If the rows in memory cannot be written to the local disk. The + spool is then as before the call, with no partial file. """ - if self._closed: - raise ValueError("the row spool is closed") + self._require_usable() if not table.num_rows: return + schema, size = self._schema, self.size if self._schema is None: self._schema = table.schema # One chunk that owns its rows: a slice would keep its whole parent alive. - self._add(_Segment(self.size, _owned(table))) + added = _Segment(self.size, _owned(table)) + self._add(added) self.size += table.num_rows if self._in_memory > self._memory_bytes: - self._spill() + try: + self._spill() + except BaseException: + # The new rows are in the last run, so they were not written. + self._segments.remove(added) + self._starts = None + if added.table is not None: + self._in_memory -= added.table.nbytes + self._schema, self.size = schema, size + raise + + def _require_usable(self) -> None: + """Refuse a closed spool, and a forked child's copy of its parent's.""" + if self._owner != os.getpid(): + raise RuntimeError( + "a row spool is used only in the process that made it: this is a " + + "forked child's copy" + ) + if self._closed: + raise ValueError("the row spool is closed") def _add(self, segment: _Segment) -> None: self._segments.append(segment) @@ -207,7 +276,12 @@ def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: Args: rows: Row numbers, at least one, none of them discarded. + + Raises: + ValueError: If the spool is closed. + RuntimeError: In a process other than the one that made the spool. """ + self._require_usable() if self._starts is None: self._starts = np.fromiter( (s.start for s in self._segments), np.int64, len(self._segments) @@ -234,9 +308,67 @@ def _take_from(self, segment: _Segment, local: pa.Array[Any]) -> pa.Table: # py if segment.table is not None: return segment.table.take(local) assert segment.path is not None and self._schema is not None + return _wrapped(self._stored(segment).take(local), self._schema) + + @staticmethod + def _stored(segment: _Segment) -> pa.Table: + """A segment's file as a table over its mapping, extension columns as storage. + + The mapping lives as long as a buffer of the table, also after the file is + deleted (POSIX). + """ + assert segment.path is not None with pa.memory_map(segment.path) as mapped: - stored = pa.ipc.open_file(mapped).read_all() - return _wrapped(stored.take(local), self._schema) + return pa.ipc.open_file(mapped).read_all() + + def table(self) -> pa.Table: + """Every row appended, in order, without copying it into memory. + + Rows in files are read through their mappings: a page is read when a value on it + is. The table stays valid after ``close`` and after the spool is gone: the rows' + memory or mapping lives until the table does (on POSIX, where a deleted file + stays mapped). + + Raises: + ValueError: If the spool is closed, a row was discarded, or nothing was ever + appended (the columns are then unknown). + RuntimeError: In a process other than the one that made the spool. + """ + return self.slice(0, self.size) + + def slice(self, start: int, length: int) -> pa.Table: + """``length`` rows from row number ``start`` on, fewer at the end. + + As ``table``: nothing is copied, and the result outlives the spool. + + Args: + start: The first row's number. + length: How many rows. + + Raises: + ValueError: As ``table``; also for a negative ``start`` or ``length``. + RuntimeError: In a process other than the one that made the spool. + """ + self._require_usable() + if start < 0 or length < 0: + raise ValueError(f"a slice of rows from {start}, {length} long") + if self._schema is None: + raise ValueError("nothing was appended to the row spool: no columns yet") + if self._discarded: + raise ValueError("rows of the row spool were discarded: no whole table") + end = min(start + length, self.size) + parts: list[pa.Table] = [] + for segment in self._segments: + first = max(start, segment.start) + last = min(end, segment.start + segment.rows) + if first >= last: + continue + if segment.table is not None: + part = segment.table + else: + part = _wrapped(self._stored(segment), self._schema) + parts.append(part.slice(first - segment.start, last - first)) + return pa.concat_tables(parts) if parts else self._schema.empty_table() def discard(self, rows: npt.NDArray[np.int64]) -> None: """Say that these rows are never fetched again. @@ -245,7 +377,12 @@ def discard(self, rows: npt.NDArray[np.int64]) -> None: Args: rows: Row numbers, each discarded once only. + + Raises: + ValueError: If the spool is closed. + RuntimeError: In a process other than the one that made the spool. """ + self._require_usable() if not len(rows): return starts = np.fromiter( @@ -253,6 +390,7 @@ def discard(self, rows: npt.NDArray[np.int64]) -> None: ) held_in = np.searchsorted(starts, rows, side="right") - 1 counts = np.bincount(held_in, minlength=len(self._segments)) + self._discarded = True emptied = False for index in np.flatnonzero(counts): segment = self._segments[int(index)] @@ -302,11 +440,16 @@ def _write(self, segment: _Segment) -> str: ) path = os.path.join(self._directory, f"{segment.start}.arrow") table = _as_storage(segment.table) - with ( - pa.OSFile(path, "wb") as sink, - pa.ipc.new_file(sink, table.schema) as writer, - ): - writer.write_table(table) + try: + with ( + pa.OSFile(path, "wb") as sink, + pa.ipc.new_file(sink, table.schema) as writer, + ): + writer.write_table(table) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(path) + raise return path def close(self) -> None: diff --git a/tests/test_core/test_row_spool.py b/tests/test_core/test_row_spool.py index 848fcb94a..6b7faa775 100644 --- a/tests/test_core/test_row_spool.py +++ b/tests/test_core/test_row_spool.py @@ -3,18 +3,20 @@ from __future__ import annotations import asyncio +import errno import gc import os +import signal import subprocess import sys from datetime import datetime, timezone from pathlib import Path +from typing import Any import numpy as np import pyarrow as pa import pytest -from orcapod.core import row_spool from orcapod.core.row_spool import RowSpool @@ -124,6 +126,66 @@ def test_rows_spilled_after_a_segment_between_them_was_freed(tmp_path: Path) -> spool.close() +@pytest.mark.parametrize("memory_bytes", [0, 3_000, 10**9]) +def test_the_whole_table_and_slices_of_it(tmp_path: Path, memory_bytes: int) -> None: + spool, rows = _filled(tmp_path, [1, 50, 7, 120, 3], memory_bytes) + assert spool.table().equals(rows, check_metadata=True) + for start, length in ((0, 1), (1, 50), (40, 100), (170, 50), (181, 1), (500, 2)): + part = spool.slice(start, length) + assert part.schema.equals(rows.schema, check_metadata=True) + assert part.equals(rows.slice(start, length)) + with pytest.raises(ValueError, match="slice"): + _ = spool.slice(-1, 2) + with pytest.raises(ValueError, match="slice"): + _ = spool.slice(1, -2) + spool.discard(np.array([3])) + with pytest.raises(ValueError, match="discarded"): + _ = spool.table() + spool.close() + with pytest.raises(ValueError, match="closed"): + _ = spool.table() + + +def test_a_spool_nothing_was_appended_to_has_no_table(tmp_path: Path) -> None: + spool = RowSpool(0, str(tmp_path)) + with pytest.raises(ValueError, match="nothing was appended"): + _ = spool.table() + spool.append(_table(0, 2)) + assert spool.slice(0, 0).equals(_table(0, 0)) + + +def test_the_table_is_mapped_and_not_copied(tmp_path: Path) -> None: + spool = RowSpool(0, str(tmp_path)) + for start in range(0, 40_000, 10_000): + spool.append(_table(start, 10_000)) + before = pa.total_allocated_bytes() + table = spool.table() + size = table.nbytes + assert size > 1_000_000 + assert pa.total_allocated_bytes() - before < size / 100 + spool.close() + + +@pytest.mark.skipif(sys.platform == "win32", reason="a mapped file cannot be deleted") +@pytest.mark.parametrize("memory_bytes", [0, 3_000, 10**9]) +@pytest.mark.parametrize("end", ["close", "collect"]) +def test_a_table_outlives_its_spool( + tmp_path: Path, memory_bytes: int, end: str +) -> None: + spool, rows = _filled(tmp_path, [40, 5_000, 40], memory_bytes) + table, part = spool.table(), spool.slice(30, 100) + if end == "close": + spool.close() + del spool + gc.collect() + assert _files(tmp_path) == [] + assert table.equals(rows, check_metadata=True) + table.validate(full=True) + del table + gc.collect() + assert part.equals(rows.slice(30, 100)) + + def test_nothing_is_written_below_the_limit(tmp_path: Path) -> None: spool, _ = _filled(tmp_path, [10, 10], 10**9) assert list(tmp_path.iterdir()) == [] @@ -219,6 +281,7 @@ def test_a_killed_process_is_swept_and_a_live_one_is_not(tmp_path: Path) -> None (held,) = tmp_path.glob("orcapod-spool-*") other = tmp_path / "orcapod-spool-not-ours" # no lock file: left alone other.mkdir() + (other / "file").touch() spool, _ = _filled(tmp_path, [10], 0) assert held.exists() and _files(held) assert other.exists() @@ -228,11 +291,213 @@ def test_a_killed_process_is_swept_and_a_live_one_is_not(tmp_path: Path) -> None assert not held.exists() -def test_a_forked_child_never_removes_its_parents_files(tmp_path: Path) -> None: - # A child inherits its parent's finalizers; the owner check is what stops them. - directory = tmp_path / "spool" - directory.mkdir() - row_spool._remove_directory(str(directory), os.getpid() + 1) # pyright: ignore[reportPrivateUsage] # the owner check itself - assert directory.exists() - row_spool._remove_directory(str(directory), os.getpid()) # pyright: ignore[reportPrivateUsage] # the owner check itself - assert not directory.exists() +_FORK = """ +import os, sys, signal, threading +import numpy as np, pyarrow as pa +from orcapod.core import row_spool +from orcapod.core.row_spool import RowSpool +case, root = sys.argv[1:] +table = pa.table({"x": [1, 2], "y": [3, 4]}) + +def in_child(function): + child = os.fork() + if child == 0: + signal.alarm(10) + try: + function() + except BaseException as error: + print(repr(error), file=sys.stderr, flush=True) + os._exit(1) + os._exit(0) + assert os.waitstatus_to_exitcode(os.waitpid(child, 0)[1]) == 0 + +if case == "guard_held": + # Another thread makes a directory while this one forks. + entered, release = threading.Event(), threading.Event() + def hold(): + with row_spool._directories._guard: + entered.set() + release.wait() + thread = threading.Thread(target=hold, daemon=True) + thread.start() + assert entered.wait(10) + def spill(): + with RowSpool(0, root) as spool: + spool.append(table) + assert spool.take(np.array([1])).equals(table.slice(1, 1)) + try: + in_child(spill) + finally: + release.set() + thread.join() +elif case == "inherited": + spool = RowSpool(0, root) + spool.append(table) + def use(): + for call in ( + lambda: spool.discard(np.array([0, 1])), + lambda: spool.take(np.array([0])), + lambda: spool.append(table), + ): + try: + call() + except RuntimeError as error: + assert "the process that made it" in str(error) + else: + raise AssertionError("a child used its parent's spool") + spool.close() + row_spool._directories.remove() + with RowSpool(0, root) as own: # sweeps, and leaves the parent's + own.append(table) + in_child(use) + assert spool.take(np.array([1, 0])).equals(table.take(pa.array([1, 0]))) + spool.close() +elif case == "outlived": + # A child that outlives its parent does not keep the parent's directory locked. + spool = RowSpool(0, root) + spool.append(table) + ready, wait = os.pipe() + child = os.fork() + if child == 0: + os.close(0) + os.write(wait, b"x") + os.close(1) + os.close(2) + signal.alarm(120) # never left behind + signal.pause() + os.read(ready, 1) + print(child, flush=True) + os.kill(os.getpid(), signal.SIGKILL) +""" + + +def _fork(case: str, root: Path) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-c", _FORK, case, str(root)], + capture_output=True, + text=True, + timeout=60, + check=False, + ) + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs fork") +@pytest.mark.parametrize("case", ["guard_held", "inherited"]) +def test_a_forked_child_neither_waits_for_nor_touches_its_parents_spools( + tmp_path: Path, case: str +) -> None: + done = _fork(case, tmp_path) + assert done.returncode == 0, done.stderr + # The child ended without its exit handlers (``os._exit``): its own directory is + # left, with no owner, for the next process to sweep. + (left,) = tmp_path.glob("orcapod-spool-*") + spool, _ = _filled(tmp_path, [10], 0) + assert not left.exists() + spool.close() + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs fork") +def test_a_child_that_outlives_its_killed_parent_does_not_stop_the_sweep( + tmp_path: Path, +) -> None: + done = _fork("outlived", tmp_path) + (left,) = tmp_path.glob("orcapod-spool-*") + child = int(done.stdout) + try: + spool, _ = _filled(tmp_path, [10], 0) + assert not left.exists() + spool.close() + finally: + os.kill(child, signal.SIGKILL) + + +@pytest.mark.parametrize("stage", ["write", "close"]) +def test_a_failed_spill_leaves_the_spool_as_it_was( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, stage: str +) -> None: + spool, rows = _filled(tmp_path, [40, 10], 1 << 14) + held, size = spool.memory_bytes, spool.size + assert held and _files(tmp_path) == [] + + class Full: + """A file writer that writes some bytes, then finds the disk full.""" + + def __init__(self, sink: Any, schema: pa.Schema) -> None: + self.sink = sink + + def __enter__(self) -> Full: + return self + + def __exit__(self, *exc: object) -> None: + if stage == "close": + raise OSError(errno.ENOSPC, "no space") + + def write_table(self, table: pa.Table) -> None: + self.sink.write(b"part of a file") + if stage == "write": + raise OSError(errno.ENOSPC, "no space") + + with monkeypatch.context() as patched: + patched.setattr(pa.ipc, "new_file", Full) + for _ in range(2): + with pytest.raises(OSError, match="no space"): + spool.append(_table(50, 5_000)) + assert (spool.memory_bytes, spool.size) == (held, size) + assert _files(tmp_path) == [] + everything = np.arange(50) + assert spool.take(everything).equals(rows.combine_chunks()) + spool.append(_table(50, 5_000)) # the retry: the rows once + assert spool.size == 5_050 + assert spool.take(np.array([5_049, 0, 50])).equals( + _table(0, 5_050).take(pa.array([5_049, 0, 50], pa.int64())) + ) + assert len(_files(tmp_path)) == 1 + spool.close() + + +def test_a_first_append_that_fails_decides_nothing( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def full(*args: object) -> None: + raise OSError(errno.ENOSPC, "no space") + + spool = RowSpool(0, str(tmp_path)) + with monkeypatch.context() as patched: + patched.setattr(pa.ipc, "new_file", full) + with pytest.raises(OSError, match="no space"): + spool.append(_table(0, 3)) + other = pa.table({"a": [1, 2], "b": [3, 4]}) # another schema: nothing was held + spool.append(other) + assert spool.take(np.array([1, 0])).equals(other.take(pa.array([1, 0], pa.int64()))) + spool.close() + + +def test_a_closed_spool_refuses_every_use(tmp_path: Path) -> None: + spool, _ = _filled(tmp_path, [10], 0) + spool.close() + with pytest.raises(ValueError, match="closed"): + _ = spool.take(np.array([0])) + with pytest.raises(ValueError, match="closed"): + spool.discard(np.array([0])) + + +@pytest.mark.skipif(sys.platform == "win32", reason="swept through fcntl locks") +def test_a_process_killed_before_it_locked_its_directory_is_swept( + tmp_path: Path, +) -> None: + left = tmp_path / "orcapod-spool-unlocked" + left.mkdir() + spool, _ = _filled(tmp_path, [10], 0) + assert not left.exists() + spool.close() + + +@pytest.mark.skipif(sys.platform == "win32", reason="swept through fcntl locks") +def test_a_removal_that_stopped_part_way_is_finished(tmp_path: Path) -> None: + left = tmp_path / "orcapod-spool-partly" + (left / "some-spool").mkdir(parents=True) + (left / "some-spool" / "0.arrow").touch() + (left / "lock").touch() + spool, _ = _filled(tmp_path, [10], 0) + assert not left.exists() + spool.close() From 8f81324561c203ebf8924cace47387a8253324b0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:46:41 -0800 Subject: [PATCH 11/26] 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 a04b7e47e0efbc894aca94ca4e309f9df43c7b77 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:53:57 -0800 Subject: [PATCH 12/26] fix(core): row spool locks no forked child inherits, and one call at a time across threads (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/row_spool.py | 289 ++++++++++++++++-------------- tests/test_core/test_row_spool.py | 126 ++++++++++++- 2 files changed, 279 insertions(+), 136 deletions(-) diff --git a/src/orcapod/core/row_spool.py b/src/orcapod/core/row_spool.py index 2ac0de2e2..94b3be6f9 100644 --- a/src/orcapod/core/row_spool.py +++ b/src/orcapod/core/row_spool.py @@ -5,21 +5,23 @@ rows by those numbers; ``discard`` says that rows are never fetched again. Format: rows wait in memory until they exceed a byte limit, then become one segment: an -Arrow IPC file of one record batch, uncompressed, read memory-mapped (a mapped page is -the operating system's to drop, not memory this process holds). An extension column is -written as its storage and wrapped again when read, so reading needs no registered type. +Arrow IPC file of one record batch, uncompressed, read memory-mapped. A mapped page is the +operating system's to drop: it counts in a process's resident size while it is there, but +it is no memory of Arrow's or of this process's own. An extension column is written as its +storage and wrapped again when read, so reading needs no registered type. Lifetime: a segment is deleted once every row of it is discarded; a spool's files are removed by ``close`` (a spool is a context manager: normal end, exception and cancellation alike) and when it is collected. A process keeps its spools in one directory of its own, removed at interpreter exit. A killed process leaves its directory behind; the next process to spill there removes it: every directory holds a lock file its process -keeps locked, so a directory whose lock is free has no owner. (Without ``fcntl``, as on -Windows, nothing is swept.) +keeps locked (a POSIX record lock, which a forked child does not inherit), so a directory +whose lock is free has no owner. (Without ``fcntl``, as on Windows, nothing is swept.) -Ownership: a spool belongs to one thread (or one event loop) of the process that made it: -it has no lock of its own, and a forked child's copy refuses every use, so a child never -touches its parent's files. Different spools may be used from different threads. +Ownership: a spool belongs to the process that made it, and any of its threads may use it: +one call at a time, a call after ``close`` refused. What ``table`` and ``slice`` returned +stays readable whatever happens to the spool. A forked child's copy refuses every read and +write, and its ``close`` does nothing, so a child never touches its parent's files. Rows: tables of one schema with at least one column, in Orcapod's normalized types (large variants, no views). The byte limit bounds what the spool keeps; a ``take`` holds the rows @@ -38,6 +40,7 @@ import tempfile import threading import weakref +from collections.abc import Collection from typing import IO, Any, Self import numpy as np @@ -61,15 +64,16 @@ class _ProcessDirectories: def __init__(self) -> None: self._guard = threading.Lock() + # Each root's directory, and its open lock file: never opened again, because + # closing any handle of a file gives up the process's record lock on it. self._held: dict[str, tuple[str, IO[str]]] = {} - self.root_lock: IO[str] | None = None - """The root's lock file while a directory is made.""" def get(self, root: str) -> str: """This process's directory under ``root``.""" with self._guard: if root not in self._held or not os.path.isdir(self._held[root][0]): - self._held[root] = _make_process_directory(root) + own = {os.path.basename(held) for held, _ in self._held.values()} + self._held[root] = _make_process_directory(root, own) return self._held[root][0] def remove(self) -> None: @@ -80,26 +84,24 @@ def remove(self) -> None: self._held = {} def after_fork_in_child(self) -> None: - """Start empty: the directories are the parent's, and so are the locks. + """Start empty: the directories are the parent's, and so are their locks. - The guard may be held by a thread that does not exist in the child. The lock - files are closed, never unlocked: the parent's open files keep them locked, and - the child keeps none of them locked after the parent is gone. + The guard may be held by a thread that does not exist in the child. """ self._guard = threading.Lock() - inherited = [lock for _, lock in self._held.values()] - if self.root_lock is not None: - inherited.append(self.root_lock) - self._held, self.root_lock = {}, None - for lock in inherited: - lock.close() + self._held = {} -def _make_process_directory(root: str) -> tuple[str, IO[str]]: +def _make_process_directory(root: str, own: Collection[str]) -> tuple[str, IO[str]]: """Make this process's directory under ``root``, locked, and sweep abandoned ones. Both happen under one lock of the root, so a sweep never sees a directory that is - made but not yet locked. + made but not yet locked. The locks are record locks: a child forked at any point + holds none of them. + + Args: + root: The directory to make it under. + own: The names of the directories this process holds already. """ os.makedirs(root, exist_ok=True) if fcntl is None: @@ -108,15 +110,11 @@ def _make_process_directory(root: str) -> tuple[str, IO[str]]: name = os.path.join(root, f".{_PREFIX}{os.getuid()}.lock") flags = os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC with os.fdopen(os.open(name, flags, 0o600), "w") as root_lock: - _directories.root_lock = root_lock - try: - fcntl.flock(root_lock, fcntl.LOCK_EX) - _sweep(root) - directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) - lock = open(os.path.join(directory, _LOCK_NAME), "w") - fcntl.flock(lock, fcntl.LOCK_EX) - finally: - _directories.root_lock = None + fcntl.lockf(root_lock, fcntl.LOCK_EX) + _sweep(root, own) + directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) + lock = open(os.path.join(directory, _LOCK_NAME), "w") + fcntl.lockf(lock, fcntl.LOCK_EX) return directory, lock @@ -133,14 +131,22 @@ def _remove_process_directory(directory: str) -> None: os.rmdir(directory) -def _sweep(root: str) -> None: - """Remove this user's spool directories under ``root`` that no process holds.""" +def _sweep(root: str, own: Collection[str]) -> None: + """Remove this user's spool directories under ``root`` that no process holds. + + Args: + root: The directory to look in. + own: The names of the directories this process holds: its own record locks do + not stop it, so they are left out by name. + """ assert fcntl is not None with os.scandir(root) as entries: candidates = [ entry.path for entry in entries - if entry.name.startswith(_PREFIX) and entry.is_dir(follow_symlinks=False) + if entry.name.startswith(_PREFIX) + and entry.name not in own + and entry.is_dir(follow_symlinks=False) ] for directory in candidates: # A directory held by a live process, being removed, or not a spool's is left. @@ -148,8 +154,8 @@ def _sweep(root: str) -> None: if os.stat(directory).st_uid != os.getuid(): continue try: - with open(os.path.join(directory, _LOCK_NAME)) as lock: - fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + with open(os.path.join(directory, _LOCK_NAME), "r+") as lock: + fcntl.lockf(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) _remove_process_directory(directory) except FileNotFoundError: # Its process was killed before it made the lock file (the root's lock @@ -204,6 +210,8 @@ def __init__( self._root: str | None = root self._closed: bool = False self._owner: int = os.getpid() + # One call at a time; a call waits for the one before it, ``close`` included. + self._lock = threading.RLock() self._schema: pa.Schema | None = None self._segments: list[_Segment] = [] self._starts: npt.NDArray[np.int64] | None = None @@ -231,35 +239,40 @@ def append(self, table: pa.Table) -> None: OSError: If the rows in memory cannot be written to the local disk. The spool is then as before the call, with no partial file. """ - self._require_usable() - if not table.num_rows: - return - schema, size = self._schema, self.size - if self._schema is None: - self._schema = table.schema - # One chunk that owns its rows: a slice would keep its whole parent alive. - added = _Segment(self.size, _owned(table)) - self._add(added) - self.size += table.num_rows - if self._in_memory > self._memory_bytes: - try: - self._spill() - except BaseException: - # The new rows are in the last run, so they were not written. - self._segments.remove(added) - self._starts = None - if added.table is not None: - self._in_memory -= added.table.nbytes - self._schema, self.size = schema, size - raise - - def _require_usable(self) -> None: - """Refuse a closed spool, and a forked child's copy of its parent's.""" + self._require_owner() + with self._lock: + self._require_usable() + if not table.num_rows: + return + schema, size = self._schema, self.size + if self._schema is None: + self._schema = table.schema + # One chunk that owns its rows: a slice would keep its whole parent alive. + added = _Segment(self.size, _owned(table)) + self._add(added) + self.size += table.num_rows + if self._in_memory > self._memory_bytes: + try: + self._spill() + except BaseException: + # The new rows are in the last run, so they were not written. + self._segments.remove(added) + self._starts = None + if added.table is not None: + self._in_memory -= added.table.nbytes + self._schema, self.size = schema, size + raise + + def _require_owner(self) -> None: + """Refuse a forked child's copy of its parent's spool, before its lock is touched.""" if self._owner != os.getpid(): raise RuntimeError( "a row spool is used only in the process that made it: this is a " + "forked child's copy" ) + + def _require_usable(self) -> None: + """Refuse a closed spool.""" if self._closed: raise ValueError("the row spool is closed") @@ -281,27 +294,29 @@ def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: ValueError: If the spool is closed. RuntimeError: In a process other than the one that made the spool. """ - self._require_usable() - if self._starts is None: - self._starts = np.fromiter( - (s.start for s in self._segments), np.int64, len(self._segments) - ) - held_in = np.searchsorted(self._starts, rows, side="right") - 1 - order = np.argsort(held_in, kind="stable") - sorted_rows, sorted_in = rows[order], held_in[order] - edges = np.flatnonzero(np.diff(sorted_in)) + 1 - parts: list[pa.Table] = [] - for group in np.split(np.arange(len(rows)), edges): - segment = self._segments[int(sorted_in[group[0]])] - local = pa.array(sorted_rows[group] - segment.start, pa.int64()) - parts.append(self._take_from(segment, local)) - if len(parts) == 1: - # One segment: the stable sort changed nothing. - return parts[0].combine_chunks() - taken = pa.concat_tables(parts).combine_chunks() - back = np.empty(len(order), np.int64) - back[order] = np.arange(len(order)) - return taken.take(pa.array(back, pa.int64())).combine_chunks() + self._require_owner() + with self._lock: + self._require_usable() + if self._starts is None: + self._starts = np.fromiter( + (s.start for s in self._segments), np.int64, len(self._segments) + ) + held_in = np.searchsorted(self._starts, rows, side="right") - 1 + order = np.argsort(held_in, kind="stable") + sorted_rows, sorted_in = rows[order], held_in[order] + edges = np.flatnonzero(np.diff(sorted_in)) + 1 + parts: list[pa.Table] = [] + for group in np.split(np.arange(len(rows)), edges): + segment = self._segments[int(sorted_in[group[0]])] + local = pa.array(sorted_rows[group] - segment.start, pa.int64()) + parts.append(self._take_from(segment, local)) + if len(parts) == 1: + # One segment: the stable sort changed nothing. + return parts[0].combine_chunks() + taken = pa.concat_tables(parts).combine_chunks() + back = np.empty(len(order), np.int64) + back[order] = np.arange(len(order)) + return taken.take(pa.array(back, pa.int64())).combine_chunks() def _take_from(self, segment: _Segment, local: pa.Array[Any]) -> pa.Table: # pyright: ignore[reportExplicitAny] # row numbers """Rows of one segment, by their numbers in it.""" @@ -349,26 +364,30 @@ def slice(self, start: int, length: int) -> pa.Table: ValueError: As ``table``; also for a negative ``start`` or ``length``. RuntimeError: In a process other than the one that made the spool. """ - self._require_usable() - if start < 0 or length < 0: - raise ValueError(f"a slice of rows from {start}, {length} long") - if self._schema is None: - raise ValueError("nothing was appended to the row spool: no columns yet") - if self._discarded: - raise ValueError("rows of the row spool were discarded: no whole table") - end = min(start + length, self.size) - parts: list[pa.Table] = [] - for segment in self._segments: - first = max(start, segment.start) - last = min(end, segment.start + segment.rows) - if first >= last: - continue - if segment.table is not None: - part = segment.table - else: - part = _wrapped(self._stored(segment), self._schema) - parts.append(part.slice(first - segment.start, last - first)) - return pa.concat_tables(parts) if parts else self._schema.empty_table() + self._require_owner() + with self._lock: + self._require_usable() + if start < 0 or length < 0: + raise ValueError(f"a slice of rows from {start}, {length} long") + if self._schema is None: + raise ValueError( + "nothing was appended to the row spool: no columns yet" + ) + if self._discarded: + raise ValueError("rows of the row spool were discarded: no whole table") + end = min(start + length, self.size) + parts: list[pa.Table] = [] + for segment in self._segments: + first = max(start, segment.start) + last = min(end, segment.start + segment.rows) + if first >= last: + continue + if segment.table is not None: + part = segment.table + else: + part = _wrapped(self._stored(segment), self._schema) + parts.append(part.slice(first - segment.start, last - first)) + return pa.concat_tables(parts) if parts else self._schema.empty_table() def discard(self, rows: npt.NDArray[np.int64]) -> None: """Say that these rows are never fetched again. @@ -382,27 +401,29 @@ def discard(self, rows: npt.NDArray[np.int64]) -> None: ValueError: If the spool is closed. RuntimeError: In a process other than the one that made the spool. """ - self._require_usable() - if not len(rows): - return - starts = np.fromiter( - (s.start for s in self._segments), np.int64, len(self._segments) - ) - held_in = np.searchsorted(starts, rows, side="right") - 1 - counts = np.bincount(held_in, minlength=len(self._segments)) - self._discarded = True - emptied = False - for index in np.flatnonzero(counts): - segment = self._segments[int(index)] - segment.live -= int(counts[index]) - if not segment.live: - if segment.table is not None: - self._in_memory -= segment.table.nbytes - segment.drop() - emptied = True - if emptied: - self._segments = [s for s in self._segments if s.live] - self._starts = None + self._require_owner() + with self._lock: + self._require_usable() + if not len(rows): + return + starts = np.fromiter( + (s.start for s in self._segments), np.int64, len(self._segments) + ) + held_in = np.searchsorted(starts, rows, side="right") - 1 + counts = np.bincount(held_in, minlength=len(self._segments)) + self._discarded = True + emptied = False + for index in np.flatnonzero(counts): + segment = self._segments[int(index)] + segment.live -= int(counts[index]) + if not segment.live: + if segment.table is not None: + self._in_memory -= segment.table.nbytes + segment.drop() + emptied = True + if emptied: + self._segments = [s for s in self._segments if s.live] + self._starts = None def _spill(self) -> None: """Write the segments in memory to one file, as one segment.""" @@ -453,14 +474,20 @@ def _write(self, segment: _Segment) -> str: return path def close(self) -> None: - """Let every row go and remove the files. Calling it again does nothing.""" - self._closed = True - self._segments = [] - self._starts = None - self._in_memory = 0 - if self._cleanup is not None: - _ = self._cleanup() - self._directory = self._cleanup = None + """Let every row go and remove the files. Calling it again does nothing. + + It waits for a call of another thread to end. In a forked child it does nothing. + """ + if self._owner != os.getpid(): + return + with self._lock: + self._closed = True + self._segments = [] + self._starts = None + self._in_memory = 0 + if self._cleanup is not None: + _ = self._cleanup() + self._directory = self._cleanup = None def __enter__(self) -> Self: return self diff --git a/tests/test_core/test_row_spool.py b/tests/test_core/test_row_spool.py index 6b7faa775..67b69651b 100644 --- a/tests/test_core/test_row_spool.py +++ b/tests/test_core/test_row_spool.py @@ -9,6 +9,9 @@ import signal import subprocess import sys +import threading +from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import TimeoutError as FutureTimeout from datetime import datetime, timezone from pathlib import Path from typing import Any @@ -352,6 +355,44 @@ def use(): in_child(use) assert spool.take(np.array([1, 0])).equals(table.take(pa.array([1, 0]))) spool.close() +elif case in ("root_lock", "unpublished"): + # A fork while another thread has just opened the root's lock file, or has made a + # directory and not yet recorded it; then the parent is killed holding the lock. + opened, resume = threading.Event(), threading.Event() + name = "fdopen" if case == "root_lock" else "_make_process_directory" + where = os if case == "root_lock" else row_spool + original = getattr(where, name) + def paused(*args, **kwargs): + result = original(*args, **kwargs) + opened.set() + resume.wait(30) + return result + setattr(where, name, paused) + if case == "root_lock": + import fcntl + locked, take_lock = threading.Event(), fcntl.lockf + def lockf(*args): + take_lock(*args) + locked.set() + threading.Event().wait(30) + fcntl.lockf = lockf + spool = RowSpool(0, root) + threading.Thread(target=spool.append, args=(table,), daemon=True).start() + assert opened.wait(10) + ready, wait = os.pipe() + child = os.fork() + if child == 0: + signal.alarm(120) # never left behind + os.write(wait, b"x") + os.close(1) + os.close(2) + signal.pause() + os.read(ready, 1) + if case == "root_lock": + resume.set() + assert locked.wait(10) + print(child, flush=True) + os.kill(os.getpid(), signal.SIGKILL) elif case == "outlived": # A child that outlives its parent does not keep the parent's directory locked. spool = RowSpool(0, root) @@ -397,15 +438,21 @@ def test_a_forked_child_neither_waits_for_nor_touches_its_parents_spools( @pytest.mark.skipif(not hasattr(os, "fork"), reason="needs fork") -def test_a_child_that_outlives_its_killed_parent_does_not_stop_the_sweep( - tmp_path: Path, +@pytest.mark.parametrize("case", ["outlived", "root_lock", "unpublished"]) +def test_a_child_that_outlives_its_killed_parent_holds_none_of_its_locks( + tmp_path: Path, case: str ) -> None: - done = _fork("outlived", tmp_path) - (left,) = tmp_path.glob("orcapod-spool-*") + done = _fork(case, tmp_path) + left = list(tmp_path.glob("orcapod-spool-*")) + assert bool(left) == (case != "root_lock") child = int(done.stdout) try: + # Another process spills at once, and sweeps what the killed one left. + other = _child(tmp_path, "exit") + _ = other.communicate(timeout=30) + assert other.returncode == 0 + assert not any(directory.exists() for directory in left) spool, _ = _filled(tmp_path, [10], 0) - assert not left.exists() spool.close() finally: os.kill(child, signal.SIGKILL) @@ -501,3 +548,72 @@ def test_a_removal_that_stopped_part_way_is_finished(tmp_path: Path) -> None: spool, _ = _filled(tmp_path, [10], 0) assert not left.exists() spool.close() + + +def test_a_process_never_sweeps_its_own_directory(tmp_path: Path) -> None: + """Its own record lock would not stop it: also when a root has two names.""" + root, alias = tmp_path / "root", tmp_path / "alias" + root.mkdir() + alias.symlink_to(root, target_is_directory=True) + first, rows = _filled(root, [10], 0) + second, _ = _filled(alias, [10], 0) + assert len(list(root.glob("orcapod-spool-*"))) == 2 + # And the first directory is still locked for every other process. + other = _child(root, "exit") + _ = other.communicate() + assert other.returncode == 0 + assert first.take(np.array([9])).equals(rows.slice(9, 1)) + first.close() + second.close() + + +@pytest.mark.parametrize("read", ["take", "table", "slice"]) +def test_a_close_waits_for_a_read_of_another_thread( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, read: str +) -> None: + spool, rows = _filled(tmp_path, [10, 10], 0) + about_to_map, go_on = threading.Event(), threading.Event() + original = pa.memory_map + + def parked(path: str) -> Any: + about_to_map.set() + assert go_on.wait(10) + return original(path) + + monkeypatch.setattr(pa, "memory_map", parked) + reads: dict[str, Any] = { + "take": lambda: spool.take(np.arange(20)), + "table": spool.table, + "slice": lambda: spool.slice(0, 20), + } + with ThreadPoolExecutor(2) as pool: + result = pool.submit(reads[read]) + assert about_to_map.wait(10) + closed = pool.submit(spool.close) + with pytest.raises(FutureTimeout): + closed.result(timeout=0.1) + go_on.set() + assert result.result(10).equals(rows) + closed.result(10) + assert _files(tmp_path) == [] + with pytest.raises(ValueError, match="closed"): + reads[read]() + + +def test_threads_append_and_read_one_spool(tmp_path: Path) -> None: + spool = RowSpool(1 << 12, str(tmp_path)) + + def work(number: int) -> None: + for i in range(20): + spool.append(pa.table({"a": [number] * 5, "b": [i] * 5})) + rows = np.arange(0, spool.size, 7) + assert spool.take(rows).num_rows == len(rows) + _ = spool.table() + + with ThreadPoolExecutor(4) as pool: + for done in [pool.submit(work, n) for n in range(4)]: + done.result(60) + assert spool.size == spool.table().num_rows == 400 + counts = spool.table().group_by(["a", "b"]).aggregate([([], "count_all")]) + assert set(counts.column("count_all").to_pylist()) == {5} + spool.close() From e846289f3f7e21ef407b8619e5727bb70985980d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:55:13 -0800 Subject: [PATCH 13/26] 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 14/26] 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 e89544fe565fe1cc0aec3e7638f93e743ec23404 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:08:38 -0800 Subject: [PATCH 15/26] feat(pipeline): a job node keeps a large output on local disk, read memory-mapped (ITL-1464) An operator job node kept its run's rows as one Arrow table in process memory. Its kept rows now go through the row spool: in memory up to 64 MiB, beyond that in a private temporary file read back memory-mapped, on the async path chunk by chunk as rows arrive and on the sync path when the result is kept. The stream a node keeps is the same ArrowTableStream over the same values; a table read from it stays valid after the node, the job and the file are gone. Co-Authored-By: Claude Fable 5.2 --- tests/test_core/operators/test_row_chunks.py | 55 ++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/tests/test_core/operators/test_row_chunks.py b/tests/test_core/operators/test_row_chunks.py index f5d6275a2..409ac58f4 100644 --- a/tests/test_core/operators/test_row_chunks.py +++ b/tests/test_core/operators/test_row_chunks.py @@ -482,3 +482,58 @@ def iter_data(self): # pyright: ignore[reportIncompatibleMethodOverride] # a n 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] + + +def test_a_small_table_is_kept_as_it_is() -> None: + table = _table() + assert static_output_pod.kept_table(table) is table + + +def test_a_large_table_is_kept_on_disk_with_the_same_schema_and_values( + spilled: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import gc + + monkeypatch.setattr(static_output_pod, "SPILL_SLICE_ROWS", 4) + table = _source(False).as_table(all_info=True) + + kept = static_output_pod.kept_table(table) + + assert kept is not table + # Its spool is gone with the call and the file deleted: the mapping is the table's. + assert not _spool_files(spilled) + assert kept.schema.equals(table.schema, check_metadata=True) + assert kept.equals(table) + _ = gc.collect() + # The spool that wrote it is gone; the table still reads. + assert kept.to_pylist() == table.to_pylist() + + +@pytest.mark.parametrize("tag_only", [False, True], ids=["data_tags", "tag_only"]) +@pytest.mark.parametrize("chain", ["map", "group", "batch"]) +def test_a_sync_job_node_over_spilled_rows_reads_exactly_as_one_in_memory( + spilled: Path, tmp_path: Path, chain: str, tag_only: bool +) -> None: + job = _job(tmp_path, "spilled_sync", chain, tag_only) + _ = job.run() + node = job.nodes["out"] + table = node.as_table(all_info=True) + + with pytest.MonkeyPatch.context() as patched: + patched.setattr(static_output_pod, "KEPT_ROWS_MEMORY_BYTES", 1 << 40) + in_memory = _job(tmp_path, "in_memory_sync", chain, tag_only) + _ = in_memory.run() + expected = in_memory.nodes["out"] + + # Sync: the same rows in the same order, the same schema, the same hashes. + wanted = expected.as_table(all_info=True) + assert table.schema.equals(wanted.schema, check_metadata=True) + assert table.equals(wanted) + assert node.content_hash() == expected.content_hash() + assert [(t.as_dict(), d.as_dict()) for t, d in node.iter_data()] == [ + (t.as_dict(), d.as_dict()) for t, d in expected.iter_data() + ] + assert node.head(3).table.equals(expected.head(3).table) + + node.clear_cache() + assert table.to_pylist() == wanted.to_pylist() From 393a35663bc9039d1bc096de4fcc96893ebd0c3e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:08:52 -0800 Subject: [PATCH 16/26] docs(changelog): job nodes keep large outputs on disk (ITL-1464) Co-Authored-By: Claude Fable 5.2 --- changelog.d/ITL-1464.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md index ee40b64d5..c871bf857 100644 --- a/changelog.d/ITL-1464.md +++ b/changelog.d/ITL-1464.md @@ -12,3 +12,8 @@ (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). +- An operator job node keeps a large output of its run (more than 64 MiB) in a private + temporary file, read back memory-mapped, instead of in process memory. Every read of the + node gives the same rows; a table read from it stays valid after the node and the job are + gone. An async job of one row-by-row operator over 1 million rows holds 0.9 GiB of its own + memory instead of 7.4 GiB (ITL-1464). From 612f21c452bc8ad0151629628307cd0a7f0b05c2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:12:22 -0800 Subject: [PATCH 17/26] docs(changelog): measured figure for node rows on disk (ITL-1464) Co-Authored-By: Claude Fable 5.2 --- changelog.d/ITL-1464.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md index c871bf857..c05f273d3 100644 --- a/changelog.d/ITL-1464.md +++ b/changelog.d/ITL-1464.md @@ -16,4 +16,4 @@ temporary file, read back memory-mapped, instead of in process memory. Every read of the node gives the same rows; a table read from it stays valid after the node and the job are gone. An async job of one row-by-row operator over 1 million rows holds 0.9 GiB of its own - memory instead of 7.4 GiB (ITL-1464). + memory instead of 4.4 GiB (ITL-1464). From 7596150e967c4e694cab3c991067b60258184564 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:19:19 -0800 Subject: [PATCH 18/26] feat(pipeline): read a job node's current run a page at a time (ITL-1464) current_run_row_count() and read_current_run(start, length, columns) on an operator job node, over ArrowTableStream.num_rows and read_rows: the row reference a view needs, equal to as_table(...).slice(start, length). Co-Authored-By: Claude Fable 5.2 --- src/orcapod/core/nodes/operator_node.py | 45 +++++++++++++++++++ .../core/streams/arrow_table_stream.py | 34 ++++++++++++++ tests/test_core/operators/test_row_chunks.py | 40 +++++++++++++++++ 3 files changed, 119 insertions(+) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 9c1cacc08..8ddd93cbc 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -2027,6 +2027,51 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: return iter([]) return current.iter_data() + def current_run_row_count(self) -> int | None: + """How many rows the node's current run has, or ``None`` without one. + + Read-only, as ``as_table``: never computes and never reads the database. + ``None`` before a run in this process, after ``clear_cache()`` or once the + node is stale (where ``as_table`` gives a zero-row table). Nothing is read + when the node holds its run as a table (ITL-1464). + """ + current = self._current_output() + if current is None: + return None + if isinstance(current, ArrowTableStream): + return current.num_rows + return current.as_table().num_rows + + def read_current_run( + self, + start: int, + length: int, + *, + columns: ColumnConfig | dict[str, Any] | None = None, + all_info: bool = False, + ) -> "pa.Table | None": + """Return rows ``start`` to ``start + length`` of the current run, or ``None``. + + Exactly ``as_table(columns=columns, all_info=all_info).slice(start, length)`` + when the node holds a current run, for a view that shows a page at a time + (ITL-1464): a large run is kept in a memory-mapped file, and only the pages + of the rows read are touched (see ``ArrowTableStream.read_rows`` for the two + configurations that read every row). ``None`` without a current run, as + ``current_run_row_count``. + + Args: + start: The first row's position. + length: How many rows; fewer are returned at the end. + columns: Column groups, exactly as for ``as_table``. + all_info: As for ``as_table``. + """ + current = self._current_output() + if current is None: + return None + if isinstance(current, ArrowTableStream): + return current.read_rows(start, length, columns=columns, all_info=all_info) + return current.as_table(columns=columns, all_info=all_info).slice(start, length) + def as_table( self, *, diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 3c6e2045a..dbfc1290a 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -379,6 +379,40 @@ def head( total_rows=self._table.num_rows, ) + @property + def num_rows(self) -> int: + """How many rows the stream holds; nothing is read or assembled.""" + return self._table.num_rows + + def read_rows( + self, + start: int, + length: int, + *, + columns: ColumnConfig | dict[str, Any] | None = None, + all_info: bool = False, + ) -> "pa.Table": + """Return rows ``start`` to ``start + length`` of ``as_table(...)``. + + Exactly ``as_table(columns=columns, all_info=all_info).slice(start, length)``, + for a reader that shows a page at a time (ITL-1464). The columns are views of + the table the stream holds: when that table is memory-mapped, only the pages + of the rows read are touched. Two configurations read every row first: + ``sort_by_tags`` (the page is of the sorted rows) and ``content_hash`` (a + row's hash is computed from the row). + + Args: + start: The first row's position. + length: How many rows; fewer are returned at the end. + columns: Column groups, exactly as for ``as_table``. + all_info: As for ``as_table``. + + Returns: + The rows, in the order ``as_table`` gives them. + """ + config = ColumnConfig.handle_config(columns, all_info=all_info) + return self._assemble_table(config, limit=None).slice(start, length) + def _typed_zero_row_table(self) -> "pa.Table": """This stream's table cut to no rows: its own Arrow types, no row assembled.""" return self._assemble_table(ZERO_ROW_INPUT_COLUMNS, limit=0) diff --git a/tests/test_core/operators/test_row_chunks.py b/tests/test_core/operators/test_row_chunks.py index 409ac58f4..1e0016014 100644 --- a/tests/test_core/operators/test_row_chunks.py +++ b/tests/test_core/operators/test_row_chunks.py @@ -537,3 +537,43 @@ def test_a_sync_job_node_over_spilled_rows_reads_exactly_as_one_in_memory( node.clear_cache() assert table.to_pylist() == wanted.to_pylist() + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +@pytest.mark.parametrize("on_disk", [False, True], ids=["in_memory", "on_disk"]) +def test_a_job_nodes_current_run_is_read_a_page_at_a_time( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, orchestrator: str, on_disk: bool +) -> None: + monkeypatch.setattr(static_output_pod, "ROW_CHUNK_ROWS", 3) + if on_disk: + monkeypatch.setattr(static_output_pod, "KEPT_ROWS_MEMORY_BYTES", 0) + monkeypatch.setattr("tempfile.tempdir", str(tmp_path)) + job = _job(tmp_path, "paged", "map", False) + node = job.nodes["out"] + + # No current run: nothing to count or read. + assert node.current_run_row_count() is None + assert node.read_current_run(0, 5) is None + + if orchestrator == "sync": + _ = job.run() + else: + _ = job.run(orchestrator=AsyncPipelineOrchestrator()) + + assert node.current_run_row_count() == _ROWS + configurations: list[dict[str, Any]] = [ + {}, + {"columns": {"system_tags": True, "source": True}}, + {"columns": {"sort_by_tags": True}}, + {"all_info": True}, + ] + for given in configurations: + whole = node.as_table(**given) + pages = [node.read_current_run(start, 4, **given) for start in (0, 4, 8, 12)] + assert [page.num_rows for page in pages] == [4, 4, 3, 0] + assert pa.concat_tables(pages).equals(whole) + assert pages[0].schema.equals(whole.schema, check_metadata=True) + + node.clear_cache() + assert node.current_run_row_count() is None + assert node.read_current_run(0, 5) is None From 29218d4bd1136b9074fa1a6d579f9ec90db53693 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:29:31 -0800 Subject: [PATCH 19/26] fix(pipeline): a kept chunk is sealed whole or not at all; a barrier leaves no reader behind (ITL-1464) Review of PR 562, round 2: a chunk that failed part way was built again and its rows given twice; the first row's keys were read as it arrived; after a failed chunk the pairs accumulated; a failing barrier left its sibling's reader alive. A failure is now permanent, a want of memory ends the run at once, a row is read only when its chunk is built, and the barriers end every reader on any error. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/operators/base.py | 6 +- .../core/operators/static_output_pod.py | 122 ++++++++--- tests/test_core/operators/test_row_chunks.py | 202 +++++++++++++++++- 3 files changed, 290 insertions(+), 40 deletions(-) diff --git a/src/orcapod/core/operators/base.py b/src/orcapod/core/operators/base.py index 96b97ade3..e7b26a4a7 100644 --- a/src/orcapod/core/operators/base.py +++ b/src/orcapod/core/operators/base.py @@ -1,6 +1,5 @@ from __future__ import annotations -import asyncio from abc import abstractmethod from collections.abc import Collection, Sequence from typing import TYPE_CHECKING, Any @@ -14,6 +13,7 @@ from orcapod.core.operators.arrow_keys import part_without_rule from orcapod.core.operators.static_output_pod import ( StaticOutputOperatorPod, + collect_all_row_chunks, collect_row_chunks, rows_once, ) @@ -347,9 +347,7 @@ async def async_execute( f"must match inputs length ({len(inputs)})" ) left_hash, right_hash = input_pipeline_hashes - left_rows, right_rows = await asyncio.gather( - collect_row_chunks(inputs[0]), collect_row_chunks(inputs[1]) - ) + left_rows, right_rows = await collect_all_row_chunks(inputs) 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 diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index a4ec5d410..7f2c7542d 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1078,7 +1078,7 @@ 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(*(collect_row_chunks(ch) for ch in inputs)) + all_rows = await collect_all_row_chunks(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 @@ -1311,7 +1311,8 @@ class RowChunks: same table. Rows whose columns disagree raise ``pyarrow.ArrowInvalid`` as there, 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. + chunk's place. Once a chunk could not be built, no later row is kept and every read + raises that error; a chunk is never built again. 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 @@ -1319,57 +1320,83 @@ class 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 + # One entry per sealed chunk (tags, data, contexts): a chunk is published whole. + self._chunks: list[tuple[pa.Table, pa.Table, 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._failure: Exception | 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.""" - 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)) + """Keep one row, after every row added before it. + + Nothing of the row is read until its chunk is built. + + Raises: + MemoryError: If a full chunk cannot be built for want of memory. + OSError: If a full chunk cannot be kept for want of a system resource. + """ self.num_rows += 1 - if len(self._pending) >= ROW_CHUNK_ROWS and not self._unsealable: + if self._failure is not None: + # The rows can no longer make a table: ``row_table`` raises, so none is kept. + return + self._pending.append((tag, data)) + if len(self._pending) >= ROW_CHUNK_ROWS: try: self._seal() - except Exception: + except (MemoryError, OSError): + # The process, not the rows, failed: the run ends here. + raise + except Exception: # noqa: BLE001 # raised by ``row_table`` # 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 + # a row never raised for them: the error belongs to the read of the + # table, which a barrier whose other input is empty never makes. + pass def _seal(self) -> None: - """Build the pending rows into Arrow tables and let the pairs go.""" - from orcapod.utils import arrow_utils + """Build the pending rows into one chunk and let the pairs go. - rows = self._pending - if not rows: + All or nothing, and never twice: a chunk is published whole by one append, and + after a failure nothing is built or given again (every read raises the failure). + """ + if self._failure is not None: + raise self._failure + if not self._pending: return + try: + chunk = self._build_chunk(self._pending) + nothing: list[tuple[TagProtocol, DataProtocol]] = [] + self._chunks.append(chunk) + except Exception as error: + self._failure = error + self._pending = [] + raise + self._pending = nothing + + def _build_chunk( + self, rows: list[tuple[TagProtocol, DataProtocol]] + ) -> tuple[pa.Table, pa.Table, pa.Array[Any]]: # pyright: ignore[reportExplicitAny] # any array + """Build rows into their tag table, data table and data contexts.""" + from orcapod.utils import arrow_utils + + if not self._chunks: + tag, data = 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 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()) + return ( + arrow_utils.concat_tables_by_name(tag_tables).combine_chunks(), + arrow_utils.concat_tables_by_name(data_tables).combine_chunks(), + 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. @@ -1379,15 +1406,18 @@ def row_table(self) -> tuple[pa.Table, tuple[str, ...], tuple[str, ...]]: Raises: ValueError: If no row was added. + Exception: The error of a chunk that could not be built, on every call. """ 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_tags = arrow_utils.concat_tables_by_name( + [tags for tags, _, _ in self._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) + arrow_utils.concat_tables_by_name([data for _, data, _ in self._chunks]) ) return ( arrow_utils.hstack_tables(combined_tags, combined_data), @@ -1414,7 +1444,7 @@ def input_stream(self, pipeline_hash: ContentHash) -> StreamProtocol: 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()), + pa.chunked_array([c for _, _, c in self._chunks], pa.large_string()), ) return _RowsOfStream( table, @@ -1467,6 +1497,30 @@ async def collect_row_chunks( return chunks +async def collect_all_row_chunks( + channels: Sequence[ReadableChannel[tuple[TagProtocol, DataProtocol]]], +) -> list[RowChunks]: + """Read every channel to its end, at the same time (``collect_row_chunks``). + + When one read fails, or this call is cancelled, every other read is cancelled and + ended before the error is raised: no reader outlives the call. + + Args: + channels: The input channels. + + Returns: + The rows of each channel, in the channels' order. + """ + tasks = [asyncio.create_task(collect_row_chunks(channel)) for channel in channels] + try: + return await asyncio.gather(*tasks) + except BaseException: + for task in tasks: + _ = task.cancel() + _ = await asyncio.gather(*tasks, return_exceptions=True) + raise + + 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/tests/test_core/operators/test_row_chunks.py b/tests/test_core/operators/test_row_chunks.py index 1368d4c4b..447a17cc3 100644 --- a/tests/test_core/operators/test_row_chunks.py +++ b/tests/test_core/operators/test_row_chunks.py @@ -8,6 +8,7 @@ from __future__ import annotations import asyncio +import contextlib from pathlib import Path from typing import Any, cast @@ -24,9 +25,10 @@ rows_once, ) from orcapod.core.streams import ArrowTableStream -from orcapod.databases import DeltaTableDatabase +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.sources import ArrowTableSource +from orcapod.utils import arrow_utils _ROWS = 11 @@ -153,7 +155,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 [tags.num_rows for tags, _, _ in chunks._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: @@ -373,3 +375,199 @@ def iter_data(self): # pyright: ignore[reportIncompatibleMethodOverride] # a n 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] + + +class _FailOnce: + """A callable that raises ``error`` the first time ``when`` holds, then delegates.""" + + def __init__(self, real: Any, error: Exception, when: Any) -> None: + self.real, self.error, self.when, self.failures = real, error, when, 0 + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + if not self.failures and self.when(*args): + self.failures += 1 + raise self.error + return self.real(*args, **kwargs) + + +def _fail_one_allocation(monkeypatch: pytest.MonkeyPatch, step: str) -> _FailOnce: + """Make one allocation of a chunk's build fail: of its tags, data or contexts.""" + error = MemoryError(f"synthetic allocation failure ({step})") + if step == "context": + real = pa.array + fault = _FailOnce( + real, + error, + lambda values, *_: ( + isinstance(values, list) + and bool(values) + and str(values[0]).startswith("std:") + ), + ) + + class _Arrow: + """``pyarrow`` as ``static_output_pod`` sees it, with the failing ``array``.""" + + array = staticmethod(fault) + + def __getattr__(self, name: str) -> Any: + return getattr(pa, name) + + monkeypatch.setattr(static_output_pod, "pa", _Arrow()) + else: + column = "value" if step == "data" else "subject" + fault = _FailOnce( + arrow_utils.concat_tables_by_name, + error, + lambda tables: column in tables[0].column_names, + ) + monkeypatch.setattr(arrow_utils, "concat_tables_by_name", fault) + return fault + + +@pytest.mark.parametrize("step", ["tags", "data", "context"]) +def test_a_chunk_that_failed_once_is_never_built_or_given_again( + step: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """Review of PR 562, round 2: a retried chunk gave its rows twice.""" + monkeypatch.setattr(static_output_pod, "ROW_CHUNK_ROWS", 4) + rows = _rows(True) + fault = _fail_one_allocation(monkeypatch, step) + chunks = RowChunks() + for tag, data in rows[:3]: + chunks.add(tag, data) + + with pytest.raises(MemoryError, match="synthetic"): + chunks.add(*rows[3]) + + for tag, data in rows[4:]: + chunks.add(tag, data) + for _ in range(2): + with pytest.raises(MemoryError, match="synthetic"): + chunks.row_table() + assert fault.failures == 1 + + +@pytest.mark.parametrize("step", ["tags", "data", "context"]) +@pytest.mark.parametrize("size", [1, 2, 8192]) +def test_a_job_never_succeeds_with_rows_twice_after_a_failed_allocation( + step: str, size: int, monkeypatch: pytest.MonkeyPatch +) -> None: + """Review of PR 562, round 2: the job succeeded with ``[3, 4, 3, 4]``.""" + monkeypatch.setattr(static_output_pod, "ROW_CHUNK_ROWS", size) + with PipelineJob(name="one_failure", database=InMemoryArrowDatabase()) as job: + _ = ArrowTableSource( + pa.table({"subject": [1, 2], "trial": [1, 2], "value": [3, 4]}), + tag_columns=["subject", "trial"], + tag_only_columns=True, + ).map_data({"value": "value"}, label="out", drop_unmapped=True) + fault = _fail_one_allocation(monkeypatch, step) + + with contextlib.suppress(MemoryError): + _ = job.run(orchestrator=AsyncPipelineOrchestrator()) + + assert fault.failures == 1 + assert job.nodes["out"].as_table().num_rows == 0 + # Nothing of the failed run is left: the next one gives every row once. + _ = job.run(orchestrator=AsyncPipelineOrchestrator()) + values = job.nodes["out"].as_table()["value"].to_pylist() + assert sorted(values) == [3, 4] + + +def test_rows_after_a_chunk_that_cannot_be_built_are_not_kept( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Review of PR 562, round 2: after a failed seal the pairs accumulated.""" + monkeypatch.setattr(static_output_pod, "ROW_CHUNK_ROWS", 3) + rows = _rows(False)[:2] + _other_rows() + _rows(False) + + chunks = _chunks(rows) + + assert chunks.num_rows == len(rows) + assert chunks._pending == [] # pyright: ignore[reportPrivateUsage] # the bound on rows held as objects + with pytest.raises(pa.ArrowInvalid): + _ = chunks.output_stream() + + +class _NoKeys: + """A row's data whose keys cannot be looked up.""" + + def __init__(self, data: Any) -> None: + self._data = data + + def __getattr__(self, name: str) -> Any: + return getattr(self._data, name) + + def keys(self, **_: Any) -> Any: + raise RuntimeError("synthetic key lookup failure") + + +def test_a_row_is_not_read_when_it_is_added() -> None: + """Review of PR 562, round 2: the first row's keys were read as it arrived.""" + tag, data = _rows(False)[0] + chunks = _chunks([(tag, _NoKeys(data))]) + with pytest.raises(RuntimeError, match="synthetic key lookup"): + _ = chunks.row_table() + + +def _barriers() -> list[Any]: + """Every barrier that reads two inputs: ``BinaryOperator``'s and the default one.""" + from orcapod.operators import MergeJoin + + class Default(MergeJoin): + async_execute = StaticOutputOperatorPod.async_execute + + return [pytest.param(MergeJoin, id="binary"), pytest.param(Default, id="default")] + + +@pytest.mark.parametrize("operator", _barriers()) +@pytest.mark.parametrize("failing", [0, 1]) +@pytest.mark.parametrize("failure", ["lookup", "memory", "channel", "cancel"]) +def test_a_barrier_leaves_no_reader_behind( + operator: Any, failing: int, failure: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """Review of PR 562, round 2: a sibling reader outlived the barrier's error.""" + monkeypatch.setattr(static_output_pod, "ROW_CHUNK_ROWS", 1) + rows = _rows(False)[:2] + pipeline_hash = _source(False).pipeline_hash() + if failure == "lookup": + rows = [(tag, _NoKeys(data)) for tag, data in rows] + elif failure == "memory": + _ = _fail_one_allocation(monkeypatch, "data") + + class Broken: + def __aiter__(self) -> Any: + return self + + async def __anext__(self) -> Any: + raise OSError("synthetic channel failure") + + async def run() -> None: + inputs: list[Any] = [None, None] + inputs[failing] = Broken() if failure == "channel" else await _closed(rows) + waiting: Channel[tuple[Any, Any]] = Channel(buffer_size=1) + inputs[1 - failing] = waiting.reader + output: Channel[tuple[Any, Any]] = Channel(buffer_size=4) + before = asyncio.all_tasks() + task = asyncio.create_task( + operator().async_execute( + inputs, output.writer, input_pipeline_hashes=[pipeline_hash] * 2 + ) + ) + for _ in range(20): + await asyncio.sleep(0) + if failure == "cancel": + _ = task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + elif failure == "lookup": + # The row is never read: the other input turns out empty. + await waiting.writer.close() + await task + else: + with pytest.raises((MemoryError, OSError), match="synthetic"): + await task + assert await output.reader.collect() == [] + assert asyncio.all_tasks() - before == set() + + asyncio.run(run()) From 1fc3ebbb05d146fbc54a54ba435472e4f369bbcd Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 03:18:33 -0800 Subject: [PATCH 20/26] feat(pipeline): function and side-effect job nodes keep their rows in a spool (ITL-1464) Full chunks of a node's rows become Arrow data, on local disk when large, and a pair is built again when read. Only a row that reads back as exactly the pair that was held is kept that way; every other row stays the pair it is. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1464.md | 6 + src/orcapod/core/held_rows.py | 556 ++++++++++++++++++++++ src/orcapod/core/nodes/function_node.py | 204 +++++--- src/orcapod/side_effects.py | 53 ++- tests/test_core/test_held_rows.py | 607 ++++++++++++++++++++++++ 5 files changed, 1348 insertions(+), 78 deletions(-) create mode 100644 src/orcapod/core/held_rows.py create mode 100644 tests/test_core/test_held_rows.py diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md index b064ba031..f9dc3151f 100644 --- a/changelog.d/ITL-1464.md +++ b/changelog.d/ITL-1464.md @@ -19,3 +19,9 @@ node gives the same rows; a table read from it stays valid after the node and the job are gone. An async job of one row-by-row operator over 1 million rows holds 0.9 GiB of its own memory instead of 4.4 GiB (ITL-1464). +- A function job node and a side-effect job node keep the rows of their run the same way: + full chunks of 8,192 rows become Arrow data, in a private temporary file beyond 64 MiB. A + row is kept that way only when reading it gives back exactly the row that was held (the + same Python values, types, ids and source info); any other row, such as one that holds a + user class instance or an array, stays in memory as it is. A sync run still hands its rows + to the next steps in memory. A full local disk fails the run (ITL-1464). diff --git a/src/orcapod/core/held_rows.py b/src/orcapod/core/held_rows.py new file mode 100644 index 000000000..e39318e00 --- /dev/null +++ b/src/orcapod/core/held_rows.py @@ -0,0 +1,556 @@ +"""Rows a job node holds, as Arrow data on local disk when they are many (ITL-1464). + +A function job node holds its results and a side-effect job node the rows it passed on, +each as a ``(Tag, Data)`` pair: about 20 KiB per row for a few numbers. ``HeldPairs`` (a +list of pairs) and ``HeldRows`` (pairs by entry id) hold them in chunks: a full chunk's +rows become one Arrow table in a ``RowSpool`` (in memory up to its limit, then a private +temporary file read back memory-mapped), and a pair is built again when it is read. + +A row is kept that way only when the pair built again is the pair that was held, in every +view of it: both are plain ``Tag`` and ``Data``, its tables have the chunk's schema, and +each Python value it already holds (a function's own return value, its meta values) is of +a kind that the Arrow value gives back exactly (``_same``). Any other row (a user class +instance, an array, a missing result) stays the pair it is, in its place. + +This module imports no other part of Orcapod but the spool, so that the node modules can +import it without a cycle: the classes of a row, ``Tag`` and ``Data``, are given to it. + +The spool's files go when the rows do: ``clear`` and ``close``, which a node calls when +its run fails, is cancelled or is cleared. +""" + +from __future__ import annotations + +import bisect +import datetime as dt +import decimal +import functools +import itertools +import pathlib +import struct +import uuid +from collections.abc import Iterable, Iterator, Mapping, MutableMapping, Sequence +from typing import Any, NamedTuple, TypeVar, cast, overload + +import pyarrow as pa +from typing_extensions import override + +from orcapod.core.row_spool import SPOOL_MEMORY_BYTES, RowSpool +from orcapod.system_constants import constants + +_T = TypeVar("_T") + +Pair = tuple[Any, Any] +"""A tag and its data; the data is ``None`` for an input without output.""" + + +HELD_CHUNK_ROWS = 8_192 +"""Rows held as pairs before they become a chunk.""" + +HELD_MEMORY_BYTES = SPOOL_MEMORY_BYTES +"""Bytes of chunks that stay in memory; beyond them they are on local disk.""" + +_TAG = "t:" +_DATA = "d:" +_TAG_ID = "tag_id" +_DATA_ID = "data_id" +_TAG_COLUMNS = {"system_tags": True, "meta": True} +_DATA_COLUMNS = {"source": True, "meta": True} + + +_EXACT_KINDS = frozenset( + ( + type(None), + bool, + int, + str, + bytes, + dt.date, + dt.timedelta, + uuid.UUID, + pathlib.PosixPath, + pathlib.WindowsPath, + ) +) +"""Kinds whose values, when equal, are the same.""" + + +def _same(given: object, read: object) -> bool: + """Whether ``read``, a value read from Arrow, is ``given`` in every respect. + + Only for kinds whose equality and type say so; any other kind is not the same. + """ + kind = type(given) + if kind is not type(read): + return False + if kind is float: + # Bit for bit: -0.0 is not 0.0, and a NaN is itself. + return struct.pack(" bool: + """Whether ``value`` is of a kind ``_same`` compares; nothing is converted.""" + kind = type(value) + if kind is list: + return all(map(_may_be_same, cast("list[object]", value))) + if kind is dict: + items = cast("dict[object, object]", value) + return all(map(_may_be_same, items)) and all(map(_may_be_same, items.values())) + return kind in _EXACT_KINDS or kind in (float, dt.datetime, decimal.Decimal) + + +def _same_values(given: Mapping[str, object], read: Mapping[str, object]) -> bool: + """Whether two rows' values have the same names, in order, and are the same.""" + return list(given) == list(read) and all( + _same(value, read[name]) for name, value in given.items() + ) + + +class _Origin(NamedTuple): + """What every row of a chunk shares besides its columns.""" + + tag_context: Any + data_context: Any + tag_config: Any + data_config: Any + + +def _origin(tag: Any, data: Any) -> _Origin: + return _Origin( + tag.data_context, data.data_context, tag.orcapod_config, data.orcapod_config + ) + + +class _Candidate(NamedTuple): + """A row whose tables can be part of a chunk.""" + + place: int + tag: Any + data: Any + tag_table: pa.Table + data_table: pa.Table + + +class RowTypes(NamedTuple): + """The classes of the rows that become chunks (``Tag`` and ``Data``), exactly.""" + + tag: type[Any] + data: type[Any] + + +def _candidate(types: RowTypes, place: int, pair: Pair) -> _Candidate | None: + """The row as tables, or ``None`` for a row that stays the pair it is.""" + tag, data = pair + if type(tag) is not types.tag or type(data) is not types.data: + return None + try: + if not tag.keys() or set(data._source_info) != set( + data.keys() + ): # a token dropped or filled in would differ + return None + for datagram in (tag, data): + # Before its table is built: a row held as it is gets no second form. + values = datagram._data_dict # ``None``: every value comes from Arrow + if values is not None and not all(map(_may_be_same, values.values())): + return None + tag_table = tag.as_table(columns=_TAG_COLUMNS) + data_table = data.as_table(columns=_DATA_COLUMNS) + except (MemoryError, OSError): + raise + except Exception: # noqa: BLE001 # a row that makes no table is held as it is + return None + if not data_table.num_columns: + return None + return _Candidate(place, tag, data, tag_table, data_table) + + +def _prefixed(table: pa.Table, prefix: str) -> pa.Table: + return table.rename_columns([prefix + name for name in table.column_names]) + + +def _unprefixed(table: pa.Table, prefix: str) -> pa.Table: + names = [name for name in table.column_names if name.startswith(prefix)] + return table.select(names).rename_columns([n.removeprefix(prefix) for n in names]) + + +def _pairs_of(types: RowTypes, table: pa.Table, origin: _Origin) -> Iterator[Pair]: + """Build the pairs of a chunk's rows again.""" + tags = types.tag.rows_of(_unprefixed(table, _TAG), origin.tag_context) + datas = types.data.rows_of(_unprefixed(table, _DATA), origin.data_context) + tag_ids = table.column(_TAG_ID).to_pylist() + data_ids = table.column(_DATA_ID).to_pylist() + for tag, data, tag_id, data_id in zip(tags, datas, tag_ids, data_ids, strict=True): + tag._datagram_uuid = uuid.UUID( + bytes=tag_id + ) # the row's own id, as constructing it with one sets it + data._datagram_uuid = uuid.UUID(bytes=data_id) # as above + tag._orcapod_config = origin.tag_config # as constructing it with one sets it + data._orcapod_config = origin.data_config # as above + yield tag, data + + +class _PythonSide: + """What the rows of a chunk's tag, or data, columns read as in Python.""" + + def __init__(self, table: pa.Table, context: Any) -> None: + not_values = ( + constants.META_PREFIX, + constants.SYSTEM_TAG_PREFIX, + constants.SOURCE_PREFIX, + ) + names = table.column_names + self._own = table.select([n for n in names if not n.startswith(not_values)]) + self._meta = table.select( + [n for n in names if n.startswith(constants.META_PREFIX)] + ) + self._converter = context.type_converter + + def _rows(self, table: pa.Table) -> list[dict[str, Any]]: + if not table.num_columns: + return [{}] * table.num_rows + return cast( + "list[dict[str, Any]]", + cast(object, self._converter.arrow_table_to_python_dicts(table)), + ) + + def _schema(self, table: pa.Table) -> Any: + return self._converter.arrow_schema_to_python_schema(table.schema) + + # Each read once for the whole chunk, and only when a row asks for it. + @functools.cached_property + def values(self) -> list[dict[str, Any]]: + return self._rows(self._own) + + @functools.cached_property + def schema(self) -> Any: + return self._schema(self._own) + + @functools.cached_property + def meta(self) -> list[dict[str, Any]]: + return self._rows(self._meta) + + @functools.cached_property + def meta_schema(self) -> Any: + return self._schema(self._meta) + + def gives_back(self, row: int, datagram: Any) -> bool: + """Whether row ``row`` reads as everything ``datagram`` holds in Python.""" + held = datagram._data_dict # ``None``: every value comes from Arrow already + if held is not None and not _same_values(held, self.values[row]): + return False + schema = datagram._data_python_schema # ``None``: from Arrow already + if schema is not None and not _same_schema(schema, self.schema): + return False + meta = datagram.get_meta_info() + return ( + not meta + or ( + _same_values(meta, self.meta[row]) + and _same_schema( + datagram._meta_python_schema, # the types its meta columns are built with + self.meta_schema, + ) + ) + ) + + +def _same_schema(given: Any, read: Any) -> bool: + return list(given.items()) == list(read.items()) and ( + given.optional_fields == read.optional_fields + ) + + +class _Chunk(NamedTuple): + """Consecutive rows: those in the spool by number, the others as they are.""" + + first: int + """The spool's number of the chunk's first spooled row.""" + stored: int + """How many of its rows are in the spool.""" + kept: dict[int, Pair] + """The rows that are not, by place in the chunk.""" + origin: _Origin | None + + +class HeldPairs(Sequence[Pair]): + """Pairs in the order appended, full chunks of them in a ``RowSpool``. + + Appending never builds a chunk: ``spill`` does, where the caller can let a full disk + end the run. + """ + + def __init__(self, types: RowTypes) -> None: + self._types: RowTypes = types + self._start() + + def _start(self) -> None: + self._spool: RowSpool | None = None + self._schema: pa.Schema | None = None + self._chunks: list[_Chunk] = [] + self._chunk_rows: int = 0 + self._starts: list[int] = [] + self._pending: list[Pair] = [] + # The last chunk read, so reading neighbours reads its rows from the spool once. + self._last: tuple[int, pa.Table] | None = None + # Every spooled row, read through mappings: a forked child reads it too. + self._table: pa.Table | None = None + + def append(self, pair: Pair) -> None: + """Hold ``pair`` after every pair held.""" + self._pending.append(pair) + + def spill(self) -> None: + """Make chunks of the pairs appended, as far as they fill one. + + Raises: + OSError: If a chunk cannot be written to the local disk. Every pair is then + still held. + """ + while len(self._pending) >= HELD_CHUNK_ROWS: + rows = self._pending[:HELD_CHUNK_ROWS] + chunk = self._chunk_of(rows) + if self._spool is not None: + self._table = self._spool.table() + # From here on nothing can fail: the chunk replaces its pairs. + self._starts.append(self._chunk_rows) + self._chunks.append(chunk) + self._chunk_rows += len(rows) + self._pending = self._pending[HELD_CHUNK_ROWS:] + self._last = None + + def _chunk_of(self, rows: list[Pair]) -> _Chunk: + """Put the rows that can be into the spool.""" + kept = dict(enumerate(rows)) + candidates = [ + c + for place, pair in enumerate(rows) + if (c := _candidate(self._types, place, pair)) + ] + origin: _Origin | None = None + table: pa.Table | None = None + if candidates: + first = candidates[0] + origin = _origin(first.tag, first.data) + alike = [ + c + for c in candidates + if all( + a is b for a, b in zip(_origin(c.tag, c.data), origin, strict=True) + ) + and c.tag_table.schema.equals(first.tag_table.schema, True) + and c.data_table.schema.equals(first.data_table.schema, True) + ] + table = self._table_of(alike) + if self._schema is not None and not table.schema.equals(self._schema, True): + table = None + else: + tags = _PythonSide(_unprefixed(table, _TAG), origin.tag_context) + datas = _PythonSide(_unprefixed(table, _DATA), origin.data_context) + good = [ + i + for i, c in enumerate(alike) + if tags.gives_back(i, c.tag) and datas.gives_back(i, c.data) + ] + if len(good) < len(alike): + table = table.take(pa.array(good, pa.int64())) if good else None + if table is not None: + for i in good: + del kept[alike[i].place] + if table is None: + return _Chunk(0, 0, dict(enumerate(rows)), None) + if self._spool is None: + self._spool = RowSpool(memory_bytes=HELD_MEMORY_BYTES) + first_number = self._spool.size + self._spool.append(table) + self._schema = table.schema + return _Chunk(first_number, table.num_rows, kept, origin) + + @staticmethod + def _table_of(rows: list[_Candidate]) -> pa.Table: + ids = pa.schema( + [ + pa.field(_TAG_ID, pa.large_binary(), nullable=False), + pa.field(_DATA_ID, pa.large_binary(), nullable=False), + ] + ) + parts = ( + _prefixed(pa.concat_tables([c.tag_table for c in rows]), _TAG), + _prefixed(pa.concat_tables([c.data_table for c in rows]), _DATA), + pa.Table.from_arrays( + [ + pa.array([c.tag.datagram_uuid.bytes for c in rows], ids.types[0]), + pa.array([c.data.datagram_uuid.bytes for c in rows], ids.types[1]), + ], + schema=ids, + ), + ) + return pa.Table.from_arrays( + [column for part in parts for column in part.columns], + schema=pa.schema([field for part in parts for field in part.schema]), + ).combine_chunks() + + def _stored_table(self, index: int) -> pa.Table: + """The spooled rows of chunk ``index``.""" + if self._last is None or self._last[0] != index: + chunk = self._chunks[index] + assert self._table is not None + self._last = (index, self._table.slice(chunk.first, chunk.stored)) + return self._last[1] + + def has_data(self, place: int) -> bool: + """Whether the pair at ``place`` has data; nothing is read or built.""" + if place >= self._chunk_rows: + return self._pending[place - self._chunk_rows][1] is not None + index = bisect.bisect_right(self._starts, place) - 1 + kept = self._chunks[index].kept.get(place - self._starts[index]) + return kept is None or kept[1] is not None + + def is_kept(self, place: int) -> bool: + """Whether the pair at ``place`` is held as it is; nothing is read or built.""" + if place >= self._chunk_rows: + return True + index = bisect.bisect_right(self._starts, place) - 1 + return place - self._starts[index] in self._chunks[index].kept + + @override + def __len__(self) -> int: + return self._chunk_rows + len(self._pending) + + @overload + def __getitem__(self, index: int) -> Pair: ... + @overload + def __getitem__(self, index: slice) -> Sequence[Pair]: ... + @override + def __getitem__(self, index: int | slice) -> Pair | Sequence[Pair]: + if isinstance(index, slice): + return [self[i] for i in range(*index.indices(len(self)))] + place = index + len(self) if index < 0 else index + if not 0 <= place < len(self): + raise IndexError(index) + if place >= self._chunk_rows: + return self._pending[place - self._chunk_rows] + number = bisect.bisect_right(self._starts, place) - 1 + chunk, row = self._chunks[number], place - self._starts[number] + if row in chunk.kept: + return chunk.kept[row] + assert chunk.origin is not None + before = sum(1 for other in chunk.kept if other < row) + table = self._stored_table(number).slice(row - before, 1) + return next(_pairs_of(self._types, table, chunk.origin)) + + @override + def __iter__(self) -> Iterator[Pair]: + """The pairs held now, in order, also if they are let go while reading.""" + return self._read( + self._table, list(self._chunks), list(self._starts), self._pending + ) + + def _read( + self, + table: pa.Table | None, + chunks: list[_Chunk], + starts: list[int], + pending: list[Pair], + ) -> Iterator[Pair]: + pending = list(pending) + ends = [*starts[1:], sum(c.stored + len(c.kept) for c in chunks)] + for chunk, start, end in zip(chunks, starts, ends, strict=False): + stored: Iterator[Pair] = iter(()) + if chunk.origin is not None and table is not None: + stored = _pairs_of( + self._types, table.slice(chunk.first, chunk.stored), chunk.origin + ) + for row in range(end - start): + yield chunk.kept[row] if row in chunk.kept else next(stored) + yield from pending + + def close(self) -> None: + """Let every pair go, and delete the files; rows being read stay readable.""" + if self._spool is not None: + self._spool.close() + self._start() + + +class HeldRows(MutableMapping[bytes, Pair]): + """Pairs by entry id, in the order first given, held in ``HeldPairs``.""" + + def __init__(self, types: RowTypes) -> None: + self._pairs: HeldPairs = HeldPairs(types) + self._places: dict[bytes, int] = {} + + def spill(self) -> None: + """Make full chunks of the pairs held (``HeldPairs.spill``).""" + self._pairs.spill() + + def has_data(self, key: bytes) -> bool: + """Whether ``key`` is held with data; nothing is read or built.""" + place = self._places.get(key) + return place is not None and self._pairs.has_data(place) + + def is_kept(self, key: bytes) -> bool: + """Whether ``key`` is held as the pair it is; nothing is read or built. + + A pair that is not is always a ``Tag`` and a ``Data`` with values. + """ + place = self._places.get(key) + return place is not None and self._pairs.is_kept(place) + + @override + def __getitem__(self, key: bytes) -> Pair: + return self._pairs[self._places[key]] + + @override + def __setitem__(self, key: bytes, pair: Pair) -> None: + self._pairs.append(pair) + self._places[key] = len(self._pairs) - 1 + + @override + def __delitem__(self, key: bytes) -> None: + del self._places[key] + + @override + def __iter__(self) -> Iterator[bytes]: + return iter(self._places) + + @override + def __len__(self) -> int: + return len(self._places) + + @override + def __contains__(self, key: object) -> bool: + return key in self._places + + @override + def clear(self) -> None: + """Let every pair go, and delete the files.""" + self._pairs.close() + self._places.clear() + + +def batched(pairs: Iterable[_T], size: int) -> Iterator[list[_T]]: + """``pairs`` in lists of ``size``, the last one shorter.""" + iterator = iter(pairs) + while batch := list(itertools.islice(iterator, size)): + yield batch diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 9a0353053..08266d43c 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -24,7 +24,7 @@ import uuid from abc import abstractmethod from collections import Counter -from collections.abc import Callable, Iterator, Mapping, Sequence +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from datetime import datetime, timezone from functools import partial from typing import Any, Literal, NamedTuple, cast @@ -34,6 +34,13 @@ from orcapod import contexts from orcapod.core.nodes.provenance_methods import ProvenanceMethods +from orcapod.core.held_rows import ( + HELD_CHUNK_ROWS, + HeldPairs, + HeldRows, + RowTypes, + batched, +) from orcapod.core.function_pod import ( fall_through_tags, function_input, @@ -298,6 +305,17 @@ def _with_datagram_id(data: Data, datagram_id: uuid.UUID) -> Data: ) +_ROW_TYPES = RowTypes(Tag, Data) + + +def held_pairs() -> HeldPairs: + """An empty ``HeldPairs`` for rows of ``Tag`` and ``Data``. + + For the side-effect job nodes: one place gives them the row classes. + """ + return HeldPairs(_ROW_TYPES) + + def rows_as_output_stream( rows: Sequence[tuple[TagProtocol, DataProtocol]], node: StreamProtocol ) -> StreamProtocol: @@ -750,7 +768,7 @@ def as_table( if self._read_finds_stale(): self.clear_cache() if self._cached_output_table is None: - self._cached_output_table = self._table_from_pairs(list(self.iter_data())) + self._cached_output_table = self._table_from_pairs(self.iter_data()) column_config = ColumnConfig.handle_config(columns, all_info=all_info) @@ -818,7 +836,7 @@ def _zero_row_table(self, config: ColumnConfig) -> "pa.Table | None": ) def _table_from_pairs( - self, pairs: "list[tuple[TagProtocol, DataProtocol]]" + self, pairs: "Iterable[tuple[TagProtocol, DataProtocol]]" ) -> "pa.Table": """Return the output rows ``pairs`` as one table with every column group. @@ -836,7 +854,31 @@ def _table_from_pairs( InputValidationError: If two rows give one column different Arrow types, naming this node, the column and both types. """ - if not pairs: + # A batch of rows at a time, one chunk each, so at most that many rows are held + # as pairs and one-row tables (ITL-1464). + tag_tables: list[pa.Table] = [] + data_tables: list[pa.Table] = [] + try: + for rows in batched(pairs, HELD_CHUNK_ROWS): + tag_tables.append( + _concat_row_tables( + [tag.as_table(columns={"system_tags": True}) for tag, _ in rows] + ).combine_chunks() + ) + data_tables.append( + _concat_row_tables( + [ + data.as_table(columns={"source": True, "context": True}) + for _, data in rows + ] + ).combine_chunks() + ) + # One table per batch, put together by the rule that makes each batch's. + tag_table = _concat_row_tables(tag_tables) if tag_tables else None + data_table = _concat_row_tables(data_tables) if data_tables else None + except InputValidationError as exc: + raise InputValidationError(f"Function node {self.label!r}: {exc}") from exc + if tag_table is None or data_table is None: # No data was produced (node has not been run yet or produced zero # outputs): the table computed rows would have, with no row (ITL-912). typed = self._zero_row_output_table() @@ -850,18 +892,6 @@ def _table_from_pairs( tag_python_schema + data_python_schema ), ) - try: - tag_table = _concat_row_tables( - [tag.as_table(columns={"system_tags": True}) for tag, _ in pairs] - ) - data_table = _concat_row_tables( - [ - data.as_table(columns={"source": True, "context": True}) - for _, data in pairs - ] - ) - except InputValidationError as exc: - raise InputValidationError(f"Function node {self.label!r}: {exc}") from exc # A data-tag is one column: laid out once, among the tags. shared = [c for c in data_table.column_names if c in tag_table.column_names] if shared: @@ -911,23 +941,27 @@ def head( note=BLUEPRINT_NOTE, ) - def _head_of_pairs( + def _head_of_rows( self, - pairs: "Sequence[tuple[TagProtocol, DataProtocol | None]]", + rows: "Sequence[tuple[TagProtocol, DataProtocol]]", + total: int, + missing: int, n: int, config: ColumnConfig, origin: str, ) -> StreamView: - """Return the first ``n`` of ``pairs`` as this node's head. + """Return the first ``n`` of ``rows`` as this node's head. - A ``None`` output (a filtered input) is not a row. An ``EmptyData`` placeholder - (a result kept in an ephemeral database that is gone) has no values to show: it is - left out and counted in the note. + Args: + rows: The node's first rows with values: every one of them with sorting, at + least one when there is one. + total: How many rows with values the node has. + missing: How many results have no values to show: kept in an ephemeral + database that is gone (``EmptyData``). They are left out and noted. + n: How many rows to show. + config: The column groups. + origin: Where the rows came from (``StreamView``). """ - rows = [ - (t, d) for t, d in pairs if d is not None and not isinstance(d, EmptyData) - ] - missing = sum(1 for _, d in pairs if isinstance(d, EmptyData)) # With sorting, every row is shaped and sorted (each keeps its own content # hash), then the first n are taken: the head is ``as_table(config)[:n]``. # At least one row is shaped even for n == 0, so that the empty head has the @@ -951,7 +985,7 @@ def _head_of_pairs( self, table, tag_columns=self.keys(columns=config)[0], - total_rows=len(rows), + total_rows=total, origin=origin, note=note, ) @@ -1464,9 +1498,8 @@ def __init__( ) # stream-level caching state - self._cached_output_datas: dict[ - bytes, tuple[TagProtocol, DataProtocol | None] - ] = {} + # Full chunks of them on local disk when they are many (ITL-1464). + self._cached_output_datas: HeldRows = HeldRows(_ROW_TYPES) self._cached_output_table: "pa.Table | None" = None self._cached_content_hash_column: "pa.Array | None" = None self._run_entry_counts = None @@ -1936,7 +1969,7 @@ def from_descriptor( ) # FunctionJobNode — stream-level caching state - node._cached_output_datas = {} + node._cached_output_datas = HeldRows(_ROW_TYPES) node._cached_output_table = None node._cached_content_hash_column = None @@ -2024,6 +2057,31 @@ def _held_pairs(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: if pair is not None and pair[1] is not None: yield pair[0], pair[1] + def _held_head( + self, n: int + ) -> tuple[list[tuple[TagProtocol, DataProtocol]], int, int]: + """The first ``n`` of ``_held_pairs`` that have values, and two counts. + + Returns: + The rows, how many rows have values, and how many are placeholders for a + result that is gone. Rows not returned are counted, not built. + """ + cache = self._cached_output_datas + rows: list[tuple[TagProtocol, DataProtocol]] = [] + total = missing = 0 + for eid in self._run_entry_order if self._run_entry_counts is not None else (): + if not cache.has_data(eid): + continue + kept = cache.is_kept(eid) + pair = cache[eid] if kept or len(rows) < n else None + if kept and pair is not None and isinstance(pair[1], EmptyData): + missing += 1 + continue + total += 1 + if pair is not None and pair[1] is not None and len(rows) < n: + rows.append((pair[0], pair[1])) + return rows, total, missing + def _set_run_rows( self, entry_ids: list[bytes], @@ -2683,12 +2741,10 @@ def execute( base_entry_ids = [eid for _, _, eid in upstream_entries] # Hot-load any already-computed results from DB into _cached_output_datas. - # get_cached_results() is called for its side effect (populating the - # in-memory cache); the returned dict is intentionally discarded here so - # that the per-data cache-hit check below uses _cached_output_datas - # directly — which includes None-output entries (function returned None) - # and prevents spurious recomputation of already-processed data. - self.get_cached_results(base_entry_ids=base_entry_ids) + # The per-data cache-hit check below uses _cached_output_datas directly, + # which includes None-output entries (function returned None) and prevents + # spurious recomputation of already-processed data. + self._load_missing(base_entry_ids) # Base entry ids of the inputs that gave a row (a cache hit or a # successful computation), one per input: the node's rows afterwards. @@ -2697,10 +2753,9 @@ def execute( for tag, data, base_entry_id in upstream_entries: ctx_obs.on_data_start(node_label, tag, data) - if base_entry_id in self._cached_output_datas and not isinstance( - self._cached_output_datas[base_entry_id][1], EmptyData - ): - tag_out, result = self._cached_output_datas[base_entry_id] + entry = self._cached_output_datas.get(base_entry_id) + if entry is not None and not isinstance(entry[1], EmptyData): + tag_out, result = entry ctx_obs.on_data_end(node_label, tag, data, result, cached=True) emitted_entry_ids.append(base_entry_id) if result is not None: @@ -2757,6 +2812,8 @@ def execute( self._commit_or_end_node( self._row_processed, ctx_obs, node_label, node_hash ) + # Outside the row's handler: a full local disk is no row failure. + self._cached_output_datas.spill() self._commit_or_end_node( self._commit_at_node_end, ctx_obs, node_label, node_hash @@ -2985,22 +3042,37 @@ def get_cached_results( if self._cached_function_pod is None or not base_entry_ids: return {} + self._load_missing(base_entry_ids) + return { + eid: cast( + "tuple[TagProtocol, DataProtocol]", self._cached_output_datas[eid] + ) + for eid in base_entry_ids + if self._cached_output_datas.has_data(eid) + } + + def _load_missing(self, base_entry_ids: list[bytes]) -> None: + """Load the stored results of the entries not held yet (``get_cached_results``).""" + if self._cached_function_pod is None: + return missing = [ eid for eid in base_entry_ids if eid not in self._cached_output_datas ] - if missing: - loaded = self._load_cached_entries(missing) - self._cached_output_datas.update(loaded) - if loaded: - self._cached_output_table = None - self._cached_content_hash_column = None + if not missing: + return + loaded = self._load_cached_entries(missing) + self._hold_loaded(loaded) - return { - eid: self._cached_output_datas[eid] - for eid in base_entry_ids - if eid in self._cached_output_datas - and self._cached_output_datas[eid][1] is not None - } + def _hold_loaded( + self, loaded: "dict[bytes, tuple[TagProtocol, DataProtocol]]" + ) -> None: + """Hold the results ``loaded`` from the databases.""" + for entry_id, pair in loaded.items(): + self._cached_output_datas[entry_id] = pair + self._cached_output_datas.spill() + if loaded: + self._cached_output_table = None + self._cached_content_hash_column = None async def _async_process_data_internal( self, @@ -4109,13 +4181,11 @@ async def _async_execute_cache_only( ctx_obs.on_node_start(node_label, node_hash, tag_schema=None) try: loaded = self._load_cached_entries() - self._cached_output_datas.update(loaded) - if loaded: - self._cached_output_table = None - self._cached_content_hash_column = None + self._hold_loaded(loaded) sent: list[bytes] = [] - for entry_id, (tag, data) in list(self._cached_output_datas.items()): + for entry_id in list(self._cached_output_datas): + tag, data = self._cached_output_datas[entry_id] if data is not None and not isinstance(data, EmptyData): ctx_obs.on_data_start(node_label, tag, data) ctx_obs.on_data_end(node_label, tag, data, data, cached=True) @@ -4174,7 +4244,11 @@ def head( return self._head_without_rows( config, ViewStatus.NOT_COMPUTED, note=STALE_NOTE ) - head = self._head_of_pairs(list(self._held_pairs()), n, config, origin="held") + # With sorting every row is shaped and sorted; otherwise the first ones are. + rows, total, missing = self._held_head( + sys.maxsize if config.sort_by_tags else max(n, 1) + ) + head = self._head_of_rows(rows, total, missing, n, config, origin="held") if not self._run_load_only: return head # A load-only run's rows have their own status: they may lack the inputs it @@ -4245,9 +4319,9 @@ def held_row_count(self) -> int: if counts is None: return 0 return sum( - counts.get(entry_id, 0) - for entry_id, (_, data) in self._cached_output_datas.items() - if data is not None + count + for entry_id, count in counts.items() + if self._cached_output_datas.has_data(entry_id) ) def _prepare_held_read(self) -> None: @@ -4545,10 +4619,7 @@ async def async_execute( # Load pipeline DB → in-memory cache keyed by base_entry_id. loaded = self._load_cached_entries() - self._cached_output_datas.update(loaded) - if loaded: - self._cached_output_table = None - self._cached_content_hash_column = None + self._hold_loaded(loaded) cached_by_base_entry_id: dict[ bytes, tuple[TagProtocol, DataProtocol] ] = dict(loaded) @@ -4669,6 +4740,7 @@ async def record_and_forward() -> None: # Commits every commit_every_rows rows inside a job (ITL-919); # no await in between, so no other row interleaves. self._row_processed() + self._cached_output_datas.spill() await output.send((clean_tag, output_data)) # Recorded once the output took the row (see route_inputs). run_entry_ids.append(base_entry_id) diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 071aa82ac..5aededb76 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -19,9 +19,11 @@ from typing_extensions import override from orcapod.core.base import TraceableBase +from orcapod.core.held_rows import HeldPairs from orcapod.core.nodes.staleness import RunHoldingNode from orcapod.core.nodes.function_node import ( _build_record_id_preimage, + held_pairs, rows_as_output_stream, run_job_node, ) @@ -1101,7 +1103,7 @@ def __init__( self._current_log_checked = False # The rows the last completed run passed on, in the order it passed them; # ``None`` when no run in this process completed (ITL-1091). - self._held_rows: list[tuple[TagProtocol, DataProtocol]] | None = None + self._held_rows: HeldPairs | None = None # Whether those rows came from a load-only run, which delivers nothing. self._run_load_only = False # A node that has not run in this process holds nothing and is stale (ITL-1095). @@ -1121,10 +1123,16 @@ def clear_cache(self) -> None: Its next ``run()`` (or job run) delivers again what its invocation log does not record (every row without ``track_completion``) (ITL-1095). """ - self._held_rows = None + self._drop_held_rows() self._run_load_only = False self._set_modified_time(None) + def _drop_held_rows(self) -> None: + """Let the held rows go, and their files; a read begun goes on to its end.""" + rows, self._held_rows = self._held_rows, None + if rows is not None: + rows.close() + def _refuse_log_of_another_data_context(self) -> None: """Refuse an invocation log holding deliveries of another data context. @@ -1252,7 +1260,7 @@ def execute( SideEffectLogDataContextError: If the invocation log holds deliveries logged under another data context; nothing is delivered then. """ - self._held_rows = None + self._drop_held_rows() if load_only: try: rows = list(input_stream.iter_data()) @@ -1260,7 +1268,7 @@ def execute( # A run that raised defines no rows, as on the async path (ITL-1121). self.clear_cache() raise - self._hold(rows, load_only=True) + self._hold_run(rows, load_only=True) return self._output_stream(rows) try: results = self._deliver_rows(input_stream, run_id=run_id) @@ -1269,7 +1277,7 @@ def execute( # node below it (ITL-1095). self.clear_cache() raise - self._hold(results) + self._hold_run(results) return self._output_stream(results) def _output_stream( @@ -1310,9 +1318,22 @@ def _deliver_rows( results.append(result) return results - def _hold( + def _hold_run( self, rows: list[tuple[TagProtocol, DataProtocol]], *, load_only: bool = False ) -> None: + """``_hold`` the rows of a sync run; a run whose rows cannot be held failed.""" + pairs = held_pairs() + try: + for row in rows: + pairs.append(row) + pairs.spill() + self._hold(pairs, load_only=load_only) + except BaseException: + pairs.close() + self.clear_cache() + raise + + def _hold(self, rows: HeldPairs, *, load_only: bool = False) -> None: """Keep the rows a completed run passed on and stamp the node as modified. Stamped after the upstream nodes, which stamp at the end of their own run, so the @@ -1326,14 +1347,14 @@ def _hold( self._run_load_only = load_only self._update_modified_time() - def _current_rows(self) -> list[tuple[TagProtocol, DataProtocol]] | None: + def _current_rows(self) -> HeldPairs | None: """The rows the last run passed on, or ``None`` if there are none or they are stale. Held rows go stale, and are dropped, when an upstream changed after the run: the judgement ``FunctionJobNode`` uses for the rows it holds. """ if self._held_rows is not None and self.is_stale: - self._held_rows = None + self._drop_held_rows() return self._held_rows # ------------------------------------------------------------------ @@ -1350,7 +1371,9 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: job has not run, the last run raised, or an upstream changed since), there are no rows. ``run()`` or ``job.run()`` delivers. """ - yield from self._current_rows() or () + for tag, data in self._current_rows() or (): + # A row passed on always has data. + yield tag, cast("DataProtocol", data) def held_row_count(self) -> int: """The number of rows the last run of this node passed on (``iter_data``'s count). @@ -1516,17 +1539,20 @@ async def async_execute( f"SideEffectJobNode.async_execute expects exactly 1 input channel; " f"got {len(inputs)}." ) - self._held_rows = None + self._drop_held_rows() # A load-only run reads no pod configuration: it delivers nothing. if load_only: + # Full chunks on local disk (ITL-1464), closed if the run fails. + rows = held_pairs() try: - rows: list[tuple[TagProtocol, DataProtocol]] = [] async for item in inputs[0]: rows.append(item) + rows.spill() await output.send(item) # Held and stamped before the output closes (ITL-1042). self._hold(rows, load_only=True) except BaseException: + rows.close() self.clear_cache() raise finally: @@ -1537,7 +1563,8 @@ async def async_execute( asyncio.Semaphore(max_concurrency) if max_concurrency is not None else None ) # This run's rows, in the order they were sent downstream. - passed_on: list[tuple[TagProtocol, DataProtocol]] = [] + # Full chunks on local disk (ITL-1464), closed if the run fails. + passed_on = held_pairs() # Makes recording a row and sending it one step: a send blocked by a full channel # can be overtaken by a later one, so without it the held order could differ from # the order downstream received. Never held across the delivery itself. @@ -1564,6 +1591,7 @@ async def process_one(tag: TagProtocol, data: DataProtocol) -> None: if result is not None: async with send_lock: passed_on.append(result) + passed_on.spill() await output.send(result) finally: if sem is not None: @@ -1579,6 +1607,7 @@ async def process_one(tag: TagProtocol, data: DataProtocol) -> None: self._hold(passed_on) except BaseException: # A run that raised or was cancelled defines no rows (ITL-1095). + passed_on.close() self.clear_cache() raise finally: diff --git a/tests/test_core/test_held_rows.py b/tests/test_core/test_held_rows.py new file mode 100644 index 000000000..f7cf839c7 --- /dev/null +++ b/tests/test_core/test_held_rows.py @@ -0,0 +1,607 @@ +"""Rows held in chunks read exactly as the pairs that were held (ITL-1464).""" + +from __future__ import annotations + +import asyncio +import dataclasses +import datetime as dt +import errno +import math +import os +import uuid +from collections.abc import Iterator +from decimal import Decimal +from pathlib import Path +from typing import Any + +import numpy as np +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.channels import Channel +from orcapod.core import held_rows +from orcapod.core.datagrams import Data, EmptyData, Tag +from orcapod.core.held_rows import HeldPairs, HeldRows, RowTypes, _same +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.side_effects import side_effect_pod +from orcapod.sources import ArrowTableSource +from orcapod.system_constants import constants + +_TYPES = RowTypes(Tag, Data) +_N = 11 + + +@pytest.fixture() +def spilled(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path: + """Chunks of three rows, every chunk on disk.""" + monkeypatch.setattr(held_rows, "HELD_CHUNK_ROWS", 3) + monkeypatch.setattr(held_rows, "HELD_MEMORY_BYTES", 0) + root = tmp_path / "spool" + root.mkdir() + monkeypatch.setattr("tempfile.tempdir", str(root)) + return root + + +def _files(root: Path) -> list[Path]: + return [p for p in root.rglob("*") if p.is_file() and not p.name.endswith("lock")] + + +@dataclasses.dataclass +class Point: + x: int + + +@dataclasses.dataclass +class FarPoint(Point): + """A subclass of the declared class: the row keeps the returned instance.""" + + y: int + + +class Odd(Data): + """A subclass of ``Data``: never built again as a plain one.""" + + +def _arrow_rows() -> list[tuple[Any, Any]]: + table = pa.table( + { + "subject": pa.array([f"s{n % 3}" for n in range(_N)], pa.large_string()), + "trial": pa.array(range(_N), pa.int8()), + "when": pa.array( + [dt.datetime(2026, 1, 1, n) for n in range(_N)], + pa.timestamp("us", "UTC"), + ), + "x": pa.array([n / 3 for n in range(_N)], pa.float32()), + "note": pa.array([None if n % 4 == 0 else f"n{n}" for n in range(_N)]), + "samples": pa.array( + [[n, None] for n in range(_N)], pa.large_list(pa.int8()) + ), + } + ) + source = ArrowTableSource( + table, + tag_columns=["subject", "trial"], + tag_only_columns=True, + record_id_columns=["trial"], + source_id="rows", + ) + return list(source.iter_data()) + + +def _tag(n: int) -> Tag: + return Tag( + {"k": n, "name": f"k{n}"}, + system_tags={f"{constants.SYSTEM_TAG_PREFIX}a": f"r{n}"}, + ) + + +def _dict_data(n: int, **values: Any) -> Data: + return Data( + values, + source_info={name: f"src::{n}::{name}" for name in values}, + record_uuid=uuid.uuid4(), + python_schema={ + name: Path if isinstance(value, Path) else type(value) + for name, value in values.items() + if not isinstance(value, (list, dict)) + }, + meta_info={"__computed": True}, + ) + + +_VALUES: dict[str, Any] = { + "numbers": lambda n: {"a": n, "b": n + 0.5, "c": bool(n % 2)}, + "floats": lambda n: {"a": [-0.0, math.nan, math.inf, 0.0][n % 4]}, + "text": lambda n: {"a": f"t{n}", "b": bytes([n])}, + "lists": lambda n: {"a": [n, n + 1], "b": [[0.5], []]}, + "dicts": lambda n: {"a": {"p": n, "q": n}}, + "paths": lambda n: {"a": Path(f"/x/{n}"), "b": uuid.UUID(int=n)}, + "dates": lambda n: {"a": dt.date(2026, 1, n + 1)}, + "utc": lambda n: {"a": dt.datetime(2026, 1, n + 1, tzinfo=dt.timezone.utc)}, + "zoned": lambda n: { + "a": dt.datetime(2026, 1, 1, n, tzinfo=dt.timezone(dt.timedelta(hours=5))) + }, + "arrays": lambda n: {"a": np.arange(n + 1)}, + "numpy_scalars": lambda n: {"a": float(n), "b": np.float64(n)}, +} + + +def _rows(kind: str) -> list[tuple[Any, Any]]: + if kind == "arrow": + return _arrow_rows() + if kind == "arrow_read": + rows = _arrow_rows() + for tag, data in rows: + _ = tag.as_dict(), data.as_dict() + return rows + rows = _arrow_rows() if kind == "mixed" else [] + if kind == "mixed": + rows[1] = (rows[1][0], None) + rows[2] = (rows[2][0], rows[2][1].with_source_info(x=None)) + rows[4] = (rows[4][0], EmptyData()) + rows[5] = (rows[5][0], Odd({"x": 1})) + rows[7] = (rows[7][0], rows[7][1].with_meta_columns(__extra=[1, 2])) + rows[8] = (rows[8][0], rows[8][1].drop("x")) + rows[9] = (_tag(9), _dict_data(9, a=1)) + return rows + return [(_tag(n), _dict_data(n, **_VALUES[kind](n))) for n in range(_N)] + + +def _is_exactly(read: Any, given: Any) -> None: + """``read`` and ``given`` agree in type and in every view.""" + assert type(read) is type(given) + if given is None or isinstance(given, EmptyData): + assert read is given + return + assert read.datagram_uuid == given.datagram_uuid + assert read.data_context_key == given.data_context_key + for config in ({}, {"all_info": True}): + assert read.keys(**config) == given.keys(**config) + assert list(read.schema(**config).items()) == list( + given.schema(**config).items() + ) + assert read.arrow_schema(**config).equals( + given.arrow_schema(**config), check_metadata=True + ) + table, expected = read.as_table(**config), given.as_table(**config) + assert table.schema.equals(expected.schema, check_metadata=True) + # ``equals`` takes NaN for unequal: the values, bit for bit, by their text. + assert repr(table.to_pylist()) == repr(expected.to_pylist()) + values, wanted = read.as_dict(**config), given.as_dict(**config) + assert list(values) == list(wanted) + for name, value in wanted.items(): + assert type(values[name]) is type(value) + assert repr(values[name]) == repr(value) + assert read.content_hash() == given.content_hash() + assert read.get_meta_info() == given.get_meta_info() + if isinstance(given, Data): + assert read.source_info() == given.source_info() + else: + assert read.system_tags() == given.system_tags() + + +_KINDS = ["arrow", "arrow_read", "mixed", *_VALUES] + + +@pytest.mark.parametrize("kind", _KINDS) +def test_held_pairs_read_as_the_pairs_held(spilled: Path, kind: str) -> None: + rows = _rows(kind) + pairs = HeldPairs(_TYPES) + for row in rows: + pairs.append(row) + pairs.spill() + + assert len(pairs) == _N + assert [pairs.has_data(i) for i in range(_N)] == [d is not None for _, d in rows] + for read in (list(pairs), [pairs[i] for i in range(_N)], pairs[:]): + for (tag, data), (given_tag, given_data) in zip(read, rows, strict=True): + _is_exactly(tag, given_tag) + _is_exactly(data, given_data) + for i in (7, 0, 10, 3, -1): + _is_exactly(pairs[i][1], rows[i][1]) + with pytest.raises(IndexError): + _ = pairs[_N] + + +@pytest.mark.parametrize( + ("kind", "chunked"), + [ + ("arrow", 9), + ("arrow_read", 9), + ("numbers", 9), + ("floats", 9), + ("text", 9), + ("lists", 9), + ("paths", 9), + # A value Arrow does not give back as it is stays the object it is. + ("zoned", 0), + ("arrays", 0), + ("numpy_scalars", 0), + ], +) +def test_only_rows_that_read_the_same_become_chunks( + spilled: Path, kind: str, chunked: int +) -> None: + rows = _rows(kind) + pairs = HeldPairs(_TYPES) + for row in rows: + pairs.append(row) + pairs.spill() + assert sum(not pairs.is_kept(i) for i in range(_N)) == chunked + for i in range(_N): + if pairs.is_kept(i): + assert pairs[i] is rows[i] + assert bool(_files(spilled)) == bool(chunked) + + +@pytest.mark.parametrize( + ("a", "b"), + [ + (0.0, -0.0), + (1, True), + (1, 1.0), + ([1], [True]), + ((1,), (1,)), + ({"a": 1, "b": 2}, {"b": 2, "a": 1}), + (Decimal("1.0"), Decimal("1.00")), + (Point(1), Point(1)), + (dt.datetime(2026, 1, 1), dt.datetime(2026, 1, 1, fold=1)), + ], +) +def test_values_that_differ_in_anything_are_not_the_same(a: Any, b: Any) -> None: + assert not _same(a, b) + + +def test_rows_being_read_outlive_the_holder(spilled: Path) -> None: + rows = _rows("mixed") + pairs = HeldPairs(_TYPES) + for row in rows: + pairs.append(row) + pairs.spill() + reading = iter(pairs) + first = next(reading) + assert _files(spilled) + + pairs.close() + + assert not _files(spilled) + assert len(pairs) == 0 + for (_, data), (_, given) in zip([first, *reading], rows, strict=True): + _is_exactly(data, given) + pairs.append(rows[0]) + assert pairs[0] is rows[0] + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="no fork on this system") +def test_a_forked_child_reads_the_rows(spilled: Path) -> None: + pairs = HeldPairs(_TYPES) + for row in _rows("arrow"): + pairs.append(row) + pairs.spill() + child = os.fork() + if child == 0: + try: + ok = [t.as_dict()["trial"] for t, _ in pairs] == list(range(_N)) + ok = ok and pairs[4][0].as_dict()["trial"] == 4 + os._exit(0 if ok else 1) + except BaseException: + os._exit(2) + assert os.waitstatus_to_exitcode(os.waitpid(child, 0)[1]) == 0 + assert _files(spilled) + + +def test_rows_by_entry_id(spilled: Path) -> None: + rows = _rows("mixed") + held = HeldRows(_TYPES) + for n, row in enumerate(rows): + held[b"%d" % n] = row + held.spill() + held[b"0"] = rows[3] + assert list(held) == [b"%d" % n for n in range(_N)] + assert len(held) == _N and b"4" in held and b"x" not in held + assert held.get(b"x") is None + _is_exactly(held[b"0"][1], rows[3][1]) + assert not held.has_data(b"1") and held.has_data(b"0") and not held.has_data(b"x") + assert not held.is_kept(b"x") + del held[b"2"] + assert b"2" not in held + held.clear() + assert not held and not _files(spilled) + + +class _FullDisk: + def __init__(self, room: int) -> None: + self.room, self.calls, self.real = room, 0, pa.ipc.new_file + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + self.calls += 1 + if self.calls > self.room: + raise OSError(errno.ENOSPC, "synthetic full disk") + return self.real(*args, **kwargs) + + +def test_a_chunk_that_cannot_be_written_leaves_every_pair_once( + spilled: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + rows = _rows("arrow") + pairs = HeldPairs(_TYPES) + for row in rows: + pairs.append(row) + with monkeypatch.context() as patched: + patched.setattr(pa.ipc, "new_file", _FullDisk(1)) + with pytest.raises(OSError, match="synthetic full disk"): + pairs.spill() + for retry in (False, True): + if retry: + pairs.spill() + assert [t.as_dict()["trial"] for t, _ in pairs] == list(range(_N)) + + +@pytest.mark.parametrize("step", ["_candidate", "_PythonSide"]) +def test_a_failed_allocation_leaves_every_pair_once( + spilled: Path, monkeypatch: pytest.MonkeyPatch, step: str +) -> None: + pairs = HeldPairs(_TYPES) + for row in _rows("arrow"): + pairs.append(row) + + def fail(*_: Any) -> Any: + raise MemoryError("synthetic") + + with monkeypatch.context() as patched: + patched.setattr(held_rows, step, fail) + with pytest.raises(MemoryError): + pairs.spill() + pairs.spill() + assert [t.as_dict()["trial"] for t, _ in pairs] == list(range(_N)) + + +# --------------------------------------------------------------------------- +# Job nodes +# --------------------------------------------------------------------------- + + +@function_pod(output_keys=["total", "label"], version="v0.0") +def _numbers(a: int, b: int) -> tuple[int, str]: + return a + b, f"{a}" + + +@function_pod(output_keys="seen", version="v0.0") +def _array(a: int, b: int) -> np.ndarray: # pyright: ignore[reportMissingTypeArgument] # the declared type under test + return np.arange(a + b) + + +@function_pod(output_keys="seen", version="v0.0") +def _some(a: int, b: int) -> int | None: + return None if a % 4 == 0 else a + + +_DELIVERED: list[int] = [] + + +@function_pod(output_keys="point", version="v0.0") +def _instance(a: int, b: int) -> Point: + return FarPoint(a, b) if a % 2 else Point(a) + + +@side_effect_pod +def _deliver(a: int, b: int, ctx: Any) -> None: + _DELIVERED.append(a) + + +def _source(rows: int = _N) -> ArrowTableSource: + numbers = list(range(rows)) + return ArrowTableSource( + pa.table( + { + "subject": [f"s{n % 3}" for n in numbers], + "trial": numbers, + "a": numbers, + "b": [n * 10 for n in numbers], + }, + schema=pa.schema( + [ + pa.field("subject", pa.large_string(), nullable=False), + *( + pa.field(name, pa.int64(), nullable=False) + for name in ("trial", "a", "b") + ), + ] + ), + ), + tag_columns=["subject", "trial"], + tag_only_columns=True, + record_id_columns=["trial"], + source_id="numbers", + ) + + +_PODS: dict[str, Any] = { + "numbers": _numbers, + "arrays": _array, + "instances": _instance, + "some": _some, + "effect": _deliver, +} + + +def _job(pod: str, database: Any = None) -> PipelineJob: + with PipelineJob( + name=f"held_{pod}", database=database or InMemoryArrowDatabase() + ) as job: + source = _source() + step = _PODS[pod] + out = getattr(step, "pod", step).process(source, label="out") + _ = out.select_tag_columns(["trial"], label="after") + return job + + +def _run(job: PipelineJob, orchestrator: str) -> Any: + if orchestrator == "sync": + return job.run() + return job.run(orchestrator=AsyncPipelineOrchestrator()) + + +def _by_trial(table: pa.Table) -> pa.Table: + names = [n for n in table.column_names if "record" not in n] + return table.select(names).sort_by("trial") + + +def _view(node: Any) -> dict[str, Any]: + # Record ids of computed results are random; everything else is compared. + table = node.as_table(columns={"system_tags": True}) + return { + "table": table.to_pylist(), + "schema": table.schema, + "rows": [ + (t.as_dict(), {k: repr(v) for k, v in d.as_dict(all_info=False).items()}) + for t, d in node.iter_data() + ], + "types": [[type(v) for v in d.as_dict().values()] for _, d in node.iter_data()], + "count": node.held_row_count(), + "head": node.head(4).table.to_pylist(), + "head_rows": node.head(4).total_rows, + "sorted_head": node.head(4, columns={"sort_by_tags": True}).table.to_pylist(), + "hash": node.content_hash(), + } + + +@pytest.mark.parametrize("pod", list(_PODS)) +def test_a_sync_node_over_chunks_reads_exactly_as_one_over_pairs( + spilled: Path, pod: str +) -> None: + job = _job(pod) + _ = _run(job, "sync") + found = {label: _view(job.nodes[label]) for label in ("out",)} + after = job.nodes["after"].as_table(columns={"system_tags": True}) + assert bool(_files(spilled)) == (pod not in ("arrays", "instances")) + + with pytest.MonkeyPatch.context() as patched: + patched.setattr(held_rows, "HELD_CHUNK_ROWS", 8192) + plain = _job(pod) + _ = _run(plain, "sync") + expected = {label: _view(plain.nodes[label]) for label in ("out",)} + expected_after = plain.nodes["after"].as_table(columns={"system_tags": True}) + + assert repr(found) == repr(expected) + assert after.equals(expected_after) + # Tables, source info included, are the rows': the same on every read. + node = job.nodes["out"] + first = node.as_table(all_info=True) + ids = [d.datagram_uuid for _, d in node.iter_data()] + assert ids == [d.datagram_uuid for _, d in node.iter_data()] + node._cached_output_table = None + assert node.as_table(all_info=True).to_pylist() == first.to_pylist() + + +@pytest.mark.parametrize("pod", list(_PODS)) +def test_an_async_node_over_chunks_holds_the_sync_rows(spilled: Path, pod: str) -> None: + sync_job, async_job = _job(pod), _job(pod) + _ = _run(sync_job, "sync") + _ = _run(async_job, "async") + for label in ("out", "after"): + found = _by_trial(async_job.nodes[label].as_table()) + expected = _by_trial(sync_job.nodes[label].as_table()) + assert found.schema.equals(expected.schema, check_metadata=True) + assert repr(found.to_pylist()) == repr(expected.to_pylist()) + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +@pytest.mark.parametrize("pod", list(_PODS)) +def test_clearing_a_node_removes_its_files( + spilled: Path, pod: str, orchestrator: str +) -> None: + job = _job(pod) + _ = _run(job, orchestrator) + table = job.nodes["out"].as_table() + values = repr(table.to_pylist()) + for node in job.nodes.values(): + if hasattr(node, "clear_cache"): + node.clear_cache() + assert not _files(spilled) + assert job.nodes["out"].as_table().num_rows == 0 + assert repr(table.to_pylist()) == values + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_stored_results_are_loaded_and_held_in_chunks( + spilled: Path, orchestrator: str +) -> None: + database = InMemoryArrowDatabase() + first = _job("numbers", database) + _ = _run(first, "sync") + expected = _by_trial(first.nodes["out"].as_table(columns={"source": True})) + + again = _job("numbers", database) + _ = _run(again, orchestrator) + + found = _by_trial(again.nodes["out"].as_table(columns={"source": True})) + assert found.to_pylist() == expected.to_pylist() + assert _files(spilled) + loaded = _job("numbers", database) + _ = loaded.run(load_only=True) + assert ( + _by_trial(loaded.nodes["out"].as_table(columns={"source": True})).to_pylist() + == expected.to_pylist() + ) + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +@pytest.mark.parametrize("pod", ["numbers", "effect"]) +@pytest.mark.parametrize("room", [0, 1]) +def test_a_full_disk_fails_the_run_and_leaves_no_file( + spilled: Path, + monkeypatch: pytest.MonkeyPatch, + pod: str, + orchestrator: str, + room: int, +) -> None: + """It is no row failure: the run fails, whatever the error policy.""" + job = _job(pod) + with monkeypatch.context() as patched: + patched.setattr(pa.ipc, "new_file", _FullDisk(room)) + with pytest.raises(BaseException) as kept: + _ = _run(job, orchestrator) + assert not _files(spilled), f"left behind with {kept.value!r} kept" + assert job.nodes["out"].as_table().num_rows == 0 + _ = _run(job, orchestrator) + assert job.nodes["out"].as_table().num_rows == _N + + +@pytest.mark.parametrize("pod", ["numbers", "effect"]) +def test_a_cancelled_run_leaves_no_file(spilled: Path, pod: str) -> None: + job = _job(pod) + node = job.nodes["out"] + + async def run() -> BaseException: + given: Channel[tuple[Any, Any]] = Channel(buffer_size=_N) + output: Channel[tuple[Any, Any]] = Channel(buffer_size=_N) + if pod == "effect": + started = node.async_execute([given.reader], output.writer) + else: + started = node.async_execute(given.reader, output.writer) + task = asyncio.create_task(started) + for row in _source().iter_data(): + await given.writer.send(row) + for _ in range(_N): + _ = await output.reader.receive() + assert _files(spilled) + _ = task.cancel() + with pytest.raises(asyncio.CancelledError) as kept: + await task + return kept.value + + error = asyncio.run(run()) + assert not _files(spilled), f"left behind with {error!r} kept" + assert node.as_table().num_rows == 0 + + +def test_a_side_effect_nodes_read_goes_on_after_it_is_cleared(spilled: Path) -> None: + job = _job("effect") + _ = _run(job, "sync") + reading: Iterator[Any] = job.nodes["out"].iter_data() + first = next(reading) + job.nodes["out"].clear_cache() + assert [t.as_dict()["trial"] for t, _ in [first, *reading]] == list(range(_N)) From 27c7db04c8f3a0447274139aac810e1c8247689d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 05:01:06 -0800 Subject: [PATCH 21/26] Revert "feat(pipeline): function and side-effect job nodes keep their rows in a spool (ITL-1464)" This reverts commit 1fc3ebbb05d146fbc54a54ba435472e4f369bbcd. --- changelog.d/ITL-1464.md | 6 - src/orcapod/core/held_rows.py | 556 ---------------------- src/orcapod/core/nodes/function_node.py | 204 +++----- src/orcapod/side_effects.py | 53 +-- tests/test_core/test_held_rows.py | 607 ------------------------ 5 files changed, 78 insertions(+), 1348 deletions(-) delete mode 100644 src/orcapod/core/held_rows.py delete mode 100644 tests/test_core/test_held_rows.py diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md index f9dc3151f..b064ba031 100644 --- a/changelog.d/ITL-1464.md +++ b/changelog.d/ITL-1464.md @@ -19,9 +19,3 @@ node gives the same rows; a table read from it stays valid after the node and the job are gone. An async job of one row-by-row operator over 1 million rows holds 0.9 GiB of its own memory instead of 4.4 GiB (ITL-1464). -- A function job node and a side-effect job node keep the rows of their run the same way: - full chunks of 8,192 rows become Arrow data, in a private temporary file beyond 64 MiB. A - row is kept that way only when reading it gives back exactly the row that was held (the - same Python values, types, ids and source info); any other row, such as one that holds a - user class instance or an array, stays in memory as it is. A sync run still hands its rows - to the next steps in memory. A full local disk fails the run (ITL-1464). diff --git a/src/orcapod/core/held_rows.py b/src/orcapod/core/held_rows.py deleted file mode 100644 index e39318e00..000000000 --- a/src/orcapod/core/held_rows.py +++ /dev/null @@ -1,556 +0,0 @@ -"""Rows a job node holds, as Arrow data on local disk when they are many (ITL-1464). - -A function job node holds its results and a side-effect job node the rows it passed on, -each as a ``(Tag, Data)`` pair: about 20 KiB per row for a few numbers. ``HeldPairs`` (a -list of pairs) and ``HeldRows`` (pairs by entry id) hold them in chunks: a full chunk's -rows become one Arrow table in a ``RowSpool`` (in memory up to its limit, then a private -temporary file read back memory-mapped), and a pair is built again when it is read. - -A row is kept that way only when the pair built again is the pair that was held, in every -view of it: both are plain ``Tag`` and ``Data``, its tables have the chunk's schema, and -each Python value it already holds (a function's own return value, its meta values) is of -a kind that the Arrow value gives back exactly (``_same``). Any other row (a user class -instance, an array, a missing result) stays the pair it is, in its place. - -This module imports no other part of Orcapod but the spool, so that the node modules can -import it without a cycle: the classes of a row, ``Tag`` and ``Data``, are given to it. - -The spool's files go when the rows do: ``clear`` and ``close``, which a node calls when -its run fails, is cancelled or is cleared. -""" - -from __future__ import annotations - -import bisect -import datetime as dt -import decimal -import functools -import itertools -import pathlib -import struct -import uuid -from collections.abc import Iterable, Iterator, Mapping, MutableMapping, Sequence -from typing import Any, NamedTuple, TypeVar, cast, overload - -import pyarrow as pa -from typing_extensions import override - -from orcapod.core.row_spool import SPOOL_MEMORY_BYTES, RowSpool -from orcapod.system_constants import constants - -_T = TypeVar("_T") - -Pair = tuple[Any, Any] -"""A tag and its data; the data is ``None`` for an input without output.""" - - -HELD_CHUNK_ROWS = 8_192 -"""Rows held as pairs before they become a chunk.""" - -HELD_MEMORY_BYTES = SPOOL_MEMORY_BYTES -"""Bytes of chunks that stay in memory; beyond them they are on local disk.""" - -_TAG = "t:" -_DATA = "d:" -_TAG_ID = "tag_id" -_DATA_ID = "data_id" -_TAG_COLUMNS = {"system_tags": True, "meta": True} -_DATA_COLUMNS = {"source": True, "meta": True} - - -_EXACT_KINDS = frozenset( - ( - type(None), - bool, - int, - str, - bytes, - dt.date, - dt.timedelta, - uuid.UUID, - pathlib.PosixPath, - pathlib.WindowsPath, - ) -) -"""Kinds whose values, when equal, are the same.""" - - -def _same(given: object, read: object) -> bool: - """Whether ``read``, a value read from Arrow, is ``given`` in every respect. - - Only for kinds whose equality and type say so; any other kind is not the same. - """ - kind = type(given) - if kind is not type(read): - return False - if kind is float: - # Bit for bit: -0.0 is not 0.0, and a NaN is itself. - return struct.pack(" bool: - """Whether ``value`` is of a kind ``_same`` compares; nothing is converted.""" - kind = type(value) - if kind is list: - return all(map(_may_be_same, cast("list[object]", value))) - if kind is dict: - items = cast("dict[object, object]", value) - return all(map(_may_be_same, items)) and all(map(_may_be_same, items.values())) - return kind in _EXACT_KINDS or kind in (float, dt.datetime, decimal.Decimal) - - -def _same_values(given: Mapping[str, object], read: Mapping[str, object]) -> bool: - """Whether two rows' values have the same names, in order, and are the same.""" - return list(given) == list(read) and all( - _same(value, read[name]) for name, value in given.items() - ) - - -class _Origin(NamedTuple): - """What every row of a chunk shares besides its columns.""" - - tag_context: Any - data_context: Any - tag_config: Any - data_config: Any - - -def _origin(tag: Any, data: Any) -> _Origin: - return _Origin( - tag.data_context, data.data_context, tag.orcapod_config, data.orcapod_config - ) - - -class _Candidate(NamedTuple): - """A row whose tables can be part of a chunk.""" - - place: int - tag: Any - data: Any - tag_table: pa.Table - data_table: pa.Table - - -class RowTypes(NamedTuple): - """The classes of the rows that become chunks (``Tag`` and ``Data``), exactly.""" - - tag: type[Any] - data: type[Any] - - -def _candidate(types: RowTypes, place: int, pair: Pair) -> _Candidate | None: - """The row as tables, or ``None`` for a row that stays the pair it is.""" - tag, data = pair - if type(tag) is not types.tag or type(data) is not types.data: - return None - try: - if not tag.keys() or set(data._source_info) != set( - data.keys() - ): # a token dropped or filled in would differ - return None - for datagram in (tag, data): - # Before its table is built: a row held as it is gets no second form. - values = datagram._data_dict # ``None``: every value comes from Arrow - if values is not None and not all(map(_may_be_same, values.values())): - return None - tag_table = tag.as_table(columns=_TAG_COLUMNS) - data_table = data.as_table(columns=_DATA_COLUMNS) - except (MemoryError, OSError): - raise - except Exception: # noqa: BLE001 # a row that makes no table is held as it is - return None - if not data_table.num_columns: - return None - return _Candidate(place, tag, data, tag_table, data_table) - - -def _prefixed(table: pa.Table, prefix: str) -> pa.Table: - return table.rename_columns([prefix + name for name in table.column_names]) - - -def _unprefixed(table: pa.Table, prefix: str) -> pa.Table: - names = [name for name in table.column_names if name.startswith(prefix)] - return table.select(names).rename_columns([n.removeprefix(prefix) for n in names]) - - -def _pairs_of(types: RowTypes, table: pa.Table, origin: _Origin) -> Iterator[Pair]: - """Build the pairs of a chunk's rows again.""" - tags = types.tag.rows_of(_unprefixed(table, _TAG), origin.tag_context) - datas = types.data.rows_of(_unprefixed(table, _DATA), origin.data_context) - tag_ids = table.column(_TAG_ID).to_pylist() - data_ids = table.column(_DATA_ID).to_pylist() - for tag, data, tag_id, data_id in zip(tags, datas, tag_ids, data_ids, strict=True): - tag._datagram_uuid = uuid.UUID( - bytes=tag_id - ) # the row's own id, as constructing it with one sets it - data._datagram_uuid = uuid.UUID(bytes=data_id) # as above - tag._orcapod_config = origin.tag_config # as constructing it with one sets it - data._orcapod_config = origin.data_config # as above - yield tag, data - - -class _PythonSide: - """What the rows of a chunk's tag, or data, columns read as in Python.""" - - def __init__(self, table: pa.Table, context: Any) -> None: - not_values = ( - constants.META_PREFIX, - constants.SYSTEM_TAG_PREFIX, - constants.SOURCE_PREFIX, - ) - names = table.column_names - self._own = table.select([n for n in names if not n.startswith(not_values)]) - self._meta = table.select( - [n for n in names if n.startswith(constants.META_PREFIX)] - ) - self._converter = context.type_converter - - def _rows(self, table: pa.Table) -> list[dict[str, Any]]: - if not table.num_columns: - return [{}] * table.num_rows - return cast( - "list[dict[str, Any]]", - cast(object, self._converter.arrow_table_to_python_dicts(table)), - ) - - def _schema(self, table: pa.Table) -> Any: - return self._converter.arrow_schema_to_python_schema(table.schema) - - # Each read once for the whole chunk, and only when a row asks for it. - @functools.cached_property - def values(self) -> list[dict[str, Any]]: - return self._rows(self._own) - - @functools.cached_property - def schema(self) -> Any: - return self._schema(self._own) - - @functools.cached_property - def meta(self) -> list[dict[str, Any]]: - return self._rows(self._meta) - - @functools.cached_property - def meta_schema(self) -> Any: - return self._schema(self._meta) - - def gives_back(self, row: int, datagram: Any) -> bool: - """Whether row ``row`` reads as everything ``datagram`` holds in Python.""" - held = datagram._data_dict # ``None``: every value comes from Arrow already - if held is not None and not _same_values(held, self.values[row]): - return False - schema = datagram._data_python_schema # ``None``: from Arrow already - if schema is not None and not _same_schema(schema, self.schema): - return False - meta = datagram.get_meta_info() - return ( - not meta - or ( - _same_values(meta, self.meta[row]) - and _same_schema( - datagram._meta_python_schema, # the types its meta columns are built with - self.meta_schema, - ) - ) - ) - - -def _same_schema(given: Any, read: Any) -> bool: - return list(given.items()) == list(read.items()) and ( - given.optional_fields == read.optional_fields - ) - - -class _Chunk(NamedTuple): - """Consecutive rows: those in the spool by number, the others as they are.""" - - first: int - """The spool's number of the chunk's first spooled row.""" - stored: int - """How many of its rows are in the spool.""" - kept: dict[int, Pair] - """The rows that are not, by place in the chunk.""" - origin: _Origin | None - - -class HeldPairs(Sequence[Pair]): - """Pairs in the order appended, full chunks of them in a ``RowSpool``. - - Appending never builds a chunk: ``spill`` does, where the caller can let a full disk - end the run. - """ - - def __init__(self, types: RowTypes) -> None: - self._types: RowTypes = types - self._start() - - def _start(self) -> None: - self._spool: RowSpool | None = None - self._schema: pa.Schema | None = None - self._chunks: list[_Chunk] = [] - self._chunk_rows: int = 0 - self._starts: list[int] = [] - self._pending: list[Pair] = [] - # The last chunk read, so reading neighbours reads its rows from the spool once. - self._last: tuple[int, pa.Table] | None = None - # Every spooled row, read through mappings: a forked child reads it too. - self._table: pa.Table | None = None - - def append(self, pair: Pair) -> None: - """Hold ``pair`` after every pair held.""" - self._pending.append(pair) - - def spill(self) -> None: - """Make chunks of the pairs appended, as far as they fill one. - - Raises: - OSError: If a chunk cannot be written to the local disk. Every pair is then - still held. - """ - while len(self._pending) >= HELD_CHUNK_ROWS: - rows = self._pending[:HELD_CHUNK_ROWS] - chunk = self._chunk_of(rows) - if self._spool is not None: - self._table = self._spool.table() - # From here on nothing can fail: the chunk replaces its pairs. - self._starts.append(self._chunk_rows) - self._chunks.append(chunk) - self._chunk_rows += len(rows) - self._pending = self._pending[HELD_CHUNK_ROWS:] - self._last = None - - def _chunk_of(self, rows: list[Pair]) -> _Chunk: - """Put the rows that can be into the spool.""" - kept = dict(enumerate(rows)) - candidates = [ - c - for place, pair in enumerate(rows) - if (c := _candidate(self._types, place, pair)) - ] - origin: _Origin | None = None - table: pa.Table | None = None - if candidates: - first = candidates[0] - origin = _origin(first.tag, first.data) - alike = [ - c - for c in candidates - if all( - a is b for a, b in zip(_origin(c.tag, c.data), origin, strict=True) - ) - and c.tag_table.schema.equals(first.tag_table.schema, True) - and c.data_table.schema.equals(first.data_table.schema, True) - ] - table = self._table_of(alike) - if self._schema is not None and not table.schema.equals(self._schema, True): - table = None - else: - tags = _PythonSide(_unprefixed(table, _TAG), origin.tag_context) - datas = _PythonSide(_unprefixed(table, _DATA), origin.data_context) - good = [ - i - for i, c in enumerate(alike) - if tags.gives_back(i, c.tag) and datas.gives_back(i, c.data) - ] - if len(good) < len(alike): - table = table.take(pa.array(good, pa.int64())) if good else None - if table is not None: - for i in good: - del kept[alike[i].place] - if table is None: - return _Chunk(0, 0, dict(enumerate(rows)), None) - if self._spool is None: - self._spool = RowSpool(memory_bytes=HELD_MEMORY_BYTES) - first_number = self._spool.size - self._spool.append(table) - self._schema = table.schema - return _Chunk(first_number, table.num_rows, kept, origin) - - @staticmethod - def _table_of(rows: list[_Candidate]) -> pa.Table: - ids = pa.schema( - [ - pa.field(_TAG_ID, pa.large_binary(), nullable=False), - pa.field(_DATA_ID, pa.large_binary(), nullable=False), - ] - ) - parts = ( - _prefixed(pa.concat_tables([c.tag_table for c in rows]), _TAG), - _prefixed(pa.concat_tables([c.data_table for c in rows]), _DATA), - pa.Table.from_arrays( - [ - pa.array([c.tag.datagram_uuid.bytes for c in rows], ids.types[0]), - pa.array([c.data.datagram_uuid.bytes for c in rows], ids.types[1]), - ], - schema=ids, - ), - ) - return pa.Table.from_arrays( - [column for part in parts for column in part.columns], - schema=pa.schema([field for part in parts for field in part.schema]), - ).combine_chunks() - - def _stored_table(self, index: int) -> pa.Table: - """The spooled rows of chunk ``index``.""" - if self._last is None or self._last[0] != index: - chunk = self._chunks[index] - assert self._table is not None - self._last = (index, self._table.slice(chunk.first, chunk.stored)) - return self._last[1] - - def has_data(self, place: int) -> bool: - """Whether the pair at ``place`` has data; nothing is read or built.""" - if place >= self._chunk_rows: - return self._pending[place - self._chunk_rows][1] is not None - index = bisect.bisect_right(self._starts, place) - 1 - kept = self._chunks[index].kept.get(place - self._starts[index]) - return kept is None or kept[1] is not None - - def is_kept(self, place: int) -> bool: - """Whether the pair at ``place`` is held as it is; nothing is read or built.""" - if place >= self._chunk_rows: - return True - index = bisect.bisect_right(self._starts, place) - 1 - return place - self._starts[index] in self._chunks[index].kept - - @override - def __len__(self) -> int: - return self._chunk_rows + len(self._pending) - - @overload - def __getitem__(self, index: int) -> Pair: ... - @overload - def __getitem__(self, index: slice) -> Sequence[Pair]: ... - @override - def __getitem__(self, index: int | slice) -> Pair | Sequence[Pair]: - if isinstance(index, slice): - return [self[i] for i in range(*index.indices(len(self)))] - place = index + len(self) if index < 0 else index - if not 0 <= place < len(self): - raise IndexError(index) - if place >= self._chunk_rows: - return self._pending[place - self._chunk_rows] - number = bisect.bisect_right(self._starts, place) - 1 - chunk, row = self._chunks[number], place - self._starts[number] - if row in chunk.kept: - return chunk.kept[row] - assert chunk.origin is not None - before = sum(1 for other in chunk.kept if other < row) - table = self._stored_table(number).slice(row - before, 1) - return next(_pairs_of(self._types, table, chunk.origin)) - - @override - def __iter__(self) -> Iterator[Pair]: - """The pairs held now, in order, also if they are let go while reading.""" - return self._read( - self._table, list(self._chunks), list(self._starts), self._pending - ) - - def _read( - self, - table: pa.Table | None, - chunks: list[_Chunk], - starts: list[int], - pending: list[Pair], - ) -> Iterator[Pair]: - pending = list(pending) - ends = [*starts[1:], sum(c.stored + len(c.kept) for c in chunks)] - for chunk, start, end in zip(chunks, starts, ends, strict=False): - stored: Iterator[Pair] = iter(()) - if chunk.origin is not None and table is not None: - stored = _pairs_of( - self._types, table.slice(chunk.first, chunk.stored), chunk.origin - ) - for row in range(end - start): - yield chunk.kept[row] if row in chunk.kept else next(stored) - yield from pending - - def close(self) -> None: - """Let every pair go, and delete the files; rows being read stay readable.""" - if self._spool is not None: - self._spool.close() - self._start() - - -class HeldRows(MutableMapping[bytes, Pair]): - """Pairs by entry id, in the order first given, held in ``HeldPairs``.""" - - def __init__(self, types: RowTypes) -> None: - self._pairs: HeldPairs = HeldPairs(types) - self._places: dict[bytes, int] = {} - - def spill(self) -> None: - """Make full chunks of the pairs held (``HeldPairs.spill``).""" - self._pairs.spill() - - def has_data(self, key: bytes) -> bool: - """Whether ``key`` is held with data; nothing is read or built.""" - place = self._places.get(key) - return place is not None and self._pairs.has_data(place) - - def is_kept(self, key: bytes) -> bool: - """Whether ``key`` is held as the pair it is; nothing is read or built. - - A pair that is not is always a ``Tag`` and a ``Data`` with values. - """ - place = self._places.get(key) - return place is not None and self._pairs.is_kept(place) - - @override - def __getitem__(self, key: bytes) -> Pair: - return self._pairs[self._places[key]] - - @override - def __setitem__(self, key: bytes, pair: Pair) -> None: - self._pairs.append(pair) - self._places[key] = len(self._pairs) - 1 - - @override - def __delitem__(self, key: bytes) -> None: - del self._places[key] - - @override - def __iter__(self) -> Iterator[bytes]: - return iter(self._places) - - @override - def __len__(self) -> int: - return len(self._places) - - @override - def __contains__(self, key: object) -> bool: - return key in self._places - - @override - def clear(self) -> None: - """Let every pair go, and delete the files.""" - self._pairs.close() - self._places.clear() - - -def batched(pairs: Iterable[_T], size: int) -> Iterator[list[_T]]: - """``pairs`` in lists of ``size``, the last one shorter.""" - iterator = iter(pairs) - while batch := list(itertools.islice(iterator, size)): - yield batch diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 08266d43c..9a0353053 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -24,7 +24,7 @@ import uuid from abc import abstractmethod from collections import Counter -from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from collections.abc import Callable, Iterator, Mapping, Sequence from datetime import datetime, timezone from functools import partial from typing import Any, Literal, NamedTuple, cast @@ -34,13 +34,6 @@ from orcapod import contexts from orcapod.core.nodes.provenance_methods import ProvenanceMethods -from orcapod.core.held_rows import ( - HELD_CHUNK_ROWS, - HeldPairs, - HeldRows, - RowTypes, - batched, -) from orcapod.core.function_pod import ( fall_through_tags, function_input, @@ -305,17 +298,6 @@ def _with_datagram_id(data: Data, datagram_id: uuid.UUID) -> Data: ) -_ROW_TYPES = RowTypes(Tag, Data) - - -def held_pairs() -> HeldPairs: - """An empty ``HeldPairs`` for rows of ``Tag`` and ``Data``. - - For the side-effect job nodes: one place gives them the row classes. - """ - return HeldPairs(_ROW_TYPES) - - def rows_as_output_stream( rows: Sequence[tuple[TagProtocol, DataProtocol]], node: StreamProtocol ) -> StreamProtocol: @@ -768,7 +750,7 @@ def as_table( if self._read_finds_stale(): self.clear_cache() if self._cached_output_table is None: - self._cached_output_table = self._table_from_pairs(self.iter_data()) + self._cached_output_table = self._table_from_pairs(list(self.iter_data())) column_config = ColumnConfig.handle_config(columns, all_info=all_info) @@ -836,7 +818,7 @@ def _zero_row_table(self, config: ColumnConfig) -> "pa.Table | None": ) def _table_from_pairs( - self, pairs: "Iterable[tuple[TagProtocol, DataProtocol]]" + self, pairs: "list[tuple[TagProtocol, DataProtocol]]" ) -> "pa.Table": """Return the output rows ``pairs`` as one table with every column group. @@ -854,31 +836,7 @@ def _table_from_pairs( InputValidationError: If two rows give one column different Arrow types, naming this node, the column and both types. """ - # A batch of rows at a time, one chunk each, so at most that many rows are held - # as pairs and one-row tables (ITL-1464). - tag_tables: list[pa.Table] = [] - data_tables: list[pa.Table] = [] - try: - for rows in batched(pairs, HELD_CHUNK_ROWS): - tag_tables.append( - _concat_row_tables( - [tag.as_table(columns={"system_tags": True}) for tag, _ in rows] - ).combine_chunks() - ) - data_tables.append( - _concat_row_tables( - [ - data.as_table(columns={"source": True, "context": True}) - for _, data in rows - ] - ).combine_chunks() - ) - # One table per batch, put together by the rule that makes each batch's. - tag_table = _concat_row_tables(tag_tables) if tag_tables else None - data_table = _concat_row_tables(data_tables) if data_tables else None - except InputValidationError as exc: - raise InputValidationError(f"Function node {self.label!r}: {exc}") from exc - if tag_table is None or data_table is None: + if not pairs: # No data was produced (node has not been run yet or produced zero # outputs): the table computed rows would have, with no row (ITL-912). typed = self._zero_row_output_table() @@ -892,6 +850,18 @@ def _table_from_pairs( tag_python_schema + data_python_schema ), ) + try: + tag_table = _concat_row_tables( + [tag.as_table(columns={"system_tags": True}) for tag, _ in pairs] + ) + data_table = _concat_row_tables( + [ + data.as_table(columns={"source": True, "context": True}) + for _, data in pairs + ] + ) + except InputValidationError as exc: + raise InputValidationError(f"Function node {self.label!r}: {exc}") from exc # A data-tag is one column: laid out once, among the tags. shared = [c for c in data_table.column_names if c in tag_table.column_names] if shared: @@ -941,27 +911,23 @@ def head( note=BLUEPRINT_NOTE, ) - def _head_of_rows( + def _head_of_pairs( self, - rows: "Sequence[tuple[TagProtocol, DataProtocol]]", - total: int, - missing: int, + pairs: "Sequence[tuple[TagProtocol, DataProtocol | None]]", n: int, config: ColumnConfig, origin: str, ) -> StreamView: - """Return the first ``n`` of ``rows`` as this node's head. + """Return the first ``n`` of ``pairs`` as this node's head. - Args: - rows: The node's first rows with values: every one of them with sorting, at - least one when there is one. - total: How many rows with values the node has. - missing: How many results have no values to show: kept in an ephemeral - database that is gone (``EmptyData``). They are left out and noted. - n: How many rows to show. - config: The column groups. - origin: Where the rows came from (``StreamView``). + A ``None`` output (a filtered input) is not a row. An ``EmptyData`` placeholder + (a result kept in an ephemeral database that is gone) has no values to show: it is + left out and counted in the note. """ + rows = [ + (t, d) for t, d in pairs if d is not None and not isinstance(d, EmptyData) + ] + missing = sum(1 for _, d in pairs if isinstance(d, EmptyData)) # With sorting, every row is shaped and sorted (each keeps its own content # hash), then the first n are taken: the head is ``as_table(config)[:n]``. # At least one row is shaped even for n == 0, so that the empty head has the @@ -985,7 +951,7 @@ def _head_of_rows( self, table, tag_columns=self.keys(columns=config)[0], - total_rows=total, + total_rows=len(rows), origin=origin, note=note, ) @@ -1498,8 +1464,9 @@ def __init__( ) # stream-level caching state - # Full chunks of them on local disk when they are many (ITL-1464). - self._cached_output_datas: HeldRows = HeldRows(_ROW_TYPES) + self._cached_output_datas: dict[ + bytes, tuple[TagProtocol, DataProtocol | None] + ] = {} self._cached_output_table: "pa.Table | None" = None self._cached_content_hash_column: "pa.Array | None" = None self._run_entry_counts = None @@ -1969,7 +1936,7 @@ def from_descriptor( ) # FunctionJobNode — stream-level caching state - node._cached_output_datas = HeldRows(_ROW_TYPES) + node._cached_output_datas = {} node._cached_output_table = None node._cached_content_hash_column = None @@ -2057,31 +2024,6 @@ def _held_pairs(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: if pair is not None and pair[1] is not None: yield pair[0], pair[1] - def _held_head( - self, n: int - ) -> tuple[list[tuple[TagProtocol, DataProtocol]], int, int]: - """The first ``n`` of ``_held_pairs`` that have values, and two counts. - - Returns: - The rows, how many rows have values, and how many are placeholders for a - result that is gone. Rows not returned are counted, not built. - """ - cache = self._cached_output_datas - rows: list[tuple[TagProtocol, DataProtocol]] = [] - total = missing = 0 - for eid in self._run_entry_order if self._run_entry_counts is not None else (): - if not cache.has_data(eid): - continue - kept = cache.is_kept(eid) - pair = cache[eid] if kept or len(rows) < n else None - if kept and pair is not None and isinstance(pair[1], EmptyData): - missing += 1 - continue - total += 1 - if pair is not None and pair[1] is not None and len(rows) < n: - rows.append((pair[0], pair[1])) - return rows, total, missing - def _set_run_rows( self, entry_ids: list[bytes], @@ -2741,10 +2683,12 @@ def execute( base_entry_ids = [eid for _, _, eid in upstream_entries] # Hot-load any already-computed results from DB into _cached_output_datas. - # The per-data cache-hit check below uses _cached_output_datas directly, - # which includes None-output entries (function returned None) and prevents - # spurious recomputation of already-processed data. - self._load_missing(base_entry_ids) + # get_cached_results() is called for its side effect (populating the + # in-memory cache); the returned dict is intentionally discarded here so + # that the per-data cache-hit check below uses _cached_output_datas + # directly — which includes None-output entries (function returned None) + # and prevents spurious recomputation of already-processed data. + self.get_cached_results(base_entry_ids=base_entry_ids) # Base entry ids of the inputs that gave a row (a cache hit or a # successful computation), one per input: the node's rows afterwards. @@ -2753,9 +2697,10 @@ def execute( for tag, data, base_entry_id in upstream_entries: ctx_obs.on_data_start(node_label, tag, data) - entry = self._cached_output_datas.get(base_entry_id) - if entry is not None and not isinstance(entry[1], EmptyData): - tag_out, result = entry + if base_entry_id in self._cached_output_datas and not isinstance( + self._cached_output_datas[base_entry_id][1], EmptyData + ): + tag_out, result = self._cached_output_datas[base_entry_id] ctx_obs.on_data_end(node_label, tag, data, result, cached=True) emitted_entry_ids.append(base_entry_id) if result is not None: @@ -2812,8 +2757,6 @@ def execute( self._commit_or_end_node( self._row_processed, ctx_obs, node_label, node_hash ) - # Outside the row's handler: a full local disk is no row failure. - self._cached_output_datas.spill() self._commit_or_end_node( self._commit_at_node_end, ctx_obs, node_label, node_hash @@ -3042,37 +2985,22 @@ def get_cached_results( if self._cached_function_pod is None or not base_entry_ids: return {} - self._load_missing(base_entry_ids) - return { - eid: cast( - "tuple[TagProtocol, DataProtocol]", self._cached_output_datas[eid] - ) - for eid in base_entry_ids - if self._cached_output_datas.has_data(eid) - } - - def _load_missing(self, base_entry_ids: list[bytes]) -> None: - """Load the stored results of the entries not held yet (``get_cached_results``).""" - if self._cached_function_pod is None: - return missing = [ eid for eid in base_entry_ids if eid not in self._cached_output_datas ] - if not missing: - return - loaded = self._load_cached_entries(missing) - self._hold_loaded(loaded) + if missing: + loaded = self._load_cached_entries(missing) + self._cached_output_datas.update(loaded) + if loaded: + self._cached_output_table = None + self._cached_content_hash_column = None - def _hold_loaded( - self, loaded: "dict[bytes, tuple[TagProtocol, DataProtocol]]" - ) -> None: - """Hold the results ``loaded`` from the databases.""" - for entry_id, pair in loaded.items(): - self._cached_output_datas[entry_id] = pair - self._cached_output_datas.spill() - if loaded: - self._cached_output_table = None - self._cached_content_hash_column = None + return { + eid: self._cached_output_datas[eid] + for eid in base_entry_ids + if eid in self._cached_output_datas + and self._cached_output_datas[eid][1] is not None + } async def _async_process_data_internal( self, @@ -4181,11 +4109,13 @@ async def _async_execute_cache_only( ctx_obs.on_node_start(node_label, node_hash, tag_schema=None) try: loaded = self._load_cached_entries() - self._hold_loaded(loaded) + self._cached_output_datas.update(loaded) + if loaded: + self._cached_output_table = None + self._cached_content_hash_column = None sent: list[bytes] = [] - for entry_id in list(self._cached_output_datas): - tag, data = self._cached_output_datas[entry_id] + for entry_id, (tag, data) in list(self._cached_output_datas.items()): if data is not None and not isinstance(data, EmptyData): ctx_obs.on_data_start(node_label, tag, data) ctx_obs.on_data_end(node_label, tag, data, data, cached=True) @@ -4244,11 +4174,7 @@ def head( return self._head_without_rows( config, ViewStatus.NOT_COMPUTED, note=STALE_NOTE ) - # With sorting every row is shaped and sorted; otherwise the first ones are. - rows, total, missing = self._held_head( - sys.maxsize if config.sort_by_tags else max(n, 1) - ) - head = self._head_of_rows(rows, total, missing, n, config, origin="held") + head = self._head_of_pairs(list(self._held_pairs()), n, config, origin="held") if not self._run_load_only: return head # A load-only run's rows have their own status: they may lack the inputs it @@ -4319,9 +4245,9 @@ def held_row_count(self) -> int: if counts is None: return 0 return sum( - count - for entry_id, count in counts.items() - if self._cached_output_datas.has_data(entry_id) + counts.get(entry_id, 0) + for entry_id, (_, data) in self._cached_output_datas.items() + if data is not None ) def _prepare_held_read(self) -> None: @@ -4619,7 +4545,10 @@ async def async_execute( # Load pipeline DB → in-memory cache keyed by base_entry_id. loaded = self._load_cached_entries() - self._hold_loaded(loaded) + self._cached_output_datas.update(loaded) + if loaded: + self._cached_output_table = None + self._cached_content_hash_column = None cached_by_base_entry_id: dict[ bytes, tuple[TagProtocol, DataProtocol] ] = dict(loaded) @@ -4740,7 +4669,6 @@ async def record_and_forward() -> None: # Commits every commit_every_rows rows inside a job (ITL-919); # no await in between, so no other row interleaves. self._row_processed() - self._cached_output_datas.spill() await output.send((clean_tag, output_data)) # Recorded once the output took the row (see route_inputs). run_entry_ids.append(base_entry_id) diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 5aededb76..071aa82ac 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -19,11 +19,9 @@ from typing_extensions import override from orcapod.core.base import TraceableBase -from orcapod.core.held_rows import HeldPairs from orcapod.core.nodes.staleness import RunHoldingNode from orcapod.core.nodes.function_node import ( _build_record_id_preimage, - held_pairs, rows_as_output_stream, run_job_node, ) @@ -1103,7 +1101,7 @@ def __init__( self._current_log_checked = False # The rows the last completed run passed on, in the order it passed them; # ``None`` when no run in this process completed (ITL-1091). - self._held_rows: HeldPairs | None = None + self._held_rows: list[tuple[TagProtocol, DataProtocol]] | None = None # Whether those rows came from a load-only run, which delivers nothing. self._run_load_only = False # A node that has not run in this process holds nothing and is stale (ITL-1095). @@ -1123,16 +1121,10 @@ def clear_cache(self) -> None: Its next ``run()`` (or job run) delivers again what its invocation log does not record (every row without ``track_completion``) (ITL-1095). """ - self._drop_held_rows() + self._held_rows = None self._run_load_only = False self._set_modified_time(None) - def _drop_held_rows(self) -> None: - """Let the held rows go, and their files; a read begun goes on to its end.""" - rows, self._held_rows = self._held_rows, None - if rows is not None: - rows.close() - def _refuse_log_of_another_data_context(self) -> None: """Refuse an invocation log holding deliveries of another data context. @@ -1260,7 +1252,7 @@ def execute( SideEffectLogDataContextError: If the invocation log holds deliveries logged under another data context; nothing is delivered then. """ - self._drop_held_rows() + self._held_rows = None if load_only: try: rows = list(input_stream.iter_data()) @@ -1268,7 +1260,7 @@ def execute( # A run that raised defines no rows, as on the async path (ITL-1121). self.clear_cache() raise - self._hold_run(rows, load_only=True) + self._hold(rows, load_only=True) return self._output_stream(rows) try: results = self._deliver_rows(input_stream, run_id=run_id) @@ -1277,7 +1269,7 @@ def execute( # node below it (ITL-1095). self.clear_cache() raise - self._hold_run(results) + self._hold(results) return self._output_stream(results) def _output_stream( @@ -1318,22 +1310,9 @@ def _deliver_rows( results.append(result) return results - def _hold_run( + def _hold( self, rows: list[tuple[TagProtocol, DataProtocol]], *, load_only: bool = False ) -> None: - """``_hold`` the rows of a sync run; a run whose rows cannot be held failed.""" - pairs = held_pairs() - try: - for row in rows: - pairs.append(row) - pairs.spill() - self._hold(pairs, load_only=load_only) - except BaseException: - pairs.close() - self.clear_cache() - raise - - def _hold(self, rows: HeldPairs, *, load_only: bool = False) -> None: """Keep the rows a completed run passed on and stamp the node as modified. Stamped after the upstream nodes, which stamp at the end of their own run, so the @@ -1347,14 +1326,14 @@ def _hold(self, rows: HeldPairs, *, load_only: bool = False) -> None: self._run_load_only = load_only self._update_modified_time() - def _current_rows(self) -> HeldPairs | None: + def _current_rows(self) -> list[tuple[TagProtocol, DataProtocol]] | None: """The rows the last run passed on, or ``None`` if there are none or they are stale. Held rows go stale, and are dropped, when an upstream changed after the run: the judgement ``FunctionJobNode`` uses for the rows it holds. """ if self._held_rows is not None and self.is_stale: - self._drop_held_rows() + self._held_rows = None return self._held_rows # ------------------------------------------------------------------ @@ -1371,9 +1350,7 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: job has not run, the last run raised, or an upstream changed since), there are no rows. ``run()`` or ``job.run()`` delivers. """ - for tag, data in self._current_rows() or (): - # A row passed on always has data. - yield tag, cast("DataProtocol", data) + yield from self._current_rows() or () def held_row_count(self) -> int: """The number of rows the last run of this node passed on (``iter_data``'s count). @@ -1539,20 +1516,17 @@ async def async_execute( f"SideEffectJobNode.async_execute expects exactly 1 input channel; " f"got {len(inputs)}." ) - self._drop_held_rows() + self._held_rows = None # A load-only run reads no pod configuration: it delivers nothing. if load_only: - # Full chunks on local disk (ITL-1464), closed if the run fails. - rows = held_pairs() try: + rows: list[tuple[TagProtocol, DataProtocol]] = [] async for item in inputs[0]: rows.append(item) - rows.spill() await output.send(item) # Held and stamped before the output closes (ITL-1042). self._hold(rows, load_only=True) except BaseException: - rows.close() self.clear_cache() raise finally: @@ -1563,8 +1537,7 @@ async def async_execute( asyncio.Semaphore(max_concurrency) if max_concurrency is not None else None ) # This run's rows, in the order they were sent downstream. - # Full chunks on local disk (ITL-1464), closed if the run fails. - passed_on = held_pairs() + passed_on: list[tuple[TagProtocol, DataProtocol]] = [] # Makes recording a row and sending it one step: a send blocked by a full channel # can be overtaken by a later one, so without it the held order could differ from # the order downstream received. Never held across the delivery itself. @@ -1591,7 +1564,6 @@ async def process_one(tag: TagProtocol, data: DataProtocol) -> None: if result is not None: async with send_lock: passed_on.append(result) - passed_on.spill() await output.send(result) finally: if sem is not None: @@ -1607,7 +1579,6 @@ async def process_one(tag: TagProtocol, data: DataProtocol) -> None: self._hold(passed_on) except BaseException: # A run that raised or was cancelled defines no rows (ITL-1095). - passed_on.close() self.clear_cache() raise finally: diff --git a/tests/test_core/test_held_rows.py b/tests/test_core/test_held_rows.py deleted file mode 100644 index f7cf839c7..000000000 --- a/tests/test_core/test_held_rows.py +++ /dev/null @@ -1,607 +0,0 @@ -"""Rows held in chunks read exactly as the pairs that were held (ITL-1464).""" - -from __future__ import annotations - -import asyncio -import dataclasses -import datetime as dt -import errno -import math -import os -import uuid -from collections.abc import Iterator -from decimal import Decimal -from pathlib import Path -from typing import Any - -import numpy as np -import pyarrow as pa -import pytest - -from orcapod import PipelineJob, function_pod -from orcapod.channels import Channel -from orcapod.core import held_rows -from orcapod.core.datagrams import Data, EmptyData, Tag -from orcapod.core.held_rows import HeldPairs, HeldRows, RowTypes, _same -from orcapod.databases import InMemoryArrowDatabase -from orcapod.pipeline import AsyncPipelineOrchestrator -from orcapod.side_effects import side_effect_pod -from orcapod.sources import ArrowTableSource -from orcapod.system_constants import constants - -_TYPES = RowTypes(Tag, Data) -_N = 11 - - -@pytest.fixture() -def spilled(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path: - """Chunks of three rows, every chunk on disk.""" - monkeypatch.setattr(held_rows, "HELD_CHUNK_ROWS", 3) - monkeypatch.setattr(held_rows, "HELD_MEMORY_BYTES", 0) - root = tmp_path / "spool" - root.mkdir() - monkeypatch.setattr("tempfile.tempdir", str(root)) - return root - - -def _files(root: Path) -> list[Path]: - return [p for p in root.rglob("*") if p.is_file() and not p.name.endswith("lock")] - - -@dataclasses.dataclass -class Point: - x: int - - -@dataclasses.dataclass -class FarPoint(Point): - """A subclass of the declared class: the row keeps the returned instance.""" - - y: int - - -class Odd(Data): - """A subclass of ``Data``: never built again as a plain one.""" - - -def _arrow_rows() -> list[tuple[Any, Any]]: - table = pa.table( - { - "subject": pa.array([f"s{n % 3}" for n in range(_N)], pa.large_string()), - "trial": pa.array(range(_N), pa.int8()), - "when": pa.array( - [dt.datetime(2026, 1, 1, n) for n in range(_N)], - pa.timestamp("us", "UTC"), - ), - "x": pa.array([n / 3 for n in range(_N)], pa.float32()), - "note": pa.array([None if n % 4 == 0 else f"n{n}" for n in range(_N)]), - "samples": pa.array( - [[n, None] for n in range(_N)], pa.large_list(pa.int8()) - ), - } - ) - source = ArrowTableSource( - table, - tag_columns=["subject", "trial"], - tag_only_columns=True, - record_id_columns=["trial"], - source_id="rows", - ) - return list(source.iter_data()) - - -def _tag(n: int) -> Tag: - return Tag( - {"k": n, "name": f"k{n}"}, - system_tags={f"{constants.SYSTEM_TAG_PREFIX}a": f"r{n}"}, - ) - - -def _dict_data(n: int, **values: Any) -> Data: - return Data( - values, - source_info={name: f"src::{n}::{name}" for name in values}, - record_uuid=uuid.uuid4(), - python_schema={ - name: Path if isinstance(value, Path) else type(value) - for name, value in values.items() - if not isinstance(value, (list, dict)) - }, - meta_info={"__computed": True}, - ) - - -_VALUES: dict[str, Any] = { - "numbers": lambda n: {"a": n, "b": n + 0.5, "c": bool(n % 2)}, - "floats": lambda n: {"a": [-0.0, math.nan, math.inf, 0.0][n % 4]}, - "text": lambda n: {"a": f"t{n}", "b": bytes([n])}, - "lists": lambda n: {"a": [n, n + 1], "b": [[0.5], []]}, - "dicts": lambda n: {"a": {"p": n, "q": n}}, - "paths": lambda n: {"a": Path(f"/x/{n}"), "b": uuid.UUID(int=n)}, - "dates": lambda n: {"a": dt.date(2026, 1, n + 1)}, - "utc": lambda n: {"a": dt.datetime(2026, 1, n + 1, tzinfo=dt.timezone.utc)}, - "zoned": lambda n: { - "a": dt.datetime(2026, 1, 1, n, tzinfo=dt.timezone(dt.timedelta(hours=5))) - }, - "arrays": lambda n: {"a": np.arange(n + 1)}, - "numpy_scalars": lambda n: {"a": float(n), "b": np.float64(n)}, -} - - -def _rows(kind: str) -> list[tuple[Any, Any]]: - if kind == "arrow": - return _arrow_rows() - if kind == "arrow_read": - rows = _arrow_rows() - for tag, data in rows: - _ = tag.as_dict(), data.as_dict() - return rows - rows = _arrow_rows() if kind == "mixed" else [] - if kind == "mixed": - rows[1] = (rows[1][0], None) - rows[2] = (rows[2][0], rows[2][1].with_source_info(x=None)) - rows[4] = (rows[4][0], EmptyData()) - rows[5] = (rows[5][0], Odd({"x": 1})) - rows[7] = (rows[7][0], rows[7][1].with_meta_columns(__extra=[1, 2])) - rows[8] = (rows[8][0], rows[8][1].drop("x")) - rows[9] = (_tag(9), _dict_data(9, a=1)) - return rows - return [(_tag(n), _dict_data(n, **_VALUES[kind](n))) for n in range(_N)] - - -def _is_exactly(read: Any, given: Any) -> None: - """``read`` and ``given`` agree in type and in every view.""" - assert type(read) is type(given) - if given is None or isinstance(given, EmptyData): - assert read is given - return - assert read.datagram_uuid == given.datagram_uuid - assert read.data_context_key == given.data_context_key - for config in ({}, {"all_info": True}): - assert read.keys(**config) == given.keys(**config) - assert list(read.schema(**config).items()) == list( - given.schema(**config).items() - ) - assert read.arrow_schema(**config).equals( - given.arrow_schema(**config), check_metadata=True - ) - table, expected = read.as_table(**config), given.as_table(**config) - assert table.schema.equals(expected.schema, check_metadata=True) - # ``equals`` takes NaN for unequal: the values, bit for bit, by their text. - assert repr(table.to_pylist()) == repr(expected.to_pylist()) - values, wanted = read.as_dict(**config), given.as_dict(**config) - assert list(values) == list(wanted) - for name, value in wanted.items(): - assert type(values[name]) is type(value) - assert repr(values[name]) == repr(value) - assert read.content_hash() == given.content_hash() - assert read.get_meta_info() == given.get_meta_info() - if isinstance(given, Data): - assert read.source_info() == given.source_info() - else: - assert read.system_tags() == given.system_tags() - - -_KINDS = ["arrow", "arrow_read", "mixed", *_VALUES] - - -@pytest.mark.parametrize("kind", _KINDS) -def test_held_pairs_read_as_the_pairs_held(spilled: Path, kind: str) -> None: - rows = _rows(kind) - pairs = HeldPairs(_TYPES) - for row in rows: - pairs.append(row) - pairs.spill() - - assert len(pairs) == _N - assert [pairs.has_data(i) for i in range(_N)] == [d is not None for _, d in rows] - for read in (list(pairs), [pairs[i] for i in range(_N)], pairs[:]): - for (tag, data), (given_tag, given_data) in zip(read, rows, strict=True): - _is_exactly(tag, given_tag) - _is_exactly(data, given_data) - for i in (7, 0, 10, 3, -1): - _is_exactly(pairs[i][1], rows[i][1]) - with pytest.raises(IndexError): - _ = pairs[_N] - - -@pytest.mark.parametrize( - ("kind", "chunked"), - [ - ("arrow", 9), - ("arrow_read", 9), - ("numbers", 9), - ("floats", 9), - ("text", 9), - ("lists", 9), - ("paths", 9), - # A value Arrow does not give back as it is stays the object it is. - ("zoned", 0), - ("arrays", 0), - ("numpy_scalars", 0), - ], -) -def test_only_rows_that_read_the_same_become_chunks( - spilled: Path, kind: str, chunked: int -) -> None: - rows = _rows(kind) - pairs = HeldPairs(_TYPES) - for row in rows: - pairs.append(row) - pairs.spill() - assert sum(not pairs.is_kept(i) for i in range(_N)) == chunked - for i in range(_N): - if pairs.is_kept(i): - assert pairs[i] is rows[i] - assert bool(_files(spilled)) == bool(chunked) - - -@pytest.mark.parametrize( - ("a", "b"), - [ - (0.0, -0.0), - (1, True), - (1, 1.0), - ([1], [True]), - ((1,), (1,)), - ({"a": 1, "b": 2}, {"b": 2, "a": 1}), - (Decimal("1.0"), Decimal("1.00")), - (Point(1), Point(1)), - (dt.datetime(2026, 1, 1), dt.datetime(2026, 1, 1, fold=1)), - ], -) -def test_values_that_differ_in_anything_are_not_the_same(a: Any, b: Any) -> None: - assert not _same(a, b) - - -def test_rows_being_read_outlive_the_holder(spilled: Path) -> None: - rows = _rows("mixed") - pairs = HeldPairs(_TYPES) - for row in rows: - pairs.append(row) - pairs.spill() - reading = iter(pairs) - first = next(reading) - assert _files(spilled) - - pairs.close() - - assert not _files(spilled) - assert len(pairs) == 0 - for (_, data), (_, given) in zip([first, *reading], rows, strict=True): - _is_exactly(data, given) - pairs.append(rows[0]) - assert pairs[0] is rows[0] - - -@pytest.mark.skipif(not hasattr(os, "fork"), reason="no fork on this system") -def test_a_forked_child_reads_the_rows(spilled: Path) -> None: - pairs = HeldPairs(_TYPES) - for row in _rows("arrow"): - pairs.append(row) - pairs.spill() - child = os.fork() - if child == 0: - try: - ok = [t.as_dict()["trial"] for t, _ in pairs] == list(range(_N)) - ok = ok and pairs[4][0].as_dict()["trial"] == 4 - os._exit(0 if ok else 1) - except BaseException: - os._exit(2) - assert os.waitstatus_to_exitcode(os.waitpid(child, 0)[1]) == 0 - assert _files(spilled) - - -def test_rows_by_entry_id(spilled: Path) -> None: - rows = _rows("mixed") - held = HeldRows(_TYPES) - for n, row in enumerate(rows): - held[b"%d" % n] = row - held.spill() - held[b"0"] = rows[3] - assert list(held) == [b"%d" % n for n in range(_N)] - assert len(held) == _N and b"4" in held and b"x" not in held - assert held.get(b"x") is None - _is_exactly(held[b"0"][1], rows[3][1]) - assert not held.has_data(b"1") and held.has_data(b"0") and not held.has_data(b"x") - assert not held.is_kept(b"x") - del held[b"2"] - assert b"2" not in held - held.clear() - assert not held and not _files(spilled) - - -class _FullDisk: - def __init__(self, room: int) -> None: - self.room, self.calls, self.real = room, 0, pa.ipc.new_file - - def __call__(self, *args: Any, **kwargs: Any) -> Any: - self.calls += 1 - if self.calls > self.room: - raise OSError(errno.ENOSPC, "synthetic full disk") - return self.real(*args, **kwargs) - - -def test_a_chunk_that_cannot_be_written_leaves_every_pair_once( - spilled: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - rows = _rows("arrow") - pairs = HeldPairs(_TYPES) - for row in rows: - pairs.append(row) - with monkeypatch.context() as patched: - patched.setattr(pa.ipc, "new_file", _FullDisk(1)) - with pytest.raises(OSError, match="synthetic full disk"): - pairs.spill() - for retry in (False, True): - if retry: - pairs.spill() - assert [t.as_dict()["trial"] for t, _ in pairs] == list(range(_N)) - - -@pytest.mark.parametrize("step", ["_candidate", "_PythonSide"]) -def test_a_failed_allocation_leaves_every_pair_once( - spilled: Path, monkeypatch: pytest.MonkeyPatch, step: str -) -> None: - pairs = HeldPairs(_TYPES) - for row in _rows("arrow"): - pairs.append(row) - - def fail(*_: Any) -> Any: - raise MemoryError("synthetic") - - with monkeypatch.context() as patched: - patched.setattr(held_rows, step, fail) - with pytest.raises(MemoryError): - pairs.spill() - pairs.spill() - assert [t.as_dict()["trial"] for t, _ in pairs] == list(range(_N)) - - -# --------------------------------------------------------------------------- -# Job nodes -# --------------------------------------------------------------------------- - - -@function_pod(output_keys=["total", "label"], version="v0.0") -def _numbers(a: int, b: int) -> tuple[int, str]: - return a + b, f"{a}" - - -@function_pod(output_keys="seen", version="v0.0") -def _array(a: int, b: int) -> np.ndarray: # pyright: ignore[reportMissingTypeArgument] # the declared type under test - return np.arange(a + b) - - -@function_pod(output_keys="seen", version="v0.0") -def _some(a: int, b: int) -> int | None: - return None if a % 4 == 0 else a - - -_DELIVERED: list[int] = [] - - -@function_pod(output_keys="point", version="v0.0") -def _instance(a: int, b: int) -> Point: - return FarPoint(a, b) if a % 2 else Point(a) - - -@side_effect_pod -def _deliver(a: int, b: int, ctx: Any) -> None: - _DELIVERED.append(a) - - -def _source(rows: int = _N) -> ArrowTableSource: - numbers = list(range(rows)) - return ArrowTableSource( - pa.table( - { - "subject": [f"s{n % 3}" for n in numbers], - "trial": numbers, - "a": numbers, - "b": [n * 10 for n in numbers], - }, - schema=pa.schema( - [ - pa.field("subject", pa.large_string(), nullable=False), - *( - pa.field(name, pa.int64(), nullable=False) - for name in ("trial", "a", "b") - ), - ] - ), - ), - tag_columns=["subject", "trial"], - tag_only_columns=True, - record_id_columns=["trial"], - source_id="numbers", - ) - - -_PODS: dict[str, Any] = { - "numbers": _numbers, - "arrays": _array, - "instances": _instance, - "some": _some, - "effect": _deliver, -} - - -def _job(pod: str, database: Any = None) -> PipelineJob: - with PipelineJob( - name=f"held_{pod}", database=database or InMemoryArrowDatabase() - ) as job: - source = _source() - step = _PODS[pod] - out = getattr(step, "pod", step).process(source, label="out") - _ = out.select_tag_columns(["trial"], label="after") - return job - - -def _run(job: PipelineJob, orchestrator: str) -> Any: - if orchestrator == "sync": - return job.run() - return job.run(orchestrator=AsyncPipelineOrchestrator()) - - -def _by_trial(table: pa.Table) -> pa.Table: - names = [n for n in table.column_names if "record" not in n] - return table.select(names).sort_by("trial") - - -def _view(node: Any) -> dict[str, Any]: - # Record ids of computed results are random; everything else is compared. - table = node.as_table(columns={"system_tags": True}) - return { - "table": table.to_pylist(), - "schema": table.schema, - "rows": [ - (t.as_dict(), {k: repr(v) for k, v in d.as_dict(all_info=False).items()}) - for t, d in node.iter_data() - ], - "types": [[type(v) for v in d.as_dict().values()] for _, d in node.iter_data()], - "count": node.held_row_count(), - "head": node.head(4).table.to_pylist(), - "head_rows": node.head(4).total_rows, - "sorted_head": node.head(4, columns={"sort_by_tags": True}).table.to_pylist(), - "hash": node.content_hash(), - } - - -@pytest.mark.parametrize("pod", list(_PODS)) -def test_a_sync_node_over_chunks_reads_exactly_as_one_over_pairs( - spilled: Path, pod: str -) -> None: - job = _job(pod) - _ = _run(job, "sync") - found = {label: _view(job.nodes[label]) for label in ("out",)} - after = job.nodes["after"].as_table(columns={"system_tags": True}) - assert bool(_files(spilled)) == (pod not in ("arrays", "instances")) - - with pytest.MonkeyPatch.context() as patched: - patched.setattr(held_rows, "HELD_CHUNK_ROWS", 8192) - plain = _job(pod) - _ = _run(plain, "sync") - expected = {label: _view(plain.nodes[label]) for label in ("out",)} - expected_after = plain.nodes["after"].as_table(columns={"system_tags": True}) - - assert repr(found) == repr(expected) - assert after.equals(expected_after) - # Tables, source info included, are the rows': the same on every read. - node = job.nodes["out"] - first = node.as_table(all_info=True) - ids = [d.datagram_uuid for _, d in node.iter_data()] - assert ids == [d.datagram_uuid for _, d in node.iter_data()] - node._cached_output_table = None - assert node.as_table(all_info=True).to_pylist() == first.to_pylist() - - -@pytest.mark.parametrize("pod", list(_PODS)) -def test_an_async_node_over_chunks_holds_the_sync_rows(spilled: Path, pod: str) -> None: - sync_job, async_job = _job(pod), _job(pod) - _ = _run(sync_job, "sync") - _ = _run(async_job, "async") - for label in ("out", "after"): - found = _by_trial(async_job.nodes[label].as_table()) - expected = _by_trial(sync_job.nodes[label].as_table()) - assert found.schema.equals(expected.schema, check_metadata=True) - assert repr(found.to_pylist()) == repr(expected.to_pylist()) - - -@pytest.mark.parametrize("orchestrator", ["sync", "async"]) -@pytest.mark.parametrize("pod", list(_PODS)) -def test_clearing_a_node_removes_its_files( - spilled: Path, pod: str, orchestrator: str -) -> None: - job = _job(pod) - _ = _run(job, orchestrator) - table = job.nodes["out"].as_table() - values = repr(table.to_pylist()) - for node in job.nodes.values(): - if hasattr(node, "clear_cache"): - node.clear_cache() - assert not _files(spilled) - assert job.nodes["out"].as_table().num_rows == 0 - assert repr(table.to_pylist()) == values - - -@pytest.mark.parametrize("orchestrator", ["sync", "async"]) -def test_stored_results_are_loaded_and_held_in_chunks( - spilled: Path, orchestrator: str -) -> None: - database = InMemoryArrowDatabase() - first = _job("numbers", database) - _ = _run(first, "sync") - expected = _by_trial(first.nodes["out"].as_table(columns={"source": True})) - - again = _job("numbers", database) - _ = _run(again, orchestrator) - - found = _by_trial(again.nodes["out"].as_table(columns={"source": True})) - assert found.to_pylist() == expected.to_pylist() - assert _files(spilled) - loaded = _job("numbers", database) - _ = loaded.run(load_only=True) - assert ( - _by_trial(loaded.nodes["out"].as_table(columns={"source": True})).to_pylist() - == expected.to_pylist() - ) - - -@pytest.mark.parametrize("orchestrator", ["sync", "async"]) -@pytest.mark.parametrize("pod", ["numbers", "effect"]) -@pytest.mark.parametrize("room", [0, 1]) -def test_a_full_disk_fails_the_run_and_leaves_no_file( - spilled: Path, - monkeypatch: pytest.MonkeyPatch, - pod: str, - orchestrator: str, - room: int, -) -> None: - """It is no row failure: the run fails, whatever the error policy.""" - job = _job(pod) - with monkeypatch.context() as patched: - patched.setattr(pa.ipc, "new_file", _FullDisk(room)) - with pytest.raises(BaseException) as kept: - _ = _run(job, orchestrator) - assert not _files(spilled), f"left behind with {kept.value!r} kept" - assert job.nodes["out"].as_table().num_rows == 0 - _ = _run(job, orchestrator) - assert job.nodes["out"].as_table().num_rows == _N - - -@pytest.mark.parametrize("pod", ["numbers", "effect"]) -def test_a_cancelled_run_leaves_no_file(spilled: Path, pod: str) -> None: - job = _job(pod) - node = job.nodes["out"] - - async def run() -> BaseException: - given: Channel[tuple[Any, Any]] = Channel(buffer_size=_N) - output: Channel[tuple[Any, Any]] = Channel(buffer_size=_N) - if pod == "effect": - started = node.async_execute([given.reader], output.writer) - else: - started = node.async_execute(given.reader, output.writer) - task = asyncio.create_task(started) - for row in _source().iter_data(): - await given.writer.send(row) - for _ in range(_N): - _ = await output.reader.receive() - assert _files(spilled) - _ = task.cancel() - with pytest.raises(asyncio.CancelledError) as kept: - await task - return kept.value - - error = asyncio.run(run()) - assert not _files(spilled), f"left behind with {error!r} kept" - assert node.as_table().num_rows == 0 - - -def test_a_side_effect_nodes_read_goes_on_after_it_is_cleared(spilled: Path) -> None: - job = _job("effect") - _ = _run(job, "sync") - reading: Iterator[Any] = job.nodes["out"].iter_data() - first = next(reading) - job.nodes["out"].clear_cache() - assert [t.as_dict()["trial"] for t, _ in [first, *reading]] == list(range(_N)) From bb7bab572abe477c05ee3063157d702898b6f7c6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 00:46:13 -0800 Subject: [PATCH 22/26] docs(specs): answer the review of the streaming design and its measurements (ITL-1464) The design states that the cache root must be on disk, bounds the pairs of one join match, qualifies the SQLite primary-key trust, counts small results kept in memory and narrows the preview's side-effect promise. The measurement steps each use their own emptied result location, and setup runs under the memory guard. One test runs an operator over the source in a job, sync and async, in two tag orders. Co-Authored-By: Claude Fable 5.2 --- docs/dev/specs/itl-1464-streaming-design.md | 45 ++++++++++-- docs/dev/specs/itl-1464/measure.py | 26 +++++-- docs/dev/specs/itl-1464/run_measurements.py | 71 ++++++++++++------- .../test_spiraldb_table_source_tokens.py | 44 ++++++++++++ 4 files changed, 148 insertions(+), 38 deletions(-) diff --git a/docs/dev/specs/itl-1464-streaming-design.md b/docs/dev/specs/itl-1464-streaming-design.md index 16ff3c515..67cd7c3bb 100644 --- a/docs/dev/specs/itl-1464-streaming-design.md +++ b/docs/dev/specs/itl-1464-streaming-design.md @@ -61,6 +61,15 @@ One mechanism holds rows that are computed but not in memory. 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. +- **The cache root must be on disk.** The memory promise of section 8 holds only when the + cache root is on storage backed by a disk. On a memory-backed file system (`tmpfs` or + `ramfs`, which some Linux systems mount as the temporary directory) a cache file's + bytes are memory however the file is read, and dropping mapped pages frees nothing: the + job then holds every cached row in memory, as before this design. Proposed (part of + L1): the default stays the system's temporary directory; where Orcapod can tell that + the cache root is memory-backed (Linux: the file system type of the directory), it + issues one warning per process naming the directory and `local_cache_dir`, and the + stated bound then does not apply. It never moves the cache to another place on its own. - **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 @@ -153,7 +162,9 @@ Decisions the issue lists: 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. +- A preview refuses a `SideEffectPod` in the chain. That is all it enforces: it does not + exclude what a user function in a function pod does outside Orcapod (a write to an + external service). Whether a preview runs user functions is open (P2). ## 5. Batch-wise execution, per operator kind @@ -240,6 +251,17 @@ join keeps, per row that can still match, an index entry: batch with the sync path's own rule (`join._matched_pairs`); and - the row's reference, `(batch number, row number)`: 8 bytes. +**The pairs of one match are bounded too.** The size of an arriving batch does not bound +the number of pairs it matches: rows of the batch that share a key with many indexed rows +give their product. So no match builds its whole pair frame at once. Before matching, the +join counts the pairs per arriving row (the batch's keys against a count of index entries +per key, kept beside the index: at most one count per arriving row) and cuts the batch +into row ranges whose pairs fit a pair budget (proposed 1,048,576 pairs, 16 MiB of row +references). One arriving row whose matches alone pass the budget is matched against +successive ranges of that key's index entries. Each range is matched, fetched, sent and +let go before the next, so the transient is `16 bytes × pair budget` plus one output +batch, whatever the keys hold. **OPEN (J3)**: the pair budget. + 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. @@ -329,7 +351,8 @@ uniqueness over the key, Orcapod trusts it without the running check. | Source | Guaranteed by the store? | |---|---| -| SQLite, PostgreSQL table, key = the table's primary key | yes: the database enforces it | +| PostgreSQL table, key = the table's primary key | yes: the database enforces it (a primary key column is never null) | +| SQLite table, key = the table's primary key | yes when every key column is declared `NOT NULL`, or is the `INTEGER PRIMARY KEY`, or the table is `WITHOUT ROWID`; otherwise no (such a column can hold NULL, and SQLite keeps rows with a NULL key apart): running check | | 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 | @@ -359,6 +382,7 @@ uniqueness over the key, Orcapod trusts it without the running check. | 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) | | +| Any case, while one range of pairs is matched | the pairs of that range (two row references each) and its output batch | 16 bytes × pair budget + one output batch, whatever the keys hold | 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 @@ -445,15 +469,21 @@ With sections 2 to 7 in place, for a job run by the async orchestrator: | 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 join | its keys-only index (section 6), and the pairs of one range being matched (at most the pair budget) | +| A job node after the run | a reference (a file name or a set of stored entries), or its rows when they are below the in-memory threshold (section 2) | | 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`. +`(batches in flight) × (batch bytes) + (key bytes + 8) × (rows indexed by joins and groupings) + 16 × (rows of verified sources) + 16 × (pair budget) × (joins matching at once) + (small results kept in memory) + the largest single row`. 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. +Small results kept in memory are part of the bound, and a per-stream threshold alone +does not limit them: 100 nodes each keeping 63 MiB hold 6.2 GiB. So the threshold comes +with a total for the process (proposed 512 MiB, part of L2): a result that would take the +kept total past it goes to the cache whatever its size, and the term is at most that +total. The bound also assumes a cache root on disk (section 2). + **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. @@ -511,8 +541,8 @@ holds rows (cache files, `as_table()`, the sync path). | 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 | +| L1 | Where the local cache lives by default; what happens when that place is memory-backed | the system temporary directory, configurable; a warning when it is memory-backed, and no bound then | +| L2 | The size below which rows stay in memory, and the total kept in memory per process | 64 MiB per stream, 512 MiB in total | | 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 | @@ -520,6 +550,7 @@ holds rows (cache files, `as_table()`, the sync path). | 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 | +| J3 | The pair budget of one match range | 1,048,576 pairs (16 MiB) | | 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 | diff --git a/docs/dev/specs/itl-1464/measure.py b/docs/dev/specs/itl-1464/measure.py index 629f2d549..4332463de 100644 --- a/docs/dev/specs/itl-1464/measure.py +++ b/docs/dev/specs/itl-1464/measure.py @@ -26,6 +26,7 @@ import gc import json import resource +import shutil import sys import time import tracemalloc @@ -333,18 +334,29 @@ def step_function_pod() -> tuple[int, int, Any]: return _raw(SERIES).nbytes, table.nbytes, table -def _job(store: Path) -> Any: +def _fresh_results(store: Path, step: str) -> str: + """Return a result location no other step uses, emptied of any earlier run. + + A job step that found another step's (or its own earlier run's) stored function + results would skip that work, and its figures would not compare with the others'. + """ + results = store / f"results_{step}" + shutil.rmtree(results, ignore_errors=True) + return str(results) + + +def _job(store: Path, step: str) -> Any: from orcapod import PipelineJob from orcapod.databases import DeltaTableDatabase - database = DeltaTableDatabase(str(store / "results")) + database = DeltaTableDatabase(_fresh_results(store, step)) 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 = _job(store, "job_run") job.run() return _raw(SERIES).nbytes, 0, job @@ -352,7 +364,7 @@ def step_job_run(store: Path) -> tuple[int, int, Any]: def step_job_run_async_unkept(store: Path) -> tuple[int, int, Any]: from orcapod.pipeline import AsyncPipelineOrchestrator - job = _job(store) + job = _job(store, "job_run_async_unkept") job.run(orchestrator=AsyncPipelineOrchestrator(), materialize_results=False) return _raw(SERIES).nbytes, 0, job @@ -360,7 +372,7 @@ def step_job_run_async_unkept(store: Path) -> tuple[int, int, Any]: def step_job_run_async(store: Path) -> tuple[int, int, Any]: from orcapod.pipeline import AsyncPipelineOrchestrator - job = _job(store) + job = _job(store, "job_run_async") job.run(orchestrator=AsyncPipelineOrchestrator()) return _raw(SERIES).nbytes, 0, job @@ -385,7 +397,9 @@ def step(store: Path) -> tuple[int, int, Any]: from orcapod.databases import DeltaTableDatabase from orcapod.pipeline import AsyncPipelineOrchestrator - database = DeltaTableDatabase(str(store / f"results_{chain}_{orchestrator}")) + database = DeltaTableDatabase( + _fresh_results(store, f"job_{chain}_{orchestrator}") + ) with PipelineJob(name=f"only_{chain}", database=database) as job: _operator_chains()[chain]() if orchestrator == "async": diff --git a/docs/dev/specs/itl-1464/run_measurements.py b/docs/dev/specs/itl-1464/run_measurements.py index ac72ac539..8f4eef917 100644 --- a/docs/dev/specs/itl-1464/run_measurements.py +++ b/docs/dev/specs/itl-1464/run_measurements.py @@ -48,26 +48,58 @@ 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[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], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - ) +def _guarded( + command: list[str], guard_bytes: int, *, capture: bool +) -> tuple[int | None, int, str, str]: + """Run a command; kill it when its resident memory passes the guard. + + Returns: + The resident memory at which it was killed (``None`` when it ran to its end), + its return code, and its captured output and error text (empty when not + captured). + """ + pipe = subprocess.PIPE if capture else None + process = subprocess.Popen(command, stdout=pipe, stderr=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} + return seen, process.returncode, "", "" time.sleep(0.2) out, err = process.communicate() - if process.returncode != 0: + return None, process.returncode, out or "", err or "" + + +def run_setup(store: Path, rows: int, guard_bytes: int) -> None: + """Write the synthetic tables, under the same guard as every step.""" + killed_at, code, _, _ = _guarded( + [sys.executable, str(MEASURE), "setup", "--store", str(store)] + + ["--rows", str(rows)], + guard_bytes, + capture=False, + ) + if killed_at is not None: + raise SystemExit( + f"setup killed: resident memory {killed_at} bytes passed the guard" + ) + if code != 0: + raise SystemExit(f"setup failed with exit code {code}") + + +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.""" + killed_at, code, out, err = _guarded( + [sys.executable, str(MEASURE), step, "--store", str(store), *extra], + guard_bytes, + capture=True, + ) + if killed_at is not None: + return {"step": step, "killed": True, "rss_when_killed_bytes": killed_at} + if code != 0: return {"step": step, "failed": True, "error": err.strip()[-2000:]} record = json.loads(out.strip().splitlines()[-1]) for line in err.splitlines(): @@ -87,21 +119,10 @@ def main() -> None: parser.add_argument("--skip-setup", action="store_true") args = parser.parse_args() + guard = int(args.guard_gb * 1024**3) if not args.skip_setup: - subprocess.run( - [ - sys.executable, - str(MEASURE), - "setup", - "--store", - str(args.store), - "--rows", - str(args.rows), - ], - check=True, - ) + run_setup(args.store, args.rows, guard) 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) diff --git a/tests/test_core/sources/test_spiraldb_table_source_tokens.py b/tests/test_core/sources/test_spiraldb_table_source_tokens.py index 658ef73c6..42ea4fa79 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_tokens.py +++ b/tests/test_core/sources/test_spiraldb_table_source_tokens.py @@ -15,7 +15,10 @@ import pyarrow as pa import pytest +from orcapod import PipelineJob from orcapod.core.sources import spiraldb_table_source as source_module +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.sources import SpiralDBTableSource from orcapod.utils import arrow_utils from tests.test_databases import fake_spiral_sdk @@ -201,6 +204,47 @@ def test_an_operator_over_the_source_still_reads_its_tokens( assert table.equals(expected) +def _job_rows(tag_columns: list[str], tag_only: bool, orchestrator: Any) -> pa.Table: + """Run ``drop_nulls`` over the source as a job's only node; return its rows.""" + source = SpiralDBTableSource( + _PROJECT, "event", tag_columns=tag_columns, tag_only_columns=tag_only + ) + with PipelineJob(name="tokens", database=InMemoryArrowDatabase()) as job: + source.drop_nulls(["quality", "amplitude"], label="kept") + job.run(orchestrator=orchestrator) + return job.nodes["kept"].as_table(all_info=True) + + +def _row_set(table: pa.Table) -> set[tuple[tuple[str, Any], ...]]: + return {tuple(sorted(row.items())) for row in table.to_pylist()} + + +@pytest.mark.parametrize("tag_only", [False, True], ids=["data_tags", "tag_only"]) +@pytest.mark.parametrize( + "tag_columns", [["subject_id", "timestamp"], ["timestamp", "subject_id"]] +) +def test_an_operator_in_a_job_reads_the_tokens_on_both_paths( + project: Any, + monkeypatch: pytest.MonkeyPatch, + tag_columns: list[str], + tag_only: bool, +) -> None: + sync = _job_rows(tag_columns, tag_only, None) + on_async = _job_rows(tag_columns, tag_only, AsyncPipelineOrchestrator()) + + assert sync.num_rows == _ROWS - 1 + assert sync.column("_source_quality").null_count == 0 + assert sync.column("_source_amplitude").null_count == 0 + with monkeypatch.context() as patched: + _with_tokens_always(patched) + expected = _job_rows(tag_columns, tag_only, None) + # Sync is exact; async rows are compared as a set, never by order. + assert sync.schema.equals(expected.schema, check_metadata=True) + assert sync.equals(expected) + assert on_async.schema.equals(expected.schema, check_metadata=True) + assert _row_set(on_async) == _row_set(expected) + + def test_iteration_still_gives_each_row_its_tokens(project: Any) -> None: source = _source(False) From 78e581c9cd8f14674e9a855ab9806e26c110c4c2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 02:55:07 -0800 Subject: [PATCH 23/26] docs(specs): second review round of the streaming design (ITL-1464) The design names how a database-backed node read keeps the emitted order, runs a PolarsFilter per batch only for a predicate known to be row-wise, corrects the 1:1 join bound for inputs that share no key and fixes the arrival order of the bound's tests. The job test over the source covers the named columns as data, data-tags and tags, two table layouts and row multiplicity on the async path; the measurement scripts get docstrings. Co-Authored-By: Claude Fable 5.2 --- docs/dev/specs/itl-1464-streaming-design.md | 52 ++++++-- docs/dev/specs/itl-1464/measure.py | 124 ++++++++++++++++++ docs/dev/specs/itl-1464/run_measurements.py | 2 + .../test_spiraldb_table_source_tokens.py | 63 +++++++-- 4 files changed, 216 insertions(+), 25 deletions(-) diff --git a/docs/dev/specs/itl-1464-streaming-design.md b/docs/dev/specs/itl-1464-streaming-design.md index 67cd7c3bb..a192e1eb4 100644 --- a/docs/dev/specs/itl-1464-streaming-design.md +++ b/docs/dev/specs/itl-1464-streaming-design.md @@ -105,6 +105,15 @@ current run's rows, not the rows: cache, where the run wrote them; - below the in-memory threshold, the rows are kept as today. +A read from the database keeps the run's order. A database is a set of rows: the order a +store returns them in (key order, file order) is never a result, and no stored column +holds a position. So the reference of a function node or a `LOG`-mode operator node is +the run's entry ids *in the order the run emitted them* (one id per row; held as rows +are, so in the local cache above the in-memory threshold). A page read takes the ids of +its page from that list, fetches those entries from the database, and puts them in the +list's order before returning them. The sync read is then the emitted order (ITL-1441) +whatever the store's own order is; nothing is added to a stored table. + 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 @@ -174,7 +183,7 @@ join kernels). This design finishes the wiring and adds what the memory bound ne | 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 | +| Row by row (`ROW_BY_ROW`) | `Select*`/`Drop*` columns, `MapTags`, `MapData`, `MapColumns`, `DropNulls`, `Filter`, `PolarsFilter` with a predicate known to be row-wise (below), `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 | @@ -184,11 +193,21 @@ join kernels). This design finishes the wiring and adds what the memory bound ne 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. +- `PolarsFilter` has no async form today, so it gathers its input. The sync path applies + the predicate to the whole table and accepts any expression, also one that reads other + rows (`pl.col("x") > pl.col("x").mean()`, a window, a rank): applied per batch, such a + predicate would keep other rows than the sync path does. So a predicate runs per batch + only when it is known to be row-wise, and otherwise over the whole input, as today + (a barrier: the same rows as the sync path, and no memory bound for that filter). + Nothing the sync path accepts is refused and no result changes. "Known to be row-wise" + is decided from the expression's tree, by a closed list of node kinds (a column, a + literal, comparison, boolean and arithmetic operators, null and NaN tests, `is_in` a + literal list, `is_between`, string predicates on a literal pattern, casts); a node not + on the list means the whole input. Polars offers no public test for this, so the list + is Orcapod's and starts short. The choice is per predicate, not per class: the + `ROW_BY_ROW` declaration of `PolarsFilter` is read from the instance. **OPEN (B1)**: + the list, and whether a filter that falls back to the whole input says so (proposed: one + info log naming the node kind, no warning). - `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 @@ -378,7 +397,7 @@ uniqueness over the key, Orcapod trusts it without the running check. | 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 | +| 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 of both inputs, while both are open). Worst case, inputs that share no key and arrive in step (sorted or not): nothing matches and both indexes are whole, index × (n + m). One input arriving entirely before the other: index × (that input), since nothing more is kept for the second once the first has closed. Inputs with the same keys arriving in step: the out-of-order window only. Without an "in tag order" certificate (J2) an unmatched entry cannot be dropped before the other input closes | | 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) | | @@ -394,7 +413,9 @@ rows between the two read positions. That needs a second certificate, "in tag or 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. +whenever the inputs hold the same keys and happen to arrive in step. It gives nothing for +keys that never match: only this certificate would let a join drop an entry whose key +the other input has passed. **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, @@ -418,8 +439,12 @@ back-pressure, and why the worst case counts both sides. - 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. + grow as the index does (key bytes × rows), not as the rows do. For "unique side small", + the arrival order is fixed by the test: with the unique side read to its end and closed + before the first row of the other side arrives, a 10 times larger other side must not + move the peak; with the other side arriving entirely first (the early-arrival bound), + the peak must grow by the index of those rows and by no more. 1:1 has a third run, + inputs that share no key arriving in step, whose peak must be the index of both. - 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 @@ -470,7 +495,7 @@ With sections 2 to 7 in place, for a job run by the async orchestrator: | 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), and the pairs of one range being matched (at most the pair budget) | -| A job node after the run | a reference (a file name or a set of stored entries), or its rows when they are below the in-memory threshold (section 2) | +| A job node after the run | a reference (a file name, or the run's entry ids in emitted order, themselves in the cache when large), or its rows when they are below the in-memory threshold (section 2) | | A view | the rows shown | **The bound to state to users**: peak memory of an async job is @@ -521,7 +546,8 @@ value. 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. + stages), run a `PolarsFilter` whose predicate is known to be row-wise per batch (B1). + 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)`. @@ -547,7 +573,7 @@ holds rows (cache files, `as_table()`, the sync path). | 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 | +| B1 | `PolarsFilter` with an expression that is not known to be row-wise | run it over the whole input, as today (same rows as sync, no bound); per batch only for a closed list of row-wise node kinds | | 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 | | J3 | The pair budget of one match range | 1,048,576 pairs (16 MiB) | diff --git a/docs/dev/specs/itl-1464/measure.py b/docs/dev/specs/itl-1464/measure.py index 4332463de..35d9f425b 100644 --- a/docs/dev/specs/itl-1464/measure.py +++ b/docs/dev/specs/itl-1464/measure.py @@ -94,6 +94,7 @@ def _constant(value: Any, kind: pa.DataType, rows: int) -> pa.Array[Any]: + """Return an array of ``rows`` copies of one value.""" return pa.array([value] * rows, kind) @@ -194,12 +195,14 @@ def setup(rows: int) -> None: def _source(name: str) -> Any: + """Return the SpiralDB source over the named synthetic table, with no row limit.""" from orcapod.core.sources import SpiralDBTableSource return SpiralDBTableSource(PROJECT, name, max_rows=None) def _raw(name: str) -> pa.Table: + """Return the named synthetic table as the fake store holds it.""" store = fake._store() found = store.find(PROJECT, "default", name) assert found is not None @@ -215,11 +218,23 @@ def step_raw_copy() -> tuple[int, int, Any]: def step_as_table() -> tuple[int, int, Any]: + """Read the time series with ``as_table()``. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ table = _source(SERIES).as_table() return _raw(SERIES).nbytes, table.nbytes, table def step_as_table_all_info() -> tuple[int, int, Any]: + """Read the time series with every column group; report each group's bytes. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ 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: @@ -237,11 +252,23 @@ def step_as_table_all_info() -> tuple[int, int, Any]: def step_run() -> tuple[int, int, Any]: + """Call ``run()`` on the time series source and keep its view. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ view = _source(SERIES).run() return _raw(SERIES).nbytes, 0, view def step_run_then_as_table() -> tuple[int, int, Any]: + """Call ``run()`` and then ``as_table()`` on one source. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ source = _source(SERIES) view = source.run() table = source.as_table() @@ -249,11 +276,23 @@ def step_run_then_as_table() -> tuple[int, int, Any]: def step_as_polars_df() -> tuple[int, int, Any]: + """Read the time series as a Polars data frame. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ frame = _source(SERIES).as_polars_df() return _raw(SERIES).nbytes, int(frame.estimated_size()), frame def step_iterate() -> tuple[int, int, Any]: + """Iterate the time series row by row, reading no value. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ count = 0 for _tag, _data in _source(SERIES): count += 1 @@ -261,6 +300,12 @@ def step_iterate() -> tuple[int, int, Any]: def step_iterate_read_one_value() -> tuple[int, int, Any]: + """Iterate the time series row by row, reading one value of each row. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ total = 0.0 for _tag, data in _source(SERIES): total += data["level"] @@ -268,16 +313,34 @@ def step_iterate_read_one_value() -> tuple[int, int, Any]: def step_flow() -> tuple[int, int, Any]: + """Call ``flow()`` on the time series source. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ pairs = _source(SERIES).flow() return _raw(SERIES).nbytes, 0, pairs def step_drop_nulls() -> tuple[int, int, Any]: + """Apply ``drop_nulls`` to the time series and read the result. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ 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]: + """Apply ``polars_filter`` to the time series and read the result. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ import polars as pl table = _source(SERIES).polars_filter(pl.col("level") > 0.5).as_table() @@ -285,16 +348,29 @@ def step_polars_filter() -> tuple[int, int, Any]: def step_map_data() -> tuple[int, int, Any]: + """Rename one data column of the time series and read the result. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ table = _source(SERIES).map_data({"level": "pupil"}).as_table() return _raw(SERIES).nbytes, table.nbytes, table def step_join() -> tuple[int, int, Any]: + """Join the event table with its lookup table and read the result. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ table = _source(EVENTS).join(_source(LOCATIONS)).as_table() return _raw(EVENTS).nbytes + _raw(LOCATIONS).nbytes, table.nbytes, table def _grouped_series() -> Any: + """Return the time series with nulls dropped, grouped by block, one column renamed.""" return ( _source(SERIES) .drop_nulls(["x_small", "y_small"]) @@ -304,22 +380,36 @@ def _grouped_series() -> Any: def step_group_by() -> tuple[int, int, Any]: + """Group the time series by block and read the result. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ 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]: + """Read the three-operator chain of ``_grouped_series``. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ table = _grouped_series().as_table() return _raw(SERIES).nbytes, table.nbytes, table def _onsets_pod() -> Any: + """Return the function pod that finds onsets in one block's samples.""" from orcapod import function_pod @function_pod(output_keys="onset") def onsets( sample_time: list[int], x_small: list[float], y_small: list[float] ) -> list[int]: + """Return the times at which the speed falls below the threshold.""" 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 @@ -330,6 +420,12 @@ def onsets( def step_function_pod() -> tuple[int, int, Any]: + """Apply the onsets function pod to the grouped time series, outside a job. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ table = _onsets_pod().pod(_grouped_series()).as_table() return _raw(SERIES).nbytes, table.nbytes, table @@ -346,6 +442,7 @@ def _fresh_results(store: Path, step: str) -> str: def _job(store: Path, step: str) -> Any: + """Return the job of the whole chain, storing into the step's own fresh location.""" from orcapod import PipelineJob from orcapod.databases import DeltaTableDatabase @@ -356,12 +453,24 @@ def _job(store: Path, step: str) -> Any: def step_job_run(store: Path) -> tuple[int, int, Any]: + """Run the whole chain as a job on the sync orchestrator. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ job = _job(store, "job_run") job.run() return _raw(SERIES).nbytes, 0, job def step_job_run_async_unkept(store: Path) -> tuple[int, int, Any]: + """Run the whole chain as a job on the async orchestrator, which keeps no rows. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ from orcapod.pipeline import AsyncPipelineOrchestrator job = _job(store, "job_run_async_unkept") @@ -370,6 +479,12 @@ def step_job_run_async_unkept(store: Path) -> tuple[int, int, Any]: def step_job_run_async(store: Path) -> tuple[int, int, Any]: + """Run the whole chain as a job on the async orchestrator. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ from orcapod.pipeline import AsyncPipelineOrchestrator job = _job(store, "job_run_async") @@ -378,6 +493,7 @@ def step_job_run_async(store: Path) -> tuple[int, int, Any]: def _operator_chains() -> dict[str, Callable[[], Any]]: + """Return, by name, a builder of each one-operator stream measured as a job.""" import polars as pl return { @@ -393,6 +509,12 @@ 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]: + """Run the one-operator job on the named orchestrator. + + Returns: + The input's Arrow bytes, the output's Arrow bytes (0 when no table is + returned), and the result, which the caller keeps alive while it measures. + """ from orcapod import PipelineJob from orcapod.databases import DeltaTableDatabase from orcapod.pipeline import AsyncPipelineOrchestrator @@ -444,11 +566,13 @@ def step(store: Path) -> tuple[int, int, Any]: def _peak_rss_bytes() -> int: + """Return this process's peak resident memory, in bytes.""" peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss return peak if sys.platform == "darwin" else peak * 1024 def main() -> None: + """Run one step, or the setup, and print the step's measurements as one JSON line.""" parser = argparse.ArgumentParser() parser.add_argument("step", choices=["setup", *STEPS]) parser.add_argument("--store", required=True, type=Path) diff --git a/docs/dev/specs/itl-1464/run_measurements.py b/docs/dev/specs/itl-1464/run_measurements.py index 8f4eef917..475bca784 100644 --- a/docs/dev/specs/itl-1464/run_measurements.py +++ b/docs/dev/specs/itl-1464/run_measurements.py @@ -42,6 +42,7 @@ def _rss_bytes(pid: int) -> int: + """Return the resident memory of a process, in bytes (0 once it has ended).""" found = subprocess.run( ["ps", "-o", "rss=", "-p", str(pid)], capture_output=True, text=True ).stdout.strip() @@ -109,6 +110,7 @@ def run_step( def main() -> None: + """Run the setup, then every requested step, appending one JSON record per step.""" parser = argparse.ArgumentParser() parser.add_argument("--store", required=True, type=Path) parser.add_argument("--rows", type=int, default=2_200_000) diff --git a/tests/test_core/sources/test_spiraldb_table_source_tokens.py b/tests/test_core/sources/test_spiraldb_table_source_tokens.py index 42ea4fa79..6f74a1e25 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_tokens.py +++ b/tests/test_core/sources/test_spiraldb_table_source_tokens.py @@ -9,6 +9,7 @@ from __future__ import annotations +import collections from pathlib import Path from typing import Any @@ -20,6 +21,7 @@ from orcapod.databases import InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.sources import SpiralDBTableSource +from orcapod.system_constants import constants from orcapod.utils import arrow_utils from tests.test_databases import fake_spiral_sdk @@ -67,6 +69,10 @@ def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): with fake_spiral_sdk.install(tmp_path / "spiral"): made = fake_spiral_sdk.ExternalProject(_PROJECT) made.create_table("default.event", key_schema=_KEYS).write(_rows()) + # The same rows with the value columns laid out in the other order. + made.create_table("default.event_other_layout", key_schema=_KEYS).write( + _rows().select(["subject_id", "timestamp", "quality", "amplitude"]) + ) yield made @@ -204,45 +210,78 @@ def test_an_operator_over_the_source_still_reads_its_tokens( assert table.equals(expected) -def _job_rows(tag_columns: list[str], tag_only: bool, orchestrator: Any) -> pa.Table: +def _job_rows( + table: str, + tag_columns: list[str], + tag_only: bool, + dropped: list[str], + orchestrator: Any, +) -> pa.Table: """Run ``drop_nulls`` over the source as a job's only node; return its rows.""" source = SpiralDBTableSource( - _PROJECT, "event", tag_columns=tag_columns, tag_only_columns=tag_only + _PROJECT, table, tag_columns=tag_columns, tag_only_columns=tag_only ) with PipelineJob(name="tokens", database=InMemoryArrowDatabase()) as job: - source.drop_nulls(["quality", "amplitude"], label="kept") + source.drop_nulls(dropped, label="kept") job.run(orchestrator=orchestrator) return job.nodes["kept"].as_table(all_info=True) -def _row_set(table: pa.Table) -> set[tuple[tuple[str, Any], ...]]: - return {tuple(sorted(row.items())) for row in table.to_pylist()} +def _row_counts(table: pa.Table) -> collections.Counter[tuple[tuple[str, Any], ...]]: + """Count each row of a table: a comparison by rows that ignores their order.""" + return collections.Counter(tuple(sorted(row.items())) for row in table.to_pylist()) + + +# The named columns in two orders, as data only and with a tag among them (a data-tag +# or a tag-only tag, by ``tag_only``). +_DROPPED = [ + ["quality", "amplitude"], + ["amplitude", "quality"], + ["quality", "subject_id", "amplitude"], + ["timestamp", "amplitude", "subject_id", "quality"], +] +@pytest.mark.parametrize("table", ["event", "event_other_layout"]) @pytest.mark.parametrize("tag_only", [False, True], ids=["data_tags", "tag_only"]) @pytest.mark.parametrize( "tag_columns", [["subject_id", "timestamp"], ["timestamp", "subject_id"]] ) +@pytest.mark.parametrize("dropped", _DROPPED, ids="-".join) def test_an_operator_in_a_job_reads_the_tokens_on_both_paths( project: Any, monkeypatch: pytest.MonkeyPatch, + table: str, tag_columns: list[str], tag_only: bool, + dropped: list[str], ) -> None: - sync = _job_rows(tag_columns, tag_only, None) - on_async = _job_rows(tag_columns, tag_only, AsyncPipelineOrchestrator()) + sync = _job_rows(table, tag_columns, tag_only, dropped, None) + on_async = _job_rows( + table, tag_columns, tag_only, dropped, AsyncPipelineOrchestrator() + ) assert sync.num_rows == _ROWS - 1 - assert sync.column("_source_quality").null_count == 0 - assert sync.column("_source_amplitude").null_count == 0 + assert on_async.num_rows == _ROWS - 1 + for name in sync.column_names: + if name.startswith("_source_"): + assert sync.column(name).null_count == 0 with monkeypatch.context() as patched: _with_tokens_always(patched) - expected = _job_rows(tag_columns, tag_only, None) - # Sync is exact; async rows are compared as a set, never by order. + expected = _job_rows(table, tag_columns, tag_only, dropped, None) + # The whole table is compared: rows, Arrow schema, system tags, tokens and row + # hashes. Sync is exact; async rows are compared by count, never by order. + assert "_content_hash" in expected.column_names + assert any( + name.startswith(constants.SYSTEM_TAG_PREFIX) for name in expected.column_names + ) assert sync.schema.equals(expected.schema, check_metadata=True) assert sync.equals(expected) assert on_async.schema.equals(expected.schema, check_metadata=True) - assert _row_set(on_async) == _row_set(expected) + assert _row_counts(on_async) == _row_counts(expected) + # The order of the named columns changes nothing. + again = _job_rows(table, tag_columns, tag_only, dropped[::-1], None) + assert again.equals(sync) def test_iteration_still_gives_each_row_its_tokens(project: Any) -> None: From d744e8d25a71f508164f29775626b24d831b7b87 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 03:54:01 -0800 Subject: [PATCH 24/26] docs(specs): third review round of the streaming design (ITL-1464) A node's reference names the stored row the run emitted (base entry id and recomputation index), the stated bound excludes steps that need their whole input, and async results are compared with sync row for row with multiplicity. Co-Authored-By: Claude Fable 5.2 --- docs/dev/specs/itl-1464-streaming-design.md | 30 ++++++++++++++++----- 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/docs/dev/specs/itl-1464-streaming-design.md b/docs/dev/specs/itl-1464-streaming-design.md index a192e1eb4..621c7dd59 100644 --- a/docs/dev/specs/itl-1464-streaming-design.md +++ b/docs/dev/specs/itl-1464-streaming-design.md @@ -109,9 +109,16 @@ A read from the database keeps the run's order. A database is a set of rows: the store returns them in (key order, file order) is never a result, and no stored column holds a position. So the reference of a function node or a `LOG`-mode operator node is the run's entry ids *in the order the run emitted them* (one id per row; held as rows -are, so in the local cache above the in-memory threshold). A page read takes the ids of -its page from that list, fetches those entries from the database, and puts them in the -list's order before returning them. The sync read is then the emitted order (ITL-1441) +are, so in the local cache above the in-memory threshold). An id here names one stored +row, not an input: for a function node it is the base entry id together with the +recomputation index of the row the run emitted (the base entry id alone is stable across +recomputation, and a lookup by it alone returns the row with the greatest index, which a +later recomputation can replace). Today's node holds base entry ids only, which is enough +while it also holds the rows; a node that reads its rows back must hold the pair. A page +read takes the ids of its page from that list, fetches exactly those rows from the +database (base entry id and index both matched, never "the newest"), and puts them in the +list's order before returning them. A row the run emitted is therefore the row every +later read of that run returns, whatever is computed afterwards. The sync read is then the emitted order (ITL-1441) whatever the store's own order is; nothing is added to a stored table. Every read keeps its meaning: `node.as_table()` returns the current run's rows (now read @@ -428,7 +435,7 @@ 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 +- Async: the output is the sync join's rows, each as often, in any order; 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 @@ -445,8 +452,10 @@ back-pressure, and why the worst case counts both sides. move the peak; with the other side arriving entirely first (the early-arrival bound), the peak must grow by the index of those rows and by no more. 1:1 has a third run, inputs that share no key arriving in step, whose peak must be the index of both. -- The differential of ITL-1347 for results: async equals sync as a set of rows, sync - equals pinned `main` byte for byte. +- The differential of ITL-1347 for results: async equals sync row for row with + multiplicity (each row as often on one path as on the other, in any order; never a + comparison of sets, which a duplicated row passes), 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. @@ -492,6 +501,7 @@ With sections 2 to 7 in place, for a job run by the async orchestrator: |---|---| | 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 step that needs its whole input (`PolarsFilter` with a predicate not known to be row-wise, `Batch` without a size) | its whole input: outside the bound below | | 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), and the pairs of one range being matched (at most the pair budget) | @@ -509,6 +519,14 @@ with a total for the process (proposed 512 MiB, part of L2): a result that would kept total past it goes to the cache whatever its size, and the term is at most that total. The bound also assumes a cache root on disk (section 2). +The formula covers a job whose every step is one of the bounded kinds of section 5. A +step that needs its whole input by definition is outside it and adds that input, whole +and in memory, for as long as the step runs: a `PolarsFilter` whose predicate is not +known to be row-wise (B1; `pl.col("x") > pl.col("x").mean()`), and `Batch` without a +size. So the statement to users is the formula +`+ (the whole input of each such step running at once)`, and a job with none of them has +the bound as written. + **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. From 5664f1d0cf521cbf109d10bc0b09f1683f4e5391 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 04:29:19 -0800 Subject: [PATCH 25/26] docs(specs): fourth review round of the streaming design (ITL-1464) The cache is read only from closed segments and waiting rows, a preview continues one open read, the join index counts its per-key counts, and a whole-input step counts its output and conversion buffers. Co-Authored-By: Claude Fable 5.2 --- docs/dev/specs/itl-1464-streaming-design.md | 60 +++++++++++++++------ 1 file changed, 44 insertions(+), 16 deletions(-) diff --git a/docs/dev/specs/itl-1464-streaming-design.md b/docs/dev/specs/itl-1464-streaming-design.md index 621c7dd59..af9862523 100644 --- a/docs/dev/specs/itl-1464-streaming-design.md +++ b/docs/dev/specs/itl-1464-streaming-design.md @@ -15,8 +15,8 @@ a session of them is a different problem. Nothing here is designed or tested for 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). +- **Async results equal the sync results row for row with multiplicity** (each row as + often as it occurs, in any order; never a comparison of sets); 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 @@ -54,9 +54,19 @@ memory. `head()` and the notebook display still never compute. 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)`. + memory-mapped), holding a stream's rows in the form the rows have on a job's edges + (ITL-1347's row-built form). A row is addressed by its number in the stream. +- **Segments: nothing reads a file that is being written.** An Arrow IPC file has its + footer (schema and batch offsets) only once it is closed, so an open file cannot be + read. A stream's rows are therefore kept as a sequence of *segments*: arriving rows + wait in memory until they pass the segment size (the in-memory threshold below), then + are written as one file of one record batch, which is closed before anything reads it. + A read, at any moment, takes rows from closed segments (mapped) and from the waiting + rows (in memory); a join that fetches rows of an input still arriving reads exactly + these. The waiting rows of each open stream are memory the process holds: at most one + segment size per stream being written, counted in section 8. A segment is deleted when + every row of it is let go, so a stream's files shrink as a join releases rows. This is + what `core/row_spool.py` (PR 559) implements. - **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 @@ -160,7 +170,12 @@ 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); + batch size doubles when a batch yields too few (a selective filter). Each further + batch continues after the last row read: the preview holds one open read of each source + for its whole duration and asks it for the next rows; it never starts a read again, so + no row is read or computed twice. A limit is pushed down into a source only when no + step of the chain can remove a row (then `n` source rows are enough); with a filter in + the chain the source read is open-ended and stopped when `n` rows have come out; - 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 @@ -275,13 +290,19 @@ 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. +- the row's reference, its row number in the cached input: 8 bytes. + +For an input that is not certified unique on the join key the join also keeps one count +per distinct key of its index (the key and 8 bytes), which the pair bound below needs. +Distinct keys can be as many as the indexed rows, so this can double that input's index; +a certified-unique input needs no counts (every count is 1). "Index" in the bounds below +includes these counts. **The pairs of one match are bounded too.** The size of an arriving batch does not bound the number of pairs it matches: rows of the batch that share a key with many indexed rows give their product. So no match builds its whole pair frame at once. Before matching, the -join counts the pairs per arriving row (the batch's keys against a count of index entries -per key, kept beside the index: at most one count per arriving row) and cuts the batch +join counts the pairs per arriving row (the batch's keys against the counts per key kept +beside the index: the lookup gives at most one count per arriving row) and cuts the batch into row ranges whose pairs fit a pair budget (proposed 1,048,576 pairs, 16 MiB of row references). One arriving row whose matches alone pass the budget is matched against successive ranges of that key's index entries. Each range is matched, fetched, sent and @@ -400,7 +421,8 @@ uniqueness over the key, Orcapod trusts it without the running check. ### 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. +8 bytes), with the per-key counts of an input that is not certified unique (at most as +much again); rows themselves are in the cache, on disk. | Case | What is held in memory | Bound | |---|---|---| @@ -444,7 +466,10 @@ back-pressure, and why the worst case counts both sides. ### 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 + unique side small, many to many), at two sizes a factor of 10 apart (the expected index + includes the per-key counts for the many-to-many case and for the non-unique side, and + each run reads rows of an input that is still arriving, so across segments and the + waiting rows), 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. For "unique side small", the arrival order is fixed by the test: with the unique side read to its end and closed @@ -501,7 +526,8 @@ With sections 2 to 7 in place, for a job run by the async orchestrator: |---|---| | 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 step that needs its whole input (`PolarsFilter` with a predicate not known to be row-wise, `Batch` without a size) | its whole input: outside the bound below | +| A step that needs its whole input (`PolarsFilter` with a predicate not known to be row-wise, `Batch` without a size) | its whole input, its whole output and its conversion buffers: outside the bound below | +| A stream being written to the cache | its waiting rows, at most one segment size (section 2) | | 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), and the pairs of one range being matched (at most the pair budget) | @@ -509,7 +535,7 @@ With sections 2 to 7 in place, for a job run by the async orchestrator: | 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) + 16 × (pair budget) × (joins matching at once) + (small results kept in memory) + the largest single row`. +`(batches in flight) × (batch bytes) + (key bytes + 8) × (rows indexed by joins and groupings) + 16 × (rows of verified sources) + 16 × (pair budget) × (joins matching at once) + (segment size) × (streams being written to the cache at once) + (small results kept in memory) + the largest single row`. 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. @@ -523,9 +549,11 @@ The formula covers a job whose every step is one of the bounded kinds of section step that needs its whole input by definition is outside it and adds that input, whole and in memory, for as long as the step runs: a `PolarsFilter` whose predicate is not known to be row-wise (B1; `pl.col("x") > pl.col("x").mean()`), and `Batch` without a -size. So the statement to users is the formula -`+ (the whole input of each such step running at once)`, and a job with none of them has -the bound as written. +size. Such a step also builds its output while it still holds its input, and a +`PolarsFilter` holds the Polars copy of the columns it evaluates. So the statement to +users is the formula +`+ (the whole input and the whole output of each such step running at once, plus the conversion buffers it holds)`, +and a job with none of them has the bound as written. **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 From 27a78a1242aeb5e56f5dbfffb68036e3be160337 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 05:01:48 -0800 Subject: [PATCH 26/26] docs(specs): per-key counts in the join's cost and the stated bound (ITL-1464) Co-Authored-By: Claude Fable 5.2 --- docs/dev/specs/itl-1464-streaming-design.md | 23 ++++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/docs/dev/specs/itl-1464-streaming-design.md b/docs/dev/specs/itl-1464-streaming-design.md index af9862523..20d1ed09c 100644 --- a/docs/dev/specs/itl-1464-streaming-design.md +++ b/docs/dev/specs/itl-1464-streaming-design.md @@ -313,9 +313,12 @@ For each batch of matches the join fetches the matched rows of the other side fr 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 +Cost per indexed row: the key's own size plus 8 bytes, and for an input that is not +certified unique up to as much again for its per-key counts (one count per distinct key: +nothing more when every row shares one key, the same again when every key is distinct). +For the measured tables the prepared key is 60 to 90 bytes (two short strings, a +timestamp, two integers), so a row costs 70 to 100 bytes, or up to 140 to 200 with +counts, 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), @@ -432,10 +435,14 @@ much again); rows themselves are in the cache, on disk. | Any case, a side whose other side has closed | nothing more is kept for it (the kernels' present rule) | | | Any case, while one range of pairs is matched | the pairs of that range (two row references each) and its output batch | 16 bytes × pair budget + one output batch, whatever the keys hold | -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. +In every case the memory is keys and counts only, so it compares with the size of an +input by the ratio of row size to index cost. With today's tokens that is 4.2 KiB a row +against 70 to 100 bytes (140 to 200 with per-key counts): far below one input. Without +tokens the measured rows are 120 bytes, so the index of a wide key is of the size of the +rows themselves, and with counts it can pass them; the hashed index of J1 (24 bytes a +row, 48 with counts) is what brings it back below. The developer's worst case, "linear +in the size of one input", holds as linear in the *keys* of both inputs; it is below one +input's own size only while rows are wider than the index cost above. **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", @@ -535,7 +542,7 @@ With sections 2 to 7 in place, for a job run by the async orchestrator: | 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) + 16 × (pair budget) × (joins matching at once) + (segment size) × (streams being written to the cache at once) + (small results kept in memory) + the largest single row`. +`(batches in flight) × (batch bytes) + (key bytes + 8) × (rows indexed by joins and groupings) + (key bytes + 8) × (distinct keys of join inputs not certified unique) + 16 × (rows of verified sources) + 16 × (pair budget) × (joins matching at once) + (segment size) × (streams being written to the cache at once) + (small results kept in memory) + the largest single row`. 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.