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..3c606d77b --- /dev/null +++ b/docs/dev/specs/itl-1464-memory-diagnosis.md @@ -0,0 +1,224 @@ +# 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 in [draft PR 603](https://github.com/metamorphic-labs/orcapod-python/pull/603). + +## 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 (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 + 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 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; + - 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 + 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 (about 2.2 million 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 | +| `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 | +| `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 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 + +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 | +| 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? + +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.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) | +| 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 about 2.2 million 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. + +## 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/measure.py b/docs/dev/specs/itl-1464/measure.py new file mode 100644 index 000000000..35d9f425b --- /dev/null +++ b/docs/dev/specs/itl-1464/measure.py @@ -0,0 +1,626 @@ +"""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 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 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 +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 shutil +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" +SERIES = "time_series" +EVENTS = "event" +LOCATIONS = "lookup" + +SESSION_START = datetime(2026, 1, 1, 12, 0, 0) +SUBJECT = "subject" +HASH = "0123456789abcdef0123456789abcdef" +BLOCKS = 6 +ITEMS = 300 + +SERIES_KEYS = [ + "processing_hash", + "subject_id", + "session_start", + "block_index", + "timestamp", +] +BLOCK_KEY = SERIES_KEYS[:4] +EVENT_KEYS = [ + "extraction_hash", + "subject_id", + "session_start", + "recording_index", + "device_index", + "timestamp", + "item_id", +] +ITEM_KEY = [ + "extraction_hash", + "subject_id", + "session_start", + "recording_index", + "device_index", + "item_id", +] +LOCATION_KEYS = [ + "extraction_hash", + "placement_hash", + "subject_id", + "session_start", + "recording_index", + "device_index", + "item_id", + "map_id", + "region_short", +] + + +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) + + +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_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: ``drop_nulls`` has rows to drop. + missing = rng.random(rows) < 0.02 + return pa.table( + { + "processing_hash": _constant(HASH, pa.string(), rows), + "subject_id": _constant(SUBJECT, pa.string(), rows), + "session_start": _constant(SESSION_START, pa.timestamp("us"), rows), + "block_index": pa.array(block), + "timestamp": pa.array(timestamp), + "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 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( + { + "extraction_hash": _constant(HASH, pa.string(), rows), + "subject_id": _constant(SUBJECT, pa.string(), rows), + "session_start": _constant(SESSION_START, pa.timestamp("us"), rows), + "recording_index": _constant(0, pa.uint32(), rows), + "device_index": _constant(0, pa.uint32(), rows), + "timestamp": pa.array(timestamp), + "item_id": pa.array(rng.integers(0, ITEMS, rows).astype(np.uint32)), + "amplitude": pa.array(rng.normal(size=rows).astype(np.float32)), + } + ) + + +def lookup_table() -> pa.Table: + """Return one row per item, shaped like the lookup table.""" + rng = np.random.default_rng(2) + rows = ITEMS + return pa.table( + { + "extraction_hash": _constant(HASH, pa.string(), rows), + "placement_hash": _constant(HASH[::-1], pa.string(), rows), + "subject_id": _constant(SUBJECT, pa.string(), rows), + "session_start": _constant(SESSION_START, pa.timestamp("us"), rows), + "recording_index": _constant(0, pa.uint32(), 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)), + } + ) + + +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 ( + (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] + ) + # 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: + """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 + return store.read(found["id"], 1) + + +def step_raw_copy() -> tuple[int, int, Any]: + """The rows alone, copied into process memory: the floor every step stands on.""" + 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]: + """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: + 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(SERIES).nbytes, table.nbytes, table + + +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() + return _raw(SERIES).nbytes, table.nbytes, (view, table) + + +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 + return _raw(SERIES).nbytes, 0, count + + +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"] + return _raw(SERIES).nbytes, 0, total + + +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() + return _raw(SERIES).nbytes, table.nbytes, table + + +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"]) + .group_by(BLOCK_KEY) + .map_data({"timestamp": "sample_time"}) + ) + + +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 + ends = np.flatnonzero(moving[:-1] & ~moving[1:]) + 1 + return [int(t[i]) for i in ends] + + return 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 + + +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: + """Return the job of the whole chain, storing into the step's own fresh location.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + + 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]: + """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") + job.run(orchestrator=AsyncPipelineOrchestrator(), materialize_results=False) + return _raw(SERIES).nbytes, 0, job + + +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") + job.run(orchestrator=AsyncPipelineOrchestrator()) + return _raw(SERIES).nbytes, 0, job + + +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 { + "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), + } + + +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 + + 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": + 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 = EVENTS if chain == "join" else SERIES + 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", "async_unkept") + }, + "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, + "job_run_async_unkept": step_job_run_async_unkept, +} + + +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) + parser.add_argument("--rows", type=int, default=2_200_000) + 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(SERIES).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..475bca784 --- /dev/null +++ b/docs/dev/specs/itl-1464/run_measurements.py @@ -0,0 +1,137 @@ +"""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 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. +""" + +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +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: + """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() + return int(found) * 1024 if found else 0 + + +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 seen, process.returncode, "", "" + time.sleep(0.2) + out, err = process.communicate() + 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(): + if line.startswith("{"): + record.update(json.loads(line)) + return record + + +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) + 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() + + guard = int(args.guard_gb * 1024**3) + if not args.skip_setup: + run_setup(args.store, args.rows, guard) + extra = ["--tracemalloc"] if args.tracemalloc else [] + 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 8d534e5a3..c56202658 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: @@ -828,11 +845,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. @@ -842,7 +864,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( @@ -852,6 +878,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``. @@ -862,6 +889,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 @@ -926,6 +956,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]"]: @@ -962,8 +993,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( @@ -975,8 +1009,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..6f74a1e25 --- /dev/null +++ b/tests/test_core/sources/test_spiraldb_table_source_tokens.py @@ -0,0 +1,298 @@ +"""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 + +import collections +from pathlib import Path +from typing import Any + +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.system_constants import constants +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()) + # 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 + + +@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 _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, table, tag_columns=tag_columns, tag_only_columns=tag_only + ) + with PipelineJob(name="tokens", database=InMemoryArrowDatabase()) as job: + source.drop_nulls(dropped, label="kept") + job.run(orchestrator=orchestrator) + return job.nodes["kept"].as_table(all_info=True) + + +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(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 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(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_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: + 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