diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md new file mode 100644 index 000000000..b064ba031 --- /dev/null +++ b/changelog.d/ITL-1464.md @@ -0,0 +1,21 @@ +### 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). +- 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). +- 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. So does, on the + async path, the input of an operator that reads all of its input first. The files are + removed when the run ends, fails or is cancelled. 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 4.4 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..4bf2c9276 --- /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 `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 (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-streaming-design.md b/docs/dev/specs/itl-1464-streaming-design.md new file mode 100644 index 000000000..20d1ed09c --- /dev/null +++ b/docs/dev/specs/itl-1464-streaming-design.md @@ -0,0 +1,654 @@ +# 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. + +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 + +- **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 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 + 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), 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 + 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 + 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.2 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. + +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). 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 +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). 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 + `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 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 + +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` 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 | +| 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` 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 + 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, 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 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 +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. + +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), +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? | +|---|---| +| 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 | +| 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), 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 | +|---|---|---| +| 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) | | +| 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 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", +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 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, +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, 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 + 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 (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 + 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 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. + +## 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 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) | +| 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 +`(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. + +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). + +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. 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 +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. **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), 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)`. +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; 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 | +| P4 | `preview` order | the first `n` of the sync order | +| 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) | +| 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, 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; 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 new file mode 100644 index 000000000..112434675 --- /dev/null +++ b/docs/dev/specs/itl-1464/measure.py @@ -0,0 +1,650 @@ +"""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 _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: + """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(), + "peak_footprint_bytes": _peak_footprint_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/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index b2134184a..e29dced81 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -41,7 +41,9 @@ from orcapod.config import OrcapodConfig from orcapod.core.operators.static_output_pod import ( RowBuiltFormUnavailable, + RowChunks, StaticOutputOperatorPod, + kept_table as spilled_when_large, produced_stream, rows_on_read, ) @@ -1758,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 ) @@ -2023,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, *, @@ -2266,6 +2315,10 @@ async def async_execute( node_hash = self.content_hash().to_string() ctx_obs = obs.contextualize(*self.node_identity_path) + # Kept as Arrow tables, not as a list of every pair (ITL-1464); closed below, + # so a run that fails or is cancelled leaves no file on local disk. + collected = RowChunks() + try: ctx_obs.on_node_start(node_label, node_hash) self._run_load_only = load_only @@ -2311,11 +2364,10 @@ async def async_execute( require_same_data_context( input_stream.data_context_key, self.data_context_key ) - collected: list[tuple[TagProtocol, DataProtocol]] = [] 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 +2393,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) @@ -2377,6 +2429,7 @@ async def forward() -> None: self.clear_cache() raise finally: + collected.close() try: await output.close() except BaseException: diff --git a/src/orcapod/core/operators/base.py b/src/orcapod/core/operators/base.py index c0fd0c320..f9cd659db 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 @@ -12,7 +11,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, + collected_row_chunks, + rows_once, +) from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import ( ArgumentGroup, @@ -228,16 +231,16 @@ 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: - # 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]) - result = self.static_process(stream) - for tag, data in result.iter_data(): - await output.send((tag, data)) + async with collected_row_chunks(inputs[:1]) as (rows,): + 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 = rows.input_stream(input_pipeline_hashes[0]) + result = self.static_process(stream) + for tag, data in rows_once(result): + await output.send((tag, data)) finally: await output.close() @@ -343,20 +346,18 @@ 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( - inputs[0].collect(), inputs[1].collect() - ) - if not left_rows or not right_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) - result = self.static_process(left_stream, right_stream) - for tag, data in result.iter_data(): - await output.send((tag, data)) + async with collected_row_chunks(inputs) as (left_rows, 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 = 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 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..8c6971192 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, + collected_row_chunks, concatenate_batches, finish_operator, + rows_once, ) from orcapod.core.data_tags import stream_data_tags from orcapod.core.streams import ArrowTableStream @@ -278,12 +280,12 @@ 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) - result = self.unary_static_process(stream) - for tag, data in result.iter_data(): - await output.send((tag, data)) + async with collected_row_chunks(inputs[:1]) as (rows,): + if rows.num_rows: + stream = rows.input_stream(pipeline_hash) + result = self.unary_static_process(stream) + for tag, data in rows_once(result): + await output.send((tag, data)) return batch: list[tuple[TagProtocol, DataProtocol]] = [] diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f829d44a5..18595c9f9 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import contextlib import dataclasses import logging from abc import abstractmethod @@ -36,6 +37,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, @@ -512,7 +514,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. + with contextlib.closing(RowChunks()) as chunks: + for tag, data in rows: + chunks.add(tag, data) + return chunks.output_stream() return StaticOutputOperatorPod._zero_rows_in_row_order(result) @staticmethod @@ -1078,19 +1085,19 @@ 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): - # 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) - for rows, pipeline_hash in zip(all_rows, input_pipeline_hashes) - ] - result = self.static_process(*streams) - for tag, data in result.iter_data(): - await output.send((tag, data)) + async with collected_row_chunks(inputs) as all_rows: + 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 = [ + 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 rows_once(result): + await output.send((tag, data)) finally: await output.close() @@ -1289,6 +1296,323 @@ 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.""" + + +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. + + 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, + 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. Once a chunk could not be built, no later row is kept and every read + raises that error; a chunk is never built again. + + 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: + # Sealed chunks: in memory up to the spool's limit, then on local disk, read + # back memory-mapped, so a large output is not process memory. + self._spool: RowSpool = RowSpool(memory_bytes=KEPT_ROWS_MEMORY_BYTES) + 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, ...] = () + self._data_tags: tuple[str, ...] = () + self._first_context_key: str | None = None + self._failure: Exception | None = None + self.num_rows: int = 0 + + def add(self, tag: TagProtocol, data: DataProtocol) -> None: + """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: no room on the local disk. + """ + self.num_rows += 1 + 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 (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 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 one chunk and let the pairs go. + + All or nothing, and never twice: after a failure nothing is built or given + again (every read raises the failure), and the rows kept so far are let go, + their files with them. + """ + if self._failure is not None: + raise self._failure + if not self._pending: + return + try: + chunk, contexts_of_rows = self._build_chunk(self._pending) + self._spool.append(chunk) + self._context_chunks.append(contexts_of_rows) + self._pending = [] + except Exception as error: + self._failure = error + self.close() + raise + + def _build_chunk( + self, rows: list[tuple[TagProtocol, DataProtocol]] + ) -> tuple[pa.Table, pa.Array[Any]]: # pyright: ignore[reportExplicitAny] # any array + """Build rows into a table in the first chunk's columns, and their contexts.""" + from orcapod.utils import arrow_utils + + if self._schema is None: + 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. + 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(), + ) + 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, the columns + # matched by name, or the error a table built from rows of differing + # columns raises. + chunk = arrow_utils.concat_tables_by_name( + [first.empty_table(), chunk] + ).combine_chunks() + return chunk, pa.array( + [data.data_context_key for _, data in rows], pa.large_string() + ) + + def close(self) -> None: + """Let the rows go and delete their files; a table already built stays valid. + + Whoever made this closes it, also on an error or a cancellation: an exception + that is kept keeps the frames of the run, and this object with them. + """ + self._spool.close() + self._pending = [] + self._context_chunks = [] + + 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. The + table stays valid after ``close``. + + Raises: + ValueError: If no row was added, or the rows were let go (``close``). + Exception: The error of a chunk that could not be built, on every call. + """ + if self.num_rows == 0: + raise ValueError("Cannot materialize an empty list of rows into a stream") + self._seal() + # 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.""" + 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. + """ + # 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() + + +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 + with RowSpool(memory_bytes=KEPT_ROWS_MEMORY_BYTES) as spool: + 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: + """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, for the caller to close; ``num_rows`` is 0 when the channel delivered + none. Closed here when the read fails or is cancelled. + """ + chunks = RowChunks() + try: + async for tag, data in channel: + chunks.add(tag, data) + except BaseException: + chunks.close() + raise + 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) + for task in tasks: + if not task.cancelled() and task.exception() is None: + task.result().close() + raise + + +@contextlib.asynccontextmanager +async def collected_row_chunks( + channels: Sequence[ReadableChannel[tuple[TagProtocol, DataProtocol]]], +) -> AsyncIterator[list[RowChunks]]: + """``collect_all_row_chunks``, closing every channel's rows when the block ends. + + Args: + channels: The input channels. + + Yields: + The rows of each channel, in the channels' order. + """ + rows = await collect_all_row_chunks(channels) + try: + yield rows + finally: + for chunks in rows: + chunks.close() + + 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/row_spool.py b/src/orcapod/core/row_spool.py new file mode 100644 index 000000000..94b3be6f9 --- /dev/null +++ b/src/orcapod/core/row_spool.py @@ -0,0 +1,529 @@ +"""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: 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 (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 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 +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 +import threading +import weakref +from collections.abc import Collection +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() + # 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]]] = {} + + 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]): + 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: + """Remove this process's directories (at exit).""" + for directory, lock in self._held.values(): + _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 their locks. + + The guard may be held by a thread that does not exist in the child. + """ + self._guard = threading.Lock() + self._held = {} + + +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. 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: + 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.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 + + +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, 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.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. + with contextlib.suppress(OSError): + if os.stat(directory).st_uid != os.getuid(): + continue + try: + 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 + # 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: + """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._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 + 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 + """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. + 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. + """ + 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") + + 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. + + Raises: + ValueError: If the spool is closed. + RuntimeError: In a process other than the one that made the spool. + """ + 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.""" + 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: + 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_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. + + A segment whose rows are all discarded is let go, and its file deleted. + + 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_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.""" + 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) + 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: + """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 + + 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/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/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index df49eaff6..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) @@ -454,42 +488,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({}) + for pair in self._build_rows(): + yield pair - yield tag, data - - 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..86b4352cb --- /dev/null +++ b/tests/test_core/operators/test_row_chunks.py @@ -0,0 +1,929 @@ +"""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 +import contextlib +import errno +from pathlib import Path +from typing import Any, cast + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.channels import Channel +from orcapod.core.nodes.operator_node import OperatorJobNode +from orcapod.core.operators import MapData, 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, InMemoryArrowDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.sources import ArrowTableSource +from orcapod.utils import arrow_utils + +_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 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: + 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 + + +@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 + + +@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) + + +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] + + +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() + + +@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 + + +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()) + + +class _FullDisk: + """``pa.ipc.new_file`` on a disk that fills up after ``room`` files.""" + + 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) + + +@pytest.mark.parametrize("room", [0, 1, 2]) +def test_rows_that_cannot_be_written_are_all_let_go( + spilled: Path, monkeypatch: pytest.MonkeyPatch, room: int +) -> None: + """Review of PR 566: a failed spill raises at once and leaves no file.""" + disk = _FullDisk(room) + monkeypatch.setattr(pa.ipc, "new_file", disk) + rows = _rows(False) + chunks = RowChunks() + with pytest.raises(OSError, match="synthetic full disk"): + for tag, data in rows: + chunks.add(tag, data) + + # The disk is asked once more, and no more rows are kept. + assert disk.calls == room + 1 + chunks.add(*rows[0]) + assert chunks._pending == [] # pyright: ignore[reportPrivateUsage] # nothing is kept after a failure + assert not _spool_files(spilled) + with pytest.raises(OSError, match="synthetic full disk"): + _ = chunks.row_table() + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +@pytest.mark.parametrize("room", [0, 1]) +def test_a_job_that_fills_the_disk_leaves_no_file_while_its_error_is_kept( + spilled: Path, + tmp_path_factory: pytest.TempPathFactory, + monkeypatch: pytest.MonkeyPatch, + orchestrator: str, + room: int, +) -> None: + """Review of PR 566: the kept error pinned the files written before it.""" + monkeypatch.setattr(static_output_pod, "SPILL_SLICE_ROWS", 3) + job = _job(tmp_path_factory.mktemp("store"), "full", "map", False) + disk = _FullDisk(room) + with monkeypatch.context() as patched: + patched.setattr(pa.ipc, "new_file", disk) + with pytest.raises(BaseException) as held: + if orchestrator == "sync": + _ = job.run() + else: + _ = job.run(orchestrator=AsyncPipelineOrchestrator()) + + assert disk.calls > room + assert not _spool_files(spilled), f"left behind with {held.value!r} kept" + assert job.nodes["out"].as_table().num_rows == 0 + # With room again the same job gives every row once. + _ = job.run() + assert job.nodes["out"].as_table().num_rows == _ROWS + + +@pytest.mark.parametrize("failure", ["disk", "cancel", "compute"]) +def test_a_barrier_that_fails_leaves_no_file_of_either_input( + spilled: Path, monkeypatch: pytest.MonkeyPatch, failure: str +) -> None: + """Review of PR 566: a barrier's gathered inputs are spilled too.""" + from orcapod.operators import MergeJoin + + rows = _rows(False) + pipeline_hash = _source(False).pipeline_hash() + disk = _FullDisk(4) + if failure == "disk": + monkeypatch.setattr(pa.ipc, "new_file", disk) + operator = MergeJoin() + + def refuse(*_: Any) -> Any: + raise RuntimeError("synthetic computation failure") + + if failure == "compute": + monkeypatch.setattr(operator, "static_process", refuse) + + async def run() -> BaseException: + left: Channel[tuple[Any, Any]] = Channel(buffer_size=_ROWS + 1) + for row in rows: + await left.writer.send(row) + if failure != "cancel": + await left.writer.close() + output: Channel[tuple[Any, Any]] = Channel(buffer_size=4) + before = asyncio.all_tasks() + task = asyncio.create_task( + operator.async_execute( + [left.reader, await _closed(rows)], + output.writer, + input_pipeline_hashes=[pipeline_hash] * 2, + ) + ) + if failure == "cancel": + while len(_spool_files(spilled)) < 6: + await asyncio.sleep(0) + _ = task.cancel() + with pytest.raises((OSError, RuntimeError, asyncio.CancelledError)) as held: + await task + assert asyncio.all_tasks() - before == set() + return held.value + + error = asyncio.run(run()) + + assert not _spool_files(spilled), f"left behind with {error!r} kept" + + +def test_a_cancelled_node_leaves_no_file_while_its_cancellation_is_kept( + spilled: Path, +) -> None: + """Review of PR 566: the kept cancellation pinned three files.""" + node = OperatorJobNode( + operator=MapData({"value": "amplitude"}), input_streams=[_source(False)] + ) + + async def run() -> BaseException: + given: Channel[tuple[Any, Any]] = Channel(buffer_size=_ROWS) + output: Channel[tuple[Any, Any]] = Channel(buffer_size=_ROWS) + task = asyncio.create_task(node.async_execute([given.reader], output.writer)) + for row in _rows(False): + await given.writer.send(row) + for _ in range(_ROWS): + _ = await output.reader.receive() + assert _spool_files(spilled) + _ = task.cancel() + with pytest.raises(asyncio.CancelledError) as held: + await task + return held.value + + error = asyncio.run(run()) + + assert not _spool_files(spilled), f"left behind with {error!r} kept" + assert node.as_table().num_rows == 0 + + +def test_a_finished_async_run_leaves_no_file_either( + spilled: Path, tmp_path_factory: pytest.TempPathFactory +) -> None: + job = _job(tmp_path_factory.mktemp("store"), "done", "group", False) + _ = job.run(orchestrator=AsyncPipelineOrchestrator()) + assert not _spool_files(spilled) + assert job.nodes["out"].as_table().num_rows == 3 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 diff --git a/tests/test_core/test_row_spool.py b/tests/test_core/test_row_spool.py new file mode 100644 index 000000000..67b69651b --- /dev/null +++ b/tests/test_core/test_row_spool.py @@ -0,0 +1,619 @@ +"""Rows held by number, in memory and on local disk (``core/row_spool``, ITL-1464).""" + +from __future__ import annotations + +import asyncio +import errno +import gc +import os +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 + +import numpy as np +import pyarrow as pa +import pytest + +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() + + +@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()) == [] + 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() + (other / "file").touch() + spool, _ = _filled(tmp_path, [10], 0) + assert held.exists() and _files(held) + assert other.exists() + spool.close() + finally: + _ = live.communicate() + assert not held.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 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) + 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") +@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(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) + 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() + + +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()