diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md new file mode 100644 index 000000000..d966436c6 --- /dev/null +++ b/changelog.d/ITL-1464.md @@ -0,0 +1,9 @@ +### 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). +- Reading a SpiralDB table remembers each row's key as 16 bytes instead of its text, to + find a key read twice: about 130 MB for 8 million rows instead of 2 GB (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..16ff3c515 --- /dev/null +++ b/docs/dev/specs/itl-1464-streaming-design.md @@ -0,0 +1,544 @@ +# 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 as a set of rows** (each row as often as it + occurs); row order is not a result on the async path (developer, November 22, 2026). +- **The async path is the primary memory-bounded path** (developer, November 25, 2026). + The sync path gets what it can get without giving up its order. +- **Fewest special cases.** One mechanism for rows that are not in memory (the local + cache, below), used by every part that needs one. + +## What the diagnosis found, in one paragraph + +A row of the measured table is 120 bytes. Held as a `(Tag, Data)` pair it costs 18 to +110 KiB; the async path passes rows that way and every operator job node keeps all of +them. Its source-info tokens are 4.2 KiB (35 times the data), built at every source +read. Every sync operator holds its whole input and whole output, tokens included. So the +design has three parts, in this order of worth: rows move and are kept as Arrow record +batches, never as objects; a node does not keep its rows in memory; tokens are not +materialized per row where they can be derived. + +## 1. The `run()` contract + +`run()` is the way to trigger computation (developer, November 24, 2026). It promises: + +- every row of the stream is computed, with every effect and every write a job makes; +- on the sync path, in the deterministic order of today; +- it returns a `StreamView`. + +It promises nothing about how the rows are produced or what is held meanwhile: not one +table, not batches of a given size, not a thread. "Does exactly the work `as_table()` +does" (ITL-1081) is replaced by "computes every row; `as_table()` afterwards does not +compute them again" (section 3 says how). + +`as_table()`, `as_polars_df()` and iteration stay the way to get all rows, and +`as_table()` still returns one Arrow table: asking for it is asking for the rows in +memory. `head()` and the notebook display still never compute. + +## 2. The local cache + +One mechanism holds rows that are computed but not in memory. + +- **What it is.** Arrow IPC files (the file format, uncompressed, so they can be + memory-mapped), one per stream of rows, written a record batch at a time as the rows + are produced, in the form the rows have on a job's edges (ITL-1347's row-built form). + A row is addressed by `(batch number, row number)`. +- **Where.** A directory per process run, `/orcapod--/`. The + cache root is `OrcapodConfig.local_cache_dir`, by default the system's temporary + directory. **OPEN (L1)**: the default location, and whether a job's cache may live + beside the job's database. +- **Reading.** A reader memory-maps the file. Pages of a mapped file are the operating + system's to drop under pressure, so they are not memory the process holds: this is + what makes "fetch the row by reference, emit it, let it go" cheap. Rows are fetched in + batches of references (`take` on the mapped batches), never one by one. +- **Lifetime.** A file belongs to the object that wrote it (an operator's run, a job + node's current run, a stream's computed result) and is deleted when that object lets + go of it: an operator when it finishes or fails (`finally`), a node at + `clear_cache()`, at its next run and when it is collected, a stream when it is + collected. The process directory is removed at exit. A directory whose process no + longer exists is removed at the next start (the directory name holds the process id + and a lock file). +- **Small results skip it.** Rows below a threshold (`OrcapodConfig.keep_in_memory_bytes`, + proposed 64 MiB per stream) stay in memory as one Arrow table, as today; nothing is + written. Tutorial-sized work never touches the disk. **OPEN (L2)**: the threshold. +- **What it never is.** It is not a store: nothing in it is an identity, nothing survives + the process, no result is read from it by a later process, and it holds no hash. + +Without source-info tokens materialized (section 7) a cache file is about the size of the +rows' Arrow data: 248 MiB for the measured 2.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. + +Every read keeps its meaning: `node.as_table()` returns the current run's rows (now read +from the reference, memory-mapped where it is the cache), iteration yields them a batch +at a time, a downstream node's read is a batch reader. "A job node shows its current +run" stays true; "holds them in memory" does not. + +**The view** (`StreamView`) follows the same rule and needs no special case: + +- inside a job, it reads pages from the node's reference; +- outside a job, `run()` writes the computed rows to the local cache (or keeps them in + memory below the threshold) and the stream keeps that reference, as a pod's stream + keeps its computed table today. So nothing is computed twice: `as_table()` after + `run()` reads the reference. +- `head(n)` and `tail(n)` read the first and last `n` rows; `total_rows` and the schema + are recorded while the rows are written; +- `sort_by_tags()` on a result in memory sorts as today; on a cached result it sorts an + index of the tags (the same keys-only index a join uses, section 6) and fetches the + rows shown. The view then shows exactly what it shows today. +- The notebook display of a view is its `head` in tag order plus the row count, as + today. + +The issue's alternative, a view that keeps only the first and last rows, the count and +the schema, would make `as_table()` after `run()` compute everything again (calling +every function again outside a job) and would need a rule for every view method beyond +the kept rows. The cache-backed view has neither problem. **OPEN (N2)**: confirm the +cache-backed view over the bounded-window view. + +A source that holds no rows (`SpiralDBTableSource`) is the one case where "keep a +reference" means "read again": its `run()` view may keep a cache file of the read, or +the first and last rows and the count. **OPEN (N3)**; proposed: the cache file, so a +source behaves as every other stream. + +## 4. A bounded preview: `stream.preview(n)` + +`head()` never computes, so it cannot show the first rows of a derived stream that was +never run. `preview(n)` computes only what `n` rows need: + +- the limit is passed down: a source reads at most the rows asked of it (a SpiralDB or + database source as a pushed-down `limit`, a file source by stopping the read); +- row-by-row steps (section 5) are applied to batches until `n` rows have come out; the + batch size doubles when a batch yields too few (a selective filter); +- a step that needs its whole input (`GroupBy`, `Batch`, a join) is **computed in full** + under `preview`, with a note in the view saying so. **OPEN (P1)**: compute in full, or + refuse and point to `run()`. Proposed: refuse by default with + `preview(n, compute_all=True)` to allow it, because a preview that silently reads + 2 million rows is the surprise this method exists to avoid. + +Decisions the issue lists: + +- **OPEN (P2)**: does a preview call user functions? Proposed: yes; it is the point of + the method, and the name says it computes. `head()` stays the method that never does. +- **OPEN (P3)**: are a preview's results stored? Proposed: outside a job nothing is + stored, as for any stream outside a job. A job node's `preview` is not offered in the + first version: `job.run()` and `node.head()` cover it. +- **OPEN (P4)**: is the order defined? Proposed: the preview's rows are the first `n` the + sync path would produce when every source has a defined read order (in-memory, CSV, + Delta: the order given; SpiralDB and database tables: key order). A source without one + (none today) would say "some `n` rows". +- A preview delivers no side effect: a `SideEffectPod` in the chain is refused. + +## 5. Batch-wise execution, per operator kind + +Rows move between job nodes as Arrow record batches (ITL-1347, already designed and +partly built: `InputChannel`, `OutputChannel`, `async_execute_batches`, the streaming +join kernels). This design finishes the wiring and adds what the memory bound needs. + +| Kind | Operators | Holds | +|---|---|---| +| Row by row (`ROW_BY_ROW`) | `Select*`/`Drop*` columns, `MapTags`, `MapData`, `MapColumns`, `DropNulls`, `Filter`, `PolarsFilter`, `AddTags`, `TagBy`, `Pick`, `Index` | the batch in hand | +| Per row, user code | function pods, side-effect pods | the batch in hand; results go to the database as they are computed | +| Probe against one small or indexed side | `SemiJoin` | a keys-only index of the right input (section 6) | +| Joins | `Join`, `MergeJoin`, `Rejoin` | a keys-only index, section 6 | +| Grouping by key | `GroupBy` | a keys-only index of the input and one group at a time (below) | +| Grouping by arrival | `Batch` with a size | one batch of `size` rows | +| Whole input, by definition | `Batch` without a size | one row holding everything: its output is the input | + +Notes: + +- `PolarsFilter` is row by row but has no async form today, so it gathers its input; it + gets `ROW_BY_ROW`. Its predicate is applied per batch; a predicate is an expression + over one row's columns (an expression that reads other rows, such as a window, is + already outside what the sync path's identity describes). **OPEN (B1)**: refuse + expressions that are not row-wise (they exist in Polars), or document. +- `GroupBy` sorts its input by key and member order. Batch-wise: the input goes to the + local cache while a keys-only index is built (the prepared key columns, the + member-order tags, record id and source id, and the row's reference); the index is + sorted exactly as today's sort frame is; groups are emitted one at a time by fetching + their members. It holds the index (the size of the tag columns) and one group. Its + output order is today's, on both paths. A group larger than memory is a row larger + than memory: out of scope. +- A function pod over grouped rows receives one group's lists at a time; that row is as + large as the group, by the user's choice. + +### How sync stays deterministic + +The sync orchestrator runs nodes in topological order, each to completion. Batch-wise it +does the same, with these rules: + +- a row-by-row operator applied to the batches of its input in order, with the results + concatenated in order, gives exactly its result over the whole input, because each + output row comes from one input row; the differential test of ITL-1347 (sync against + pinned `main`, byte for byte) is the gate; +- every other operator runs its one sync body (`static_process`) as today; what changes + is only where its inputs' rows live (the cache instead of memory) and, for `GroupBy` + and the joins, that the body fetches rows by reference. The matching, the order of the + output rows and every value are the present code's: `Join` and `SemiJoin` already + match on key columns and row numbers and take every value from the input by row number + (ITL-1284), and a row number is a reference; +- the order of a sync read is the order the run emitted (ITL-1441): the cache file is + written in that order and read in it. + +So the sync path gets the same bounds as async for row-by-row chains and grouping, and +for joins the bound of "keys-only index plus the output written to the cache". It does +not get the early-release rules of section 6 that depend on arrival order. + +## 6. Joins + +Joins are where rows multiply and where an operator must remember rows. The aim is a +stated bound per case, not a join that is free (developer, November 25, 2026). + +**The target (Decided).** An async join's memory is, in the worst case, linear in the +size of one of its inputs: never the product, never all inputs plus the output at once. +Everything else on the async path is bounded by the batches in flight. + +### What a join holds today + +- Sync `Join`: both inputs whole, as tokenized Arrow tables (about 4 KiB per row here), a + Polars frame of the prepared key columns and row numbers, and the whole output. It is + already a keys-only match: Polars sees keys and row numbers, and the rows are taken + from the tables by row number. +- Async `Join` (today's row form): both inputs as lists of `(Tag, Data)` pairs (tens of + KiB per row) until the other side closes. +- The streaming join kernels of ITL-1362 (built, not wired): each side's rows as Arrow + tables plus a key frame, a side dropped when the other closes. + +### Keys only in memory, rows in the local cache (Decided direction) + +Each input of an async join is written to the local cache as it arrives. In memory the +join keeps, per row that can still match, an index entry: + +- the row's join key in prepared form (`arrow_keys.polars_ready`, the present + preparation), as a Polars frame, so matching stays one vectorized join per arriving + batch with the sync path's own rule (`join._matched_pairs`); and +- the row's reference, `(batch number, row number)`: 8 bytes. + +For each batch of matches the join fetches the matched rows of the other side from the +cache by reference (one `take` per input per batch of pairs), builds the output batch +with the sync path's column work, sends it, and lets the rows go. + +Cost per indexed row: the key's own size plus 8 bytes. For the measured tables the +prepared key is 60 to 90 bytes (two short strings, a timestamp, two integers), against +4.2 KiB for the tokenized row today and 120 bytes for the bare row. **OPEN (J1)**: index +a 128-bit hash of the key instead of the key (24 bytes per row whatever the key's +width); matches are then confirmed on the fetched rows, so a hash collision costs a +fetch, never a wrong row. Proposed: start with the key itself (it is the present code), +measure, and switch only if the index is the limit. + +Compared with today's sync `Join`: the same match, on the same prepared keys, with a +reference where today there is a row number; the difference is that the rows behind the +references are in a mapped file, not in process memory. + +### Uniqueness certificates + +A stream can be certified to have unique tags: each tag tuple occurs at most once. + +**Where a certificate comes from (Decided).** Certificates originate inside Orcapod and +are trusted by every step that derives them; no step re-checks. The one claim that is +verified is a source's own. + +The certificate is a set of *unique keys*: sets of tag names such that no two rows agree +on all of them. A stream has unique tags when one of its unique keys is a subset of its +tags. (**OPEN (C1)**: this form, or a single yes/no. The key form survives dropping a +tag that is not part of the key, and lets a join say more; the yes/no form is simpler +and must be given up whenever a tag is dropped. Proposed: the key form.) + +| Step | Certificate of the output | +|---|---| +| Source with key columns `K` that are all tags | `{K}` (verified or store-guaranteed, below) | +| Source identified by position, or whose key columns are not all tags | none | +| Select/drop data columns, `MapData`, `DropNulls`, `Filter`, `PolarsFilter`, function pod, side-effect pod, `Pick`, `Index` | the input's (rows are removed or data changes; tags stay) | +| `AddTags`, `TagBy` | the input's (a superset of a unique key is unique) | +| Select/drop tag columns | the input's keys that are still tags | +| `MapTags`, `MapColumns` | the input's keys, renamed | +| `SemiJoin` | the left input's | +| `GroupBy(by)` | `{by}`: one row per key | +| `Batch` | none (its tags are lists) | +| `Join`, `MergeJoin` of inputs with keys `Ka`, `Kb`, joined on shared tags `S` | `Ka ∪ Kb`; also `Ka` when `Kb ⊆ S` (each left row matches at most one right row), and `Kb` when `Ka ⊆ S` | +| `Rejoin` | the inputs' common keys (a result row is its origin row) | + +**How it travels (Decided: not in any hash or identity).** It is a read-only member of +the stream's description, beside `condition` and `row_limit`: `StreamProtocol.unique_keys`. +Each operator derives it from its inputs' certificates when the graph is built; no data +is read. It is not Arrow metadata, enters no hash, identity, config, stored path or +stored row, and a loaded job derives it again from its sources. Nothing in the design +requires it in an identity: it never changes a result, only how much a join remembers. + +**Verification as data flows (Decided).** A source that claims a key keeps the keys it +has emitted and checks each batch before it is sent on. On a duplicate it raises, and +the duplicate row never proceeds, so nothing downstream computes on a wrong assumption. + +- *Memory*: keys only. Today `SpiralDBTableSource` already does this with a Python set + of record-id strings (about 250 bytes per row, 0.5 GiB for the measured session). The + proposal keeps 128-bit digests of the record id (16 bytes per row, in a sorted + numeric structure checked per batch): 35 MiB for the measured session. A digest + collision would raise a false duplicate (never a wrong result); at 100 million rows + its probability is below 10^-20. +- *What has happened when a duplicate appears late*: the rows before it were emitted, and + downstream nodes may have computed and stored results for them. Those stored results + are correct for their rows (a function result is kept by its input row's hash), exactly + as after any run that fails part-way. +- *The error*: `RowIdentifierError`, as today, naming the source (its id and label), the + key, and that an earlier row of the read holds it. (Naming the earlier row's position + needs 8 more bytes per key. **OPEN (C2)**; proposed: not kept.) +- *The error policy*: a uniqueness violation is a condition of the whole input, not of a + row, so it is outside the row error policy, as the data-context check is: it stops the + source's node and fails the run under `continue` and `fail_fast` alike. Every node + downstream of the source holds rows computed on a claim that turned out false; a run + that raised defines no rows for the nodes that ran, which is the present rule. +- In-memory sources check their keys when they are built (they hold every row), so their + certificate is verified before the first read; nothing changes for them. + +**Keys the store guarantees (Decided).** Where the source's own system guarantees +uniqueness over the key, Orcapod trusts it without the running check. + +- *How a source states it*: a class-level declaration, never a user flag: + `RootSource.key_enforced_by_store()`, answered by the source class from what it knows + of its table. A user's claim on a file is a claim to verify. +- *The rule*: the key columns the source identifies rows by must be exactly a key the + store enforces, and, for the certificate, the tags must contain them (a superset of a + unique key is unique; a subset is not). +- *Which kinds*: + +| Source | Guaranteed by the store? | +|---|---| +| SQLite, PostgreSQL table, key = the table's primary key | yes: the database enforces it | +| The same, key = columns of a `UNIQUE` constraint, all `NOT NULL` | yes, once the connector reads constraints (not today: running check until then) | +| The same, `record_id_columns` given and not such a key | no: running check | +| `DBTableSource` over a generic connector | only if the connector reports an enforced key; otherwise running check | +| SpiralDB keyed table, key = its key columns, one pinned version | yes, with one reservation (below) | +| CSV, Delta, in-memory (Arrow table, dict, list, data frame) | never: checked at construction (in memory) or as the rows flow (files) | +| `PollingSource` | never trusted; it already refuses a key an earlier batch held | +| `CachedSource` | its wrapped source's answer | +| `DerivedSource` over a job node's stored records | **OPEN (C3)**: the records are kept by record id, which is unique per row of a run, but its tags are the node's output tags, unique only if the node's certificate says so. Proposed: the node's certificate, verified by the running check on read | + + SpiralDB: a keyed table stores at most one row per key; a write of an existing key + replaces that row (upsert), and a repeated key within one write is refused. This was + observed on the service with spiral-sdk 0.16.74 and 0.16.75 (the rules `upsert` and + `dup` of the test fake record it). I did not find a statement of it in documentation + I could cite, so the confidence is "observed, and the meaning of a keyed table", not + "documented guarantee". A source reads one pinned version, so no concurrent write can + show two versions of a row. Proposed: trust it, and keep the conformance test that + would notice a change. + +### The bound for each case + +`n` and `m` are the rows of the two inputs; "index" is the per-row cost above (key plus +8 bytes); rows themselves are in the cache, on disk. + +| Case | What is held in memory | Bound | +|---|---|---| +| Both inputs certified unique on the join key (the tags fully overlap): 1:1 | the index of rows not yet matched; an entry is dropped the moment it matches, and both rows are emitted and let go | index × (unmatched rows). Worst case, one input arriving entirely before the other: index × max(n, m). With both inputs in key order: the out-of-order window only | +| One input certified unique on the join key (a large table against its lookup table) | the unique side's index for the whole join; rows of the other side that arrive before the unique side has closed are indexed until then, after which each arriving row matches at most one row, is emitted and is not kept | index × (unique side) + index × (rows of the other side that arrived early). Worst case index × (n + m): still keys only | +| Neither unique (many to many) | the index of both sides | index × (n + m). The output can be n × m rows; it is sent a batch at a time and never held | +| Any case, a side whose other side has closed | nothing more is kept for it (the kernels' present rule) | | + +In every case the memory is keys only, so it is below the full size of one input by the +ratio of row size to key size (here 120 bytes against 70 to 100, without tokens; 4.2 KiB +against 70 to 100 with today's tokens). The developer's worst case, "linear in the size +of one input", holds with room: the worst case is linear in the *keys* of both. + +**Key-ordered inputs.** Two inputs sorted by their tags can be merged holding only the +rows between the two read positions. That needs a second certificate, "in tag order", +which a source can give (a SpiralDB or database scan in key order) and which few +operators preserve on the async path, where arrival order is not a result. **OPEN (J2)**: +proposed not in the first version; the 1:1 early release already gives the window bound +whenever the inputs happen to arrive in step. + +**Three or more inputs.** `Join` folds pairwise in its canonical order, as today; each +step is one of the cases above, and a step's output goes to the next step as batches, +not to a cache file, unless that next step must index it. + +**Diamonds.** When both inputs come from one upstream through a broadcast, one input +cannot be read to its end while the other waits: the wait would block the upstream. This +is why rows that arrive "early" are indexed and cached rather than refused by +back-pressure, and why the worst case counts both sides. + +### Order and determinism + +- Async: the output is the sync join's rows as a set; batches are sent as matches are + found. +- Sync: `Join.static_process` as today, over references. Its row order is today's (the + order Polars gives the match, kept by ITL-1355's rule), so the stored and returned + tables are identical. + +### Test plan that proves the bound + +- A measurement in `measure.py` style for each case (1:1 in step, 1:1 one side first, + unique side small, many to many), at two sizes a factor of 10 apart, recording peak + resident memory less mapped file pages, and the peak of the Arrow pool: the peak must + grow as the index does (key bytes × rows), not as the rows do, and a 10 times larger + non-indexed side must not move it. +- The differential of ITL-1347 for results: async equals sync as a set of rows, sync + equals pinned `main` byte for byte. +- A violation test per certificate rule: a source that claims a key and repeats it late + raises, the duplicate reaches no downstream node, and the run fails under both error + policies. + +## 7. Source-info tokens that are derived, not stored per row + +A source row's token for column `c` is `::::`, and the row's two +system tags hold the source id and the record id. So the 35-fold cost is a copy of what +the row already carries. + +**Proposed (OPEN, T1).** A stream may hold a column's tokens as a *recipe* instead of a +column: "the token of `c` is built from system-tag columns `S` and `R` and the name +`c0`" (`c0` is the column's name at the source, which a rename does not change). Record +batches then carry no token column for it. The tokens are materialized, by one helper, +exactly where they are read: + +- a table or row that shows them (`as_table(columns={"source": True})`, `all_info`, + `data.source_info()`); +- a function node writing its pipeline records, a database write of an operator's + output: the stored rows hold the same tokens as today, byte for byte; +- an operator that computes with tokens: `MergeJoin` (token pairs), `Batch` and + `GroupBy` (token lists), a function pod's output (new tokens). + +Operators that pass tokens through (select, map, filter, `DropNulls`, `Join`, `SemiJoin`) +pass the recipe; `Join` renames the system-tag columns a recipe names as it renames the +columns. + +This is an in-memory representation only: every stored token, hash and layout is +identical. It touches how every operator treats `_source_` columns, so it is the largest +step and comes after the transport. Its worth, from the measured column groups: a +tokenized table falls from 911 MiB to about 107 MiB per 200,000 rows (8.5 times). + +Second step (**OPEN, T2**): `GroupBy` and `Batch` emit one token list per column, each +with one token per member: the same 35-fold cost inside the lists. A recipe for those +("the tokens of `c` are built from the members' record ids", one hidden list per group +instead of one per column) removes it. Proposed: after T1, measured first. + +## 8. The memory we can promise + +With sections 2 to 7 in place, for a job run by the async orchestrator: + +| Part | Held in memory | +|---|---| +| A source | one batch read (65,536 rows at most), plus 16 bytes per row read if its key is verified as data flows, nothing if the store guarantees it | +| A row-by-row operator, a function pod | the batch in hand | +| A channel between two nodes | its buffered batches (a fixed number) | +| `GroupBy` | its keys-only index, and one group | +| A join | its keys-only index (section 6) | +| A job node after the run | a reference (a file name or a set of stored entries) | +| A view | the rows shown | + +**The bound to state to users**: peak memory of an async job is +`(batches in flight) × (batch bytes) + (key bytes + 8) × (rows indexed by joins and groupings) + 16 × (rows of verified sources) + the largest single row`. +For the measured session (2.2 million rows of 120 bytes, one grouping, one function +pod) that is under 0.5 GiB, against about 210 GiB today. + +**Proposed budget for the workshop** (**OPEN, M1**): a job over every 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), give `PolarsFilter` `ROW_BY_ROW`. Removes the 18 to 110 KiB per row. +3. The local cache, and job nodes that keep a reference (section 3). Removes "every node + holds its output". +4. The view and `run()` on the cache; `preview(n)`. +5. Certificates and the running check with digests; store-guaranteed keys. +6. Joins on a keys-only index over the cache, with the early-release rules; `GroupBy` + on the index. +7. Derived tokens (T1), then token lists (T2). + +Steps 2 and 3 together give the bound for row-by-row chains and function pods; step 6 +for joins and grouping; step 7 removes the 35-fold factor from everything that still +holds rows (cache files, `as_table()`, the sync path). + +## Open decisions for the developer + +| Id | Decision | Proposed | +|---|---|---| +| N1 | A job node keeps a reference to its run's rows (database or local cache), not the rows in memory: changes the ITL-1095 promise | yes | +| N2 | The view is backed by the cache (keeps every method's meaning, nothing computed twice) rather than a bounded window of first and last rows | cache-backed | +| N3 | A source that holds no rows: its `run()` view keeps a cache file of the read | yes | +| L1 | Where the local cache lives by default | the system temporary directory, configurable | +| L2 | The size below which rows stay in memory | 64 MiB per stream | +| P1 | `preview(n)` over a step that needs its whole input: compute in full or refuse | refuse unless `compute_all=True` | +| P2 | `preview` calls user functions | yes | +| P3 | `preview` results are stored | no; not offered on job nodes at first | +| P4 | `preview` order | the first `n` of the sync order | +| B1 | `PolarsFilter` with an expression that is not row-wise | refuse | +| J1 | The join index holds the key or a 128-bit hash of it | the key first; measure | +| J2 | An "in tag order" certificate for a streaming merge | not in the first version | +| C1 | Certificate as a set of unique keys or as yes/no | set of unique keys | +| C2 | The duplicate-key error names the earlier row's position (8 bytes per key) | no | +| C3 | `DerivedSource` over a node's records: certificate | the node's, verified on read | +| T1 | Source tokens held as a recipe until read | yes, after the transport | +| T2 | Token lists of `GroupBy` and `Batch` as a recipe | after T1, measured first | +| U1 | Iteration keeps no row objects | accept | +| M1 | The workshop budget | 4 GiB peak, async, 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..629f2d549 --- /dev/null +++ b/docs/dev/specs/itl-1464/measure.py @@ -0,0 +1,488 @@ +"""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 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 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: + from orcapod.core.sources import SpiralDBTableSource + + return SpiralDBTableSource(PROJECT, name, max_rows=None) + + +def _raw(name: str) -> pa.Table: + store = fake._store() + found = store.find(PROJECT, "default", name) + assert found is not None + return store.read(found["id"], 1) + + +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]: + table = _source(SERIES).as_table() + return _raw(SERIES).nbytes, table.nbytes, table + + +def step_as_table_all_info() -> tuple[int, int, Any]: + 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]: + view = _source(SERIES).run() + return _raw(SERIES).nbytes, 0, view + + +def step_run_then_as_table() -> tuple[int, int, Any]: + 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]: + frame = _source(SERIES).as_polars_df() + return _raw(SERIES).nbytes, int(frame.estimated_size()), frame + + +def step_iterate() -> tuple[int, int, Any]: + count = 0 + for _tag, _data in _source(SERIES): + count += 1 + return _raw(SERIES).nbytes, 0, count + + +def step_iterate_read_one_value() -> tuple[int, int, Any]: + 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]: + pairs = _source(SERIES).flow() + return _raw(SERIES).nbytes, 0, pairs + + +def step_drop_nulls() -> tuple[int, int, Any]: + table = _source(SERIES).drop_nulls(["x_small", "y_small"]).as_table() + return _raw(SERIES).nbytes, table.nbytes, table + + +def step_polars_filter() -> tuple[int, int, Any]: + import polars as pl + + table = _source(SERIES).polars_filter(pl.col("level") > 0.5).as_table() + return _raw(SERIES).nbytes, table.nbytes, table + + +def step_map_data() -> tuple[int, int, Any]: + table = _source(SERIES).map_data({"level": "pupil"}).as_table() + return _raw(SERIES).nbytes, table.nbytes, table + + +def step_join() -> tuple[int, int, Any]: + table = _source(EVENTS).join(_source(LOCATIONS)).as_table() + return _raw(EVENTS).nbytes + _raw(LOCATIONS).nbytes, table.nbytes, table + + +def _grouped_series() -> Any: + 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]: + table = _source(SERIES).group_by(BLOCK_KEY).as_table() + return _raw(SERIES).nbytes, table.nbytes, table + + +def step_group_by_chain() -> tuple[int, int, Any]: + table = _grouped_series().as_table() + return _raw(SERIES).nbytes, table.nbytes, table + + +def _onsets_pod() -> Any: + 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]: + 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]: + table = _onsets_pod().pod(_grouped_series()).as_table() + return _raw(SERIES).nbytes, table.nbytes, table + + +def _job(store: Path) -> Any: + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + + database = DeltaTableDatabase(str(store / "results")) + with PipelineJob(name="chain", database=database) as job: + _onsets_pod().pod(_grouped_series(), label="onsets") + return job + + +def step_job_run(store: Path) -> tuple[int, int, Any]: + job = _job(store) + job.run() + return _raw(SERIES).nbytes, 0, job + + +def step_job_run_async_unkept(store: Path) -> tuple[int, int, Any]: + from orcapod.pipeline import AsyncPipelineOrchestrator + + job = _job(store) + job.run(orchestrator=AsyncPipelineOrchestrator(), materialize_results=False) + return _raw(SERIES).nbytes, 0, job + + +def step_job_run_async(store: Path) -> tuple[int, int, Any]: + from orcapod.pipeline import AsyncPipelineOrchestrator + + job = _job(store) + job.run(orchestrator=AsyncPipelineOrchestrator()) + return _raw(SERIES).nbytes, 0, job + + +def _operator_chains() -> dict[str, Callable[[], Any]]: + 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]: + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + from orcapod.pipeline import AsyncPipelineOrchestrator + + database = DeltaTableDatabase(str(store / f"results_{chain}_{orchestrator}")) + with PipelineJob(name=f"only_{chain}", database=database) as job: + _operator_chains()[chain]() + if orchestrator == "async": + job.run(orchestrator=AsyncPipelineOrchestrator()) + 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: + peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + return peak if sys.platform == "darwin" else peak * 1024 + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("step", choices=["setup", *STEPS]) + parser.add_argument("--store", required=True, type=Path) + parser.add_argument("--rows", type=int, default=2_200_000) + parser.add_argument("--tracemalloc", action="store_true") + args = parser.parse_args() + warnings.simplefilter("ignore") + + with fake.install(args.store / "spiral"): + fake.scan_batch_rows = 65_536 + if args.step == "setup": + setup(args.rows) + return + import orcapod # noqa: F401 + + gc.collect() + before = _peak_rss_bytes() + pool = pa.default_memory_pool() + if args.tracemalloc: + tracemalloc.start(1) + started = time.perf_counter() + step = STEPS[args.step] + took_store = args.step.startswith("job_") + in_bytes, out_bytes, kept = step(args.store) if took_store else step() + elapsed = time.perf_counter() - started + record: dict[str, Any] = { + "step": args.step, + "rows": _raw(SERIES).num_rows, + "input_arrow_bytes": in_bytes, + "output_arrow_bytes": out_bytes, + "rss_before_bytes": before, + "peak_rss_bytes": _peak_rss_bytes(), + "arrow_pool_peak_bytes": pool.max_memory(), + "arrow_pool_held_bytes": pool.bytes_allocated(), + "seconds": round(elapsed, 1), + } + if args.tracemalloc: + held, peak = tracemalloc.get_traced_memory() + top = tracemalloc.take_snapshot().statistics("lineno")[:8] + record["python_held_bytes"] = held + record["python_peak_bytes"] = peak + record["python_top_lines"] = [ + f"{Path(s.traceback[0].filename).name}:{s.traceback[0].lineno} {s.size}" + for s in top + ] + del kept + print(json.dumps(record)) + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1464/run_measurements.py b/docs/dev/specs/itl-1464/run_measurements.py new file mode 100644 index 000000000..ac72ac539 --- /dev/null +++ b/docs/dev/specs/itl-1464/run_measurements.py @@ -0,0 +1,114 @@ +"""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: + found = subprocess.run( + ["ps", "-o", "rss=", "-p", str(pid)], capture_output=True, text=True + ).stdout.strip() + return int(found) * 1024 if found else 0 + + +def run_step( + step: str, store: Path, guard_bytes: int, extra: list[str] +) -> dict[str, Any]: + """Run one step; kill it when its resident memory passes the guard.""" + process = subprocess.Popen( + [sys.executable, str(MEASURE), step, "--store", str(store), *extra], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + seen = 0 + while process.poll() is None: + seen = max(seen, _rss_bytes(process.pid)) + if seen > guard_bytes: + process.kill() + process.wait() + return {"step": step, "killed": True, "rss_when_killed_bytes": seen} + time.sleep(0.2) + out, err = process.communicate() + if process.returncode != 0: + return {"step": step, "failed": True, "error": err.strip()[-2000:]} + record = json.loads(out.strip().splitlines()[-1]) + for line in err.splitlines(): + if line.startswith("{"): + record.update(json.loads(line)) + return record + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--store", required=True, type=Path) + parser.add_argument("--rows", type=int, default=2_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() + + if not args.skip_setup: + subprocess.run( + [ + sys.executable, + str(MEASURE), + "setup", + "--store", + str(args.store), + "--rows", + str(args.rows), + ], + check=True, + ) + extra = ["--tracemalloc"] if args.tracemalloc else [] + guard = int(args.guard_gb * 1024**3) + with args.out.open("a") as out: + for step in args.steps: + record = run_step(step, args.store, guard, extra) + print(json.dumps(record), flush=True) + out.write(json.dumps(record) + "\n") + out.flush() + + +if __name__ == "__main__": + main() diff --git a/src/orcapod/core/sources/seen_keys.py b/src/orcapod/core/sources/seen_keys.py new file mode 100644 index 000000000..72f643d64 --- /dev/null +++ b/src/orcapod/core/sources/seen_keys.py @@ -0,0 +1,64 @@ +"""The row identifiers a source has read, to find one it reads twice (ITL-1464).""" + +from __future__ import annotations + +import hashlib +from collections.abc import Sequence +from typing import Any + +import numpy as np +import numpy.typing as npt + +_DIGEST_BYTES = 16 + + +class SeenKeys: + """The identifiers read so far, held as 16-byte digests in sorted arrays. + + A set of the identifiers themselves is a few hundred bytes a row; this is 16. The + digest is BLAKE2b with 128 bits, so that two identifiers with one digest are not + expected in any table (for a billion rows, about one chance in 10^21): an identifier + whose digest was seen is taken as seen. + """ + + def __init__(self) -> None: + # Each array is sorted, and at least twice as long as the next, so a lookup + # reads few of them and an identifier is merged few times. + self._runs: list[npt.NDArray[Any]] = [] # pyright: ignore[reportExplicitAny] # fixed-size bytes + + def add(self, identifiers: Sequence[str]) -> list[str]: + """Take ``identifiers``, all different, as seen. + + Args: + identifiers: The identifiers of the next rows. + + Returns: + Those that were seen before, sorted; none of ``identifiers`` is then added. + """ + if not identifiers: + return [] + digests = np.frombuffer( + b"".join( + hashlib.blake2b( + text.encode("utf-8", "surrogatepass"), digest_size=_DIGEST_BYTES + ).digest() + for text in identifiers + ), + dtype=f"S{_DIGEST_BYTES}", + ) + seen = np.zeros(len(digests), dtype=bool) + for run in self._runs: + at = np.searchsorted(run, digests) + seen |= run[np.minimum(at, len(run) - 1)] == digests + if seen.any(): + return sorted(identifiers[int(i)] for i in np.flatnonzero(seen)) + added = np.sort(digests) + while self._runs and len(self._runs[-1]) < 2 * len(added): + added = np.sort(np.concatenate([self._runs.pop(), added]), kind="stable") + self._runs.append(added) + return [] + + @property + def nbytes(self) -> int: + """The bytes held.""" + return sum(run.nbytes for run in self._runs) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 6312a677f..ad3294ecd 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -55,6 +55,7 @@ from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.source_ids import joined_location, location_source_name from orcapod.core.sources.derived_source import validate_tags_as_data +from orcapod.core.sources.seen_keys import SeenKeys from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, key_column_type_allowed, @@ -113,6 +114,23 @@ class _Head(NamedTuple): counted_to: int = 0 +def _reads_source_info(config: ColumnConfig) -> bool: + """Whether a table with the column groups of ``config`` needs source-info tokens. + + The tokens are one string per row and data column, many times the size of the + rows they describe (ITL-1464), so a read builds them only when its result shows + them (``source``) or hashes each row (``content_hash``: a row's hash is computed + from the row as the stream holds it). + + Args: + config: The normalized column configuration of the read. + + Returns: + True when the tokens must be built. + """ + return bool(config.source or config.content_hash) + + def _schema_difference(found: "pa.Schema", expected: "pa.Schema") -> str: """Describe how the table's columns as found differ from the ones the source expects.""" if found.names != expected.names: @@ -825,11 +843,16 @@ def _key_tokens(self, table: "pa.Table") -> list[str]: f"SpiralDB table {self._qualified!r}: {exc}" ) from exc - def _batch_streams(self) -> Generator["ArrowTableStream", None, None]: + def _batch_streams( + self, *, with_source_info: bool = True + ) -> Generator["ArrowTableStream", None, None]: """Scan the table once and yield its rows as streams of at most ``batch_rows`` rows. Each SpiralDB batch is held while its slices are yielded. + Args: + with_source_info: As for ``_read_batches``. + Raises: SourceTooLargeError: If the read would return, or returns, more than ``max_rows`` rows. @@ -839,7 +862,11 @@ def _batch_streams(self) -> Generator["ArrowTableStream", None, None]: asof = self._asof table = self._lookup_table() yield from self._read_batches( - table, asof=asof, limit=self._limit, max_rows=self._max_rows + table, + asof=asof, + limit=self._limit, + max_rows=self._max_rows, + with_source_info=with_source_info, ) def _read_batches( @@ -849,6 +876,7 @@ def _read_batches( asof: int | None, limit: int | None, max_rows: int | None, + with_source_info: bool = True, ) -> Generator["ArrowTableStream", None, None]: """Scan the table once, reading at most ``limit`` rows, in streams of ``batch_rows``. @@ -859,6 +887,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 @@ -882,7 +913,7 @@ def _read_batches( ) seen = 0 # Keys must be unique across the whole read, not only within a slice. - identifiers: set[str] = set() + identifiers = SeenKeys() for batch in table.scan_batches( where=dict(self._condition.equalities) or None, limit=limit, @@ -907,14 +938,13 @@ def _read_batches( # Tokens first: they refuse a null key before it is copied into # a non-nullable column. tokens = self._key_tokens(rows) - repeated = identifiers.intersection(tokens) + repeated = identifiers.add(tokens) if repeated: raise RowIdentifierError( f"SpiralDB table {self._qualified!r}: key " - f"{sorted(repeated)[0]} appears in two rows; key values " + f"{repeated[0]} appears in two rows; key values " "must be unique, so each row has its own identifier" ) - identifiers.update(tokens) yield self._builder.attach_provenance( self._with_tag_copies(rows), tag_columns=self._tag_columns, @@ -923,6 +953,7 @@ def _read_batches( source_id=self.source_id, row_identifiers=tokens, data_tags=self._data_tags, + with_source_info=with_source_info, ) def iter_data(self) -> Iterator["tuple[TagProtocol, DataProtocol]"]: @@ -959,8 +990,11 @@ def as_table( all_info: bool = False, ) -> "pa.Table": """Scan the table and return its rows as one PyArrow table (all held in memory).""" + config = ColumnConfig.handle_config(columns, all_info=all_info) return self._whole_table( - self._batch_streams(), columns=columns, all_info=all_info + self._batch_streams(with_source_info=_reads_source_info(config)), + columns=columns, + all_info=all_info, ) def _whole_table( @@ -972,8 +1006,10 @@ def _whole_table( ) -> "pa.Table": """Return the rows of ``streams`` (batches of one read) as one table.""" # One stream over all the rows, so that a whole-table option (sorting by - # tags) applies across batches. - enriched = {"source": True, "system_tags": True} + # tags) applies across batches. The source-info tokens are carried only for + # a result that shows or hashes them (ITL-1464). + config = ColumnConfig.handle_config(columns, all_info=all_info) + enriched = {"source": _reads_source_info(config), "system_tags": True} tables = [stream.as_table(columns=enriched) for stream in streams] if not tables: return self._stream.as_table(columns=columns, all_info=all_info) diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 5fbb8eb52..6ece00b22 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -590,6 +590,7 @@ def attach_provenance( source_id: str, row_identifiers: Sequence[str], data_tags: Sequence[str] = (), + with_source_info: bool = True, ) -> ArrowTableStream: """Add source-info and system-tag columns to ``table`` and wrap it as a stream. @@ -611,19 +612,25 @@ def attach_provenance( source. data_tags: The tag columns that are also data columns (data-tags); they get source info like any data column. + with_source_info: Whether to build the source-info tokens. ``False`` only + for a read whose caller keeps no source-info column and hashes no row + (ITL-1464): the tokens are one string per row and data column, many + times the size of the rows. The stream then holds null tokens and + must not be handed on. Returns: The stream over the enriched table. """ - source_info = [ - f"{source_id}{constants.BLOCK_SEPARATOR}{identifier}" - for identifier in row_identifiers - ] - table = arrow_utils.add_source_info( - table, - source_info, - exclude_columns=[c for c in tag_columns if c not in data_tags], - ) + if with_source_info: + source_info = [ + f"{source_id}{constants.BLOCK_SEPARATOR}{identifier}" + for identifier in row_identifiers + ] + table = arrow_utils.add_source_info( + table, + source_info, + exclude_columns=[c for c in tag_columns if c not in data_tags], + ) table = arrow_utils.add_system_tag_columns( table, schema_hash, diff --git a/tests/test_core/sources/test_seen_keys.py b/tests/test_core/sources/test_seen_keys.py new file mode 100644 index 000000000..decb19182 --- /dev/null +++ b/tests/test_core/sources/test_seen_keys.py @@ -0,0 +1,44 @@ +"""The identifiers a source has read, held as digests (ITL-1464).""" + +from __future__ import annotations + +import random + +import pytest + +from orcapod.core.sources.seen_keys import SeenKeys + + +@pytest.mark.parametrize("seed", range(20)) +def test_it_finds_what_a_set_of_the_identifiers_finds(seed: int) -> None: + rng = random.Random(seed) + seen, expected = SeenKeys(), set[str]() + for _ in range(40): + size = rng.choice([0, 1, 2, 3, 50, 400]) + batch = list({f'{{"k":{rng.randrange(60_000)}}}' for _ in range(size)}) + repeated = sorted(expected.intersection(batch)) + assert seen.add(batch) == repeated + if not repeated: + expected.update(batch) + + +def test_any_text_is_an_identifier() -> None: + texts = ["", "a", "a\x00", "\x00", "é", "\ud800", "b" * 10_000] + seen = SeenKeys() + assert seen.add(texts) == [] + for text in texts: + assert seen.add([text]) == [text] + + +def test_a_batch_with_a_repeated_identifier_adds_nothing() -> None: + seen = SeenKeys() + assert seen.add(["a"]) == [] + assert seen.add(["b", "a"]) == ["a"] + assert seen.add(["b"]) == [] + + +def test_it_holds_sixteen_bytes_an_identifier() -> None: + seen = SeenKeys() + for start in range(0, 100_000, 1_000): + assert seen.add([f"key {i}" for i in range(start, start + 1_000)]) == [] + assert seen.nbytes == 1_600_000 diff --git a/tests/test_core/sources/test_spiraldb_table_source_tokens.py b/tests/test_core/sources/test_spiraldb_table_source_tokens.py new file mode 100644 index 000000000..658ef73c6 --- /dev/null +++ b/tests/test_core/sources/test_spiraldb_table_source_tokens.py @@ -0,0 +1,215 @@ +"""A SpiralDB read builds source-info tokens only for a result that holds them (ITL-1464). + +The tokens are one string per row and data column, many times the size of the rows. A +read whose table shows no source-info column and no content hash must not build them, +and must return exactly the table the read that builds them returns. + +Runs against the disk-backed fake of the SpiralDB client. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.core.sources import spiraldb_table_source as source_module +from orcapod.sources import SpiralDBTableSource +from orcapod.utils import arrow_utils +from tests.test_databases import fake_spiral_sdk + +_PROJECT = "sample" +_KEYS = pa.schema( + [pa.field("subject_id", pa.string()), pa.field("timestamp", pa.uint64())] +) +_ROWS = 5 + +# Column configurations whose table holds no token and no row hash. +_WITHOUT_TOKENS: list[dict[str, Any]] = [ + {}, + {"system_tags": True}, + {"context": True}, + {"meta": True}, + {"sort_by_tags": True}, + {"system_tags": True, "context": True, "sort_by_tags": True}, +] +# Column configurations whose table holds the tokens or a hash computed from the rows. +_WITH_TOKENS: list[dict[str, Any]] = [ + {"source": True}, + {"content_hash": True}, + {"source": True, "system_tags": True, "sort_by_tags": True}, +] + + +def _rows() -> pa.Table: + """Five rows with two key columns and two value columns, not in key order.""" + timestamps = [4, 1, 5, 2, 3] + table = pa.table( + { + "subject_id": ["m1", "m1", "m2", "m2", "m1"], + "timestamp": pa.array(timestamps, pa.uint64()), + "amplitude": pa.array([t + 0.5 for t in timestamps], pa.float32()), + "quality": pa.array(["a", None, "c", "d", "e"], pa.string()), + } + ) + return table.cast(pa.schema([pa.field(f.name, f.type, True) for f in table.schema])) + + +@pytest.fixture() +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """Provide a fake project holding ``event``, scanned 2 rows per batch.""" + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 2) + with fake_spiral_sdk.install(tmp_path / "spiral"): + made = fake_spiral_sdk.ExternalProject(_PROJECT) + made.create_table("default.event", key_schema=_KEYS).write(_rows()) + yield made + + +@pytest.fixture() +def token_builds(monkeypatch: pytest.MonkeyPatch) -> list[int]: + """Record the row count of every table the source builds tokens for.""" + calls: list[int] = [] + original = arrow_utils.add_source_info + + def recording(table: pa.Table, *given: Any, **options: Any) -> pa.Table: + calls.append(table.num_rows) + return original(table, *given, **options) + + monkeypatch.setattr(arrow_utils, "add_source_info", recording) + return calls + + +def _source(tag_only: bool) -> SpiralDBTableSource: + return SpiralDBTableSource(_PROJECT, "event", tag_only_columns=tag_only) + + +def _with_tokens_always(monkeypatch: pytest.MonkeyPatch) -> None: + """Make every read build the tokens, as every read did before ITL-1464.""" + monkeypatch.setattr(source_module, "_reads_source_info", lambda config: True) + + +@pytest.mark.parametrize("tag_only", [False, True], ids=["data_tags", "tag_only"]) +@pytest.mark.parametrize("columns", _WITHOUT_TOKENS) +def test_a_table_without_tokens_builds_none_and_equals_the_one_that_did( + project: Any, + token_builds: list[int], + monkeypatch: pytest.MonkeyPatch, + tag_only: bool, + columns: dict[str, Any], +) -> None: + source = _source(tag_only) + token_builds.clear() + + table = source.as_table(columns=columns) + + assert token_builds == [] + assert table.num_rows == _ROWS + with monkeypatch.context() as patched: + _with_tokens_always(patched) + expected = _source(tag_only).as_table(columns=columns) + assert sum(token_builds) == _ROWS + assert table.schema.equals(expected.schema, check_metadata=True) + assert table.equals(expected) + + +@pytest.mark.parametrize("tag_only", [False, True], ids=["data_tags", "tag_only"]) +@pytest.mark.parametrize("columns", _WITH_TOKENS) +def test_a_table_with_tokens_or_row_hashes_still_builds_them( + project: Any, + token_builds: list[int], + monkeypatch: pytest.MonkeyPatch, + tag_only: bool, + columns: dict[str, Any], +) -> None: + source = _source(tag_only) + token_builds.clear() + + table = source.as_table(columns=columns) + + assert sum(token_builds) == _ROWS + with monkeypatch.context() as patched: + _with_tokens_always(patched) + expected = _source(tag_only).as_table(columns=columns) + assert table.schema.equals(expected.schema, check_metadata=True) + assert table.equals(expected) + + +@pytest.mark.parametrize("tag_only", [False, True], ids=["data_tags", "tag_only"]) +def test_all_info_holds_every_token( + project: Any, token_builds: list[int], tag_only: bool +) -> None: + source = _source(tag_only) + + table = source.as_table(all_info=True) + + assert sum(token_builds) == _ROWS + tokens = [name for name in table.column_names if name.startswith("_source_")] + # A data-tag has a token; a tag kept tag-only has none. + expected = {"_source_amplitude", "_source_quality"} | ( + set() if tag_only else {"_source_subject_id", "_source_timestamp"} + ) + assert set(tokens) == expected + by_time = dict( + zip( + table.column("timestamp").to_pylist(), + table.column("_source_amplitude").to_pylist(), + strict=True, + ) + ) + assert by_time[4] == ( + f'{source.source_id}::{{"subject_id":"m1","timestamp":4}}::amplitude' + ) + for name in tokens: + assert table.column(name).null_count == 0 + + +def test_run_and_the_data_frame_build_no_tokens( + project: Any, token_builds: list[int] +) -> None: + source = _source(False) + token_builds.clear() + + view = source.run() + frame = source.as_polars_df() + + assert token_builds == [] + assert view.total_rows == _ROWS + assert frame.height == _ROWS + assert frame.columns == source.as_table().column_names + + +@pytest.mark.parametrize("tag_only", [False, True], ids=["data_tags", "tag_only"]) +def test_an_operator_over_the_source_still_reads_its_tokens( + project: Any, monkeypatch: pytest.MonkeyPatch, tag_only: bool +) -> None: + kept = _source(tag_only).drop_nulls(["quality", "amplitude"]) + + table = kept.as_table(all_info=True) + + assert table.num_rows == _ROWS - 1 + assert table.column("_source_quality").null_count == 0 + assert table.column("_source_amplitude").null_count == 0 + with monkeypatch.context() as patched: + _with_tokens_always(patched) + expected = ( + _source(tag_only) + .drop_nulls(["amplitude", "quality"]) + .as_table(all_info=True) + ) + assert table.equals(expected) + + +def test_iteration_still_gives_each_row_its_tokens(project: Any) -> None: + source = _source(False) + + tokens = { + tag.as_dict()["timestamp"]: data.source_info()["quality"] + for tag, data in source.iter_data() + } + + assert tokens[2] == ( + f'{source.source_id}::{{"subject_id":"m2","timestamp":2}}::quality' + ) + assert len(tokens) == _ROWS