diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md new file mode 100644 index 000000000..82700024e --- /dev/null +++ b/changelog.d/ITL-1464.md @@ -0,0 +1,43 @@ +### Added + +- `stream.preview(n)`: the first `n` rows of a stream that is not computed, computing only what + they need (ITL-1464). Functions are called on as few rows as that takes; nothing is kept, + stored or delivered. A step that needs its whole input (a join, `group_by`, ...) is refused + unless `compute_all=True`. + +### 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). +- Reading a source and applying an operator that selects, renames, filters or tags rows + no longer builds the source-info text of every row and column. The text is built when + it is shown, stored or handed to a function, a part of the rows at a time, so these + steps take a few times the memory of their data instead of tens of times (ITL-1464). + Values, hashes and stored tables are unchanged. +- `run()` of a `SpiralDBTableSource`, and of column selections, renames, `add_tags`, + `drop_nulls` and `filter` over one, reads the table in batches and no longer holds a result + of more than 50,000 rows or 64 MiB of values (ITL-1464). The view then has the row count and the first and the + last 1,000 rows; it is displayed as before, and its `table`, `as_table()`, + `as_polars_df()`, `sort_by_tags()` and a longer `head` or `tail` raise `BoundedViewError`, + which names the stream's own methods. `stream.as_table()` and iteration are unchanged; after + such a run `as_table()` reads the source again. Smaller results, and every other stream, + are as before. +- 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/concepts/streams.md b/docs/concepts/streams.md index 40c13de07..2374dc404 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -181,9 +181,10 @@ print(months.head(3).header()) ### Computing a stream outside a job: `run()` Every stream, source and node has `run()`, with no arguments: it is the one way to compute -any of them outside a job (developer, November 13, 2026). It does exactly the work -`as_table()` does, through the same cache, and returns a `StreamView` of every row with the -default columns. A stream already computed is not computed a second time; one whose input +any of them outside a job (developer, November 13, 2026). It computes every row, with every +effect, in the order of `as_table()`, and returns a `StreamView` with the default columns. It +promises nothing about how the rows are produced or what is held meanwhile (developer, +November 24, 2026). A stream already computed is not computed a second time; one whose input changed is recomputed. In a notebook, `stream.run()` at the end of a cell computes and displays. The view's own methods choose what is shown. Each returns a new view and never reads or @@ -209,21 +210,69 @@ view does not hold, so it keeps them in the order it has them. The display of a such as the one `run()` returns, shows its first and last five rows when it has more than ten, and its header gives the count. +A view holds every row of the stream, with one exception, the bounded view. A +`SpiralDBTableSource` holds no rows, and `run()` reads it in batches; so are read the +operators that choose or rename columns, add tags or drop rows (`select_*`, `drop_*`, +`map_*`, `add_tags`, `drop_nulls`, `filter`) and the chains of them over such a source. A +result of at most 50,000 rows and 64 MiB of values (the values themselves, whatever their +layout in memory), or of at most 2,000 rows, is held, as everywhere else. A larger one is not: its view has +the row count, the columns, and the first and the last 1,000 rows. It is displayed as any +view, and `head(n)` and `tail(n)` up to 1,000 rows give what any view gives. What needs the +other rows (`table`, `as_table()`, `as_polars_df()`, `sort_by_tags()`, a longer `head` or +`tail`) raises `BoundedViewError`: a part is never given as the whole. Ask the stream itself, +`stream.as_table()`, which reads the source again and applies the operators again (no function +of yours runs a second time). `stream.head(n)` after such a run shows its first rows. Whether +a view is bounded depends only on the kind of stream and on its rows, so equal data +always gives the same kind of view. A `polars_filter`, `pick`, `index`, `tag_by`, join, +`group_by` or `batch`, a function pod, and everything after one, computes its whole result +and holds it, also over a `SpiralDBTableSource`. + A view holds the default column groups only. For system tags, source info, the data context or content hashes, ask the stream after `run()`. A function pod's or operator's output stream, a job node (a job's side-effect node included), an in-memory source and a `CachedSource` keep the rows `run()` gave: their `as_table(columns=...)` and `head(columns=...)` read those rows, compute nothing and deliver no side effect. Other streams do their `as_table()` work again: a side-effect stream outside a job delivers its side effects again (its `head()` shows no rows), -a polling source polls again and a `SpiralDBTableSource` reads its whole table again. A view never asks its stream for more columns, because for those +a polling source polls again and a `SpiralDBTableSource` reads its whole table again (so does +an operator's stream whose `run()` gave a bounded view). A view never asks its stream for more columns, because for those streams asking again is not a read. +### The first rows of a stream not computed yet: `preview(n)` + +`head()` never computes, so it has nothing to show of a derived stream nobody ran. +`preview(n)` computes the first `n` rows of `as_table()`, and only what they need: + +```python +first = months.preview(2) +print(first.header()) +# FunctionPodStream[months] — preview: first 2 rows (run() computes every row) +print(first.as_table().column("age_months").to_pylist()) +# [108, 120] +``` + +A source reads no more than is needed, an operator takes batches until enough rows have +passed, and **your functions are called**, on one row after another until `n` rows have come +out. Nothing is kept on a stream, nothing is stored (a pod with stored results reads them and +adds none), and no hook fires; calling `preview` again computes again. Results a stream +already holds are used. A view of fewer rows than asked for says it shows all of them. + +A join, `group_by`, `batch`, `polars_filter`, `tag_by`, `pick`, `index` or an operator of your +own needs every row of its input, so `preview` refuses it (`PreviewRefusedError`, naming the +step). `preview(n, compute_all=True)` computes that step and everything beneath it in full, +functions included, and keeps none of it. A side-effect pod, a function that takes the +invocation context, a `CachedSource`, a `PollingSource` and a node of a pipeline or job are +refused always: a preview never acts. A `semi_join` whose inputs share no tag keeps every row +of its left input and never reads its right one, so `preview` reads only the left input, as +the full read does. A `DerivedSource` over a source shows its origin's first rows through +the origin's own `preview` (refused for a `CachedSource` or `PollingSource` origin); over a +job node it reads the stored rows, only with `compute_all=True`. It keeps none of them. + What `run()` does on each kind of object: | Object | `run()` | |---|---| | An in-memory source (`DictSource`, `ArrowTableSource`, ...), a Delta or SQL table source | nothing to compute: a view of the rows it holds | -| A `SpiralDBTableSource` | reads the whole table into memory (`head()` is the bounded read); every call reads again | +| A `SpiralDBTableSource` | reads the whole table in batches (`head()` is the bounded read); every call reads again; a bounded view above 50,000 rows or 64 MiB | | A `PollingSource` (provisional, see [Provisional sources](sources.md#provisional-sources)) | polls, as `as_table()` does | | A `CachedSource` | reads its cache and writes the wrapped source's new rows to it | | A function pod's or operator's output stream | computes what is not computed yet | diff --git a/docs/dev/specs/itl-1464-integration.md b/docs/dev/specs/itl-1464-integration.md new file mode 100644 index 000000000..432e6f3be --- /dev/null +++ b/docs/dev/specs/itl-1464-integration.md @@ -0,0 +1,98 @@ +# The ITL-1464 tracks together: batch edges, and what a whole analysis costs + +## What connects the tracks + +- **Edges.** An async job's edge carries `(Tag, Data)` pairs or record batches of a node's + rows (`core/job_edges.py`, over the channels of `orcapod.channels`). A source node whose + table is provably its rows, and an operator node, send batches of at most 8,192 rows; a + node that knows only pairs (a function, a side effect) is given pairs, made as it reads. +- **Operator nodes** run `async_execute_batches` over the edges, when the operator and every + operator above it are the library's own classes and everything is in the default data + context. Otherwise they run the row form, unchanged. Each input channel's stream is the + node's own input, so a uniqueness certificate is the node's. `Filter` is row by row. +- **Token recipes** travel between nodes on both paths; text is made where a row, a store or + a hash needs it. A join over an aggregation's output runs on its whole inputs: a kernel's + files cannot share the ids that derived token lists share. +- **Kept rows** (a node's output, a barrier's input, a sync source's table) go through a + `RowSpool`; rows with derived token lists stay in memory, where they share their ids. +- One async run derives each node's zero-row table and certificate once. + +## Measured + +`docs/dev/specs/itl-1464/chain.py`: 8.1 million events and 2.2 million series rows at 100%, +read by the real source over the fake client. Peak physical footprint / peak resident memory +in GB, and seconds. Memory beyond the footprint is memory-mapped pages of local files. + +Async: + +| Step | 25% | 50% | 100% | +|---|---|---|---| +| events semi-joined with the kept items | 0.4 / 1.1, 15 s | 0.5 / 1.8, 32 s | 0.7 / 3.2, 66 s | +| then filtered by time | 0.5 / 1.6, 15 s | 0.7 / 2.9, 32 s | 0.8 / 5.3, 68 s | +| then joined with a lookup table | 0.6 / 2.8, 17 s | 0.8 / 5.2, 34 s | 1.0 / 10.0, 85 s | +| filtered events grouped by item | 2.1 / 3.5, 27 s | 3.9 / 6.8, 55 s | 4.6 / 9.4, 115 s | +| series filtered, grouped, one function | 1.4 / 2.1, 8 s | 2.6 / 3.7, 15 s | 4.5 / 8.2, 33 s | +| the whole job | 3.0 / 4.4, 38 s | 5.3 / 8.2, 78 s | 7.4 / 20.0, 164 s | + +The 100% column includes the aggregation step that sorts text by rank and spools token +lists (#573); the 25% and 50% columns were measured before it. It lowers the footprint and +raises resident memory (mapped pages). + +Sync: + +| Step | 25% | 50% | 100% | +|---|---|---|---| +| semi-join | 1.8 / 2.6, 14 s | 3.2 / 4.6, 32 s | 6.0 / 8.9, 67 s | +| filter | 1.8 / 3.0, 15 s | 3.2 / 5.5, 33 s | 6.0 / 10.6, 69 s | +| lookup join | 2.3 / 5.0, 15 s | 4.2 / 9.3, 32 s | 7.5 / 18.6, 72 s | +| group by | 2.5 / 4.2, 25 s | 4.4 / 7.8, 55 s | 6.0 / 12.0, 115 s | +| series and function | 1.9 / 2.7, 7 s | 3.9 / 5.0, 14 s | 5.8 / 10.8, 30 s | +| the whole job | 4.8 / 7.1, 37 s | 8.7 / 13.3, 71 s | above 24 GB, killed | + +`main` at 25%: the semi-join takes 10.7 / 10.9, 12 s on sync; the semi-join on async, and +the lookup join and the whole job on both paths, pass 24 GB and are killed. + +Row-by-row steps are slower on sync than on `main` (12 s to 14 s here): the source's rows go +through a local file. + +## The shape of a real analysis: longer ids, a function per group + +`chain.py setup --items 140 --id-length 72` (98 groups kept), async, the whole job. Peak +physical footprint in GiB: + +| Job | 25% | 50% | 100% | +|---|---|---|---| +| with a cheap function per group | 2.3 | 4.2 | not completed: killed above 24 GiB of resident memory, at a footprint of at least 6.5 | +| with one outer product of a group's event times and all peak times in the function | 13.6 | not run | not run | +| the same, `PodConfig(max_concurrency=4)` | 5.4 | | | +| the same, `PodConfig(max_concurrency=1)` | 3.5 | | | + +Function calls have no limit by default (`default_max_concurrency` is `None`): 22 ran at once +here, the size of the event loop's thread pool. Each held 0.3 GiB for each of two arrays at +25%; such a function's arrays grow with events times peaks, so 16 times at 100%. No library +change bounds that: a limit on calls in flight, or a function that does not build the product. + +At 100% the mapped pages (14 of 21 GiB resident when the run was killed) are what a guard on +resident memory counts. + +## What is bounded, and what is not + +Bounded on async: sources, row-by-row operators, joins with a small or certified side. They +grow by the digests of the keys read (16 bytes a row), and by file pages the system can drop. +Whether a container that counts mapped pages drops them in time is not tested. + +Not bounded, in the order of their cost in the whole job at 100%: + +1. Writing a function node's stored rows (the peak of the whole job when profiled, before #573): a row holds the source-info text + of its inputs' token lists, millions of tokens in one row, and the Delta writer holds + copies. The stored layout decides the text. +2. `GroupBy` over its whole input (4.6 GB for 5.7 million member rows): the sort of its members + and the copies of what it takes. The members' data it keeps is 64 MB; the rest is ids. +3. A function's input row that is one large group: its token text, then Python lists. +4. On sync, each operator's own whole result while it is moved to local disk. + +## Gates + +The ITL-1347 differential against `main` (both fixtures, all modes, one and default Polars +threads): sync exact and async as sets, all equal. At the final head: equal, and 24,560 tests pass. Every operator node's rows, system tags +and tokens in the job above, at 0.5%, have `main`'s digests on both paths. diff --git a/docs/dev/specs/itl-1464-joins.md b/docs/dev/specs/itl-1464-joins.md new file mode 100644 index 000000000..e0db714d1 --- /dev/null +++ b/docs/dev/specs/itl-1464-joins.md @@ -0,0 +1,224 @@ +# Joins that hold keys, and certificates of unique tags (ITL-1464) + +Status: implemented with this document, November 25, 2026; design decisions approved by the +coordinator under the developer's delegation. It covers `Join`, `MergeJoin`, `SemiJoin` and +two-input `Rejoin` over record-batch channels (`async_execute_batches`). No job node calls +that form yet: the transport work of ITL-1464 wires it, and until then a job's memory is as +before. The sync path is unchanged, and no hash, identity, stored row or golden value moves. + +## What an async join holds + +A binary join step keeps, per row of **one** side that can still match, its prepared join +keys and its row number (a Polars frame, `streaming_joins._Side`); rows are in a row spool +(`core/row_spool.py`). Matching is the sync path's (`join._matched_pairs` on +`arrow_keys.polars_key_frame`), one vectorized join per arriving batch, and every value is +taken from the rows by number, so it is the input's, bit for bit. + +| Step | Held | When rows are emitted | +|---|---|---| +| both sides certified unique on the shared tags (1:1) | keys of the rows not matched yet; both rows of a pair go when they match | as they match | +| any other | keys of the smaller side; a row of it goes when it matches, if the other side is certified unique | once the smaller side is known | +| `SemiJoin` | the distinct keys of the right input | once the right input has ended | +| `Rejoin` of two inputs | shared columns of the rows not matched yet | as they match | + +**Which side is indexed.** While both sides are open, the rows of both are spooled without +keys. When a side ends with at most 65,536 rows it is indexed. When it ends with more, the +other side is spooled on until it has as many rows (the ended side is indexed) or ends with +fewer (it is indexed itself). The other side's spooled rows are then matched, a block at a +time, and let go; rows still to arrive are matched at once and not held. + +**Cost.** *Latency*: such a step gives no row before a side has ended and, when that side is +large, before the other has delivered as many rows or ended. An endless second input is +joined as it arrives from then on. *Disk*: each side's rows are written at most once, so at +most both inputs' rows; a chain's middle result counts as an input of its next step. A +replayed file is deleted when its rows are matched. + +**Nothing is held back.** Every input is read at once and to its end, each until 65,536 rows +wait for the join (the producer's last batch is taken whole). Draining one side while the +other waits is not safe, not even for inputs with no common upstream: of two joins of the +same two producers, one may hold back the one the other waits for. + +A join of three or more inputs is a chain of such steps in canonical order; each step's left +side has the certificate of the rows joined so far (`unique_keys.joined_keys`). + +Memory, per indexed row: the prepared key (16 bytes per string, plus its length when above +12 bytes; 8 per integer, timestamp or float; 1 for the constant key), 8 for the row number, +9 for its place and whether it is held. Beside it: at most 64 MiB of rows per side before +they go to disk, the batches in flight, a block of 65,536 rows being replayed, and one +output piece of at most 8,192 pairs. A many-to-many output is never held: the pairs are +counted first, then made in pieces; one arriving row with more pairs than a piece has its +pairs listed (16 bytes each, at most the indexed rows) and is sent in pieces. + +`Rejoin` of three or more inputs stays a barrier, because with repeated origin rows which +repeats are matched follows the whole inputs. A subclass or a customized instance of an +operator runs its own sync call over its whole inputs. A stream must implement the whole +`StreamProtocol` (`unique_keys` included): protocols are internal, and every stream class +of the library and everything built on `StreamBase` does. + +## What changes for users + +Once job nodes run joins this way (async runs only; the sync path is unchanged): + +- **Memory**: an async join holds the join keys of its smaller input (of both inputs' rows not + matched yet, when both are certified unique on the shared tags) and no rows beyond 64 MiB + per input, whatever its inputs and output are. +- **Latency**: a join that is not one to one gives its first row only once one input has + ended and, when that input has more than 65,536 rows, once the other has delivered as many + or ended. A semi-join gives its first row once its right input has ended. One-to-one joins + and two-input rejoins give rows as they match. +- **Local disk**: at most both inputs' rows (a chain's middle results count as inputs), in + the system's temporary directory, removed when the join ends, however it ends. A full disk + fails the run with the operating system's error. +- **Row order** of an async result still follows arrival and is not a result. + +## The row spool + +Rows past the memory limit become a file each: an uncompressed Arrow IPC file of one record +batch, read memory-mapped, under a directory of this process in the system's temporary +directory. A file is deleted when its last row is discarded; the rest at a normal end, a +failure, a cancellation, collection and exit. A killed process leaves its directory; the +next process to spill there removes it (it holds no lock any more). A spool belongs to one +process, whose threads may all use it, one call at a time; a forked child's copy refuses +every read and write. + +## Certificates + +`StreamProtocol.unique_keys` is a set of tag sets on which no two rows agree, under the +joins' equality. It is derived when asked and stored nowhere: in no hash, identity, config, +stored row or equality. A wrong certificate would lose rows, so only what is certain is +certified: a rule is read from the exact class, and only while no member of the instance is +replaced (`reads_as_its_class`), for the source, the pod, the stream and the node alike. A +subclass or a customized instance certifies nothing, and a customized join runs its own sync +call over its whole inputs. + +| Stream | Certificate | +|---|---| +| `ArrowTableSource`, `DictSource`, `ListSource`, `DataFrameSource`, SQLite and PostgreSQL tables | the key columns, when all are tags | +| every other source; a raw `ArrowTableStream`, also with a producer | none | +| `DropNulls`, `Filter`, `PolarsFilter`, `AddTags`, `TagBy`, `Pick`, `Index`, `MapData`, the data column selections, function pods (`FunctionPod`, `CachedFunctionPod`), `SideEffectPod` | the input's | +| the tag selections and drops | the input's keys whose tags all stay | +| `MapTags`, `MapColumns` | the input's keys renamed, without those that lose a tag | +| `GroupBy` | its keys | +| `Batch` | none | +| `SemiJoin` | the left input's | +| `Join`, `MergeJoin` on shared tags S | unions of one key of each side; a side's own keys when the other side is unique on S | +| `Rejoin` | every input's (a row is in at most one result row) | +| a source slot | its bound source's | +| an operator job node in `REPLAY` mode | none: it replays every logged run | + +Why a source's key columns are certain: those source kinds build every row through +`SourceStreamBuilder`, which names a row by its key columns and refuses a null or repeated +key, on every read. The record id is a function of the key values and a key is a string, an +integer, a boolean, a timestamp or a date (never a float), so two rows whose keys are equal +to a join have one record id and are refused. + +That direction is the safe one for a database: a store whose equality is coarser than the +join's (a case-insensitive collation, padded `CHAR`) never holds two keys the join takes as +equal; one whose equality is finer (a float key, a timestamp read at a coarser unit) could. +No store is trusted here: the SQL sources are checked as read. A later step may trust a +store's key instead of checking it, only under those conditions and only for a key without +nulls. + +CSV and Delta (a running check is a later step), `CachedSource` (rows of earlier reads), +`DerivedSource` and `PollingSource` certify nothing. + +## Measured + +`docs/dev/specs/itl-1464-joins/measure.py`, each case in a fresh process, synthetic rows +with their source-info tokens, sent and read through bounded +channels. Peak RSS includes 143 MiB of imports and the mapped pages a join reads. "Barrier" +is the form before this change. It is the operator alone, not a job. + +| Case | Rows | Form | Output rows | Peak RSS | Arrow pool peak | Disk peak | Time | +|---|---|---|---|---|---|---|---| +| `lookup` (300 units first) | 1,000,000 | barrier | 1,000,000 | 1,793 MiB | 1,323 MiB | | 2.3 s | +| `lookup` | 8,000,000 | keys | 8,000,000 | 221 MiB | 10 MiB | 0 | 21.3 s | +| `lookup_late` | 1,000,000 | keys | 1,000,000 | 455 MiB | 131 MiB | 128 MiB | 2.7 s | +| `lookup_late` | 8,000,000 | keys | 8,000,000 | 481 MiB | 132 MiB | 1,480 MiB | 21.0 s | +| `one_to_one` (in step) | 8,000,000 | keys | 8,000,000 | 262 MiB | 27 MiB | 0 | 39.2 s | +| `one_to_one_late` | 1,000,000 | barrier | 1,000,000 | 2,574 MiB | 1,854 MiB | | 4.4 s | +| `one_to_one_late` | 1,000,000 | keys | 1,000,000 | 754 MiB | 157 MiB | 128 MiB | 5.5 s | +| `one_to_one_late` | 8,000,000 | keys | 8,000,000 | 2,456 MiB | 435 MiB | 1,480 MiB | 64.6 s | +| `many` (5 per row) | 1,000,000 | barrier | 5,000,000 | 4,835 MiB | 4,111 MiB | | 2.4 s | +| `many` | 8,000,000 | keys | 40,000,000 | 330 MiB | 57 MiB | 0 | 29.8 s | +| `many_open` (5 per row) | 1,000,000 | barrier | 5,000,000 | 6,068 MiB | 5,002 MiB | | 4.2 s | +| `many_open` | 1,000,000 | keys | 5,000,000 | 684 MiB | 194 MiB | 259 MiB | 6.9 s | +| `many_open` | 8,000,000 | keys | 40,000,000 | 1,793 MiB | 423 MiB | 2,528 MiB | 62.4 s | +| `semi` | 8,000,000 | keys | 8,000,000 | 214 MiB | 8 MiB | 0 | 20.1 s | +| `semi_late` | 8,000,000 | keys | 8,000,000 | 477 MiB | 132 MiB | 1,480 MiB | 19.6 s | +| `rejoin` (two branches in step) | 8,000,000 | keys | 8,000,000 | 320 MiB | 51 MiB | 0 | 51.9 s | + +The "keys" rows are with derived tokens, the barrier rows (measured before) with text. The +disk peak is sampled every 0.2 s. What still grows with the rows: `many_open`, two inputs of +equal size with no certificate, by the keys of one of them; and `one_to_one_late`, where one +certified input arrives whole before the other, by its keys. Times were taken with other +work on the machine. + +## Batches with derived source-info tokens + +A channel and the kernels take a batch whose source-info columns are derived +(`utils/source_tokens.py`): such a column has no bytes, so it costs a held or spooled row +nothing. Derived columns travel between the library's operators only +(`streams/carried.py`; a channel's protocol has no such read): every public read of a channel (`receive`, iteration, +`collect`) gives text, and a stream is read through its own `as_table` unless its class is a +library class that declares the carried read. Batches of one input may hold a column as text +in one and derived in another, however they arrive: from the first change on, rows are held +as text, the rows before it go to disk, and rows fetched from both are text. + +Channels carry no per-row data context, as before (ITL-1347): every row of an input has its +stream's. A two-input `Rejoin` of raw streams that hold rows of several contexts therefore +matches on the streams' contexts over channels, where the sync path over the raw streams +matches on each row's. This is unchanged: the barrier did the same (ITL-1359). + +Text is built where values are needed: a source-info column both inputs of a `MergeJoin` +have, a merged data-tag one side of which is text, and the tokens that read system tags whose +values a join of one pipeline hash sorts. `Rejoin`'s kernel builds all of it. + +## The bytes of a held key row + +Measured on 4,000,000 rows with the keys of the benchmark (two strings of 24 and 10 +characters and one integer), as the growth of the process's physical footprint: + +| Form held | Bytes per row | Probe of 65,536 rows | +|---|---|---| +| the prepared key frame (what a join holds) | 95 | 26 ms, and about 100 more bytes per row while it runs | +| the same, strings as Polars categories | 38 | 15 ms, about 115 more | +| a 64-bit hash of the prepared key and a row number | 23 | 5 ms, 4 more | + +Of the 95 bytes, 42 are the key's data and 9 the row number and the constant key; the rest is +the string views and buffers Polars keeps. The join's own 9 bytes per row (its place and +whether it is held) are beside every form. These are measurements of the frames, not of a +whole join. + +### A hash index (not built; for the developer) + +The index would hold, for a key without a nested column, the 64-bit `hash_rows` of the +prepared key and the row number. An arriving batch's hashes pick candidate pairs; the rows of +the candidates are fetched, as they are for the output anyway, and each candidate pair is +matched by `join._matched_pairs` on its real keys (with the pair's number as one more key). +So there is one equality rule, and two keys of one hash cost a fetch, never a wrong row. + +Gain, estimated and not measured: the 1:1 case with one input entirely first (2,456 MiB at +8,000,000 rows) would fall well below 1 GiB, and a probe would take a fifth of the time. + +Risk: it rests on keys that a join takes as equal having equal hashes, across frames, chunks +and slices. Polars documents no such promise for `hash_rows`. If it failed, a pair would be +missing from the output and nothing would say so. The coordinator deferred it for that +reason (November 25, 2026): the memory of today's form fits the target. + +Checked so far, by hand and not as a test: signed zeros and NaNs of several payloads at +64 bits, signed zeros and NaNs at 32 bits, floats in lists and structs, strings across chunks +and slices. + +Test plan, if it is built: + +1. For every key type a join allows (`arrow_keys.part_without_rule`), every pair of values of + the types' edge pools: the join's equality implies equal hashes. +2. The same with the two keys in different frames, chunk layouts, slices and frames of other + columns beside them, and with strings on both sides of the 12-byte view limit. +3. The certificate graphs (`test_certificate_graphs.py`) and every kernel test, run with both + indexes: equal rows. +4. A run with every hash forced equal (all candidates), and with a hash of few bits: equal + rows, bounded memory of the candidates. +5. A check at the first batch of a run that Polars' hashes of fixed vectors (signed zeros, + NaN payloads, a sliced string) agree with the join; if not, the frame index is used. diff --git a/docs/dev/specs/itl-1464-joins/measure.py b/docs/dev/specs/itl-1464-joins/measure.py new file mode 100644 index 000000000..b45de8f74 --- /dev/null +++ b/docs/dev/specs/itl-1464-joins/measure.py @@ -0,0 +1,276 @@ +"""One async join over record-batch channels, its time and peak memory (ITL-1464). + +Usage: ``measure.py [barrier]``. Synthetic rows; the inputs are sent batch by +batch through bounded channels (nothing else is held) and the output is read and dropped. +``barrier`` runs the join as before this change (every input read whole, then the sync +call). Cases: + +- ``lookup``: ``rows`` spikes against 300 units, the units arriving first; +- ``lookup_late``: the same, the units arriving after every spike; +- ``one_to_one``: two inputs of ``rows`` rows, unique on every shared tag, in step; +- ``one_to_one_late``: the same, one input arriving entirely before the other; +- ``many``: ``rows`` spikes against 1,000 events, neither unique on the session and + shank they share: five output rows per spike. +- ``many_open``: two inputs of ``rows`` rows in step, neither unique on the session and + burst they share: five output rows per row, and both sides' keys held to the end. +- ``rejoin``: one stream of ``rows`` rows split in two branches and rejoined, in step; +- ``semi_late``: ``semi``, the units arriving after every spike; +- ``semi``: ``rows`` spikes kept by the units that exist (300). +""" + +from __future__ import annotations + +import asyncio +import contextlib +import resource +import sys +import time +import warnings +from collections.abc import Callable, Iterator +from pathlib import Path +from typing import Any + +import numpy as np +import pyarrow as pa + +from orcapod.core.operators import Join, Rejoin, SemiJoin +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.record_batch_channels import OutputChannel +from orcapod.core import row_spool +from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams.carried import carried_batches, carried_table +from orcapod.protocols.core_protocols import StreamProtocol + +BATCH = 8_192 +SESSION = "session-0123456789abcdef" + + +def _text(values: np.ndarray[Any, Any], pattern: str) -> pa.Array[Any]: + return pa.array([pattern % v for v in values.tolist()], pa.large_string()) + + +def spikes(start: int, n: int) -> pa.Table: + """Synthetic event rows: tags and data of several types.""" + i = np.arange(start, start + n) + return pa.table( + { + "session": pa.array([SESSION] * n, pa.large_string()), + "unit": _text(i % 300, "unit-%05d"), + "spike": pa.array(i, pa.int64()), + "shank": pa.array(i % 200, pa.int64()), + "burst": pa.array(i // 5, pa.int64()), + "time": pa.array(i / 30_000.0), + "amplitude": pa.array((i % 97) * 1.5), + } + ) + + +def second(start: int, n: int) -> pa.Table: + """A second value per spike, for the one-to-one cases.""" + i = np.arange(start, start + n) + return pa.table( + { + "session": pa.array([SESSION] * n, pa.large_string()), + "unit": _text(i % 300, "unit-%05d"), + "spike": pa.array(i, pa.int64()), + "depth": pa.array(i % 13, pa.int64()), + "width": pa.array((i % 7) * 0.5), + } + ) + + +def units(start: int, n: int) -> pa.Table: + i = np.arange(start, start + n) + return pa.table( + { + "session": pa.array([SESSION] * n, pa.large_string()), + "unit": _text(i, "unit-%05d"), + "area": _text(i % 9, "area-%d"), + "quality": pa.array(i * 1.0), + } + ) + + +def marks(start: int, n: int) -> pa.Table: + """Rows five of which share a burst, as five spikes do.""" + i = np.arange(start, start + n) + return pa.table( + { + "session": pa.array([SESSION] * n, pa.large_string()), + "burst": pa.array(i // 5, pa.int64()), + "mark": pa.array(i, pa.int64()), + "level": pa.array(i * 0.1), + "kind": _text(i % 4, "kind-%d"), + } + ) + + +def events(start: int, n: int) -> pa.Table: + i = np.arange(start, start + n) + return pa.table( + { + "session": pa.array([SESSION] * n, pa.large_string()), + "shank": pa.array(i % 200, pa.int64()), + "event": pa.array(i, pa.int64()), + "onset": pa.array(i * 0.1), + "kind": _text(i % 4, "kind-%d"), + } + ) + + +class Input: + """An input: a small source of its kind describes it, its rows are made as sent.""" + + def __init__( + self, + name: str, + make: Callable[[int, int], pa.Table], + rows: int, + tags: list[str], + key: list[str], + columns: list[str] | None = None, + ): + self.make, self.rows, self.key, self.name = make, rows, key, name + self.tags = tags + self.columns = columns + self.stream = self.source(0, 4) + + def source(self, start: int, n: int) -> StreamProtocol: + source = ArrowTableSource( + self.make(start, n), + tag_columns=self.tags, + record_id_columns=self.key, + tag_only_columns=True, + source_id=self.name, + ) + return source.select_data_columns(self.columns) if self.columns else source + + def batches(self) -> Iterator[pa.RecordBatch]: + for start in range(0, self.rows, BATCH): + stream: StreamProtocol = self.source(start, min(BATCH, self.rows - start)) + zero = StaticOutputOperatorPod._materialize_upstream([], self.stream) + names = zero.as_table(columns={"source": True, "system_tags": True}) + table = carried_table(stream, {"source": True, "system_tags": True}) + yield from table.select(names.column_names).combine_chunks().to_batches() + + +def on_disk() -> int: + """The bytes of this process's spool files now.""" + held = row_spool._directories._held.values() # pyright: ignore[reportPrivateUsage] # where they are + files = [f for directory, _ in held for f in Path(directory).rglob("*.arrow")] + total = 0 + for file in files: + with contextlib.suppress(FileNotFoundError): + total += file.stat().st_size + return total + + +async def run(case: str, rows: int, barrier: bool) -> tuple[int, float, int]: + tags = {"many": "shank", "many_open": "burst"}.get(case, "unit") + big = Input( + "spikes", + spikes, + rows, + ["session", tags, "spike"], + ["session", "spike"] + if case.startswith("many") + else ["session", "unit", "spike"], + ) + if case == "rejoin": + big, other = ( + Input("spikes", spikes, rows, big.tags, big.key, columns) + for columns in (["time"], ["amplitude", "shank"]) + ) + elif case.startswith("one_to_one"): + other = Input( + "second", + second, + rows, + ["spike", "unit", "session"], + ["session", "unit", "spike"], + ) + elif case == "many_open": + other = Input( + "marks", marks, rows, ["session", "burst", "mark"], ["session", "mark"] + ) + elif case == "many": + other = Input( + "events", events, 1_000, ["session", "shank", "event"], ["session", "event"] + ) + else: + other = Input("units", units, 300, ["unit", "session"], ["session", "unit"]) + op = ( + SemiJoin() + if case.startswith("semi") + else Rejoin() + if case == "rejoin" + else Join() + ) + result = op(big.stream, other.stream) + output = OutputChannel(result, retain=False, buffer_size=2) + reader = output.open_reader() + channels = [ + OutputChannel(i.stream, retain=False, buffer_size=2) for i in (big, other) + ] + readers = [channel.open_reader() for channel in channels] + + async def produce(index: int, source: Input, after: asyncio.Event | None) -> None: + if after is not None: + await after.wait() + for batch in source.batches(): + await channels[index].send(batch) + await asyncio.sleep(0) + await channels[index].close() + done[index].set() + + done = [asyncio.Event(), asyncio.Event()] + first = {"lookup": 1, "many": 1, "semi": 1}.get(case) + waits: list[asyncio.Event | None] = [None, None] + if first is not None: + waits[1 - first] = done[first] + if case.endswith("late"): + waits[1] = done[0] + count = 0 + + async def consume() -> None: + nonlocal count + async for batch in carried_batches(reader): + count += batch.num_rows + + if barrier: + execute = StaticOutputOperatorPod.async_execute_batches(op, readers, output) + else: + execute = op.async_execute_batches(readers, output) + disk = 0 + + async def watch() -> None: + nonlocal disk + while True: + disk = max(disk, on_disk()) + await asyncio.sleep(0.2) + + watching = asyncio.create_task(watch()) + began = time.perf_counter() + await asyncio.gather( + produce(0, big, waits[0]), produce(1, other, waits[1]), consume(), execute + ) + seconds = time.perf_counter() - began + _ = watching.cancel() + return count, seconds, disk + + +if __name__ == "__main__": + warnings.simplefilter("ignore") + case, rows = sys.argv[1], int(sys.argv[2]) + barrier = "barrier" in sys.argv + base = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + count, seconds, disk = asyncio.run(run(case, rows, barrier)) + peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + unit = 2**20 if sys.platform == "darwin" else 2**10 + print( + f"{case:16} rows={rows:>9,} {'barrier' if barrier else 'keys':8}" + + f" out={count:>11,} {seconds:7.1f} s" + + f" peak={peak / unit:8.0f} MiB (import {base / unit:.0f})" + + f" arrow_peak={(pa.default_memory_pool().max_memory() or 0) / 2**20:8.0f} MiB" + + f" disk={disk / 2**20:7.0f} MiB" + ) 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-tokens.md b/docs/dev/specs/itl-1464-tokens.md new file mode 100644 index 000000000..41207b34d --- /dev/null +++ b/docs/dev/specs/itl-1464-tokens.md @@ -0,0 +1,175 @@ +# Source-info tokens carried as a recipe (ITL-1464, track TOKENS) + +Status: direction approved November 25, 2026. Step 1 (sources and row-wise operators) +implemented with this document; step 2 (joins) and step 3 (aggregations) are stacked on it. + +## The cost + +A source row's token is `::::`, one per row and data +column: about 300 bytes each on the measured synthetic tables, 35 times the data +(`itl-1464-memory-diagnosis.md`). Everything in it is in the row's two system tags and +the column's name at the source. + +## The representation + +A `_source_x` column is **derived** while no one needs its text: a column of +`DerivedTokenType` (`src/orcapod/utils/source_tokens.py`), an internal Arrow extension +type. Its storage is a struct with no field, so a row has no byte, whatever the number of +rows. Its parameter is a recipe, `TokenRecipe(source_id, record_id, column)`: two +system-tag column names of the same table, and the column's name at the source. + +- `filter`, `take`, `slice`, `concat_tables`, `select` and `rename_columns` carry the + column with no special code, since it is one column like any other. The rows of the + table and their system tags move together, so the recipe stays right. +- Two columns have one Arrow type only with one recipe (`__eq__`), so Arrow itself refuses + to concatenate two that would read different columns. +- The system-tag names of a join change (`append_to_system_tags`): the recipes follow + there (`rename_read_columns`). The values of the system tags move between columns only + in `sort_system_tag_values` (inputs of one pipeline hash): the tokens that read them + become text first (`materialize_reading`). +- Text is made in one function, `materialize`, at most 65,536 rows at a time. + +A derived column is loud where it does not belong: reading a value, casting to text, +hashing, pickling, storing and writing Parquet each raise. + +## Where a derived table can go + +`core/streams/carried.py` holds the internal read, `carried_table(stream, columns)`: the +table of `as_table` with derived columns left as they are. It is a private library function, +no part of a stream's interface. Both ends are exact: + +- the stream: its own class declares `_carried_table` (the library's `ArrowTableStream`, + `DynamicPodStream` and source kinds), and the object reads as that class + (`reads_as_its_class`). A subclass, a replaced `as_table` and a user's stream are read + through `as_table`, and give text; +- the reader: an operator whose own class declares `CARRIES_TOKENS`, through + `StaticOutputOperatorPod._input_table`. A user's operator, also a subclass of a library + one, reads text. + +`as_table` with any columns, `iter_data`, `head`, `run`, the data frame methods and the +identity table give text, as before, and so does a read without the system tags (the recipe +would have nothing to read). The Arrow hashers (schemas, and tables without rows too) and +every database's `add_records` refuse a derived column by name (`refuse_derived`). + +## Producers of `_source_` columns + +| Producer | Form | +|---|---| +| `SourceStreamBuilder.attach_provenance` (every source's rows) | derived | +| `ArrowTableStream(source_info=...)` and a raw table's own `_source_` columns | as given (text) | +| `prepare_prefixed_columns` for a data column with no token | null text | +| `CachedSource`, `DerivedSource` over stored records | text, read from storage | +| `DerivedSource(tags_as_data=)` | derived (a new root, through the builder) | +| `PollingSource` | derived per batch; its combined stream is text (its batches are combined through `as_table`) | +| A function pod's outputs (`data_function.py`) | text: an output's token names the computation, not a source row | +| `Pick` (`with_source_info`) | text: the token is extended | +| `Index` | per row, text (the element's token) | +| `Batch`, `GroupBy` | derived lists, one element per member (step 3) | +| `Join`, `MergeJoin` merged or colliding columns | text | + +## Consumers + +| Consumer | What it needs | Step 1 | +|---|---|---| +| Column selections, `MapData`, `MapTags`, `MapColumns`, `TagBy`, `AddTags`, `DropNulls`, `Filter` | none of the values | derived in, derived out | +| `PolarsFilter` | none, unless a predicate reads a token | the columns stay out of the Polars frame and are put back for the kept rows; a predicate that could read one (a selector, a regular expression, a non-expression, a name that is no column) gets text, as before | +| `without_input_meta` | names only | derived | +| `SemiJoin` (left input) | none | derived (step 2) | +| `Join`, `Rejoin`, `MergeJoin`: columns of one input | none | derived (step 2) | +| `Rejoin`: a shared data-tag | equality of the tokens | one recipe in every input: equal wherever the system tags are, so not compared; otherwise text (step 2) | +| `Join`: a shared data-tag | both tokens, folded (`join_v1`) | a fold recipe (`FoldRecipe`), the same fold run when the text is made; text when a member is text (step 2) | +| `MergeJoin`: a colliding column | both tokens, in a list | text of that column | +| `GroupBy`, `Batch` | the members' tokens, in a list | derived lists (step 3, below) | +| `iter_data` (rows: function pods, side effects, async rows) | one string per column of each row | built for 8,192 rows at a time | +| `F` (`_row_built_form`, `row_built_provenance`) | types and null flags | passes a derived column through (a token is one string and never null) | +| Job nodes (`core/nodes/*`) | the stored text; the kept table | text until the transport calls `carried_table` | +| Function node pipeline table, result table, operator and source caches | stored text | unchanged: they read rows or `as_table` | +| Record-batch channels, streaming joins | types, values | unchanged (text) | +| Provenance trace (`pipeline/provenance.py`) | text | unchanged | +| Identity of a raw stream (`_identity_table`), record hashes | text | unchanged | + +## After each operator + +| Operator | Derivable after it? | +|---|---| +| filter, drop nulls, select, drop, rename, add tags, tag by | yes, all columns | +| semi join | yes, all left columns | +| join, rejoin | yes: each input's columns through its renamed system tags; a shared data-tag through a fold of two recipes. Not for inputs of one pipeline hash in `Join`, whose system-tag values are sorted per row | +| merge join | yes for columns only one input has; a colliding column is a list of two tokens | +| group by, batch | not from the system tags, which are folded to one digest: a list column carries its members' ids | +| function pod | an output: no. Inputs' tokens are not in its output | + +## Aggregations (step 3) + +`GroupBy` and `Batch` fold the members' system tags into one digest, so a list of tokens +cannot be derived from the table's own system tags. A list column of `MemberTokenType` +holds its members' ids itself: its storage is `large_list>`, the two ids as dictionaries over the input's columns (a member is an index; the +ids' text is held once, the few source ids once each), the guard a struct with no field, +so Parquet refuses it. Every token column of one aggregation that reads the same system +tags shares one array of ids, so a further column costs nothing. + +- The text is made by the same `materialize`, 65,536 members at a time, and has the type + the aggregation gave it (F retypes it as it does text). +- A data-tag key's fold, and the system tags' folds, read the members' text a part at a + time, and the fold digests its canonical JSON a part at a time (the same bytes). +- A list of tokens that is aggregated again, and a token that is text, are aggregated as + text. Matching operators carry a list column of one input; a shared one becomes text. +- `iter_data` builds at most 8,192 rows and, beyond one row, 65,536 members at once. + +On a spill (`RowSpool`, `source_tokens.Shelf`): a column of one token a row is not written +(its type says it all), and lists whose members' ids are equal share one ids column in a +file, whose dictionaries hold only the ids that file's rows read. Rows a spool keeps in +memory are trimmed the same way, so a slice never pins the ids of the whole table. Read +back, the columns share the mapped ids again. `kept_table` cuts by bytes, what is shared +counted once. Measured with 200,000 members in 300 groups and 9 token columns: 16.1 MiB in +one file and 16.4 MiB in 150 files of 2 groups (0.11 MiB a file; it was 96 MiB), against +125.5 MiB as text. + +Refusing to leave the process: the storage of a recipe column is a list of no element of +structs nested deeper than Arrow IPC and the C data interface write (the depth costs +nothing per row, since no element exists), and a list's storage holds the same as a guard. +IPC files, streams and messages, Feather, the C stream and pandas refuse a table with rows. +A table with no rows can be written: it has no value. The hash and store guards look inside +structs, lists, dictionaries and extension storages (`refuse_derived`). + +## Grouping millions of rows + +`GroupBy` reads its keys and system tags in one chunk each (a `take` from many chunks puts +them together every time), and sorts by the record ids, the largest columns, only when rows +tie on every tag before them. Text with few distinct values is sorted by its rank (four bytes +a row). Measured outside a job with a synthetic event table of about +8 million rows, 8 columns, 100 groups of about 80,000 members (footprint: the memory the +system charges the process; the source's own read is 3.5 GiB of every line): + +| Step | Seconds before | after | Peak footprint before | after | +|---|---|---|---|---| +| read, recipes carried | | 64 | | 3.5 GiB | +| `group_by` | 411 | 143 | 10.5 GiB | 4.9 GiB | +| `group_by`, a function per group | | 155 | | 5.3 GiB | + +The values of the grouped table are 0.09 GiB: they do not dominate. What it holds is 1.7 +GiB, the members' record ids (about 190 bytes each, the canonical JSON of the key). Of the +143 seconds, about 70 are the folds of the eight system-tag and key columns, whose digests +read every member's text, as they always did. + +In a job, on the integration branch's head with this: 4.4 GiB on sync and 5.8 GiB on async +for `group_by` (3.0 GiB on async at half the rows); with a function per group 10.9 GiB on sync and 6.1 GiB on async. The +difference on sync is the function node, which holds every input row as objects before it +computes: 100 rows of 80,000 members, values and token text. + +## Measured + +A synthetic time series table, about 2.2 million rows, 13 columns, about 250 MiB of Arrow data, read through +`SpiralDBTableSource` (`measure.py` of the diagnosis, one process per step). + +| Step | Peak RSS before | after | Arrow pool peak before | after | +|---|---|---|---|---| +| `as_table()`, `run()` | 10.8 GiB | 2.0 GiB | 9.3 GiB | 0.75 GiB | +| `map_data` | 10.8 GiB | 2.0 GiB | 9.3 GiB | 0.75 GiB | +| `drop_nulls` | 19.7 GiB | 2.4 GiB | 18.6 GiB | 1.7 GiB | +| `polars_filter` | 16.6 GiB | 2.5 GiB | 9.3 GiB | 0.75 GiB | +| `join` (8 and 14 columns) | above 24 GiB | 3.6 GiB (step 2) | | 2.6 GiB | +| `group_by` | 20.9 GiB | 3.3 GiB (step 3) | 15.9 GiB | 1.6 GiB | +| `drop_nulls`, `group_by`, `map_data` | above 24 GiB | 3.9 GiB (step 3) | | 1.8 GiB | +| the same, then a function pod | above 24 GiB | 5.5 GiB (step 3) | | 2.2 GiB | diff --git a/docs/dev/specs/itl-1464-views.md b/docs/dev/specs/itl-1464-views.md new file mode 100644 index 000000000..c9e35b275 --- /dev/null +++ b/docs/dev/specs/itl-1464-views.md @@ -0,0 +1,190 @@ +# `run()`, its view and `preview(n)` without a full table (ITL-1464, track VIEWS) + +Status: V1 to V12 approved by the coordinator, November 25, 2026 (V2, V3 and V8 flagged for +the developer); the bounded view and `preview(n)` are implemented. Written, against `origin/main` 0d1e017c. Companion of +`itl-1464-streaming-design.md` (sections 1, 3 and 4 of it). Nothing here changes a hash, +identity, stored layout, stored byte or golden value. + +## Scope + +- Now: the bounded view of a plain stream (outside a job). Files: `core/streams/base.py`, + `core/streams/view.py`, with small hooks in `DynamicPodStream` and + `SpiralDBTableSource`. +- With TRANSPORT: a job node's view, which pages from the node's reference to its rows. +- After approval of its decisions: `preview(n)` (designed here, not in the first PR). + +Outside a job, only `SpiralDBTableSource` reads its rows on demand and holds none. Every +other source holds its table, so a table over those rows is not a new cost (a filter's +result over it is, and stays as today). A function pod's stream keeps its results, so +that no function is called twice: it stays as today. So the first step applies to a +**batched chain**: zero or more operators that declare `BATCHES_GIVE_THE_WHOLE` (the column +selections, the mappers, `AddTags`, `DropNulls`, `Filter`) over a source that reads in +batches. `Pick` and `Index` are row by row but excluded: they build their result from rows, +so its types and nullable flags follow the values of the batch. The flag is read from the +class itself, so a subclass declares it again. Joins, `GroupBy`, `Batch`, `PolarsFilter` and function pods +end the chain: they compute as today. + +## The `run()` contract + +`run()` computes every row, with every effect, in the order of `as_table()`, and returns a +`StreamView`. It promises nothing about how rows are produced or held. For a batched chain: + +1. The source's batches are read in order (one scan, its checks unchanged: `max_rows`, + schema, repeated keys). Each batch, shaped as `as_table()` shapes the whole, goes + through each operator's own `static_process`: the one sync body, no second kernel. +2. Result batches are kept whole up to **50,000 rows and 64 MiB of values** (default columns; offsets, + validity and chunks not counted, so equal data is treated alike however its batches are + cut). A result that ends + within it is complete: the view holds it, and an operator stream keeps it, exactly as + today. +3. A larger result drops the kept batches to a **window**: the first and last 1,000 rows + (default columns, copied, so no batch stays alive behind a slice), the row count and + the schema. The operator stream keeps the window, not the rows. + +`as_table()`, iteration and conversion are unchanged and still give every row. After a +large `run()` of a batched chain, `as_table()` reads the source again and applies the +operators again. No user function runs twice: a function pod is never in a batched chain. +An error in any batch propagates and nothing is kept, as today. When an operator raises, the +rest of the source is read first: an error of the source, which a whole read raises before +the operator runs, still comes first. + +## The view + +A *complete* view holds every row and is today's view, unchanged. A *bounded* view holds +the window. + +| Member | Bounded view | +|---|---| +| `total_rows`, schema, `status`, `header()` | as the complete view: `all 1,234,567 rows` | +| `head(n)`, `tail(n)`, `n` within the window | the same rows and header as the complete view; the result is an ordinary view | +| `head(n)`, `tail(n)`, larger `n` | raise `BoundedViewError`, naming the window and `stream.as_table()` | +| `sort_by_tags()` | raise `BoundedViewError`: sorting needs every row | +| `as_table()`, `as_polars_df()`, `table`, `len()` | `len()` is the row count; the others raise, never a part presented as the whole | +| display | identical to the complete view's: header, legend, shape line, first and last five rows | + +A view that has no cut of its own and is refused tells the caller the one call that does +it. Nothing a view does reads or computes (as today). + +`stream.head(n)` after a large run of an operator stream shows the window's first rows +(`n` within the window, default columns) while the inputs are unchanged. The preview, which +asks for tag order, sorts those and says so: the present rule of a stream that has only +some of its rows. Another column group shows `not_computed`, as before a run. + +### Inside a job + +The same class. The window of a job node's view is filled by one pass over the node's +reference (TRANSPORT's local cache or the stored entries), or, once a reference can be read +by position, `head`, `tail` and `sort_by_tags` page from it and nothing is refused: the +refusals above are the meaning of "rows not held and not addressable". This needs two +operations from TRANSPORT: `row_count` and `read(start, length, columns)`. + +## `preview(n)` + +`stream.preview(n=10)` computes what the first `n` rows need and returns a `StreamView` +with status `PARTIAL` (or `ROWS`, when the stream has at most `n` rows). `head()` still +never computes. + +- A source reads a limit: SpiralDB as a pushed-down scan limit (with its `where`), others a + slice of what they hold. `max_rows` does not apply, as for `head`. +- Row-by-row operators and function pods take batches until `n` rows have passed. The + first batch is `n` rows, or 1,024 when a step can drop rows; it doubles while too few + pass. A pushed-down limit is used only when no step drops rows; otherwise the scan is + read in batches and closed at `n`. +- `Join`, `MergeJoin`, `SemiJoin`, `Rejoin`, `GroupBy`, `Batch`, `TagBy`, `PolarsFilter` + and user operators need a whole input. Refused, naming the step and `run()`; + `preview(n, compute_all=True)` computes that step in full. An operator that gives one + input back unchanged, decided from the schemas (`input_given_back`: `SemiJoin` without a + shared tag), is previewed as that input, and its other inputs are not read. +- A `DerivedSource` takes its origin's preview batch by batch (a source origin; refused + where the origin would poll or write its cache; positional record ids continue across + batches and a key repeated in a later batch is refused when reached) or, with `compute_all`, a job node's stored rows; it keeps + nothing. +- A side-effect pod, or a function that takes the invocation context, is refused: a + preview has no effects. +- A kept result (an already computed stream) is sliced and nothing is computed. + +## Decisions + +| Id | Decision | Recommended | +|---|---|---| +| V1 | Bounded window now, disk-backed later, or wait for the local cache (N2) | window now: no file is written, and paging later only lifts refusals | +| V2 | `as_table()` / `table` / `as_polars_df()` of a bounded view: kept rows, recompute, or refuse | refuse, pointing to the stream (a part must never read as the whole; a view never recomputes) | +| V3 | `head`/`tail` beyond the window, `sort_by_tags` | refuse | +| V4 | Threshold and window | 50,000 rows and 64 MiB of values, both layout-independent (`RunSize`, `value_bytes`: Arrow's own `nbytes` differs with the batches); a result that fits in the two windows is always kept; first and last 1,000 rows; constants, no config yet | +| V5 | `as_table()` after a large run of a batched chain reads and applies operators again | yes (no user function runs again) | +| V6 | Streams in the middle of a chain keep nothing after a run of the last one (today each keeps its result) | yes, above the threshold (below it each keeps its result, as today): keeping one table per step is the cost being removed; each `run()`s by itself | +| V7 | `PolarsFilter` in a batched chain | not until B1 decides expressions that read other rows | +| V8 | `preview` calls user functions | yes, at most on the rows it looks at | +| V9 | `preview` stores or keeps anything | no: not in memory, not in a database. A cached pod reads its stored results and writes none | +| V10 | `preview` order | the first `n` rows of the sync order | +| V11 | Whole-input steps in `preview` | refuse; `compute_all=True` | +| V12 | `preview` on a job node | not offered at first: raises, naming `run()` and `head()` | + +## Tests + +- Differential: for each operator of a batched chain and chains of several, the result + pieces put together equal the unbatched `as_table()` (values, types, nullability, column + order, metadata) with several batch sizes, for every column configuration, with several + tags and data columns, data-tags, zero rows, and all rows dropped. +- Golden display: text and HTML of a bounded view equal those of the complete view of the + same rows, narrow and wide, with large cells, at sizes 11, 12, 1,000 and more; a small + stream's display is unchanged. +- The refusals; `head` after `run`; staleness after the source moves. +- Memory, about 2.2 million rows of a time series, before and after, for the source, a rename, a + `drop_nulls` and a `filter`. + +## Measured + +`run()` of a synthetic SpiralDB table, a time series (about 2.2 million rows, 13 +columns, about 250 MiB of Arrow data), peak resident memory, one process +per row: + +| Stream | Before | After | Arrow pool peak before | after | Time before | after | +|---|---|---|---|---|---|---| +| the source | 10.8 GiB | 1.24 GiB | 9.3 GiB | 0.07 GiB | 8.9 s | 10.4 s | +| `map_data` | 10.8 GiB | 1.40 GiB | 9.3 GiB | 0.25 GiB | 8.8 s | 10.5 s | +| `drop_nulls` | 19.7 GiB | 1.44 GiB | 18.6 GiB | 0.28 GiB | 9.8 s | 11.1 s | +| `filter` | 15.1 GiB | 1.45 GiB | 14.1 GiB | 0.29 GiB | 9.2 s | 10.2 s | +| `drop_nulls`, `filter`, `map_data` | 20.1 GiB | 1.55 GiB | 18.6 GiB | 0.39 GiB | 10.2 s | 9.9 s | + +The Arrow pool holds nothing large after the run. What remains is mostly the set of keys the +source remembers to refuse a repeat (outside this track), which still grows with the table. + +## Staleness of a chain that keeps nothing + +An operator stream tells a change of an operator stream beneath it by that stream's reset +generation, which moves when it discards a kept result. A stream of a batched chain may have +been read without keeping one, and then discards nothing. So the state of such a stream is +its generation, its operator's modified time and the state of its own input, down to the +source (`_chain_state`): a change anywhere beneath is seen by every kept result and window +above it, whichever streams of the chain hold rows. A source with no row gives one batch of +none, so its run scans once. + +One outermost question (`_upstream_states`) asks each stream once, so the walk is linear in +the graph: settling a stream asks for the states beneath it, and so does its own state. + +## `preview(n)` as built + +- `StreamBase.preview` pulls `_preview_batches` (`core/streams/preview.py`) and stops at `n`. A + function pod gives one row per batch, computed when asked for, so no function is called past + the last row needed, also under a filter; an operator's batch upstream of a function may be + larger, since it calls nothing. +- The limit is passed down through operators that drop no row (`rows_dropped_text`) and + through an active Python function; anything else takes batches and the scan is closed. +- `Pick` and `Index` are refused with the whole-input steps, for the reason they are not + batched by `run()`. +- `compute_all` memoizes each stream it reads in full for the one call, so a stream two + branches share is computed once. With it, functions beneath one input may have run when + another input is refused. +- No meta column is shown: a stored row and a computed one have different ones. +- A `DerivedSource` is a whole read (its origin may compute). A filter nothing passes reads the + whole table, in batches: `max_rows` does not stop it, as it does not stop `head`. + +## Job nodes, as built + +An operator job node's `run()` view is the table its current run is kept in (memory-mapped +when large), so it holds every row, refuses nothing, and equals +`read_current_run(0, current_run_row_count())`. Cutting it touches only the pages of the rows +cut; it stays valid after the node is cleared, which paging through the node would not. The +display of any long view now gives Polars the eleven rows it needs, not the whole table. A +function job node and a source job node still hold their rows in memory. diff --git a/docs/dev/specs/itl-1464/chain.py b/docs/dev/specs/itl-1464/chain.py new file mode 100644 index 000000000..d6892a1b4 --- /dev/null +++ b/docs/dev/specs/itl-1464/chain.py @@ -0,0 +1,223 @@ +"""Measure a job shaped like a whole analysis on one session (ITL-1464). + +Each run is one process:: + + uv run python docs/dev/specs/itl-1464/chain.py setup --scale 1.0 --store + uv run python docs/dev/specs/itl-1464/chain.py --store [--sync] + +The tables are ``measure.py``'s: synthetic, read by the real ``SpiralDBTableSource`` over +the disk-backed fake of the SpiralDB client. At scale 1.0 the event table has about 8 +million rows and the time series about 2 million. The steps build up one job: + +- ``semi_join``: the events of the kept items; +- ``filter``: those in a time range; +- ``group_by``: one row per item, its event times a list; +- ``series``: the time series, filtered, its nulls dropped, one row per session, and a + function over it; +- ``lookup_join``: the filtered events joined with a small table; +- ``chain``: all but ``lookup_join``, and a function over both branches. + +Each prints one JSON line: seconds, peak physical footprint, peak resident memory and +the peak of the Arrow pool; ``--digest`` adds a digest of the last node's rows as a set, +to compare one version of the library with another. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +import time +import warnings +from pathlib import Path +from typing import Any + +import numpy as np +import pyarrow as pa + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import measure # noqa: E402 # pyright: ignore[reportImplicitRelativeImport] # a script beside it + +ITEMS_TABLE = "item" +EVENT_ROWS = 8_100_000 +SERIES_ROWS = 2_200_000 +STEPS = ("semi_join", "filter", "group_by", "series", "lookup_join", "chain") +fake = measure.fake + + +def items_table() -> pa.Table: + """One row per item, with a label that keeps seven of ten.""" + rows = measure.ITEMS + table = measure.lookup_table().select(measure.ITEM_KEY) + labels = ["kept" if i % 10 < 7 else "left" for i in range(rows)] + return table.append_column("label", pa.array(labels, pa.string())) + + +def setup(scale: float, items: int, id_length: int) -> None: + """Write the tables, in key order, and record their schemas. + + Args: + scale: The part of the full row counts. + items: How many items, so how many groups of events (7 of 10 are kept). + id_length: Characters of each text key (hashes and names). + """ + measure.ITEMS = items + measure.HASH = (measure.HASH * (1 + id_length // 32))[:id_length] + measure.SUBJECT = measure.SUBJECT.ljust(id_length, "x") + from orcapod.utils import arrow_utils + + measure.BLOCKS = 6 + store = fake._store() + for name, keys, table in ( + ( + measure.SERIES, + measure.SERIES_KEYS, + measure.time_series_table(int(SERIES_ROWS * scale)), + ), + ( + measure.EVENTS, + measure.EVENT_KEYS, + measure.event_table(int(EVENT_ROWS * scale)), + ), + (measure.LOCATIONS, measure.LOCATION_KEYS, measure.lookup_table()), + (ITEMS_TABLE, measure.ITEM_KEY, items_table()), + ): + made = fake.ExternalProject(measure.PROJECT).create_table( + f"default.{name}", key_schema=[table.schema.field(k) for k in keys] + ) + 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) + 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(measure.PROJECT, {name: recorded}) + + +def build(step: str) -> None: + """Build the named step's streams inside a job.""" + from orcapod import FunctionPod, col + from orcapod.core.data_function import PythonDataFunction + + low = 1_700_000_000_000_000 + inside = col("timestamp").between(low, low + 10**15) + + def peaks(series_time: list[int], x_wide: list[float | None]) -> list[int]: + """Every 100th time where ``x`` is positive.""" + x = np.asarray(x_wide, dtype=float) + return np.asarray(series_time)[x > 0][::100].tolist() + + def count(event_time: list[int], peak_times: list[int]) -> list[int]: + """How many events follow each of the first 50 peaks.""" + times = np.sort(np.asarray(event_time)) + first = np.asarray(peak_times[:50]) + low = np.searchsorted(times, first) + return (np.searchsorted(times, first + 300_000) - low).tolist() + + def trains() -> Any: + items = measure._source(ITEMS_TABLE) + kept = items.filter(col("label").is_in(["kept"])) + chosen = measure._source(measure.EVENTS).semi_join(kept) + if step == "semi_join": + return chosen + chosen = chosen.filter(inside) + if step == "filter": + return chosen + if step == "lookup_join": + return chosen.join(measure._source(measure.LOCATIONS)) + grouped = chosen.group_by(measure.ITEM_KEY) + return grouped.map_data({"timestamp": "event_time"}) + + def series() -> Any: + chosen = measure._source(measure.SERIES).filter(inside) + present = chosen.drop_nulls(["x_small", "y_small"]) + grouped = present.group_by(["subject_id", "session_start"]) + renamed = grouped.map_data({"timestamp": "series_time"}) + pod = FunctionPod(PythonDataFunction(peaks, output_keys="peak_times")) # pyright: ignore[reportArgumentType] # its class is a data function + return pod(renamed, label="peaks") + + if step == "series": + series() + elif step == "chain": + pod = FunctionPod(PythonDataFunction(count, output_keys="counts")) # pyright: ignore[reportArgumentType] # its class is a data function + pod(trains(), series(), label="counts") + else: + trains() + + +def digest(table: pa.Table) -> str: + """A digest of the table's rows as a set, columns by name.""" + total = 0 + names = sorted(table.column_names) + for batch in table.select(names).to_batches(max_chunksize=8_192): + for row in batch.to_pylist(): + text = json.dumps(row, default=str, sort_keys=True).encode() + total += int.from_bytes(hashlib.sha256(text).digest()[:16], "big") + return f"{table.num_rows}:{total % (1 << 128):032x}" + + +def main() -> None: + """Run one step and print its measurements.""" + parser = argparse.ArgumentParser() + _ = parser.add_argument("step", choices=["setup", *STEPS]) + _ = parser.add_argument("--store", required=True, type=Path) + _ = parser.add_argument("--scale", type=float, default=0.25) + _ = parser.add_argument("--items", type=int, default=measure.ITEMS) + _ = parser.add_argument("--id-length", type=int, default=32) + _ = parser.add_argument("--sync", action="store_true") + _ = parser.add_argument("--digest", 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.scale, args.items, args.id_length) + return + import tempfile + + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + from orcapod.pipeline import AsyncPipelineOrchestrator + + with tempfile.TemporaryDirectory(dir=args.store) as results: + database = DeltaTableDatabase(results) + with PipelineJob(name="analysis", database=database) as job: + build(args.step) + started = time.perf_counter() + if args.sync: + job.run() + else: + job.run(orchestrator=AsyncPipelineOrchestrator()) + record: dict[str, Any] = { + "step": args.step, + "path": "sync" if args.sync else "async", + "events": measure._raw(measure.EVENTS).num_rows, + "seconds": round(time.perf_counter() - started, 1), + "footprint_mib": (measure._peak_footprint_bytes() or 0) // 2**20, + "rss_mib": measure._peak_rss_bytes() // 2**20, + "arrow_pool_mib": (pa.default_memory_pool().max_memory() or 0) // 2**20, + "nodes": { + name: node.as_table().num_rows + for name, node in job.nodes.items() + if args.digest and node.node_type != "source" + }, + } + if args.digest: + wanted = {"system_tags": True, "source": True} + record["digests"] = { + name: digest(_without_run_ids(node.as_table(columns=wanted))) + for name, node in job.nodes.items() + if node.node_type == "operator" + } + print(json.dumps(record), flush=True) + + +def _without_run_ids(table: pa.Table) -> pa.Table: + """``table`` without the tokens of function outputs, which hold a run's own ids.""" + names = [n for n in table.column_names if n not in ("_source_peak_times",)] + return table.select(names) + + +if __name__ == "__main__": + main() 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/docs/reference/hashing.md b/docs/reference/hashing.md index 6130f2dd5..ff72172f6 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -396,7 +396,7 @@ A record id is the row identifier (rule 8), built from row positions or key valu | hooks (`pod_hash`) | `core/function_pod.py:_FunctionPodBase._build_post_run_payload` | | in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase._record_invocation`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | | in-memory topological sort of compiled and restored nodes, using the pipeline hash to order ready invocations | `pipeline/base.py:AbstractPipelineBase._ordered_node_map..order_key` | -| canonical input order (sort by digest). Inputs with equal pipeline hashes (developer decision, November 16, 2026, ITL-1154: kept as it is): system-tag column names follow the stable pipeline-hash sort; each row's values are sorted by (source id, record id) by `sort_system_tag_values`, so the result does not depend on argument order; the operator's identity holds its inputs as a frozenset | `core/operators/join.py:Join.order_input_streams..` | +| canonical input order (sort by digest). Inputs with equal pipeline hashes (developer decision, November 16, 2026, ITL-1154: kept as it is): system-tag column names follow the stable pipeline-hash sort; each row's values are sorted by (source id, record id) by `sort_system_tag_values`, so the result does not depend on argument order; the operator's identity holds its inputs as a frozenset | `core/operators/join.py:Join.order_input_streams..`, `core/operators/streaming_joins.py:StreamingJoin.__init__..`, `core/operators/streaming_joins.py:StreamingRejoin.__init__..` | | in-memory identity and repr | `core/base.py:ContentIdentifiableBase.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__eq__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__repr__` | | comparing a stored hash with the computed one; comparing two schema hashes (bind, a stored read, a polled batch); error text | `core/nodes/source_node.py:SourceNodeBase._arrow_type_issue`, `core/sources/derived_source.py:DerivedSource._require_origin_types`, `core/sources/polling_source.py:PollingSource._require_declared_types`, `core/nodes/operator_node.py:OperatorJobNode._read_run_records`, `core/sources/source_proxy.py:SourceProxy.bind`, `core/data_function_proxy.py:DataFunctionProxy.bind`, `pipeline/job.py:PipelineJob.bind`, `errors.py:EphemeralResultMissingError.__init__` | diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 5fa41bfdb..3f585d8a5 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -6,11 +6,13 @@ import logging from datetime import datetime, timezone from collections.abc import Iterator -from typing import TYPE_CHECKING, Any +from typing import ClassVar, TYPE_CHECKING, Any, cast +from orcapod.core.unique_keys import UniqueKeys from orcapod.core.data_function import CachedDataFunction from orcapod.core.datagrams import Datagram from orcapod.core.function_pod import ( + _FunctionPodBase, # pyright: ignore[reportPrivateUsage] # one pod family FunctionPodStream, WrappedFunctionPod, function_zero_row_table, @@ -57,6 +59,10 @@ class CachedFunctionPod(WrappedFunctionPod): # Expose RESULT_COMPUTED_FLAG from the shared ResultCache RESULT_COMPUTED_FLAG = ResultCache.RESULT_COMPUTED_FLAG + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys: each row comes from one input row, its tags kept.""" + return stream.unique_keys + def __init__( self, function_pod: FunctionPodProtocol, @@ -300,6 +306,23 @@ async def async_process_data( output = output.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: True}) return tag, output + def require_preview(self) -> None: + """See ``_FunctionPodBase.require_preview``: the inner pod's answer.""" + cast(_FunctionPodBase, cast(object, self._function_pod)).require_preview() + + def preview_data(self, data: DataProtocol) -> DataProtocol | None: + """The stored result, else the inner pod's, which is not stored.""" + self.require_preview() + stored = self.lookup_cached_data(data) + if stored is not None: + return stored + output = cast(_FunctionPodBase, cast(object, self._function_pod)).preview_data( + data + ) + if output is None: + return None + return output.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: True}) + def _invoke_with_hooks( self, tag: TagProtocol, @@ -509,6 +532,8 @@ class _CachedFunctionPodStream(FunctionPodStream): table has no meta columns unless asked for, as an uncached pod's table. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: for tag, data in super().iter_data(): yield tag, _without_stored_meta(data) diff --git a/src/orcapod/core/exact_class.py b/src/orcapod/core/exact_class.py new file mode 100644 index 000000000..40f9c429b --- /dev/null +++ b/src/orcapod/core/exact_class.py @@ -0,0 +1,37 @@ +"""Whether an object is exactly its class: what it does is what the class defines.""" + +from __future__ import annotations + +import functools +import inspect + + +def reads_as_its_class(obj: object, cls: type) -> bool: + """Whether ``obj`` is exactly ``cls`` and reads only through ``cls``'s own members. + + Exact, never by inspection of what a subclass overrides: ``type(obj) is cls``, and + ``obj`` holds no attribute of its own that shadows a method or a property of + ``cls`` (an ``iter_data`` replaced on the instance). A ``functools.cached_property`` + keeps its value in the instance by design and is not a shadow. A subclass, however + small, is never ``cls`` here (ITL-1347). + + Args: + obj: The object to check. + cls: The class whose reading is proven. + + Returns: + Whether ``obj`` reads as ``cls`` does. + """ + if type(obj) is not cls: + return False + own = getattr(obj, "__dict__", None) + if not own: + return True + missing = object() + for name in own: + member = inspect.getattr_static(cls, name, missing) + if member is missing or isinstance(member, functools.cached_property): + continue + if callable(member) or hasattr(type(member), "__get__"): + return False + return True diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 8a24c3b49..8854f55d0 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -5,13 +5,22 @@ import dataclasses import logging from abc import abstractmethod -from collections.abc import Callable, Collection, Iterable, Iterator, Sequence +from collections.abc import ( + Callable, + Collection, + Generator, + Iterable, + Iterator, + Sequence, +) +from contextlib import closing from functools import update_wrapper, wraps -from typing import TYPE_CHECKING, Any, Literal, Protocol, cast +from typing import ClassVar, TYPE_CHECKING, Any, Literal, Protocol, cast import pyarrow as pa from orcapod import contexts +from orcapod.core.unique_keys import UniqueKeys, derived_keys from orcapod.channels import ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase @@ -29,6 +38,13 @@ schema_requires_io, typed_zero_row_input, ) +from orcapod.core.streams.preview import ( + PREVIEW_COLUMNS, + PreviewRequest, + preview_batches, + refused, + slices_of, +) from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, STALE_NOTE, @@ -36,7 +52,7 @@ StreamView, ) from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER -from orcapod.errors import OrcapodDatabaseError, TypeIdentityError +from orcapod.errors import OrcapodDatabaseError, PreviewRefusedError, TypeIdentityError from orcapod.utils.database_errors import keep_database_error, note_callback_failure from orcapod.protocols.core_protocols import ( ArgumentGroup, @@ -370,6 +386,28 @@ def process_data( ) return tag, self.data_function.call(data, logger=logger, **extra) + def preview_data(self, data: DataProtocol) -> DataProtocol | None: + """Call the function on one row for a preview: no effect, nothing stored. + + Stored results are read; no hook fires. + + Args: + data: The row's data. + + Raises: + PreviewRefusedError: If this kind of pod has no preview, or its function + takes the invocation context (it performs an external action). + """ + raise PreviewRefusedError(f"{type(self).__name__} has no preview") + + def require_preview(self) -> None: + """Refuse a preview of this pod before any function is called. + + Raises: + PreviewRefusedError: As ``preview_data`` would. + """ + raise PreviewRefusedError(f"{type(self).__name__} has no preview") + async def async_process_data( self, tag: TagProtocol, @@ -885,6 +923,10 @@ def output_schema( class FunctionPod(_FunctionPodBase): + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys: each row comes from one input row, its tags kept.""" + return stream.unique_keys + def __init__( self, data_function: DataFunctionProtocol, @@ -949,6 +991,21 @@ def from_fn( **kwargs, ) + def require_preview(self) -> None: + """See ``_FunctionPodBase.require_preview``.""" + if self._ctx_arg_name is not None: + raise PreviewRefusedError( + "its function takes the invocation context: it performs an action" + ) + + def preview_data(self, data: DataProtocol) -> DataProtocol | None: + """See ``_FunctionPodBase.preview_data``.""" + self.require_preview() + function = self.data_function + if isinstance(function, CachedDataFunction): + return function.call(data, skip_cache_insert=True) + return function.call(data) + @property def pod_config(self) -> PodConfig: """Per-pod executor configuration.""" @@ -1138,6 +1195,8 @@ def _no_content_hashes() -> pa.Array[Any]: class FunctionPodStream(StreamBase): """Recomputable stream wrapping a data function.""" + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def __init__( self, function_pod: FunctionPodProtocol, input_stream: StreamProtocol, **kwargs ) -> None: @@ -1172,6 +1231,11 @@ def __init__( self._reset_generation = 0 self._input_state: tuple[object, ...] | None = None + @property + def unique_keys(self) -> UniqueKeys: + """The tag sets no two rows agree on, derived from the inputs' (``core/unique_keys``).""" + return derived_keys(self.producer, self.upstreams, self) + @property def producer(self) -> PodProtocol: return self._function_pod @@ -1770,6 +1834,67 @@ def _computed_prefix( total += 1 return shown, total + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """The function's rows, one per batch, each computed only when asked for. + + Results this stream already holds are used, and nothing is kept of the others. + """ + pod = self._pod_base() + try: + pod.require_preview() + except PreviewRefusedError as error: + raise refused(self, f"cannot be previewed: {error}") from error + current = not self.is_stale + if current and self._cached_output_table is not None: + yield from slices_of(self, request) + return + known = dict(self._cached_output_datas) if current else {} + function = pod.data_function + # An inactive function gives no row; any other gives one per input row. + one_per_row = type(function) is PythonDataFunction and function.is_active() + wanted = request if one_per_row else request.without_limit() + given = False + index = 0 + with closing(preview_batches(self._input_stream, wanted)) as batches: + for batch in batches: + for tag, data in batch.iter_data(): + if index in known: + tag, output = known[index] + else: + output = pod.preview_data(data) + index += 1 + if output is not None: + given = True + yield self._preview_batch([(tag, output)]) + if not given: + yield self._preview_batch([]) + + def _preview_batch( + self, pairs: list[tuple[TagProtocol, DataProtocol]] + ) -> StreamProtocol: + """``pairs`` as a stream, laid out as ``as_table`` lays out this stream's rows. + + Without the meta columns: a stored row of a cached pod has other ones than a row + computed here, and a preview shows none. + """ + from orcapod.core.operators.meta_columns import without_meta_columns + from orcapod.core.streams.arrow_table_stream import ArrowTableStream + + tag_keys, data_keys = self.keys() + table = self._shape_table( + self._table_from_pairs(pairs), + ColumnConfig(**PREVIEW_COLUMNS), + _no_content_hashes, + ) + return ArrowTableStream( + without_meta_columns(table, tag_keys), + tag_columns=tag_keys, + data_tags=data_tag_names(tag_keys, data_keys), + data_context=self.data_context_key, + ) + def _shape_table( self, table: pa.Table, @@ -2134,6 +2259,16 @@ def with_fall_through( input_data, self._in_input_order(input_data.keys()) ) + def require_preview(self) -> None: + """See ``_FunctionPodBase.require_preview``.""" + self._plain_pod.require_preview() + + def preview_data(self, data: DataProtocol) -> DataProtocol | None: + """The plain pod's, then the fall-through columns, as ``process_data``.""" + return self.with_fall_through( + data, self._plain_pod.preview_data(self.function_input(data)) + ) + def function_input_schema(self, input_schema: Schema) -> Schema: """The part of an input data schema the function takes (see ``function_input``).""" parameters = self.input_data_schema diff --git a/src/orcapod/core/job_edges.py b/src/orcapod/core/job_edges.py new file mode 100644 index 000000000..32840ff81 --- /dev/null +++ b/src/orcapod/core/job_edges.py @@ -0,0 +1,388 @@ +"""The edges of an async job: rows, or Arrow record batches of rows (ITL-1464). + +An edge is a ``Channel`` or ``BroadcastChannel`` (``orcapod.channels``), unchanged. What it +carries is ``(Tag, Data)`` pairs, or, from a node that has its rows as Arrow data, +``RowBatch`` items: record batches of the producing node's rows in the row-built form +(``streams.base.row_built_columns``). ``EdgeWriter`` and ``EdgeReader`` are the two ends as +nodes see them. A reader gives whichever form its node asks for, so a node that knows only +pairs is unchanged, and pairs are made only for such a node. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import AsyncIterator, Generator, Iterator +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Protocol, cast, runtime_checkable + +import pyarrow as pa + +from orcapod.channels import ChannelClosed +from orcapod.core.data_tags import data_tag_names +from orcapod.core.operators import static_output_pod +from orcapod.core.operators.static_output_pod import ( + BatchSpool, + StaticOutputOperatorPod, + keys_in_delivered_order, + rows_once, + stream_from_batches, +) +from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.base import row_built_columns +from orcapod.system_constants import constants +from orcapod.utils import source_tokens + +if TYPE_CHECKING: + from orcapod.channels import ReadableChannel, WritableChannel + from orcapod.protocols.core_protocols import ( + DataProtocol, + StreamProtocol, + TagProtocol, + ) + +_PROVENANCE = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + +EDGE_BATCHES = 4 +"""How many items wait on an edge whose producer sends record batches.""" + +REFILL_TURNS = 3 +"""Turns a reader gives its producer before it takes fewer rows than a full batch.""" + + +@dataclass(frozen=True) +class RowBatch: + """Some rows of ``stream`` as one Arrow record batch, in order. + + Attributes: + batch: The rows (``row_built_columns``). + stream: The producing node: the description. + """ + + batch: pa.RecordBatch + stream: StreamProtocol + + def rows(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: + """The rows as pairs, in order.""" + return rows_once(stream_from_batches(self.stream, [self.batch])) + + +@runtime_checkable +class BatchWriter(Protocol): + """A writer that takes record batches too.""" + + async def send_batch(self, batch: pa.RecordBatch, stream: StreamProtocol) -> None: + """Send record batches of ``stream``'s rows.""" + ... + + +class EdgeWriter: + """The producing end of an edge. + + Args: + writer: The channel's writer. + """ + + def __init__(self, writer: WritableChannel[Any]) -> None: + self._writer: WritableChannel[Any] = writer + + async def send(self, item: tuple[TagProtocol, DataProtocol]) -> None: + """Send one row.""" + await self._writer.send(item) + + async def send_batch(self, batch: pa.RecordBatch, stream: StreamProtocol) -> None: + """Send a record batch of ``stream``'s rows, cut to ``ROW_CHUNK_ROWS`` rows each.""" + for start in range(0, batch.num_rows, static_output_pod.ROW_CHUNK_ROWS): + await self._writer.send( + RowBatch(batch.slice(start, static_output_pod.ROW_CHUNK_ROWS), stream) + ) + + async def close(self) -> None: + """Signal that no more items will be sent.""" + await self._writer.close() + + +async def send_batch( + output: WritableChannel[tuple[TagProtocol, DataProtocol]], + batch: pa.RecordBatch, + stream: StreamProtocol, +) -> None: + """Send a record batch of ``stream``'s rows into ``output``, as pairs if it must. + + Args: + output: A node's output: an ``EdgeWriter``, or any writer of pairs. + batch: The rows (``row_built_columns``). + stream: The producing node. + """ + if isinstance(output, BatchWriter): + await output.send_batch(batch, stream) + return + for start in range(0, batch.num_rows, static_output_pod.ROW_CHUNK_ROWS): + for row in RowBatch( + batch.slice(start, static_output_pod.ROW_CHUNK_ROWS), stream + ).rows(): + await output.send(row) + + +class EdgeReader: + """The consuming end of an edge, read as pairs or as record batches. + + Args: + reader: The channel's reader. + """ + + def __init__(self, reader: ReadableChannel[Any]) -> None: + self._reader: ReadableChannel[Any] = reader + self._rows: Iterator[tuple[TagProtocol, DataProtocol]] | None = None + + async def receive(self) -> tuple[TagProtocol, DataProtocol]: + """The next row as a pair.""" + while True: + if self._rows is not None: + row = next(self._rows, None) + if row is not None: + return row + self._rows = None + item = await self._reader.receive() + if not isinstance(item, RowBatch): + return cast("tuple[TagProtocol, DataProtocol]", item) + self._rows = item.rows() + + def __aiter__(self) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: + return self + + async def __anext__(self) -> tuple[TagProtocol, DataProtocol]: + try: + return await self.receive() + except ChannelClosed: + raise StopAsyncIteration from None + + async def collect(self) -> list[tuple[TagProtocol, DataProtocol]]: + """Every remaining row as a pair.""" + return [row async for row in self] + + async def discard(self) -> None: + """Read to the end and let every row go, making no pair.""" + self._rows = None + async for _ in self._reader: + pass + + +class EdgeFeed: + """The record batches of an edge, for an input channel (``BatchFeed``). + + Pairs are gathered into record batches of at most ``ROW_CHUNK_ROWS`` rows, built as + the table of those rows, without waiting for rows a producer has not sent yet. + A failed producer ends the edge as it ends a channel of pairs: the run's task group + cancels this reader. + + Args: + reader: The edge, or any reader of pairs. + stream: The node the rows are of. + """ + + def __init__( + self, + reader: ReadableChannel[tuple[TagProtocol, DataProtocol]], + stream: StreamProtocol, + ) -> None: + self._source: ReadableChannel[Any] = ( + reader._reader if isinstance(reader, EdgeReader) else reader # pyright: ignore[reportPrivateUsage] # the edge's own reader + ) + self._stream: StreamProtocol = stream + self._held: RowBatch | None = None + self._ended: bool = False + + async def next(self) -> pa.RecordBatch | None: + """The next record batch, or ``None`` at the end.""" + if self._held is not None: + held, self._held = self._held, None + return held.batch + if self._ended: + return None + rows: list[tuple[TagProtocol, DataProtocol]] = [] + while len(rows) < static_output_pod.ROW_CHUNK_ROWS: + try: + item = await (self._soon() if rows else self._source.receive()) + except ChannelClosed: + self._ended = True + break + if item is None: + break + if isinstance(item, RowBatch): + if not rows: + return item.batch + self._held = item + break + rows.append(cast("tuple[TagProtocol, DataProtocol]", item)) + if not rows: + return None + table, _, _ = StaticOutputOperatorPod._rows_to_table(rows) # pyright: ignore[reportPrivateUsage] # the table of rows + (batch,) = table.combine_chunks().to_batches() + return batch + + async def _soon(self) -> Any: # pyright: ignore[reportExplicitAny] # a pair or a RowBatch + """The next item if it is there within a few turns of the loop, else ``None``.""" + queue: asyncio.Queue[Any] | None = getattr(self._source, "_queue", None) + if queue is None: + queue = getattr(getattr(self._source, "_channel", None), "_queue", None) + if queue is None: + # Not a library channel: what it holds cannot be seen without waiting. + return None + for _ in range(REFILL_TURNS): + if not queue.empty(): + return await self._source.receive() + await asyncio.sleep(0) + return None + + def close(self) -> None: + """Stop reading.""" + self._ended = True + self._held = None + + @property + def opened_on(self) -> StreamProtocol | None: + """``None``: the rows are what a producer sends.""" + return None + + +class KeptBatches: + """An operator job node's output, received as record batches (ITL-1464). + + Holds them in a ``BatchSpool`` and gives, at the end, the table a run that handed on + rows keeps (``StaticOutputOperatorPod._row_built_form``: the steps decided over every + row). Every batch must have passed the node's output channel. + + Args: + node: The node the rows are of. + """ + + def __init__(self, node: StreamProtocol) -> None: + self._node: StreamProtocol = node + # The node's keys, in the order its rows have them; asked once. + self._keys: tuple[list[str], list[str]] | None = None + self._spool: BatchSpool = BatchSpool() + + @property + def num_rows(self) -> int: + """How many rows were kept.""" + return self._spool.num_rows + + def close(self) -> None: + """Let the kept rows go; an output stream already given stays valid.""" + self._spool.close() + + def add(self, batch: pa.RecordBatch) -> None: + """Keep a batch's rows after every row kept before them.""" + if not batch.num_rows: + return + if self._keys is None: + self._keys = keys_in_delivered_order(self._node.keys(), batch.schema.names) + self._spool.add(batch) + + def output_stream(self) -> StreamProtocol: + """The stream over the rows that the node keeps and stores. + + Raises: + ValueError: If no row was kept. + """ + if self._keys is None: + raise ValueError("Cannot make an output stream of no rows") + # The columns in the order of a table built from rows (a join lists its data + # before its system tags), and F's last step. + rows = self._spool.table() + assert rows is not None # a row was kept + table = StaticOutputOperatorPod._flag_by_values( # pyright: ignore[reportPrivateUsage] # F's last step + row_built_columns(rows, self._keys) + ) + tag_keys, data_keys = self._keys + return ArrowTableStream( + table, + tag_columns=tag_keys, + data_tags=data_tag_names(tag_keys, data_keys), + ) + + +class TappedFeed: + """A feed that remembers the columns of the rows it gave, and no row. + + For a run with no output row: the node rebuilds each input with no rows, as the sync + path rebuilds it (``_materialize_upstream(zero_rows=True)``); what depends on the rows + there is the columns, and whether a system-tag or source-info value was missing. + + Args: + feed: The feed. + """ + + def __init__(self, feed: EdgeFeed) -> None: + self._feed: EdgeFeed = feed + self._first: pa.Table | None = None + self._nulls: set[str] = set() + + async def next(self) -> pa.RecordBatch | None: + """The feed's next record batch.""" + batch = await self._feed.next() + if batch is not None and batch.num_rows: + if self._first is None: + self._first = pa.Table.from_batches([batch.slice(0, 0)]) + self._nulls.update( + field.name + for field, column in zip(batch.schema, batch.columns, strict=True) + if field.name.startswith(_PROVENANCE) + and column.null_count + and not source_tokens.is_derived(field.type) + ) + return batch + + def close(self) -> None: + """Stop reading.""" + self._feed.close() + + @property + def opened_on(self) -> StreamProtocol | None: + """``None``, as the feed's.""" + return None + + def zero_rows(self, upstream: StreamProtocol) -> StreamProtocol: + """The input with no rows, as ``upstream``'s stream.""" + pod = StaticOutputOperatorPod + if self._first is None: + return pod._materialize_upstream([], upstream, zero_rows=True) # pyright: ignore[reportPrivateUsage] # the zero-row input + table = source_tokens.materialize(self._first) + fields = [ + f.with_nullable(f.name in self._nulls) + if f.name.startswith(_PROVENANCE) + else f + for f in table.schema + ] + table = pa.Table.from_arrays(table.columns, schema=pa.schema(fields)) + tag_keys, data_keys = keys_in_delivered_order( + upstream.keys(), table.column_names + ) + return pod._as_upstream_stream( # pyright: ignore[reportPrivateUsage] # the zero-row input + table, tag_keys, data_tag_names(tag_keys, data_keys), upstream + ) + + +async def off_the_loop( + batches: Generator[pa.RecordBatch, None, None], +) -> AsyncIterator[pa.RecordBatch]: + """Iterate ``batches``, each made on one thread of its own, never on the event loop. + + The thread owns the generator for its whole life: when the consumer stops or is + cancelled, it closes the generator after the batch in progress. + + Args: + batches: What makes the record batches. + """ + owner = ThreadPoolExecutor(max_workers=1, thread_name_prefix="source-read") + loop = asyncio.get_running_loop() + try: + while True: + batch = await loop.run_in_executor(owner, next, batches, None) + if batch is None: + break + yield batch + finally: + _ = owner.submit(batches.close) + owner.shutdown(wait=False) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 9a0353053..7f1d55e75 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -27,12 +27,13 @@ from collections.abc import Callable, Iterator, Mapping, Sequence from datetime import datetime, timezone from functools import partial -from typing import Any, Literal, NamedTuple, cast +from typing import ClassVar, Any, Literal, NamedTuple, cast import polars as pl import pyarrow as pa from orcapod import contexts +from orcapod.core.unique_keys import UniqueKeys, derived_keys from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.core.function_pod import ( fall_through_tags, @@ -549,6 +550,11 @@ def node_type(self) -> str: """Return ``"side_effect_function"`` when the pod injects ``InvocationContext``, else ``"function"``.""" return self._node_type + @property + def unique_keys(self) -> UniqueKeys: + """The tag sets no two rows agree on, derived from the inputs' (``core/unique_keys``).""" + return derived_keys(self.producer, self.upstreams, self) + @property def producer(self) -> FunctionPodProtocol: return self._function_pod @@ -1018,6 +1024,8 @@ class FunctionNode(FunctionNodeBase): and serialized to disk via ``Pipeline.save()``. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def __init__( self, function_pod: FunctionPodProtocol, @@ -1410,6 +1418,8 @@ class FunctionJobNode(ProvenanceMethods, RunHoldingNode, FunctionNodeBase): execution. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + # Set once a read has reported the stored rows it skipped (rows of another data # context); a class default so nodes rebuilt from a saved descriptor start unset. _skipped_rows_reported: bool = False diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index b2134184a..e9b713c87 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -18,16 +18,19 @@ import asyncio import dataclasses +import functools import sys import logging from abc import abstractmethod -from collections.abc import Collection, Iterator, Mapping, Sequence -from typing import TYPE_CHECKING, Any, Literal, cast +from collections.abc import Callable, Collection, Iterator, Mapping, Sequence +from typing import ClassVar, TYPE_CHECKING, Any, Literal, cast import pyarrow as pa import pyarrow.compute as pc from orcapod import contexts +from orcapod.core.exact_class import reads_as_its_class +from orcapod.core.unique_keys import NO_UNIQUE_KEYS, UniqueKeys, derived_keys from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.core.data_tags import ( mark_data_tags, @@ -39,18 +42,35 @@ ) from orcapod.channels import Channel, ChannelClosed, ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig +from orcapod.core.operators.batch import Batch +from orcapod.core.operators.group_by import GroupBy +from orcapod.core.operators.join import Join +from orcapod.core.operators.merge_join import MergeJoin +from orcapod.core.operators.rejoin import Rejoin +from orcapod.core.operators.semijoin import SemiJoin from orcapod.core.operators.static_output_pod import ( RowBuiltFormUnavailable, + RowChunks, StaticOutputOperatorPod, + kept_table as spilled_when_large, produced_stream, rows_on_read, ) +from orcapod.core.job_edges import ( + EdgeFeed, + EdgeReader, + KeptBatches, + TappedFeed, + send_batch, +) +from orcapod.core.record_batch_channels import OutputChannel +from orcapod.core.streams.record_batch_input import InputChannel from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.carried import carried_batches, carried_table from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, StreamBase, check_head_size, - reads_as_its_class, short_stream_repr, system_tags_as_rows_give, ) @@ -67,6 +87,7 @@ from orcapod.core.nodes.staleness import RunHoldingNode from orcapod.errors import ( InputValidationError, + UpstreamFailedError, PipelineJobRequiredError, OrcapodDatabaseReadError, OrcapodDatabaseWriteError, @@ -106,10 +127,52 @@ async def _discard(channel: ReadableChannel[Any]) -> None: Args: channel: The channel to drain. """ + if isinstance(channel, EdgeReader): + await channel.discard() + return async for _ in channel: pass +def _is_library_operator(operator: object) -> bool: + """Whether ``operator`` is a library operator, used as its class.""" + kind = type(operator) + return kind.__module__.startswith("orcapod.core.operators.") and reads_as_its_class( + operator, kind + ) + + +def _nodes_above(streams: Sequence[StreamProtocol]) -> list[StreamProtocol]: + """``streams`` and every stream they come from, each once.""" + found: dict[int, StreamProtocol] = {} + waiting = list(streams) + while waiting: + stream = waiting.pop() + if id(stream) not in found: + found[id(stream)] = stream + waiting.extend(stream.upstreams) + return list(found.values()) + + +def _are_described(streams: Sequence[StreamProtocol]) -> bool: + """Whether every operator ``streams`` come from is the library's.""" + return all( + _is_library_operator(stream.producer) + for stream in _nodes_above(streams) + if isinstance(stream, OperatorNodeBase) + ) + + +def _hold_token_lists(streams: Sequence[StreamProtocol]) -> bool: + """Whether rows of ``streams`` may carry derived token lists: an aggregation's + output, through any operators.""" + return any( + isinstance(stream, OperatorNodeBase) + and isinstance(stream.producer, (Batch, GroupBy)) + for stream in _nodes_above(streams) + ) + + class _InputTap: """An input channel reader that keeps the rows needed to rebuild its columns. @@ -298,6 +361,17 @@ def pipeline_hash(self, hasher=None) -> ContentHash: # Stream interface # ------------------------------------------------------------------ + @property + def unique_keys(self) -> UniqueKeys: + """The tag sets no two rows agree on, derived from the inputs' (``core/unique_keys``). + + None in ``REPLAY`` mode: every logged run of the node's key is replayed, so a + tag tuple can occur once per run. + """ + if self.cache_mode == CacheMode.REPLAY: + return NO_UNIQUE_KEYS + return derived_keys(self.producer, self.upstreams, self) + @property def producer(self) -> OperatorPodProtocol: return self._operator @@ -593,6 +667,8 @@ class OperatorNode(OperatorNodeBase): and serialized to disk via ``Pipeline.save()``. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Raise ``PipelineJobRequiredError`` — blueprint nodes cannot produce data. @@ -832,6 +908,8 @@ class OperatorJobNode(ProvenanceMethods, RunHoldingNode, OperatorNodeBase): - **REPLAY**: skip computation, flow cached results downstream. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + # Set once a read has reported the stored rows it skipped (rows of another data # context); a class default so nodes rebuilt from a saved descriptor start unset. _skipped_rows_reported: bool = False @@ -1726,7 +1804,7 @@ def execute( # From the captured stream: reading the wrapper again could run the # operator again (an upstream with no modified time), so the table, # the keys and the gate describe one computation. - result_table = produced.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + result_table = carried_table(produced, ZERO_ROW_INPUT_COLUMNS) if not system_tags_as_rows_give(result_table): result_table = None if result_table is None: @@ -1758,6 +1836,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 +2103,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, *, @@ -2213,6 +2338,142 @@ def as_source( # Async channel execution # ------------------------------------------------------------------ + def _runs_over_batches(self, operator: StaticOutputOperatorPod) -> bool: + """Whether an async run applies ``operator`` to Arrow record batches (ITL-1464). + + For a library operator used as its class, in the default data context throughout: + a batch's rows are in the context its stream reports, and a row-form operator + may hand on rows of another (ITL-1339). The channels check batches against the + streams' descriptions, so no input may come from a user's operator, which would + be applied to no row to give one. + """ + if not (_is_library_operator(operator) and _are_described(self._input_streams)): + return False + default = contexts.get_default_context_key() + return self.data_context_key == default and all( + stream.data_context_key == default for stream in self._input_streams + ) + + async def _run_over_batches( + self, + operator: StaticOutputOperatorPod, + inputs: Sequence[ReadableChannel[tuple[TagProtocol, DataProtocol]]], + output: WritableChannel[tuple[TagProtocol, DataProtocol]], + ) -> tuple[StreamProtocol | None, Callable[[], list[StreamProtocol]]]: + """Run ``operator`` over its inputs' record batches, sending each result batch on. + + Args: + operator: The operator. + inputs: The input edges, in the operator's order. + output: This node's output. + + Returns: + The kept output, ``None`` for no row, and what gives the inputs with no rows. + """ + feeds = [ + TappedFeed(EdgeFeed(reader, stream)) + for reader, stream in zip(inputs, self._input_streams, strict=True) + ] + channels = [ + InputChannel(stream, feed) + for stream, feed in zip(self._input_streams, feeds, strict=True) + ] + result = OutputChannel(self, retain=False, buffer_size=1) + reader = result.open_reader() + batches = KeptBatches(self) + + execute = operator.async_execute_batches + if _hold_token_lists(self._input_streams): + # A join kernel holds its rows in files, which cannot share the ids that + # derived token lists share: the whole inputs, as on the sync path. + if isinstance(operator, (Join, MergeJoin, Rejoin, SemiJoin)): + execute = functools.partial( + StaticOutputOperatorPod.async_execute_batches, operator + ) + + async def forward() -> None: + try: + async for batch in carried_batches(reader): + batches.add(batch) + await send_batch(output, batch, self) + except UpstreamFailedError: + # The operator failed: its own task raises why. + return + + try: + async with asyncio.TaskGroup() as tg: + _ = tg.create_task(execute(channels, result)) + _ = tg.create_task(forward()) + except BaseException as exc: + # A run that fails or is cancelled leaves no file on local disk. + batches.close() + # Preserve direct operator errors; concurrent failures stay grouped. + if isinstance(exc, ExceptionGroup) and len(exc.exceptions) == 1: + raise exc.exceptions[0] from exc + raise + + def zero_inputs() -> list[StreamProtocol]: + return [ + feed.zero_rows(stream) + for feed, stream in zip(feeds, self._input_streams, strict=True) + ] + + try: + kept = batches.output_stream() if batches.num_rows else None + finally: + batches.close() + return kept, zero_inputs + + async def _run_over_rows( + self, + operator: StaticOutputOperatorPod, + inputs: Sequence[ReadableChannel[tuple[TagProtocol, DataProtocol]]], + output: WritableChannel[tuple[TagProtocol, DataProtocol]], + ) -> tuple[StreamProtocol | None, Callable[[], list[StreamProtocol]]]: + """Run ``operator`` over its inputs' rows; as ``_run_over_batches``.""" + intermediate: Channel[tuple[TagProtocol, DataProtocol]] = Channel() + # Kept as Arrow tables, not as a list of every pair (ITL-1464). + collected = RowChunks() + + async def forward() -> None: + async for item in intermediate.reader: + collected.add(*item) + await output.send(item) + + hashes = [s.pipeline_hash() for s in self._input_streams] + taps = [_InputTap(reader) for reader in inputs] + try: + async with asyncio.TaskGroup() as tg: + _ = tg.create_task( + operator.async_execute( + taps, + intermediate.writer, + input_pipeline_hashes=hashes, + ) + ) + _ = tg.create_task(forward()) + except BaseException as exc: + # A run that fails or is cancelled leaves no file on local disk. + collected.close() + # Preserve direct operator errors; concurrent failures stay grouped. + if isinstance(exc, ExceptionGroup) and len(exc.exceptions) == 1: + raise exc.exceptions[0] from exc + raise + + def zero_inputs() -> list[StreamProtocol]: + return [ + StaticOutputOperatorPod._materialize_upstream( + tap.rows, upstream, zero_rows=True + ) + for tap, upstream in zip(taps, self._input_streams, strict=True) + ] + + try: + kept = collected.output_stream() if collected.num_rows else None + finally: + collected.close() + return kept, zero_inputs + async def async_execute( self, inputs: Sequence[ReadableChannel[tuple[TagProtocol, DataProtocol]]], @@ -2298,7 +2559,6 @@ async def async_execute( return # finally block closes output # Delegate to the operator, forward its rows downstream and keep them. - intermediate: Channel[tuple[TagProtocol, DataProtocol]] = Channel() should_store = ( not load_only and self._pipeline_database is not None @@ -2311,41 +2571,24 @@ 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) - await output.send(item) - - hashes = [s.pipeline_hash() for s in self._input_streams] operator = cast(StaticOutputOperatorPod, self._operator) - taps = [_InputTap(reader) for reader in inputs] - try: - async with asyncio.TaskGroup() as tg: - tg.create_task( - operator.async_execute( - taps, - intermediate.writer, - input_pipeline_hashes=hashes, - ) - ) - tg.create_task(forward()) - except ExceptionGroup as exc: - # Preserve direct operator errors; concurrent failures stay grouped. - if len(exc.exceptions) == 1: - raise exc.exceptions[0] from exc - raise + kept: StreamProtocol | None + zero_inputs: Callable[[], list[StreamProtocol]] + if self._runs_over_batches(operator): + kept, zero_inputs = await self._run_over_batches( + operator, inputs, output + ) + else: + kept, zero_inputs = await self._run_over_rows(operator, inputs, output) # TaskGroup has completed. Keep the output on the node, as execute() # 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) - self._cached_output_stream = stream + if kept is not None: + self._cached_output_stream = kept if should_store: - self._store_output_stream(stream) + self._store_output_stream(kept) else: # A completed run with no rows keeps the operator's result over its # inputs rebuilt with no rows, exactly as the sync orchestrator @@ -2353,14 +2596,7 @@ async def forward() -> None: # sync path's columns and Arrow types (ITL-1080). An input that # delivered no row is its upstream's zero-row table, as on the sync # path (ITL-912). Nothing is stored for it. - empty_result = operator.process( - *( - StaticOutputOperatorPod._materialize_upstream( - tap.rows, upstream, zero_rows=True - ) - for tap, upstream in zip(taps, self._input_streams, strict=True) - ) - ) + empty_result = operator.process(*zero_inputs()) # Computed, as execute() computes it, so the node reads as run, and # kept in the column order of a run with rows, as execute() keeps it # (ITL-1131). diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b6b8bc0f6..872561357 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -14,25 +14,44 @@ import json import logging from abc import ABC, abstractmethod -from collections.abc import AsyncIterator, Collection, Iterator, Mapping, Sequence +from collections.abc import ( + AsyncIterator, + Collection, + Generator, + Iterator, + Mapping, + Sequence, +) from datetime import datetime -from typing import TYPE_CHECKING, Any +from typing import ClassVar, TYPE_CHECKING, Any import pyarrow as pa from orcapod import contexts +from orcapod.core.exact_class import reads_as_its_class +from orcapod.core.unique_keys import NO_UNIQUE_KEYS, UniqueKeys, derives_unique_keys from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase from orcapod.core.datagrams import Data, Tag from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied +from orcapod.core.job_edges import BatchWriter, off_the_loop, send_batch +from orcapod.core.operators.static_output_pod import ( + KEPT_ROWS_MEMORY_BYTES, + ROW_CHUNK_ROWS, + StaticOutputOperatorPod, +) +from orcapod.core.row_spool import RowSpool from orcapod.core.sources.base import table_is_rows +from orcapod.core.streams.carried import carried_table from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, CompleteStreamFeed, + batch_streams_of, + reads_in_batches, + row_built_columns, keys_of_rows, - reads_as_its_class, system_tags_as_rows_give, stream_arrow_schema, schema_requires_io, @@ -41,6 +60,7 @@ typed_zero_row_table, ) from orcapod.core.streams.record_batch_input import InputChannel +from orcapod.core.streams.preview import refused from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -908,6 +928,14 @@ def explain(self) -> Explanation: return explain(self) + @property + def unique_keys(self) -> UniqueKeys: + """The bound stream's unique keys (``core/unique_keys``); none when unbound.""" + if not derives_unique_keys(self): + return NO_UNIQUE_KEYS + bound = self._bound_stream() + return NO_UNIQUE_KEYS if bound is None else bound.unique_keys + @property def producer(self) -> None: """Source nodes have no producer pod — they are root nodes. @@ -1271,6 +1299,14 @@ def run(self) -> StreamView: display_all_rows=False, ) + def preview(self, n: int = 10, *, compute_all: bool = False) -> StreamView: + """Refused: a node of a pipeline or job has no preview (``StreamBase.preview``). + + Raises: + PreviewRefusedError: Always. + """ + raise refused(self, "is a node of a pipeline or job") + def open_channel(self) -> RecordBatchInput: """Open an input channel on this node's rows, for async computation (ITL-1347). @@ -1307,6 +1343,17 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Yield ``(tag, data)`` pairs, or raise if data is unavailable.""" ... + def _reads_while_sending(self) -> bool: + """Whether making a record batch waits on a read (``_record_batches``).""" + return False + + def _record_batches(self) -> Generator[pa.RecordBatch, None, None] | None: + """This node's rows as Arrow record batches in the row-built form, or ``None``. + + ``None`` here: the rows are read as ``async_iter_data`` gives them. + """ + return None + def _rows_table( self, ) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]] | None: @@ -1407,8 +1454,18 @@ async def async_execute( try: if observer is not None: observer.on_node_start(node_label, node_hash) - async for tag, data in self.async_iter_data(): - await output.send((tag, data)) + batches = ( + self._record_batches() if isinstance(output, BatchWriter) else None + ) + if batches is None: + async for tag, data in self.async_iter_data(): + await output.send((tag, data)) + elif self._reads_while_sending(): + async for batch in off_the_loop(batches): + await send_batch(output, batch, self) + else: + for batch in batches: + await send_batch(output, batch, self) if observer is not None: observer.on_node_end(node_label, node_hash) finally: @@ -1468,6 +1525,8 @@ class SourceNode(SourceNodeBase): — identical to the old ``SourceSpec`` — so existing DB paths remain valid. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def _typed_zero_row_table(self) -> "pa.Table | None": """The slot's zero-row table from its own Arrow schemas (ITL-640). @@ -1551,6 +1610,28 @@ def from_stream( return node +def _source_table(source: StreamProtocol) -> pa.Table: + """``source``'s rows as a node hands them on (``carried_table``). + + A source that reads its table in batches is read one batch at a time into a + ``RowSpool``: the same table, on local disk when large (ITL-1464). + """ + if not reads_in_batches(source): + return carried_table(source, ZERO_ROW_INPUT_COLUMNS) + with ( + contextlib.closing(batch_streams_of(source)) as streams, + RowSpool(memory_bytes=KEPT_ROWS_MEMORY_BYTES) as spool, + ): + empty: pa.Table | None = None + for stream in streams: + table = carried_table(stream, ZERO_ROW_INPUT_COLUMNS) + if empty is None: + empty = table.slice(0, 0) + spool.append(table) + assert empty is not None # at least one batch, with no row when there is none + return spool.table() if spool.size else empty + + class SourceJobNode(ProvenanceMethods, SourceNodeBase): """Execution-ready source node wrapping an optional concrete stream. @@ -1586,6 +1667,8 @@ class SourceJobNode(ProvenanceMethods, SourceNodeBase): *bound_source* is ``None``. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def __init__( self, name: str, @@ -1911,13 +1994,60 @@ def _rows_table( # one whose rows report another data context than the node's: its rows, # as main iterated them (the edge table is built in the node's context). return None - table = self._bound_source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + table = _source_table(self._bound_source) if not system_tags_as_rows_give(table): # System tags the rows would type otherwise (a narrow integer, a # nullable field): the rows decide, as on main. return None return table, keys_of_rows(table, self._bound_source.keys()) + def _reads_while_sending(self) -> bool: + """Whether the bound source reads its table batch by batch.""" + return reads_in_batches(self._bound_source) + + def _record_batches(self) -> Generator[pa.RecordBatch, None, None] | None: + """The bound source's rows as record batches (ITL-1464), or ``None``. + + Where F of the source's table is provably its rows' own table (``_rows_table``), + in the default data context. A source that reads its table in batches + (``reads_in_batches``) is read one batch at a time; another is held already. + """ + source = self._bound_source + if ( + not reads_as_its_class(self, SourceJobNode) + or source is None + or self._declared_form is not None + or not table_is_rows(source) + or source.data_context_key != self.data_context_key + or self.data_context_key != contexts.get_default_context_key() + ): + return None + zero = typed_zero_row_table(source) + if zero is None or not system_tags_as_rows_give(zero): + # The system tags may not be what the rows give: the rows decide. + return None + + def generate() -> Generator[pa.RecordBatch, None, None]: + streams = ( + batch_streams_of(source) + if reads_in_batches(source) + else (stream for stream in (source,)) + ) + with contextlib.closing(streams): + for stream in streams: + table = carried_table(stream, ZERO_ROW_INPUT_COLUMNS) + if not system_tags_as_rows_give(table): + # A null the fields do not declare: as the rows give it. + rows = list(stream.iter_data()) + table, *_ = StaticOutputOperatorPod._rows_to_table(rows) # pyright: ignore[reportPrivateUsage] # the rows' own table + keys = keys_of_rows(table, stream.keys()) + built = row_built_columns(table, keys) + for batch in built.to_batches(max_chunksize=ROW_CHUNK_ROWS): + if batch.num_rows: + yield batch + + return generate() + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Delegate to concrete source, or raise if unbound. diff --git a/src/orcapod/core/operators/add_tags.py b/src/orcapod/core/operators/add_tags.py index 9af218e81..4e0048bfd 100644 --- a/src/orcapod/core/operators/add_tags.py +++ b/src/orcapod/core/operators/add_tags.py @@ -9,6 +9,7 @@ import pyarrow as pa +from orcapod.core.unique_keys import UniqueKeys from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.data_tags import stream_data_tags from orcapod.core.datagrams import Tag @@ -116,14 +117,21 @@ class AddTags(UnaryOperator): ``::`` separator). """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). PROVISIONAL: ClassVar[bool] = True # Data-tags pass through as they are; the new tags are plain (ITL-1023). # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): tags are only added.""" + return stream.unique_keys + def __init__(self, tags: Mapping[str, TagConstant], **kwargs: Any): if not tags: raise ValueError("add_tags: no tag given") @@ -322,13 +330,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ tag_keys, _ = stream.keys() data_context = stream.data_context # pyright: ignore[reportAttributeAccessIssue] # StreamProtocol omits data_context, which every concrete stream provides (ITL-844) - table = stream.as_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) return ArrowTableStream( self._with_constants(table, tag_keys, data_context.type_converter), 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..8d809992e 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -6,6 +6,7 @@ import numpy as np import pyarrow as pa +from orcapod.core.streams.carried import carried_batches from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, @@ -18,15 +19,17 @@ 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 from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens from orcapod.types import Schema @@ -57,6 +60,8 @@ class Batch(UnaryOperator): drop_partial_batch: Drop a last batch with fewer than ``batch_size`` rows. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). PROVISIONAL: ClassVar[bool] = True @@ -150,7 +155,13 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: Returns: A stream with one row per batch. """ - table = stream.as_table(columns={"source": True, "system_tags": True}) + table = self._input_table(stream, columns={"source": True, "system_tags": True}) + # A list of tokens is aggregated as text (ITL-1464). + table = source_tokens.materialize( + table, + set(source_tokens.derived_columns(table.schema)) + - set(source_tokens.recipe_columns(table.schema)), + ) tag_columns, _ = stream.keys() @@ -162,25 +173,36 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: ), ) kept = table.slice(0, int(offsets[-1].as_py())) - bounds = cast(list[int], offsets.to_pylist()) # Every stream has a data context; StreamProtocol does not declare it. type_converter = stream.data_context.type_converter # pyright: ignore[reportAttributeAccessIssue] + # The source-info lists of tokens carried as recipes (ITL-1464). + recipes = source_tokens.recipe_columns(table.schema) + order = pa.array(np.arange(kept.num_rows), pa.int64()) + token_lists = source_tokens.MemberTokens(kept, order, offsets) + fields: list[pa.Field[Any]] = [] arrays: list[pa.Array[Any]] = [] for field in table.schema: + if field.name in recipes: + tokens = token_lists.column( + recipes[field.name], pa.large_list(pa.large_string()) + ) + fields.append(pa.field(field.name, tokens.type, nullable=False)) + arrays.append(tokens) + continue column = kept.column(field.name) if field.name.startswith(constants.SYSTEM_TAG_PREFIX): # Text values, folded per batch; text loses nothing in Python. - values = cast(list[Any], column.to_pylist()) + members = source_tokens.member_texts(kept, field.name, order, offsets) fields.append(field) arrays.append( pa.array( [ arrow_utils.fold_system_tag_values( - values[start:end], label=BATCH_FOLD_LABEL + values, label=BATCH_FOLD_LABEL ) - for start, end in zip(bounds[:-1], bounds[1:]) + for values in members ], field.type, ) @@ -278,12 +300,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]] = [] @@ -328,7 +350,7 @@ async def async_execute_batches( try: waiting: list[pa.RecordBatch] = [] rows = 0 - async for batch in channel: + async for batch in carried_batches(channel): if not batch.num_rows: continue # nothing to batch, nothing to hold waiting.append(batch) diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index cbc6570b8..c727797c8 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -3,6 +3,7 @@ from collections.abc import Collection, Sequence from typing import Any, ClassVar +from orcapod.core.unique_keys import UniqueKeys from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.operators.base import UnaryOperator @@ -57,11 +58,18 @@ class SelectTagColumns(UnaryOperator): Operator that selects specified columns from a stream. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): those whose tags all stay.""" + return stream.unique_keys + def __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): self.columns = _canonical_columns(columns) self.strict = strict @@ -90,13 +98,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("All tag columns are selected. Returning stream unaltered.") return stream - table = stream.as_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) # A dropped data-tag leaves its column as plain data (specification @@ -196,11 +205,18 @@ class SelectDataColumns(UnaryOperator): Operator that selects specified columns from a stream. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): tags are unchanged.""" + return stream.unique_keys + def __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): self.columns = _canonical_columns(columns) self.strict = strict @@ -229,7 +245,8 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("All data columns are selected. Returning stream unaltered.") return stream - table = stream.as_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, @@ -352,11 +369,18 @@ class DropTagColumns(UnaryOperator): Operator that drops specified columns from a stream. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): those whose tags all stay.""" + return stream.unique_keys + def __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): self.columns = _canonical_columns(columns) self.strict = strict @@ -388,13 +412,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("No tag columns to drop. Returning stream unaltered.") return stream - table = stream.as_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) # A dropped data-tag leaves its column as plain data (specification @@ -496,11 +521,18 @@ class DropDataColumns(UnaryOperator): Operator that drops specified columns from a stream. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): tags are unchanged.""" + return stream.unique_keys + def __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): self.columns = _canonical_columns(columns) self.strict = strict @@ -534,13 +566,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: associated_source_columns = [ f"{constants.SOURCE_PREFIX}{c}" for c in columns_to_drop ] - table = stream.as_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) # A data-tag whose data column is removed keeps its column as a plain # tag with the same values (specification section 7.2). @@ -774,13 +807,14 @@ def validate_unary_input(self, stream: StreamProtocol) -> None: def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: tag_columns, data_columns = self._user_columns(stream) tags_removed, data_removed = self._removals(tag_columns, data_columns) - table = stream.as_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) removed = { *tags_removed, @@ -881,8 +915,15 @@ class DropColumns(_TagAndDataColumnsOperator): be dropped: a stream needs at least one data column. """ + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True + CARRIES_TOKENS: ClassVar[bool] = True + _verb: ClassVar[str] = "drop" + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): those whose tags all stay.""" + return stream.unique_keys + def _removed(self, columns: Collection[str]) -> list[str]: return [c for c in columns if c in self.columns] @@ -905,7 +946,14 @@ class SelectColumns(_TagAndDataColumnsOperator): named: a stream needs at least one data column. """ + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True + CARRIES_TOKENS: ClassVar[bool] = True + _verb: ClassVar[str] = "select" + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): those whose tags all stay.""" + return stream.unique_keys + def _removed(self, columns: Collection[str]) -> list[str]: return [c for c in columns if c not in self.columns] diff --git a/src/orcapod/core/operators/drop_nulls.py b/src/orcapod/core/operators/drop_nulls.py index 1e7840935..0b181cfa7 100644 --- a/src/orcapod/core/operators/drop_nulls.py +++ b/src/orcapod/core/operators/drop_nulls.py @@ -10,6 +10,7 @@ import pyarrow as pa import pyarrow.compute as pc +from orcapod.core.unique_keys import UniqueKeys from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel @@ -90,11 +91,18 @@ class DropNulls(UnaryOperator): ValueError: If ``columns`` is an empty collection. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): rows are only left out.""" + return stream.unique_keys + def __init__( self, columns: str | Collection[str] | None = None, **kwargs: Any ) -> None: @@ -316,13 +324,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: A stream over the surviving rows, in input order, with the named columns non-nullable. A result with no rows has the same schema. """ - table = stream.as_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) tag_columns, data_columns = stream.keys() return ArrowTableStream( diff --git a/src/orcapod/core/operators/filter.py b/src/orcapod/core/operators/filter.py index e5a4fa1a8..d703ccca3 100644 --- a/src/orcapod/core/operators/filter.py +++ b/src/orcapod/core/operators/filter.py @@ -12,6 +12,7 @@ import pyarrow as pa +from orcapod.core.unique_keys import UniqueKeys from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.base import UnaryOperator @@ -74,6 +75,8 @@ class Filter(UnaryOperator): TypeError: If ``condition`` is neither a condition nor a mapping. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): a data-tag is one column, named alike as tag or data. DATA_TAGS_ISSUE: ClassVar[str | None] = None @@ -82,10 +85,16 @@ class Filter(UnaryOperator): # Its head shows the matching rows of its input's head (decision 13, ITL-1374). HEAD_FROM_INPUT_HEAD: ClassVar[bool] = True + ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True # Its identity is not frozen with data context v1 (ITL-1374). PROVISIONAL: ClassVar[bool] = True + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): rows are only left out.""" + return stream.unique_keys + def __init__( self, condition: Condition | Mapping[str, object], **kwargs: Any ) -> None: @@ -243,13 +252,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ # Every system column passes through: source info, system tags and each row's # data context (a raw stream may hold several). - table = stream.as_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) tag_columns, data_columns = stream.keys() self._check_arrow(table.schema, _user_columns(tag_columns, data_columns)) diff --git a/src/orcapod/core/operators/filters.py b/src/orcapod/core/operators/filters.py index ce01c02b5..8e377a695 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -5,12 +5,13 @@ import polars as pl import pyarrow as pa +from orcapod.core.unique_keys import UniqueKeys from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.base import UnaryOperator from orcapod.core.streams import ArrowTableStream from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import ColumnConfig, Schema -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens if TYPE_CHECKING: import numpy as np @@ -40,6 +41,8 @@ class PolarsFilter(UnaryOperator): Operator that applies Polars filtering to a stream """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. DATA_TAGS_ISSUE: ClassVar[str | None] = None @@ -49,6 +52,10 @@ class PolarsFilter(UnaryOperator): # Its identity is not frozen with data context v1 (ITL-1266, ITL-1247). PROVISIONAL = True + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): rows are only left out.""" + return stream.unique_keys + def __init__( self, predicates: Collection[ @@ -71,11 +78,28 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: return stream # TODO: improve efficiency here... - table = stream.as_table( - columns={"source": True, "system_tags": True, "sort_by_tags": False} + whole = self._input_table( + stream, columns={"source": True, "system_tags": True, "sort_by_tags": False} ) + # Polars reads no derived token column: one is left out, and put back for the + # rows kept (its recipe reads the system tags kept with them, ITL-1464), unless + # a predicate could read it. + derived = source_tokens.derived_columns(whole.schema) + others = {c for c in whole.column_names if c not in derived} + if derived and not self._reads_only(others): + whole, derived = source_tokens.materialize(whole), () + table = whole.drop_columns(list(derived)) + recipes = source_tokens.recipe_columns(whole.schema) + # A list of tokens holds its members' ids, so its kept rows are taken by number. + lists = [name for name in derived if name not in recipes] + row = arrow_utils.unused_column_name(whole, "__row") df = pl.DataFrame(table) + if lists: + df = df.with_columns(pl.int_range(pl.len()).alias(row)) filtered_table = df.filter(*self.predicates, **self.constraints).to_arrow() + kept = filtered_table.column(row) if lists else None + if lists: + filtered_table = filtered_table.drop_columns([row]) # A filter passes every column through, so each one takes the # large-normalized form of its input Arrow type (string -> # large_string, list -> large_list, recursively; hash-identical). @@ -96,6 +120,17 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: filtered_table = arrow_utils.restore_schema_nullability( filtered_table, pa.schema(input_fields) ) + for name in derived: + field = whole.schema.field(name) + if name in recipes: + column = source_tokens.derived_array( + recipes[name], filtered_table.num_rows + ) + else: + assert kept is not None + column = whole.column(name).take(kept) + filtered_table = filtered_table.append_column(field, column) + filtered_table = filtered_table.select(whole.column_names) return ArrowTableStream( filtered_table, @@ -103,6 +138,26 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: data_tags=stream_data_tags(stream), ) + def _reads_only(self, columns: Collection[str]) -> bool: + """Whether every predicate certainly reads columns of ``columns`` only. + + Certain only for expressions that name each column they read: a selector + (``pl.all()``, a regular expression, a type) can read any column, and a predicate + that is not an expression is not looked into. A name that is no column is not + certain either: Polars' error then lists the columns there are. + """ + if not set(self.constraints) <= set(columns): + return False + return all( + isinstance(predicate, pl.Expr) + and not predicate.meta.has_multiple_outputs() + and set(predicate.meta.root_names()) <= set(columns) + for predicate in ( + *self.predicates, + *(v for v in self.constraints.values() if isinstance(v, pl.Expr)), + ) + ) + def validate_unary_input(self, stream: StreamProtocol) -> None: """ This method should be implemented by subclasses to validate the inputs to the operator. diff --git a/src/orcapod/core/operators/group_by.py b/src/orcapod/core/operators/group_by.py index acce7333c..8069b6cd3 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -8,7 +8,9 @@ import numpy as np import polars as pl import pyarrow as pa +import pyarrow.compute as pc +from orcapod.core.unique_keys import UniqueKeys, certificate from orcapod.core.operators.arrow_keys import ( is_list_kind, part_without_rule, @@ -24,7 +26,7 @@ from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens from orcapod.utils.schema_utils import column_names # GroupBy decides which rows form a group, and in what order, with Polars, and builds @@ -203,6 +205,46 @@ def _member_order_names( return names +def _all_distinct(frame: "pl.DataFrame", names: Sequence[str]) -> bool: + """Whether no two rows of a sorted frame tie on ``names``. + + Nested values order by other expressions than they compare by, so with one of them + the answer is always no. + """ + if any(frame.schema[name].is_nested() for name in names): + return False + if frame.height < 2: + return True + runs = cast(int, frame.select(pl.struct(names).rle_id().max()).item()) + 1 + return runs == frame.height + + +_RANK_SAMPLE = 65_536 +"""How many values of a text column decide whether it is worth ranking (``_ranked``).""" + + +def _ranked(array: "pa.Array[Any]") -> "pa.Array[Any]": + """``array``, or the ranks of its values when it is text with few distinct values. + + The sort frame then holds four bytes a row in place of the text (ITL-1464). Ranks + order and compare as the text does: the rank is the value's place among the distinct + values in byte order, which is Polars' order of text, and a null stays null. + + Args: + array: A prepared key column (``polars_ready``). + """ + if not (pa.types.is_large_string(array.type) or pa.types.is_string(array.type)): + return array + sample = array.slice(0, _RANK_SAMPLE) + if pc.count_distinct(sample).as_py() * 2 > len(sample): + return array # a text of its own in most rows: ranking would cost a copy of it + encoded: Any = array.dictionary_encode() + by_bytes = pc.sort_indices(encoded.dictionary.cast(pa.large_binary())).to_numpy() + ranks = np.empty(len(by_bytes), dtype=np.uint32) + ranks[by_bytes] = np.arange(len(by_bytes), dtype=np.uint32) + return pa.array(ranks).take(encoded.indices) + + class GroupBy(UnaryOperator): """Reduce rows sharing a key into one row with list-valued data members. @@ -312,12 +354,19 @@ class GroupBy(UnaryOperator): NotImplementedError: If ``member_order`` is a function. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). PROVISIONAL: ClassVar[bool] = True # Data-tags (ITL-1023): handled. DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The grouping keys: one row per key, under the joins' equality.""" + del stream + return certificate([self.by]) + def __init__( self, by: str | Collection[str], @@ -448,7 +497,13 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: InputValidationError: If a key is a list of any kind, or a user tag's type has no order (``arrow_keys.part_without_rule``). """ - table = stream.as_table(columns={"source": True, "system_tags": True}) + table = self._input_table(stream, columns={"source": True, "system_tags": True}) + # A list of tokens is aggregated as text (ITL-1464). + table = source_tokens.materialize( + table, + set(source_tokens.derived_columns(table.schema)) + - set(source_tokens.recipe_columns(table.schema)), + ) tag_columns, _ = stream.keys() # The async path reaches here without ``validate_unary_input``. _refuse_unorderable_tags( @@ -458,6 +513,18 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: system_tag_columns = tuple( c for c in table.column_names if c.startswith(constants.SYSTEM_TAG_PREFIX) ) + # The folds, the sort and the members' ids read these again and again, by row + # number: each in one chunk (a ``take`` from many puts them together every time). + for name in (*self.by, *system_tag_columns): + index = table.schema.get_field_index(name) + table = table.set_column( + index, + table.schema.field(index), + source_tokens.one_chunk(table.column(index)), + ) + # The chunks let go are several GiB at millions of rows, and the pool would + # keep them beside what follows. + pa.default_memory_pool().release_unused() # The source info of a data-tag key: the key's value is the merge of its # members' equal values, so its source info is one token, the fold of the # members' tokens in member order, as the system tags fold (ITL-1017). @@ -512,21 +579,23 @@ def emitted(c: str) -> pa.Array[Any]: return table.column(c).take(rows).combine_chunks() def folded(c: str) -> pa.Array[Any]: - """The fold of system-tag column ``c`` per group, over the members in order.""" + """The fold of text column ``c`` per group, over the members in order.""" # The members' text values in member order, folded per group; text loses # nothing in Python. - values = cast(list[Any], table.column(c).take(order).to_pylist()) - bounds = cast(list[int], offsets.to_pylist()) return pa.array( [ arrow_utils.fold_system_tag_values( - values[start:end], label=GROUP_BY_FOLD_LABEL + members, label=GROUP_BY_FOLD_LABEL ) - for start, end in zip(bounds[:-1], bounds[1:]) + for members in source_tokens.member_texts(table, c, order, offsets) ], - table.schema.field(c).type, + pa.large_string(), ) + # The source-info lists of tokens carried as recipes (ITL-1464). + recipes = source_tokens.recipe_columns(table.schema) + token_lists = source_tokens.MemberTokens(table, order, offsets) + # Every stream has a data context; StreamProtocol does not declare it. type_converter = stream.data_context.type_converter # pyright: ignore[reportAttributeAccessIssue] fields: list[pa.Field[Any]] = [] @@ -535,7 +604,12 @@ def folded(c: str) -> pa.Array[Any]: # folded column keep their field, a member column becomes a list. for field in table.drop_columns(list(dropped_columns)).schema: c = field.name - if c in member_columns: + if c in member_columns and c in recipes: + list_type = pa.large_list(pa.large_string()) + column = token_lists.column(recipes[c], list_type) + fields.append(pa.field(c, column.type, nullable=False)) + arrays.append(column) + elif c in member_columns: list_type = arrow_utils.aggregated_list_type( field.type, type_converter, column=c ) @@ -546,7 +620,10 @@ def folded(c: str) -> pa.Array[Any]: ) ) else: - fields.append(field) + # A key's source info is one fold, text whatever its members were. + fields.append( + field.with_type(pa.large_string()) if c in recipes else field + ) arrays.append(emitted(c) if c in self.by else folded(c)) grouped_table = pa.Table.from_arrays(arrays, schema=pa.schema(fields)) @@ -595,6 +672,7 @@ def _member_layout( """ named = self.member_order or () sort_columns = named + tuple(sorted(c for c in non_key_tags if c not in named)) + tags = len(sort_columns) for prefix in ( constants.SYSTEM_TAG_RECORD_ID_PREFIX, constants.SYSTEM_TAG_SOURCE_ID_PREFIX, @@ -614,11 +692,17 @@ def _member_layout( key_names = [f"key{i}" for i in range(len(self.by))] order_names = [f"order{i}" for i in range(len(sort_columns))] for name, c in zip( - [*key_names, *order_names], [*self.by, *sort_columns], strict=True + [*key_names, *order_names[:tags]], + [*self.by, *sort_columns[:tags]], + strict=True, ): - frame_columns[name] = polars_ready(table.column(c).combine_chunks()) + frame_columns[name] = _ranked( + polars_ready(source_tokens.one_chunk(table.column(c))) + ) # The bits of each float key, to emit the member value with the smallest. - key_storage = {c: values_of(table.column(c).combine_chunks()) for c in self.by} + key_storage = { + c: values_of(source_tokens.one_chunk(table.column(c))) for c in self.by + } bit_names: dict[str, str] = {} for i, c in enumerate(self.by): bits = _float_bits(key_storage[c]) @@ -626,22 +710,37 @@ def _member_layout( bit_names[c] = f"bits{i}" frame_columns[f"bits{i}"] = bits - frame = cast( - "pl.DataFrame", - pl.from_arrow( - pa.Table.from_arrays( - list(frame_columns.values()), names=list(frame_columns) + def in_order(names: Sequence[str]) -> pl.DataFrame: + """The frame sorted by the keys and the columns that order the members.""" + frame = cast( + "pl.DataFrame", + pl.from_arrow( + pa.Table.from_arrays( + list(frame_columns.values()), names=list(frame_columns) + ) + ), + ) + # Keys first, so the groups come out in key order: a NaN key after every + # number and before null, null last (``nulls_last``); rows that tie on every + # column keep the input's order. + return frame.sort( + [_sort_key(name, frame.schema[name]) for name in names], + nulls_last=True, + maintain_order=True, + ) + + # The system tags are the last tiebreakers, and their texts are by far the + # largest columns: they are sorted only when rows tie on everything before them + # (ITL-1464). Nested values order by other expressions than they compare by, so + # with one of them they always are. + names = [*key_names, *order_names[:tags]] + frame = in_order(names) + if not _all_distinct(frame, names): + for name, c in zip(order_names[tags:], sort_columns[tags:], strict=True): + frame_columns[name] = polars_ready( + source_tokens.one_chunk(table.column(c)) ) - ), - ) - # Keys first, so the groups come out in key order: a NaN key after every - # number and before null, null last (``nulls_last``); rows that tie on every - # column keep the input's order. - frame = frame.sort( - [_sort_key(name, frame.schema[name]) for name in key_names + order_names], - nulls_last=True, - maintain_order=True, - ) + frame = in_order([*key_names, *order_names]) # Group boundaries by Polars' own equality: every NaN equals every NaN and # 0.0 equals -0.0, as the joins match keys (ITL-1234, ITL-1251). frame = frame.with_columns(pl.struct(key_names).rle_id().alias("group")) diff --git a/src/orcapod/core/operators/index.py b/src/orcapod/core/operators/index.py index cbb6c2c37..2ee1e90e7 100644 --- a/src/orcapod/core/operators/index.py +++ b/src/orcapod/core/operators/index.py @@ -9,6 +9,7 @@ import pyarrow as pa +from orcapod.core.unique_keys import UniqueKeys from orcapod.types.explanation import plain_repr from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.meta_columns import WithoutMetaWriter @@ -56,6 +57,10 @@ class Index(UnaryOperator): ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): each row comes from one input row.""" + return stream.unique_keys + def __init__( self, column: str, diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 430957232..c1f9c6062 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -8,6 +8,9 @@ import polars as pl import pyarrow as pa +from orcapod.protocols.core_protocols.streams import RecordBatchInput, RecordBatchOutput +from orcapod.core.exact_class import reads_as_its_class +from orcapod.core.unique_keys import UniqueKeys, joined_keys from orcapod.types.explanation import plain_repr from orcapod.core.operators.meta_columns import ( WithoutMetaWriter, @@ -45,7 +48,7 @@ ) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, DataValue, Schema -from orcapod.utils import arrow_utils, schema_utils +from orcapod.utils import arrow_utils, schema_utils, source_tokens # The row-number columns of the frames Polars joins (``_inner_join``); a tag, so a # key, never starts with the meta prefix ``__``. @@ -179,6 +182,20 @@ def _fold_members(tokens: Sequence[str | None]) -> str: return arrow_utils.fold_system_tag_values(ordered, label=JOIN_FOLD_LABEL) +# The two steps of the merge, for tokens carried as recipes (``source_tokens``, ITL-1464): +# the members met so far, and the fold the join ends with. +_PENDING_FOLD = "join pending" +source_tokens.register_fold(_PENDING_FOLD, _pending) +source_tokens.register_fold(JOIN_FOLD_LABEL, _fold_members) + + +def _pending_members(recipe: source_tokens.Recipe) -> tuple[source_tokens.Recipe, ...]: + """The member recipes a merged column holds so far (itself, if not pending).""" + if isinstance(recipe, source_tokens.FoldRecipe) and recipe.fold == _PENDING_FOLD: + return recipe.members + return (recipe,) + + def _fold_pending(value: Any) -> Any: """Replace every pending token position of ``value`` by its merged token.""" if isinstance(value, list): @@ -189,9 +206,21 @@ def _fold_pending(value: Any) -> Any: class Join(NonZeroInputOperator): + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, *streams: StreamProtocol) -> UniqueKeys: + """The inputs' unique keys, joined input by input (``joined_keys``).""" + keys = streams[0].unique_keys + tags = set(streams[0].keys()[0]) + for stream in streams[1:]: + names = set(stream.keys()[0]) + keys = joined_keys(keys, stream.unique_keys, tags & names) + tags |= names + return keys + @property def kernel_id(self) -> tuple[str, ...]: """ @@ -464,7 +493,8 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: # Source-info columns of merged data-tag columns, folded once at the end. merged_source: set[str] = set() table = without_meta_columns( - stream.as_table(columns={"source": True, "system_tags": True}), tag_keys + self._input_table(stream, columns={"source": True, "system_tags": True}), + tag_keys, ) # trick to get cartesian product; use int8 explicitly so that zero-row # tables don't produce a null-typed column that Polars rejects on join @@ -477,7 +507,9 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: for idx, next_stream in enumerate(ordered_streams[1:], start=1): next_tag_keys, _ = next_stream.keys() next_table = without_meta_columns( - next_stream.as_table(columns={"source": True, "system_tags": True}), + self._input_table( + next_stream, columns={"source": True, "system_tags": True} + ), next_tag_keys, ) next_table = arrow_utils.append_to_system_tags( @@ -580,6 +612,17 @@ def _merge_source_columns( The table with ``left_name`` holding both sides' members, pending until the join folds them (``_fold_source_column``). """ + left_recipe, right_recipe = ( + source_tokens.derived_recipe(table.schema.field(name).type) + for name in (left_name, right_name) + ) + if left_recipe is not None and right_recipe is not None: + members = (*_pending_members(left_recipe), *_pending_members(right_recipe)) + recipe = source_tokens.FoldRecipe(_PENDING_FOLD, members) + return source_tokens.with_recipe(table, left_name, recipe).drop_columns( + [right_name] + ) + table = source_tokens.materialize(table, (left_name, right_name)) field = table.schema.field(left_name) merged = pa.array( [ @@ -606,6 +649,10 @@ def _fold_source_column(table: "pa.Table", name: str) -> "pa.Table": Returns: The table with one merged token at every token position of ``name``. """ + recipe = source_tokens.derived_recipe(table.schema.field(name).type) + if recipe is not None: + fold = source_tokens.FoldRecipe(JOIN_FOLD_LABEL, _pending_members(recipe)) + return source_tokens.with_recipe(table, name, fold) field = table.schema.field(name) folded = pa.array( [_fold_pending(value) for value in table.column(name).to_pylist()], @@ -695,6 +742,28 @@ def _compute_system_tag_suffixes( suffixes.append(f"{truncated}:{canon_position[orig_idx]}") return suffixes + async def async_execute_batches( + self, inputs: Sequence[RecordBatchInput], output: RecordBatchOutput + ) -> None: + """Run over input channels of Arrow record batches, holding keys only. + + ``streaming_joins.StreamingJoin`` gives the rows of the sync path as a set, in memory + bounded by its inputs' join keys (``docs/dev/specs/itl-1464-joins.md``). + + Args: + inputs: One input channel per input stream, in the operator's order. + output: The channel the result's record batches are sent into. + """ + if not reads_as_its_class(self, Join): + # A subclass, or an instance with a member replaced, may compute other rows: + # its own sync call over all of its inputs. + await super().async_execute_batches(inputs, output) + return + # The kernels are built on this module's join rules. + from orcapod.core.operators.streaming_joins import StreamingJoin, run_kernel + + await run_kernel(lambda streams: StreamingJoin(self, streams), inputs, output) + async def async_execute( self, inputs: Sequence[ReadableChannel[tuple[TagProtocol, DataProtocol]]], diff --git a/src/orcapod/core/operators/mappers.py b/src/orcapod/core/operators/mappers.py index fa89ec4a5..6b53c9576 100644 --- a/src/orcapod/core/operators/mappers.py +++ b/src/orcapod/core/operators/mappers.py @@ -1,6 +1,7 @@ from collections.abc import Collection, Mapping, Sequence from typing import Any, ClassVar +from orcapod.core.unique_keys import UniqueKeys, renamed_keys from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.operators.base import UnaryOperator @@ -91,11 +92,18 @@ class MapData(UnaryOperator): ``SelectTagColumns`` and the other column operators. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): no tag is renamed.""" + return stream.unique_keys + def __init__( self, name_map: Mapping[str, str], @@ -179,13 +187,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: # nothing to rename in the data, return stream as is return stream - table = stream.as_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) # A data-tag column keeps its tag under its own name, now plain; the @@ -365,14 +374,24 @@ class MapTags(UnaryOperator): tag_only: Rename data-tags in the tag role only. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). PROVISIONAL: ClassVar[bool] = True # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys, renamed, without those that lose a tag.""" + dropped = set(stream.keys()[0]) - set(self.name_map) + return renamed_keys( + stream.unique_keys, self.name_map, dropped if self.drop_unmapped else () + ) + def __init__( self, name_map: Mapping[str, str], @@ -457,13 +476,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: # nothing to rename or drop in the tags, return stream as is return stream - table = stream.as_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) name_map = { @@ -664,11 +684,19 @@ class MapColumns(UnaryOperator): or (with ``drop_unmapped``) no data column would remain. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True PROVISIONAL: ClassVar[bool] = True + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys, renamed, without those that lose a tag.""" + tag_renames, _, dropped, _ = self._plan(*self._user_columns(stream)) + return renamed_keys(stream.unique_keys, tag_renames, dropped) + def __init__( self, name_map: Mapping[str, str], @@ -799,13 +827,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: tag_renames, data_renames, tags_dropped, data_dropped = self._plan( tag_columns, data_columns ) - table = stream.as_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) dropped = { *tags_dropped, diff --git a/src/orcapod/core/operators/merge_join.py b/src/orcapod/core/operators/merge_join.py index 88abafc5a..7112bce55 100644 --- a/src/orcapod/core/operators/merge_join.py +++ b/src/orcapod/core/operators/merge_join.py @@ -4,6 +4,9 @@ import numpy as np import pyarrow as pa +from orcapod.protocols.core_protocols.streams import RecordBatchInput, RecordBatchOutput +from orcapod.core.exact_class import reads_as_its_class +from orcapod.core.unique_keys import UniqueKeys, joined_keys from orcapod.types.explanation import plain_repr from orcapod.core.operators.base import ( BinaryOperator, @@ -32,7 +35,7 @@ from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema -from orcapod.utils import arrow_utils, schema_utils +from orcapod.utils import arrow_utils, schema_utils, source_tokens def _output_types( @@ -156,12 +159,24 @@ class MergeJoin(BinaryOperator): merged into a list in argument order, as for plain inputs. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). PROVISIONAL: ClassVar[bool] = True # Data-tags (ITL-1023) are handled (ITL-1194). DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, *streams: StreamProtocol) -> UniqueKeys: + """The inputs' unique keys, joined input by input (``joined_keys``).""" + keys = streams[0].unique_keys + tags = set(streams[0].keys()[0]) + for stream in streams[1:]: + names = set(stream.keys()[0]) + keys = joined_keys(keys, stream.unique_keys, tags & names) + tags |= names + return keys + @property def kernel_id(self) -> tuple[str, ...]: return (f"{self.__class__.__name__}",) @@ -397,11 +412,15 @@ def binary_static_process( # Tables with source info and system tags, each input's system-tag # column names extended with its pipeline hash and argument index. left_table = arrow_utils.append_to_system_tags( - left_stream.as_table(columns={"source": True, "system_tags": True}), + self._input_table( + left_stream, columns={"source": True, "system_tags": True} + ), self._system_tag_suffix(left_stream, 0), ) right_table = arrow_utils.append_to_system_tags( - right_stream.as_table(columns={"source": True, "system_tags": True}), + self._input_table( + right_stream, columns={"source": True, "system_tags": True} + ), self._system_tag_suffix(right_stream, 1), ) @@ -429,6 +448,12 @@ def binary_static_process( [right_source.get(c, c) for c in right_table.column_names] ) + # A source-info column both inputs have becomes a list of both tokens: text + # (ITL-1464). Any other is carried as it is. + both = set(left_table.column_names) & set(right_table.column_names) + left_table = source_tokens.materialize(left_table, both) + right_table = source_tokens.materialize(right_table, both) + # Find colliding data columns (a merged data-tag column is not one) colliding_keys = (set(left_data_keys) & set(right_data_keys)) - merged @@ -496,6 +521,8 @@ def binary_static_process( for left_name, right_name in right_source.items(): joined = Join._merge_source_columns(joined, left_name, right_name) # pyright: ignore[reportPrivateUsage] # Join's one rule joined = Join._fold_source_column(joined, left_name) # pyright: ignore[reportPrivateUsage] # Join's one rule + # A merge of derived tokens has a recipe, so a type, of its own (ITL-1464). + output_types[left_name] = joined.schema.field(left_name).type # Use the left stream's type converter — not the default context — so that a # MergeJoin over streams built with a non-default DataContext reconstructs the @@ -583,6 +610,33 @@ def binary_static_process( data_tags=data_tag_names(tag_schema, data_schema), ) + async def async_execute_batches( + self, inputs: Sequence[RecordBatchInput], output: RecordBatchOutput + ) -> None: + """Run over input channels of Arrow record batches, holding keys only. + + ``streaming_joins.StreamingMergeJoin`` gives the rows of the sync path as a set, in memory + bounded by its inputs' join keys (``docs/dev/specs/itl-1464-joins.md``). + + Args: + inputs: One input channel per input stream, in the operator's order. + output: The channel the result's record batches are sent into. + """ + if not reads_as_its_class(self, MergeJoin): + # A subclass, or an instance with a member replaced, may compute other rows: + # its own sync call over all of its inputs. + await super().async_execute_batches(inputs, output) + return + # The kernels are built on this module's join rules. + from orcapod.core.operators.streaming_joins import ( + StreamingMergeJoin, + run_kernel, + ) + + await run_kernel( + lambda streams: StreamingMergeJoin(self, streams), inputs, output + ) + def rows_dropped_text( self, position: int, diff --git a/src/orcapod/core/operators/meta_columns.py b/src/orcapod/core/operators/meta_columns.py index 674d55e46..fd6a7b00f 100644 --- a/src/orcapod/core/operators/meta_columns.py +++ b/src/orcapod/core/operators/meta_columns.py @@ -19,6 +19,7 @@ from orcapod.channels import WritableChannel from orcapod.core.data_tags import stream_data_tags, with_data_tags_first +from orcapod.core.streams.carried import carried_table from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants @@ -112,8 +113,8 @@ def without_input_meta( """ if not _carries_meta(stream, inputs): return stream - table = stream.as_table( - columns={"source": True, "system_tags": True, "context": True} + table = carried_table( + stream, {"source": True, "system_tags": True, "context": True} ) tag_columns = stream.keys()[0] return ArrowTableStream( diff --git a/src/orcapod/core/operators/pick.py b/src/orcapod/core/operators/pick.py index 09824160d..a4353b420 100644 --- a/src/orcapod/core/operators/pick.py +++ b/src/orcapod/core/operators/pick.py @@ -9,6 +9,7 @@ import pyarrow as pa +from orcapod.core.unique_keys import UniqueKeys from orcapod.types.explanation import plain_repr from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.meta_columns import WithoutMetaWriter @@ -58,6 +59,10 @@ class Pick(UnaryOperator): ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): each row comes from one input row.""" + return stream.unique_keys + def __init__( self, column: str, diff --git a/src/orcapod/core/operators/rejoin.py b/src/orcapod/core/operators/rejoin.py index d760f5865..0a2cf8309 100644 --- a/src/orcapod/core/operators/rejoin.py +++ b/src/orcapod/core/operators/rejoin.py @@ -26,6 +26,9 @@ import polars as pl import pyarrow as pa +from orcapod.core.exact_class import reads_as_its_class +from orcapod.protocols.core_protocols.streams import RecordBatchInput, RecordBatchOutput +from orcapod.core.unique_keys import UniqueKeys, certificate from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.data_tags import data_tag_names, data_tags_first from orcapod.core.operators.arrow_keys import polars_key_frame @@ -48,7 +51,7 @@ ) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, Schema -from orcapod.utils import arrow_utils, schema_utils +from orcapod.utils import arrow_utils, schema_utils, source_tokens from orcapod.utils.warning_utils import outside_orcapod_stacklevel # Row-number columns of the frames Polars matches, and the column of a row's occurrence @@ -66,6 +69,42 @@ def _system_tag_names(stream: StreamProtocol) -> list[str]: ) +def _with_comparable_tokens(tables: Sequence["pa.Table"]) -> "list[pa.Table]": + """Give each shared source-info column one form: one recipe, or text (ITL-1464). + + Rejoin compares a shared column's values. When every input that has a token column + derives it by one recipe, it is equal wherever the system tags are, which the rows + already match on, so it stays derived and is not compared (``_agrees_by_recipe``). + Otherwise its text is built in every input. + + Args: + tables: The inputs' rows. + + Returns: + The same tables; a derived column several of them have has one recipe. + """ + types: dict[str, list[pa.DataType]] = {} + for table in tables: + for field in table.schema: + types.setdefault(field.name, []).append(field.type) + differing = { + name + for name, kinds in types.items() + if len(kinds) > 1 + and any(source_tokens.is_derived(kind) for kind in kinds) + and not all( + source_tokens.derived_recipe(kind) is not None and kind == kinds[0] + for kind in kinds + ) + } + return [source_tokens.materialize(table, differing) for table in tables] + + +def _agrees_by_recipe(table: "pa.Table", name: str) -> bool: + """Whether column ``name`` is derived, so rows with equal system tags agree on it.""" + return source_tokens.derived_recipe(table.schema.field(name).type) is not None + + def _agreeing( pairs: "pl.DataFrame", left: "pa.Table", @@ -207,7 +246,7 @@ def _differing_columns(tables: Sequence["pa.Table"], keys: Sequence[str]) -> lis holders: dict[str, list[int]] = {} for index, table in enumerate(tables): for name in table.column_names: - if name not in keys: + if name not in keys and not _agrees_by_recipe(table, name): holders.setdefault(name, []).append(index) # The columns several inputs have, by the inputs that have them. shared: dict[tuple[int, ...], list[str]] = {} @@ -328,8 +367,14 @@ class Rejoin(Join): release. """ + CARRIES_TOKENS: ClassVar[bool] = True + PROVISIONAL: ClassVar[bool] = True + def derive_unique_keys(self, *streams: StreamProtocol) -> UniqueKeys: + """Every input's unique keys: a row of an input is in at most one result row.""" + return certificate(key for stream in streams for key in stream.unique_keys) + def validate_nonzero_inputs(self, *streams: StreamProtocol) -> None: """Check that the inputs can be rejoined: shared system tags, compatible columns. @@ -421,12 +466,14 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: tag_keys, _ = stream.keys() tables.append( without_meta_columns( - stream.as_table( - columns={"source": True, "system_tags": True, "context": True} + self._input_table( + stream, + columns={"source": True, "system_tags": True, "context": True}, ), tag_keys, ) ) + tables = _with_comparable_tokens(tables) # The rule on the tables themselves, in call order: an input whose schema # states no system tag (``_require_rejoinable``) is checked here. by_call = {id(stream): table for stream, table in zip(ordered_streams, tables)} @@ -572,7 +619,9 @@ def _rejoin_pair( others = [ name for name in right.column_names - if name in left.column_names and name not in keys + if name in left.column_names + and name not in keys + and not _agrees_by_recipe(left, name) ] for name in sorted(others): shared_type = require_shared_arrow_type( @@ -608,6 +657,28 @@ def _rejoin_pair( table, left.schema, right.schema, shared_tags ) + async def async_execute_batches( + self, inputs: Sequence[RecordBatchInput], output: RecordBatchOutput + ) -> None: + """Run over input channels of Arrow record batches. + + Two inputs: ``streaming_joins.StreamingRejoin``, which holds the rows not matched + yet, their shared columns in memory and the rows spooled. One input, or three or + more: every input is read first, then the sync call (with three or more, which + repeats of an origin row are matched follows the whole inputs). + + Args: + inputs: One input channel per input stream, in the operator's order. + output: The channel the result's record batches are sent into. + """ + if len(inputs) != 2 or not reads_as_its_class(self, Rejoin): + await super().async_execute_batches(inputs, output) + return + # The kernels are built on this module's rejoin rules. + from orcapod.core.operators.streaming_joins import StreamingRejoin, run_kernel + + await run_kernel(lambda streams: StreamingRejoin(self, streams), inputs, output) + async def async_execute( self, inputs: Sequence[ReadableChannel[tuple[TagProtocol, DataProtocol]]], diff --git a/src/orcapod/core/operators/semijoin.py b/src/orcapod/core/operators/semijoin.py index d2a379f50..137d4ef86 100644 --- a/src/orcapod/core/operators/semijoin.py +++ b/src/orcapod/core/operators/semijoin.py @@ -8,6 +8,9 @@ import pyarrow as pa import pyarrow.compute as pc +from orcapod.protocols.core_protocols.streams import RecordBatchInput, RecordBatchOutput +from orcapod.core.exact_class import reads_as_its_class +from orcapod.core.unique_keys import UniqueKeys from orcapod.types.explanation import plain_repr from orcapod.channels import ChannelClosed, ReadableChannel, WritableChannel from orcapod.core.operators.meta_columns import WithoutMetaWriter @@ -76,9 +79,18 @@ class SemiJoin(BinaryOperator): (a null key matches nothing) and keeps the left input's type (ITL-829). """ + CARRIES_TOKENS: ClassVar[bool] = True + CONSTRAINING_INPUTS: ClassVar[tuple[int, ...]] = (1,) CONSTRAINT_MATCHES_SHARED_TAGS: ClassVar[bool] = True + def derive_unique_keys( + self, left: StreamProtocol, right: StreamProtocol + ) -> UniqueKeys: + """The left input's unique keys: left rows are only left out.""" + del right + return left.unique_keys + @staticmethod def _match_keys( left_tag_keys: Collection[str], right_tag_keys: Collection[str] @@ -190,6 +202,11 @@ def _warn_ignored(ignored: Sequence[tuple[str, str, str]]) -> None: stacklevel=outside_orcapod_stacklevel(), ) + def input_given_back(self, inputs: Sequence[StreamProtocol]) -> int | None: + """The left input, when the inputs share no tag column: every left row is + kept and the right input is never read (``binary_static_process``).""" + return None if self._checked_match_keys(*inputs) else 0 + def _checked_match_keys( self, left_stream: StreamProtocol, right_stream: StreamProtocol ) -> tuple[str, ...]: @@ -224,8 +241,8 @@ def binary_static_process( if not common_keys: return left_stream - left_table = left_stream.as_table( - columns={"source": True, "system_tags": True, "context": True} + left_table = self._input_table( + left_stream, columns={"source": True, "system_tags": True, "context": True} ) # Only the right side's keys are read, never its data columns. right_table = right_stream.as_table().select(list(common_keys)) @@ -323,6 +340,30 @@ def _common_keys_from_schema(self) -> tuple[str, ...]: """ return getattr(self, "_validated_common_keys", ()) + async def async_execute_batches( + self, inputs: Sequence[RecordBatchInput], output: RecordBatchOutput + ) -> None: + """Run over input channels of Arrow record batches, holding keys only. + + ``streaming_joins.StreamingSemiJoin`` gives the rows of the sync path as a set, in memory + bounded by its inputs' join keys (``docs/dev/specs/itl-1464-joins.md``). + + Args: + inputs: One input channel per input stream, in the operator's order. + output: The channel the result's record batches are sent into. + """ + if not reads_as_its_class(self, SemiJoin): + # A subclass, or an instance with a member replaced, may compute other rows: + # its own sync call over all of its inputs. + await super().async_execute_batches(inputs, output) + return + # The kernels are built on this module's join rules. + from orcapod.core.operators.streaming_joins import StreamingSemiJoin, run_kernel + + await run_kernel( + lambda streams: StreamingSemiJoin(self, streams), inputs, output + ) + async def async_execute( self, inputs: Sequence[ReadableChannel[tuple[TagProtocol, DataProtocol]]], diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f829d44a5..74347b939 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1,10 +1,12 @@ from __future__ import annotations import asyncio +import contextlib import dataclasses import logging from abc import abstractmethod from collections.abc import ( + Generator, AsyncIterator, Collection, Iterable, @@ -12,12 +14,16 @@ Mapping, Sequence, ) +from contextlib import closing +from contextvars import ContextVar from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, cast import pyarrow as pa import pyarrow.compute as pc +from orcapod.core.exact_class import reads_as_its_class +from orcapod.core.unique_keys import UniqueKeys, derived_keys from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, RecordBatchOutput, @@ -36,23 +42,35 @@ stream_data_tags, ) from orcapod.core.function_pod import FunctionPodStream +from orcapod.core.row_spool import SPOOL_MEMORY_BYTES, RowSpool, held_bytes from orcapod.core.operators.provisional import ( provisional_operator_name, warn_provisional_operator, ) +from orcapod.utils import source_tokens from orcapod.utils.provisional import note_provisional_use, provisional_class_name from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.carried import carried_batches, carried_table from orcapod.core.streams.base import ( + batch_streams_of, + reads_in_batches, ZERO_ROW_INPUT_COLUMNS, StreamBase, check_head_size, - reads_as_its_class, short_stream_repr, typed_zero_row_input, typed_zero_row_table, row_built_columns, ) +from orcapod.core.streams.preview import ( + PREVIEW_COLUMNS, + PreviewRequest, + preview_batches, + refuse_without_compute_all, +) from orcapod.core.streams.view import ( + BoundedStreamView, + RunSize, STALE_NOTE, default_note, ViewStatus, @@ -117,6 +135,24 @@ class StaticOutputOperatorPod(TraceableBase): (``async_execute_batches``); every other operator needs all of an input first. """ + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = False + """Whether ``static_process`` over consecutive batches of an input gives, put + together, exactly its result over the whole input: rows, order, types, nullability. + + Stricter than ``ROW_BY_ROW``: no type or nullable flag of the result follows the + values (``Pick`` and ``Index`` build their result from rows, so theirs do). Read + from the class itself, never inherited: a subclass that changes the operator + declares it again. ``run()`` of a stream uses it (ITL-1464). + """ + + CARRIES_TOKENS: ClassVar[bool] = False + """Whether the operator passes derived token columns on (ITL-1464). + + Declared by a library operator that never reads the values of a source-info column + it passes on, or builds their text itself. It holds for exactly the class that + declares it, never for a subclass (``_input_table``). + """ + OUTPUT_SCHEMA_IS_INPUT_SCHEMA: ClassVar[bool] = False """Whether the output has exactly its single input's columns and Arrow types. @@ -220,6 +256,24 @@ def check_data_tag_support(self, *streams: StreamProtocol) -> None: if any(stream_data_tags(stream) for stream in streams): raise not_supported_yet(type(self).__name__, self.DATA_TAGS_ISSUE) + def _input_table( + self, stream: StreamProtocol, columns: dict[str, Any] + ) -> "pa.Table": + """The table of ``stream`` as this operator reads it. + + Derived token columns as they are (``carried_table``) for an operator whose class + declares ``CARRIES_TOKENS`` itself and is used as that class; text for any other, + so a user's operator, also one that subclasses a library operator, reads text. + + Args: + stream: An input stream. + columns: The column groups, as for ``as_table``. + """ + kind = type(self) + if vars(kind).get("CARRIES_TOKENS") is True and reads_as_its_class(self, kind): + return carried_table(stream, columns) + return stream.as_table(columns=columns) + def pipeline_identity_structure(self) -> Any: """Return the pipeline identity, which defaults to content identity for operators.""" return self.identity_structure() @@ -512,7 +566,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 @@ -579,6 +638,10 @@ def _type_source_info_by_values(table: pa.Table) -> pa.Table: continue if pa.types.is_large_string(field.type): continue + if source_tokens.is_derived(field.type): + # A token is one string, and a list of them is never empty: the type + # the column declares is the one its tokens give. + continue values = table.column(index).to_pylist() kinds = {arrow_utils.source_info_arrow_type(value) for value in values} if len(kinds) != 1: @@ -745,11 +808,11 @@ def _zero_row_input(upstream: StreamProtocol) -> StreamProtocol | None: table = typed_zero_row_input(upstream) if table is None: return None - tag_keys = upstream.keys()[0] + tag_keys, data_keys = upstream.keys() return StaticOutputOperatorPod._as_upstream_stream( StaticOutputOperatorPod._as_row_built_table(table, tag_keys), tag_keys, - stream_data_tags(upstream), + data_tag_names(tag_keys, data_keys), upstream, ) @@ -776,6 +839,19 @@ def rows_dropped_text( """ return None + def input_given_back(self, inputs: Sequence[StreamProtocol]) -> int | None: + """The position of the input this operator gives back unchanged over + ``inputs``, or ``None`` (the default): it computes its result. + + Decided from the inputs' schemas only: nothing is computed or read. A preview + then reads only that input, as the full read does (``SemiJoin`` without a + shared tag gives back its left input and never reads its right one). + + Args: + inputs: The operator's inputs, in order. + """ + return None + def head_rows(self, stream: StreamProtocol, table: pa.Table) -> pa.Table | None: """The rows ``head`` may show of this operator over ``stream``, from the rows ``stream``'s own ``head`` shows (``table``), before the result is computed. @@ -1078,19 +1154,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() @@ -1137,7 +1213,7 @@ async def async_execute_batches( # cannot make one table with the earlier ones is refused, as the sync # path refuses the whole input, never processed alone. settled: dict[str, pa.DataType] = {} - async for batch in channel: + async for batch in carried_batches(channel): settled = settle_token_types(batch, settled) await self._send_processed([batch], channel.stream, output) else: @@ -1178,7 +1254,7 @@ async def _send_result(result: StreamProtocol, output: RecordBatchOutput) -> Non output: The channel to send into; a result with no rows sends nothing. """ table = row_built_columns( - result.as_table(columns=ZERO_ROW_INPUT_COLUMNS), result.keys() + carried_table(result, ZERO_ROW_INPUT_COLUMNS), result.keys() ) for batch in table.to_batches(): if batch.num_rows: @@ -1289,6 +1365,327 @@ 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. + """ + held = held_bytes(table) + if held <= KEPT_ROWS_MEMORY_BYTES or not table.num_rows: + return table + with RowSpool(memory_bytes=KEPT_ROWS_MEMORY_BYTES) as spool: + # A row of lists can be megabytes: a slice is bounded in bytes too (ITL-1464). + fit = int(KEPT_ROWS_MEMORY_BYTES * table.num_rows / held) + size = max(1, min(SPILL_SLICE_ROWS, fit)) + for start in range(0, table.num_rows, size): + spool.append(table.slice(start, size)) + 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). @@ -1323,17 +1720,116 @@ def stream_from_batches( Returns: A complete, re-readable stream over the rows. """ - if not batches: - return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator - table = concatenate_batches(batches) + return _stream_of_rows(stream, concatenate_batches(batches) if batches else None) + + +def _stream_of_rows(stream: StreamProtocol, table: pa.Table | None) -> StreamProtocol: + """``table`` as ``stream``'s rows (``stream_from_batches``); ``None`` for no row.""" if table is None: return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator return StaticOutputOperatorPod._output_stream( # pyright: ignore[reportPrivateUsage] # F and the identity, stage 2's - table, _keys_in_delivered_order(stream.keys(), table.column_names), stream + table, keys_in_delivered_order(stream.keys(), table.column_names), stream ) -def _keys_in_delivered_order( +class BatchSpool: + """Record batches of one stream's rows, put under one another off process memory. + + What ``concatenate_batches`` gives, held in a ``RowSpool``: in memory up to + ``KEPT_ROWS_MEMORY_BYTES``, beyond that in a private temporary file read back + memory-mapped. As there, batches that cannot make one table raise when the table is + asked for, never when they are added. + """ + + def __init__(self) -> None: + self._spool: RowSpool = RowSpool(memory_bytes=KEPT_ROWS_MEMORY_BYTES) + self._schema: pa.Schema | None = None + self._token_types: dict[str, pa.DataType] = {} + self._error: Exception | None = None + self.num_rows: int = 0 + + def add(self, batch: pa.RecordBatch) -> None: + """Hold a batch's rows after every row added before them.""" + if not batch.num_rows: + return + self.num_rows += batch.num_rows + if self._error is None: + try: + self._add(batch) + except Exception as error: # noqa: BLE001 # raised when the table is asked for + self._error = error + + def _add(self, batch: pa.RecordBatch) -> None: + self._token_types = settle_token_types(batch, self._token_types) + table = open_provenance(batch, self._token_types) + if self._schema is None: + self._schema = table.schema + elif not table.schema.equals(self._schema, check_metadata=True): + table = self._in_one_form(table) + self._spool.append(table) + + def _in_one_form(self, table: pa.Table) -> pa.Table: + """``table`` under the held rows' schema; where only one of the two derives a + source-info column, or they derive it otherwise, both become text.""" + assert self._schema is not None + if table.column_names != self._schema.names: + # As a concatenation of them refuses them. + return pa.concat_tables([self._schema.empty_table(), table]) + derived = { + *source_tokens.derived_columns(self._schema), + *source_tokens.derived_columns(table.schema), + } + names = { + f.name + for f in table.schema + if f.name in derived and f.type != self._schema.field(f.name).type + } + if names & {*source_tokens.derived_columns(self._schema)}: + held = self._spool.table() + self._schema = source_tokens.materialize( + self._schema.empty_table(), names + ).schema + self._spool.close() + self._spool = RowSpool(memory_bytes=KEPT_ROWS_MEMORY_BYTES) + for start in range(0, held.num_rows, SPILL_SLICE_ROWS): + part = held.slice(start, SPILL_SLICE_ROWS) + self._spool.append(source_tokens.materialize(part, names)) + table = source_tokens.materialize(table, names) + return pa.concat_tables([self._schema.empty_table(), table]) + + def table(self) -> pa.Table | None: + """Every row added, in order; ``None`` for no row. It stays valid after ``close``. + + Raises: + Exception: If the batches cannot make one table. + """ + if self._error is not None: + raise self._error + return self._spool.table() if self.num_rows else None + + def close(self) -> None: + """Let the rows go and delete their files.""" + self._spool.close() + + +async def stream_of_channel(channel: RecordBatchInput) -> StreamProtocol: + """Read a reserved input channel to its end and give its rows as its stream. + + ``stream_from_batches`` of everything it delivers, held in a ``BatchSpool``. + + Args: + channel: The channel, taken over by the calling task. + """ + spool = BatchSpool() + try: + async for batch in carried_batches(channel): + spool.add(batch) + return _stream_of_rows(channel.stream, spool.table()) + finally: + spool.close() + + +def keys_in_delivered_order( keys: tuple[Sequence[str], Sequence[str]], names: Sequence[str] ) -> tuple[list[str], list[str]]: """The description's tag and data keys, in the order the delivered rows have them. @@ -1396,7 +1892,11 @@ def settle_token_types( if not field.name.startswith(constants.SOURCE_PREFIX): continue kinds: set[pa.DataType] - if pa.types.is_large_string(field.type): + # A derived column settles as the text its recipe gives (ITL-1464). + derived = source_tokens.is_derived(field.type) + if isinstance(field.type, source_tokens.MemberTokenType): + kinds = {field.type.list_type} + elif derived or pa.types.is_large_string(field.type): kinds = {pa.large_string()} else: kinds = { @@ -1408,7 +1908,8 @@ def settle_token_types( if len(kinds) > 1: raise SourceInfoTypesDisagree(field.name) (kind,) = kinds - _ = _named_tokens_as(column, kind, field.name) # representable, or refused + if not derived: + _ = _named_tokens_as(column, kind, field.name) # representable, or refused settled[field.name] = kind return settled @@ -1488,6 +1989,31 @@ def _named_tokens_as( raise RowBuiltFormUnavailable(f"{name}: {error}") from error +def _with_one_token_form(batches: Sequence[pa.RecordBatch]) -> list[pa.RecordBatch]: + """``batches`` with each source-info column in one form in all of them. + + A column every batch derives by one recipe stays derived; one that some batches hold + as text, or derive otherwise, is text in all of them (ITL-1464). + + Args: + batches: Record batches of one stream's rows. + """ + kinds: dict[str, set[pa.DataType]] = {} + for batch in batches: + for field in batch.schema: + if field.name.startswith(constants.SOURCE_PREFIX): + kinds.setdefault(field.name, set()).add(field.type) + mixed = {name for name, types in kinds.items() if len(types) > 1} + formed: list[pa.RecordBatch] = [] + for batch in batches: + if mixed & set(source_tokens.derived_columns(batch.schema)): + table = source_tokens.materialize(pa.Table.from_batches([batch]), mixed) + formed.extend(table.combine_chunks().to_batches()) + else: + formed.append(batch) + return formed + + def concatenate_batches(batches: Sequence[pa.RecordBatch]) -> pa.Table | None: """Put a stream's record batches under one another, or ``None`` with no row. @@ -1516,21 +2042,35 @@ def concatenate_batches(batches: Sequence[pa.RecordBatch]) -> pa.Table | None: settled: dict[str, pa.DataType] = {} for batch in rows: settled = settle_token_types(batch, settled) + return pa.concat_tables( + [open_provenance(batch, settled) for batch in _with_one_token_form(rows)] + ) + + +def open_provenance( + batch: pa.RecordBatch, settled: Mapping[str, pa.DataType] +) -> pa.Table: + """``batch`` with each token column of its settled type and provenance fields nullable. + + Batches of one stream then have one schema for their provenance; whether such a + field is nullable is decided over the complete table (``_flag_by_values``). + + Args: + batch: A record batch of a stream's rows. + settled: Each source-info column's token type (``settle_token_types``). + """ prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) - opened: list[pa.RecordBatch] = [] - for batch in rows: - columns: list[Any] = [] # pyright: ignore[reportExplicitAny] # any column - fields: list[pa.Field[Any]] = [] # pyright: ignore[reportExplicitAny] # any field - for field, column in zip(batch.schema, batch.columns, strict=True): - if field.name in settled: - column = _named_tokens_as(column, settled[field.name], field.name) - field = pa.field(field.name, settled[field.name]) - if field.name.startswith(prefixes): - field = field.with_nullable(True) - columns.append(column) - fields.append(field) - opened.append(pa.RecordBatch.from_arrays(columns, schema=pa.schema(fields))) - return pa.Table.from_batches(opened) + columns: list[Any] = [] # pyright: ignore[reportExplicitAny] # any column + fields: list[pa.Field[Any]] = [] # pyright: ignore[reportExplicitAny] # any field + for field, column in zip(batch.schema, batch.columns, strict=True): + if field.name in settled and not source_tokens.is_derived(field.type): + column = _named_tokens_as(column, settled[field.name], field.name) + field = pa.field(field.name, settled[field.name]) + if field.name.startswith(prefixes): + field = field.with_nullable(True) + columns.append(column) + fields.append(field) + return pa.Table.from_arrays(columns, schema=pa.schema(fields)) class RowsOnRead: @@ -1633,6 +2173,10 @@ def open_channel(self) -> Any: # The members that tell what the output is without reading it: the node's, which # the built stream takes too (``_as_upstream_stream``), or the built stream's once # it is built. A protocol check (``isinstance``) reads them and builds nothing. + @property + def unique_keys(self) -> UniqueKeys: + return self._node.unique_keys + @property def producer(self) -> Any: return self._node.producer @@ -1747,6 +2291,8 @@ class _RowsOfStream(ArrowTableStream): data_context: The rows' data context; ``None`` for the default. """ + _carried_table = ArrowTableStream._carried_table # pyright: ignore[reportPrivateUsage] # read as its base is + def __init__( self, table: pa.Table, @@ -1811,6 +2357,8 @@ def produced_stream(stream: StreamProtocol) -> StreamProtocol: class DynamicPodStream(StreamBase): """Recomputable stream wrapping a ``StaticOutputOperatorPod`` invocation.""" + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def __init__( self, pod: StaticOutputOperatorPod, @@ -1832,6 +2380,9 @@ def __init__( # that this one changed (ITL-1083). self._kept_states: tuple[tuple[str, object], ...] | None = None self._reset_generation: int = 0 + # The window of the last large ``run()`` whose rows were not kept, with what + # its inputs were then (ITL-1464); shown by ``head`` only. + self._run_window: tuple[BoundedStreamView, tuple[object, ...]] | None = None def content_hash(self, hasher=None) -> ContentHash: """The stream's content hash; notes the use of a provisional operator. @@ -1874,6 +2425,11 @@ def pipeline_identity_structure(self) -> Any: structure += (self._pod.argument_symmetry(self._upstreams),) return structure + @property + def unique_keys(self) -> UniqueKeys: + """The tag sets no two rows agree on, derived from the inputs' (``core/unique_keys``).""" + return derived_keys(self.producer, self.upstreams, self) + @property def producer(self) -> PodProtocol: return self._pod @@ -1887,6 +2443,7 @@ def clear_cache(self) -> None: self._cached_stream = None self._cached_time = None self._kept_states = None + self._run_window = None self._reset_generation += 1 def _typed_zero_row_table(self) -> pa.Table | None: @@ -2033,6 +2590,145 @@ def _refresh(self) -> None: self._cached_time = datetime.now(timezone.utc) self._kept_states = kept_states + def _reads_in_batches(self) -> bool: + """Whether the operator is applied batch by batch, over an input read so.""" + return ( + reads_as_its_class(self, DynamicPodStream) + and applied_by_batch(self._pod) + and len(self._upstreams) == 1 + and reads_in_batches(self._upstreams[0]) + ) + + def _batch_streams_of_rows(self) -> Generator[StreamProtocol, None, None]: + """This stream's rows, in order, as one stream per batch (``run()``, ITL-1464). + + Each batch of the input goes through ``static_process``, the one sync body. A + result ``RunSize`` says is kept is kept, as a read keeps it; a larger one is + not. A current kept result is given as it is. + """ + self._pod._note_provisional_identity_use() + self._update_cache_status() + if self._cached_stream is not None and self._cached_time is not None: + if reads_in_batches(self._cached_stream): + # The operator handed its input on: read as that input is. + yield from batch_streams_of(self._cached_stream) + else: + yield self._cached_stream + return + kept_states = _upstream_states(self._upstreams) + kept: list[StreamProtocol] | None = [] + size = RunSize() + handed_on = True + with closing(batch_streams_of(self._upstreams[0])) as batches: + for batch in batches: + try: + result = self._pod.static_process(batch) + except Exception: + # A read of the whole input raises before the operator runs: an + # error further on in the input comes first, as it did there. + for _ in batches: + pass + raise + handed_on = handed_on and result is batch + size.add(result.as_table()) + if kept is not None: + kept.append(result) + if not size.is_kept: + kept = None + yield result + if kept: + self._cached_stream = ( + # Its input unchanged, as a read keeps it; nothing is read again. + self._upstreams[0] if handed_on else joined_batches(kept) + ) + self._cached_time = datetime.now(timezone.utc) + self._kept_states = kept_states + self._run_window = None + + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """The operator over its input's batches, or over its whole inputs. + + A kept current result is read as it is; nothing is computed, and nothing is + kept of what is computed here. + """ + self._pod._note_provisional_identity_use() + self._update_cache_status() + if self._cached_stream is not None and self._cached_time is not None: + yield from preview_batches(self._cached_stream, request) + return + pod = cast(StaticOutputOperatorPod, self._pod) + if len(self._upstreams) == 1 and applied_by_batch(pod): + keeps_every_row = pod.rows_dropped_text(0, (), self._upstreams) is None + wanted = request if keeps_every_row else request.without_limit() + with closing(preview_batches(self._upstreams[0], wanted)) as batches: + for batch in batches: + yield pod.static_process(batch) + return + given_back = pod.input_given_back(self._upstreams) + if given_back is not None: + # The result is that input as it is: no other input is read, as in the + # full read. + yield from preview_batches(self._upstreams[given_back], request) + return + refuse_without_compute_all(self, request, "needs every row of its input") + result = pod.static_process( + *( + self._whole_input(upstream, request.of_every_row()) + for upstream in self._upstreams + ) + ) + yield from preview_batches(result, request) + + @staticmethod + def _whole_input( + upstream: StreamProtocol, request: PreviewRequest + ) -> StreamProtocol: + """Every row of ``upstream``, computed for a preview, with its pipeline hash.""" + rows = joined_batches(list(preview_batches(upstream, request))) + return _RowsOfStream( + rows.as_table(columns=PREVIEW_COLUMNS), + tag_columns=rows.keys()[0], + pipeline_hash=upstream.pipeline_hash(), + data_tags=stream_data_tags(rows), + upstreams=upstream.upstreams, + data_context=StaticOutputOperatorPod._upstream_context(upstream), # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context + ) + + def run(self) -> StreamView: + """Compute every row and return a ``StreamView`` (``StreamBase.run``). + + Over a source that reads its rows on demand, through operators applied batch by + batch, a large result (``RunSize``) is not held: the + view is bounded (``BoundedStreamView``), ``head`` then shows its first rows, + and ``as_table()`` reads and applies the operators again. + """ + # Noted before the rows are read, so a change made meanwhile is seen. + _ = self.last_modified + state = (*_upstream_states(self._upstreams), self._pod.last_modified) + view = super().run() + if isinstance(view, BoundedStreamView): + self._run_window = (view, state) + return view + + def _window_head(self, n: int, config: ColumnConfig) -> StreamView | None: + """The first rows of the last large ``run()``, or ``None`` when there are none + to show: no such run, changed inputs, more rows or other columns asked for.""" + if self._run_window is None: + return None + view, state = self._run_window + if (*_upstream_states(self._upstreams), self._pod.last_modified) != state: + self._run_window = None + return None + if ( + n > view.window_rows + or dataclasses.replace(config, sort_by_tags=False) != ColumnConfig() + ): + return None + head = view.head(n) + return head.sort_by_tags() if config.sort_by_tags else head + def as_table( self, *, @@ -2045,6 +2741,14 @@ def as_table( ) return self._cached_stream.as_table(columns=columns, all_info=all_info) + def _carried_table(self, config: ColumnConfig) -> "pa.Table": + """The operator's result, derived token columns as they are (ITL-1464).""" + self._refresh() + assert self._cached_stream is not None, ( + "StreamProtocol has not been updated or is empty." + ) + return carried_table(self._cached_stream, config) + def iter_data( self, ) -> Iterator[tuple[TagProtocol, DataProtocol]]: @@ -2089,6 +2793,8 @@ def head( view = head_of( self._cached_stream.head(n, columns=config), self, origin="computed" ) + elif (window := self._window_head(n, config)) is not None: + view = window else: matching = self._matching_head(n, config) # A view of no rows is falsy (``StreamView.__len__``): compared to None. @@ -2156,6 +2862,43 @@ def __repr__(self) -> str: ) +def applied_by_batch(pod: object) -> bool: + """Whether an operator may be applied batch by batch (``run()``, ``preview()``). + + Its own class declares ``BATCHES_GIVE_THE_WHOLE``, and no member is replaced on the + instance: what the class declares says nothing of another ``static_process``. + """ + return type(pod).__dict__.get( + "BATCHES_GIVE_THE_WHOLE" + ) is True and reads_as_its_class(pod, type(pod)) + + +def joined_batches(batches: Sequence[StreamProtocol]) -> StreamProtocol: + """Put the batches of one operator's result together as the result itself. + + Args: + batches: The results of consecutive batches of the input, in order; at least + one, all with the same columns and types. + + Returns: + A stream over all their rows, every column group included. + """ + first = batches[0] + return ArrowTableStream( + pa.concat_tables( + [ + carried_table( + batch, {"source": True, "system_tags": True, "context": True} + ) + for batch in batches + ] + ), + tag_columns=first.keys()[0], + data_tags=stream_data_tags(first), + data_context=first.data_context_key, + ) + + def _with_explain_line(view: StreamView, stream: StreamProtocol) -> StreamView: """Return ``view`` with the one-line split of ``explain()`` added to its header, for a ``Filter`` directly over a source (ITL-1402); any other view unchanged.""" @@ -2194,12 +2937,58 @@ def _upstream_state(stream: StreamProtocol) -> tuple[str, object]: return ("generation", generation + int(stream.is_stale)) if isinstance(stream, DynamicPodStream): _ = stream.last_modified + if reads_in_batches(stream): + # It may have been read without keeping a result (``run()``, ITL-1464), and + # then notices no change of its own inputs: what it is computed from is + # part of its state, up to the source. + return ("generation", _chain_state(stream)) return ("generation", stream._reset_generation) # pyright: ignore[reportPrivateUsage] # same class return ("time", stream.last_modified) +def _chain_state(stream: DynamicPodStream) -> object: + """The state of an operator stream read in batches and of everything beneath it. + + Its reset generation, its operator's modified time and the states of its inputs, so + it differs after any change of the source or of an operator in the chain, whether or + not a stream of the chain keeps a result. Keeping one is not a change. An unknown + time (``None``) counts as a change: the state equals no other. + """ + inputs = _upstream_states(stream.upstreams) + pod_time = stream.producer.last_modified + if pod_time is None or ("time", None) in inputs: + return object() + return (stream._reset_generation, pod_time, inputs) # pyright: ignore[reportPrivateUsage] # same class + + +_STATE_MEMO: ContextVar[dict[int, tuple[StreamProtocol, tuple[str, object]]] | None] = ( + ContextVar("_STATE_MEMO", default=None) +) +"""The stream states found during one outermost ``_upstream_states`` call.""" + + def _upstream_states( upstreams: tuple[StreamProtocol, ...], ) -> tuple[tuple[str, object], ...]: - """The state of each upstream (``_upstream_state``), in order.""" - return tuple(_upstream_state(stream) for stream in upstreams) + """The state of each upstream (``_upstream_state``), in order. + + Asking a stream for its state settles it, which asks for the states of its own + upstreams. Within one outermost call each stream is asked once, however many ways + lead to it, so the walk is linear in the graph (PR 560 review, round 2). The memo is + discarded when that call returns and is never shared between threads or tasks. + """ + memo = _STATE_MEMO.get() + if memo is None: + token = _STATE_MEMO.set({}) + try: + return _upstream_states(upstreams) + finally: + _STATE_MEMO.reset(token) + states: list[tuple[str, object]] = [] + for stream in upstreams: + found = memo.get(id(stream)) + if found is None: + # The stream is held with its state, so its id is not reused meanwhile. + found = memo[id(stream)] = (stream, _upstream_state(stream)) + states.append(found[1]) + return tuple(states) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 8089f0715..a2fa79c11 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -2,7 +2,8 @@ The async path of ``Join``, ``MergeJoin``, ``SemiJoin`` and ``Rejoin`` (ITL-1347, stage 5) is to read its inputs as Arrow record batches, in whatever order they arrive; these -kernels are that computation, not yet wired into ``async_execute``. A kernel gives the +kernels are that computation (``run_kernel``, for the operators' +``async_execute_batches``; no job node calls that form yet). A kernel gives the rows of the operator's sync ``static_process`` over the same inputs as a multiset (row order is not a result on the async path; developer, November 22, 2026), within the limits each kernel's docstring states (``StreamingRejoin``: repeated origins with three @@ -49,8 +50,9 @@ no rows that shares a tag with the others empties the result (an inner join), so no row was emitted before it can refuse. ``SemiJoin`` with no shared tag passes every left row whatever its right input holds, and has no shared column to refuse. -- **Matching is the sync join's.** Each input keeps the rows it needs as Arrow tables and - a Polars frame of their prepared keys and row numbers (``arrow_keys.polars_key_frame``), +- **Matching is the sync join's.** Each input keeps the rows it needs in a row spool + (memory, then local disk; ``core/row_spool``) and, when it is indexed, a Polars frame + of their prepared keys and row numbers (``arrow_keys.polars_key_frame``), with the constant key every join adds (``join._with_common_key``). An arriving batch's key frame is joined with the other side's accumulated key frame by the sync path's own rule (``join._matched_pairs``), in one vectorized join, never per row: a top-level @@ -67,9 +69,11 @@ the last step of F), so a kernel declares every such field nullable and the stream made from its batches settles them. -A kernel holds only what can still match: a side's rows are dropped when the other side -closes (nothing can arrive to match them), and an arriving row is not kept once the -other side has closed. A row whose key holds a top-level null is never kept (it matches +A kernel holds the keys of one side of a step only (``_BinaryLink``): both sides' while both +are certified unique on the keys (``core/unique_keys``), a pair's rows being let go when they +match; otherwise the smaller side's, known once a side has ended. A side's rows are dropped +when the other side ends and has been matched with them, and an arriving row is not kept +once the other side has been indexed. A row whose key holds a top-level null is never kept (it matches nothing). A step of a ``Join`` chain that can never emit again (a side closed holding no row that can match) closes its successor's left side and releases the earlier steps, except those the sync path still merges before it (``StreamingJoin._close``). @@ -77,16 +81,17 @@ from __future__ import annotations +import asyncio from abc import ABC, abstractmethod -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from typing import Any, ClassVar import numpy as np +import numpy.typing as npt import polars as pl import pyarrow as pa -import pyarrow.compute as pc -from orcapod.core.data_tags import stream_data_tags +from orcapod.core.data_tags import data_tag_names, stream_data_tags from orcapod.core.operators.arrow_keys import polars_key_frame from orcapod.core.operators.join import ( _COMMON_JOIN_KEY, # pyright: ignore[reportPrivateUsage] # Join's one rule @@ -113,13 +118,20 @@ from orcapod.core.operators.static_output_pod import ( RowBuiltFormUnavailable, StaticOutputOperatorPod, + close_inputs, + concatenate_batches, + finish_operator, settle_token_types, tokens_as, ) +from orcapod.core.row_spool import RowSpool from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.protocols.core_protocols.streams import RecordBatchInput, RecordBatchOutput +from orcapod.core.streams.carried import carried_batches +from orcapod.core.unique_keys import joined_keys, unique_on from orcapod.system_constants import constants -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens # The column groups an operator input and result are read with: user tags, system tags, # data and source info. No meta column and no context column: neither is transported. @@ -129,6 +141,19 @@ # (keys are tag columns, and a tag never starts with the meta prefix ``__``). _ROW = ("__streaming_left_row", "__streaming_right_row") +# How many rows an output batch holds at most: a row with its source-info tokens is +# several KiB, so a batch is some tens of MiB. +PAIRS_PER_BATCH = 8_192 + +# The pair-count column of a many-to-many match, and how many removed rows a side's key +# frame holds before it is compacted. +_COUNT = "__streaming_count" +_COMPACT_ROWS = 1_024 + +# How many rows of one input are read ahead and pushed at once. A push joins its rows with +# every key held, so rows that have arrived already are pushed together. +PUSH_ROWS = 65_536 + def _settled_by_values(schema: pa.Schema) -> pa.Schema: """``schema`` with every system-tag and source-info field nullable. @@ -162,12 +187,13 @@ def _row_built_zero_rows(stream: StreamProtocol) -> tuple[StreamProtocol, bool]: pod = StaticOutputOperatorPod zero = pod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the operators' one form of an input table = zero.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - row_built = pod._flag_by_values(row_built_columns(table, stream.keys())) # pyright: ignore[reportPrivateUsage] # F's last step + tag_keys, data_keys = stream.keys() + row_built = pod._flag_by_values(row_built_columns(table, (tag_keys, data_keys))) # pyright: ignore[reportPrivateUsage] # F's last step differs = any( field.type != table.schema.field(field.name).type for field in row_built.schema ) built = pod._as_upstream_stream( # pyright: ignore[reportPrivateUsage] # the operators' one form of an input - row_built, stream.keys()[0], stream_data_tags(stream), stream + row_built, tag_keys, data_tag_names(tag_keys, data_keys), stream ) return built, differs @@ -191,112 +217,323 @@ def _key_frame(table: pa.Table, keys: Sequence[str], row: str) -> pl.DataFrame: ) -def _match( - arriving: pl.DataFrame, held: pl.DataFrame, keys: Sequence[str] -) -> pl.DataFrame: - """Join two key frames by the sync join's rule (``join._matched_pairs``). +def _bounded_pairs( + arriving: pl.DataFrame, + held: pl.DataFrame, + keys: Sequence[str], + *, + at_most_one: bool, + row: str, +) -> Iterator[pl.DataFrame]: + """Join two key frames by the sync join's rule, in pieces of a bounded size. - Both frames hold the constant join key, so inputs that share no tag give every pair - and a top-level null key matches nothing, as on the sync path. + The rule is ``join._matched_pairs``. Both frames hold the constant join key, so + inputs that share no tag give every pair and a top-level null key matches nothing, + as on the sync path. A piece holds at most ``PAIRS_PER_BATCH`` pairs, or the pairs of + one arriving row when it has more: those are at most the rows held. Args: arriving: The arriving batch's key frame. held: The other side's accumulated key frame. keys: The shared tag columns. + at_most_one: Whether an arriving row matches at most one held row (the held + side is unique on the keys), so the pairs need not be counted first. + row: The arriving frame's row-number column. - Returns: - One row per matched pair, holding both row-number columns. + Yields: + One row per matched pair, holding both row-number columns; never empty. """ - return _matched_pairs(arriving, held, [*keys, _COMMON_JOIN_KEY]) + on = [*keys, _COMMON_JOIN_KEY] + if at_most_one: + pieces = [arriving] + else: + # Only the held rows that match, then how many each arriving row has. + held = held.join(arriving, on=on, how="semi") + if not held.height: + return + counts = held.group_by(on).len(name=_COUNT) + counted = arriving.join(counts, on=on, how="inner").sort(row) + pieces = [arriving] + if int(counted.get_column(_COUNT).sum()) > PAIRS_PER_BATCH: + pieces = _pieces(counted) + for piece in pieces: + pairs = _matched_pairs(piece, held, on) + for start in range(0, pairs.height, PAIRS_PER_BATCH): + yield pairs.slice(start, PAIRS_PER_BATCH) -def _joined_by_rows( - left: pa.Table, - right: pa.Table, - keys: Sequence[str], - left_rows: pa.Array[Any], - right_rows: pa.Array[Any], -) -> pa.Table: - """Take matched pairs from two tables, in the layout of ``join._inner_join``. +def _pieces(counted: pl.DataFrame) -> Iterator[pl.DataFrame]: + """Cut arriving rows into runs whose pair counts add up to ``PAIRS_PER_BATCH``. + + Args: + counted: The arriving rows that match, each with its number of pairs. + + Yields: + The runs, without the counts; a row with more pairs is a run of its own. + """ + ends = np.cumsum(counted.get_column(_COUNT).to_numpy().astype(np.int64)) + rows = counted.drop(_COUNT) + start = 0 + while start < rows.height: + before = int(ends[start - 1]) if start else 0 + end = int(np.searchsorted(ends, before + PAIRS_PER_BATCH, side="right")) + end = max(end, start + 1) + yield rows.slice(start, end - start) + start = end + + +def _side_by_side(left: pa.Table, right: pa.Table, keys: Sequence[str]) -> pa.Table: + """Put matched rows of two tables side by side, in the layout of ``join._inner_join``. The left columns (one of each key, the left row's value), then the right columns that are not keys, a name the left table also has taking the suffix ``_right``. Args: - left: The left table. - right: The right table. + left: The left row of each pair. + right: The right row of each pair. keys: The key columns. - left_rows: The left row of each pair. - right_rows: The right row of each pair. Returns: The joined table, fields without the inputs' flags (as ``_inner_join``). """ - names: list[str] = [] - arrays: list[Any] = [] - for name in left.column_names: - names.append(name) - arrays.append(left.column(name).take(left_rows)) + names: list[str] = list(left.column_names) + arrays: list[Any] = list(left.columns) for name in right.column_names: if name in keys: continue names.append(f"{name}_right" if name in left.column_names else name) - arrays.append(right.column(name).take(right_rows)) + arrays.append(right.column(name)) return pa.Table.from_arrays(arrays, names=names) +class _Rows: + """Rows numbered from 0 in the order held, spooled. + + Rows of one input may hold a source-info column as text in one batch and derived in + another (``source_tokens``). Rows are held in the form of the first ones; from the + first rows in another form on, rows are held as text. So there are at most two spools, + the first of which keeps no row in memory once there is a second, and rows fetched + from both are given as text. + """ + + def __init__(self) -> None: + self.size: int = 0 + self._runs: list[tuple[int, pa.Schema, RowSpool]] = [] + + def append(self, table: pa.Table) -> None: + """Hold ``table``'s rows, numbered from ``size`` on.""" + if not table.num_rows: + return + schema = self._runs[-1][1] if self._runs else table.schema + if not table.schema.equals(schema, check_metadata=True): + table = source_tokens.materialize(table) + if not self._runs or not table.schema.equals(schema, check_metadata=True): + if self._runs: + self._runs[-1][2].spill() + self._runs.append((self.size, table.schema, RowSpool())) + self._runs[-1][2].append(table) + self.size += table.num_rows + + def _by_run( + self, rows: npt.NDArray[np.int64] + ) -> Iterator[tuple[RowSpool, npt.NDArray[np.int64], npt.NDArray[np.int64]]]: + """Each run that holds some of ``rows``: its spool, their positions in ``rows`` + and their numbers in the spool.""" + starts = np.array([start for start, _, _ in self._runs], dtype=np.int64) + runs = np.searchsorted(starts, rows, side="right") - 1 + for run in np.unique(runs): + positions = np.flatnonzero(runs == run) + start, _, spool = self._runs[int(run)] + yield spool, positions, rows[positions] - start + + def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: + """The rows with these numbers, in this order.""" + parts = [(at, spool.take(local)) for spool, at, local in self._by_run(rows)] + if len(parts) == 1: + return parts[0][1] + taken = _one_form([part for _, part in parts]).combine_chunks() + order = np.argsort(np.concatenate([at for at, _ in parts])) + return taken.take(pa.array(order, pa.int64())) + + def block(self, start: int, length: int) -> pa.Table: + """``length`` rows from ``start`` on, none of them discarded, without copying.""" + parts: list[pa.Table] = [] + for run_start, _, spool in self._runs: + first = max(start - run_start, 0) + last = min(start + length - run_start, spool.size) + if first < last: + parts.append(spool.slice(first, last - first)) + return _one_form(parts) + + def discard(self, rows: npt.NDArray[np.int64]) -> None: + """Say that these rows are never fetched again.""" + for spool, _, local in self._by_run(rows): + spool.discard(local) + + def close(self) -> None: + """Let every row and file go.""" + for _, _, spool in self._runs: + spool.close() + self._runs = [] + + +def _one_form(tables: Sequence[pa.Table]) -> pa.Table: + """``tables`` under one another, a token column of several forms as text. + + Every derived column is looked at, whatever its name: a join holds the token column + of a data-tag both inputs have under a name of its own. + + Args: + tables: Rows of one input, at least one table. + """ + derived = { + name: table.schema.field(name).type + for table in tables + for name in source_tokens.derived_columns(table.schema) + } + mixed = { + name + for name, kind in derived.items() + if any(table.schema.field(name).type != kind for table in tables) + } + return pa.concat_tables([source_tokens.materialize(t, mixed) for t in tables]) + + class _Side: - """One side of a binary symmetric hash join: the rows it holds and their key frame. + """One side of a symmetric join: its rows' key frame, the rows themselves spooled. Args: keys: The key columns. row: This side's row-number column. + constant_key: Whether the key frame holds the constant join key. """ - def __init__(self, keys: Sequence[str], row: str) -> None: + def __init__( + self, keys: Sequence[str], row: str, *, constant_key: bool = True + ) -> None: self.keys: list[str] = list(keys) self.row: str = row self.closed: bool = False - self.schema: pa.Schema | None = None - self._tables: list[pa.Table] = [] - self._frames: list[pl.DataFrame] = [] - self._table: pa.Table | None = None - self._frame: pl.DataFrame | None = None self.rows: int = 0 + self._constant_key: bool = constant_key + self._rows: _Rows = _Rows() + # The key frame, and beside its rows their numbers (ascending) and whether each + # is still held: as long as the frame, whatever the numbers are. + self._frames: list[pl.DataFrame] = [] + self._numbers: npt.NDArray[np.int64] = np.empty(0, dtype=np.int64) + self._alive: npt.NDArray[np.bool_] = np.empty(0, dtype=np.bool_) + self._count: int = 0 + self._removed_count: int = 0 def key_frame(self, table: pa.Table) -> pl.DataFrame: """The key frame of ``table``, its rows numbered from 0.""" - return _key_frame(table, self.keys, self.row) + if self._constant_key: + return _key_frame(table, self.keys, self.row) + return polars_key_frame(table, self.keys, self.row) def append(self, table: pa.Table, frame: pl.DataFrame) -> None: """Hold ``table``'s rows, with ``frame`` from ``key_frame``.""" - self._tables.append(table) - # Numbered after the rows already held, as ``table()`` holds them. - self._frames.append( - frame.with_columns(pl.col(self.row) + self.rows) if self.rows else frame - ) - self._table = None - self._frame = None + if not table.num_rows: + return + self._add_frame(frame, self._rows.size) + self._rows.append(table) + self.rows += table.num_rows + + def _add_frame(self, frame: pl.DataFrame, first: int) -> None: + """Hold the keys of rows numbered from ``first``, in ``frame``'s order.""" + self._frames.append(frame.with_columns(pl.col(self.row) + first)) + count = self._count + frame.height + if count > len(self._numbers): + for name in ("_numbers", "_alive"): + old = getattr(self, name) + grown = np.empty(2 * count, dtype=old.dtype) + grown[: self._count] = old[: self._count] + setattr(self, name, grown) + self._numbers[self._count : count] = np.arange(first, first + frame.height) + self._alive[self._count : count] = True + self._count = count + + def spool(self, table: pa.Table) -> None: + """Hold ``table``'s rows without their keys, until ``index`` or ``replay``.""" + self._rows.append(table) self.rows += table.num_rows - def table(self) -> pa.Table: - """Every row held, numbered as in ``frame``.""" - if self._table is None: - self._table = pa.concat_tables(self._tables) - return self._table + def index(self) -> None: + """Prepare the keys of the rows held without them (every row held).""" + for start in range(0, self._rows.size, PUSH_ROWS): + # Only the keys are read, and nothing is copied. + table = self._rows.block(start, min(PUSH_ROWS, self._rows.size - start)) + self._add_frame( + self.key_frame(table.select(self.keys) if self.keys else table), start + ) + + def replay(self) -> Iterator[pa.Table]: + """Give the rows held without keys, in order, in blocks, and let each block go. + + A block's rows are let go once the next one is asked for. + """ + for start in range(0, self._rows.size, PUSH_ROWS): + rows = np.arange(start, min(start + PUSH_ROWS, self._rows.size)) + yield self._rows.take(rows) + self._rows.discard(rows) + self.rows -= len(rows) + + def held(self, rows: npt.NDArray[np.int64]) -> npt.NDArray[np.int64]: + """Those of ``rows``, numbers in the key frame, that were not removed.""" + return rows[self._alive[self._positions(rows)]] + + def _positions(self, rows: npt.NDArray[np.int64]) -> npt.NDArray[np.int64]: + """Where the rows with these numbers are in the key frame.""" + return np.searchsorted(self._numbers[: self._count], rows) + + def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: + """The held rows with these numbers, in this order.""" + return self._rows.take(rows) def frame(self) -> pl.DataFrame: - """The key frame of every row held.""" - if self._frame is None: - self._frame = pl.concat(self._frames, rechunk=False) - self._frames = [self._frame] - return self._frame + """The key frame of the rows held and, until compacted, of removed ones. + + A caller whose removed rows can match again asks ``held_frame``. + """ + if len(self._frames) != 1: + self._frames = [pl.concat(self._frames, rechunk=False)] + return self._frames[0] + + def held_frame(self) -> pl.DataFrame: + """The key frame of the rows held, without the removed ones.""" + frame = self.frame() + if not self._removed_count: + return frame + return frame.filter(pl.Series(self._alive[: self._count])) + + def remove(self, rows: npt.NDArray[np.int64]) -> None: + """Let rows go that can never match again: each is held, each given once.""" + if not len(rows): + return + self._rows.discard(rows) + self.rows -= len(rows) + self._alive[self._positions(rows)] = False + self._removed_count += len(rows) + if not self.rows or self._removed_count >= max(self.rows, _COMPACT_ROWS): + self._compact() + + def _compact(self) -> None: + """Drop the removed rows from the key frame.""" + if self.rows: + self._frames = [self.held_frame()] + self._numbers = self._numbers[: self._count][self._alive[: self._count]] + else: + self._frames, self._numbers = [], np.empty(0, dtype=np.int64) + self._count = len(self._numbers) + self._alive = np.ones(self._count, dtype=np.bool_) + self._removed_count = 0 def clear(self) -> None: - """Drop every row held.""" - self._tables, self._frames = [], [] - self._table, self._frame = None, None + """Drop every row held, and their files.""" self.rows = 0 + self._compact() + self._rows.close() + self._rows = _Rows() class _BinaryLink: @@ -306,14 +543,29 @@ class _BinaryLink: keys: The key columns. finish: Turns the pairs' joined table (``_joined_by_rows`` layout) into the link's output rows; given the two sides' schemas. + unique: Whether each side is certified unique on the keys: no two of its rows + match one row of the other side. A row is let go once it has matched if, and + only if, the other side is unique: it can match nothing else. + + With both sides unique (one to one) rows are matched as they arrive and let go. Any + other link holds the keys of its smaller side only. Rows are spooled without keys + until a side is known to be the smaller one: when one has ended, the other is spooled + on until it has as many rows (the ended side is indexed) or ends with fewer (it is + indexed itself). An ended side of at most ``PUSH_ROWS`` rows is indexed at once. Then + the other side's spooled rows are matched with the index and let go, and every row + still to arrive is matched at once and not held. """ def __init__( self, keys: Sequence[str], finish: Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table], + unique: tuple[bool, bool] = (False, False), ) -> None: + self.unique: tuple[bool, bool] = unique self.keys: list[str] = list(keys) + self.one_to_one: bool = all(unique) + self._indexed: bool = self.one_to_one self.sides: tuple[_Side, _Side] = (_Side(keys, _ROW[0]), _Side(keys, _ROW[1])) self._finish: Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table] = finish @@ -340,53 +592,116 @@ def release(self) -> None: side.closed = True side.clear() - def push(self, side: int, table: pa.Table) -> pa.Table | None: + def push(self, side: int, table: pa.Table) -> Iterator[pa.Table]: """Match ``table``'s rows with the other side's, then hold them if still needed. + The rows are held, and the matched ones let go, once the iterator is read to its + end. + Args: side: 0 for the left side, 1 for the right. table: The arriving rows; every table of one side has one schema. - Returns: - The output rows of the new pairs, or ``None`` when there is none. + Yields: + The output rows of the new pairs, in pieces of at most ``PAIRS_PER_BATCH``. """ this, other = self.sides[side], self.sides[1 - side] - if this.schema is None: - this.schema = table.schema if other.closed and not other.rows: # Nothing can pair with these rows, and none is held: no key to prepare. - return None + return if self.keys: # A row whose key holds a top-level null matches nothing: never held, so a # closed side holding only such rows is exhausted. table = table.filter(_has_whole_key(table, self.keys)) if not table.num_rows: - return None + return + if self._indexed: + yield from self._match(side, table) + return + this.spool(table) + if other.closed and this.rows >= other.rows: + yield from self._index(1 - side) + + def _index(self, side: int) -> Iterator[pa.Table]: + """Index ``side``, which has ended, and match the other side's spooled rows. + + Args: + side: The side no larger than the other. + + Yields: + The output rows of the pairs, in pieces. + """ + self._indexed = True + self.sides[side].index() + other = self.sides[1 - side] + for table in other.replay(): + yield from self._match(1 - side, table) + other.clear() + + def _match(self, side: int, table: pa.Table) -> Iterator[pa.Table]: + """Match ``table``'s rows, whose keys are whole, with the other side's keys. + + Args: + side: The side the rows are of. + table: The rows. + + Yields: + The output rows of the pairs, in pieces. + """ + this, other = self.sides[side], self.sides[1 - side] frame = this.key_frame(table) - result = None + this_unique, other_unique = self.unique[side], self.unique[1 - side] + matched = np.zeros(table.num_rows, dtype=np.bool_) + gone: list[npt.NDArray[np.int64]] = [] if other.rows: - pairs = _match(frame, other.frame(), self.keys) - if pairs.height: - rows = ( - pairs.get_column(_ROW[0]).to_arrow(), - pairs.get_column(_ROW[1]).to_arrow(), - ) - tables = (table, other.table()) if side == 0 else (other.table(), table) - joined = _joined_by_rows(*tables, self.keys, *rows) - assert self.sides[0].schema is not None - assert self.sides[1].schema is not None - result = self._finish( - joined, self.sides[0].schema, self.sides[1].schema + for pairs in _bounded_pairs( + frame, other.frame(), self.keys, at_most_one=other_unique, row=this.row + ): + mine = pairs.get_column(this.row).to_numpy().astype(np.int64) + theirs = pairs.get_column(other.row).to_numpy().astype(np.int64) + if other_unique: + matched[mine] = True + if this_unique: + gone.append(theirs) + taken = (table.take(pa.array(mine, pa.int64())), other.take(theirs)) + left, right = taken if side == 0 else (taken[1], taken[0]) + yield self._finish( + _side_by_side(left, right, self.keys), left.schema, right.schema ) + if gone: + other.remove(np.concatenate(gone)) # A row is held only for rows still to arrive on the other side. if not other.closed: + if matched.any(): + unmatched = ~matched + table = table.filter(pa.array(unmatched)) + frame = this.key_frame(table) this.append(table, frame) - return result - def close(self, side: int) -> None: - """Note that ``side`` ends: the other side's rows can never match again.""" - self.sides[side].closed = True - self.sides[1 - side].clear() + def close(self, side: int) -> Iterator[pa.Table]: + """Note that ``side`` ends: the other side's rows are needed no longer. + + Args: + side: The side that ends. + + Yields: + The output rows that decides: those of spooled rows, when it is now known + which side is the smaller one. + """ + this, other = self.sides[side], self.sides[1 - side] + this.closed = True + if not self._indexed: + if other.closed: + # Both ended: ``other`` ended first, with more rows than this one. + if this.rows: + yield from self._index(side) + this.clear() + elif this.rows and (this.rows <= PUSH_ROWS or other.rows >= this.rows): + yield from self._index(side) + return + elif this.rows: + return + other.clear() class StreamingJoinKernel(ABC): @@ -454,11 +769,24 @@ def held_rows(self) -> int: def push(self, input_index: int, batch: pa.RecordBatch) -> list[pa.RecordBatch]: """Take one record batch of an input; return the output rows it decides. + ``iter_push`` with its batches collected: for an output known to be small. + """ + return list(self.iter_push(input_index, batch)) + + def iter_push( + self, input_index: int, batch: pa.RecordBatch + ) -> Iterator[pa.RecordBatch]: + """Take one record batch of an input; yield the output rows it decides. + + The iterator must be read to its end before the kernel is used again: the + batch's own rows are held only then. Reading it piece by piece keeps the output + of a many-to-many match out of memory. + Args: input_index: The input, in call order. batch: The batch, holding the input's transport columns. - Returns: + Yields: The output record batches, possibly none. Raises: @@ -470,17 +798,26 @@ def push(self, input_index: int, batch: pa.RecordBatch) -> list[pa.RecordBatch]: self._require_open(input_index) table = self._as_input_table(input_index, batch) if not table.num_rows: - return [] + return self._received[input_index] = True - return self._emitted(self._push(input_index, table)) + yield from self._emitted(self._push(input_index, table)) def close(self, input_index: int) -> list[pa.RecordBatch]: """Note that an input has ended; return the output rows that decides. + ``iter_close`` with its batches collected: for an output known to be small. + """ + return list(self.iter_close(input_index)) + + def iter_close(self, input_index: int) -> Iterator[pa.RecordBatch]: + """Note that an input has ended; yield the output rows that decides. + + The iterator must be read to its end before the kernel is used again. + Args: input_index: The input, in call order. - Returns: + Yields: The output record batches, possibly none. Raises: @@ -491,15 +828,14 @@ def close(self, input_index: int) -> list[pa.RecordBatch]: """ self._require_open(input_index) self._closed[input_index] = True - emitted = self._emitted(self._close(input_index)) + yield from self._emitted(self._close(input_index)) if all(self._closed): self._check_settled_against_empty_inputs() result = self._check_empty_inputs() - if result is not None and not self._emitted_any and not emitted: + if result is not None and not self._emitted_any: # No row: the output is the sync path's result over the inputs as # they ended, whose types an empty input decides. self.zero_row_result = result - return emitted def _check_settled_against_empty_inputs(self) -> None: """Compare the settled token types with the inputs that delivered no rows. @@ -539,8 +875,8 @@ def _check_empty_inputs(self) -> StreamProtocol | None: ) @abstractmethod - def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: - """Take an input's rows; return the output tables they decide. + def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: + """Take an input's rows; give the output tables they decide. Args: input_index: The input, in call order. @@ -551,8 +887,8 @@ def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: """ @abstractmethod - def _close(self, input_index: int) -> list[pa.Table]: - """Note an input's end; return the output tables that decides. + def _close(self, input_index: int) -> Iterable[pa.Table]: + """Note an input's end; give the output tables that decides. Args: input_index: The input, in call order; open until this call. @@ -601,11 +937,16 @@ def _as_input_table(self, input_index: int, batch: pa.RecordBatch) -> pa.Table: ) table = pa.Table.from_batches([batch]).select(layout.names) columns = list(table.columns) + fields = list(layout) for index, (field, actual) in enumerate(zip(layout, table.schema)): if field.type == actual.type: continue if not table.num_rows and pa.types.is_null(actual.type): continue + if source_tokens.derived_recipe(actual.type) is not None: + # No token is null, and the recipe's text is the layout's type. + fields[index] = field.with_type(actual.type) + continue if table.num_rows and field.name.startswith(constants.SOURCE_PREFIX): # A batch's token type follows its own tokens and can be shallower # than the layout's (a null or an empty list fixes fewer list @@ -626,7 +967,7 @@ def _as_input_table(self, input_index: int, batch: pa.RecordBatch) -> pa.Table: self._token_types[input_index] = token_types if not table.num_rows: return layout.empty_table() - return pa.Table.from_arrays(columns, schema=layout) + return pa.Table.from_arrays(columns, schema=pa.schema(fields)) def _check_settled_token_types( self, input_index: int, token_types: Mapping[str, pa.DataType] @@ -643,13 +984,12 @@ def _check_settled_token_types( """ del input_index, token_types - def _emitted(self, tables: list[pa.Table]) -> list[pa.RecordBatch]: + def _emitted(self, tables: Iterable[pa.Table]) -> Iterator[pa.RecordBatch]: """The record batches of the output tables, holding ``output_columns``. Every system-tag and source-info field is declared nullable: the complete table's values decide those flags (``StaticOutputOperatorPod._flag_by_values``). """ - batches: list[pa.RecordBatch] = [] for table in tables: if table.num_rows: self._emitted_any = True @@ -657,8 +997,10 @@ def _emitted(self, tables: list[pa.Table]) -> list[pa.RecordBatch]: table = pa.Table.from_arrays( table.columns, schema=_settled_by_values(table.schema) ) - batches.extend(table.to_batches()) - return batches + yield from table.to_batches() + + def release(self) -> None: + """Let every row held go, with its files: the run has ended or failed.""" def _suffix(self, input_index: int, position: int) -> str: """What an input's system-tag column names gain: ``{pipeline hash}:{position}``.""" @@ -701,12 +1043,14 @@ def __init__(self, operator: Join, inputs: Sequence[StreamProtocol]) -> None: if len(inputs) == 1: return first = inputs[order[0]] + # The unique keys of the rows joined so far (``core/unique_keys``). + unique_keys = first.unique_keys tag_keys = set(first.keys()[0]) data_tags = set(stream_data_tags(first)) for position, index in enumerate(order[1:], start=1): stream = inputs[index] - next_tags = set(stream.keys()[0]) - next_data_tags = set(stream_data_tags(stream)) + keys = stream.keys() + next_tags, next_data_tags = set(keys[0]), set(data_tag_names(*keys)) merged = Join._merged_data_tags( # pyright: ignore[reportPrivateUsage] # Join's one rule tag_keys, data_tags, next_tags, next_data_tags ) @@ -719,8 +1063,13 @@ def __init__(self, operator: Join, inputs: Sequence[StreamProtocol]) -> None: keys = sorted(tag_keys & next_tags) last = position == len(inputs) - 1 self._links.append( - _BinaryLink(keys, self._link_finish(keys, rename, final=last)) + _BinaryLink( + keys, + self._link_finish(keys, rename, final=last), + (unique_on(unique_keys, keys), unique_on(stream.unique_keys, keys)), + ) ) + unique_keys = joined_keys(unique_keys, stream.unique_keys, keys) self._merges.append(bool(rename)) tag_keys |= next_tags data_tags |= next_data_tags @@ -753,7 +1102,7 @@ def finish( return finish - def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: + def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: """Feed an input's rows into its step and forward what each step emits. The input at canonical position 0 is the first step's left side, the input at @@ -776,15 +1125,30 @@ def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: if rename := self._renames.get(input_index): table = table.rename_columns([rename.get(c, c) for c in table.column_names]) step, side = (0, 0) if position == 0 else (position - 1, 1) - result = self._links[step].push(side, table) - while result is not None and step < len(self._links) - 1: - if step in self._sinks: - return [] - step += 1 - result = self._links[step].push(0, result) - return [] if result is None else [result] + return self._through(step, side, table) - def _close(self, input_index: int) -> list[pa.Table]: + def _through(self, step: int, side: int, table: pa.Table) -> Iterator[pa.Table]: + """Push rows into a step, and what it emits through the steps after it.""" + for result in self._links[step].push(side, table): + yield from self._after(step, result) + + def _after(self, step: int, result: pa.Table) -> Iterator[pa.Table]: + """Take rows a step emitted through the steps after it.""" + if step == len(self._links) - 1: + yield result + elif step not in self._sinks: + yield from self._through(step + 1, 0, result) + + def _end(self, step: int, side: int) -> Iterator[pa.Table]: + """End a step's side, and take what that emits through the steps after it.""" + for result in self._links[step].close(side): + yield from self._after(step, result) + + def release(self) -> None: + for link in self._links: + link.release() + + def _close(self, input_index: int) -> Iterator[pa.Table]: """End an input's side of its step, and every side that can no longer receive. A step that can never emit again (``_BinaryLink.exhausted``) closes its @@ -793,19 +1157,19 @@ def _close(self, input_index: int) -> list[pa.Table]: the sync path joins those steps before it reaches the empty one, and a merge refuses token lists of different lengths (a value-decided refusal, module docstring). Those steps keep matching, and the last of them drops its output - (``_sinks``). Closing never emits a row. + (``_sinks``). Args: input_index: The input, in call order. - Returns: - No table. + Yields: + The last step's output, possibly none. """ if not self._links: - return [] + return position = self._position[input_index] step, side = (0, 0) if position == 0 else (position - 1, 1) - self._links[step].close(side) + yield from self._end(step, side) for step, link in enumerate(self._links): if not link.exhausted: continue @@ -821,8 +1185,7 @@ def _close(self, input_index: int) -> list[pa.Table]: step + 1 < len(self._links) and not self._links[step + 1].sides[0].closed ): - self._links[step + 1].close(0) - return [] + yield from self._end(step + 1, 0) class StreamingMergeJoin(StreamingJoinKernel): @@ -857,6 +1220,9 @@ def __init__(self, operator: MergeJoin, inputs: Sequence[StreamProtocol]) -> Non for name in sorted(merged) if f"{constants.SOURCE_PREFIX}{name}" in right_names } + self._in_both = set(self._layouts[0].names) & { + self._rename.get(name, name) for name in right_names + } self._colliding = (set(left_data) & set(right_data)) - merged self._captured = ( set(left_tags) | set(left_data) | set(right_tags) | set(right_data) @@ -865,7 +1231,14 @@ def __init__(self, operator: MergeJoin, inputs: Sequence[StreamProtocol]) -> Non self._type_converter = StaticOutputOperatorPod._upstream_context( # pyright: ignore[reportPrivateUsage] # the operators' one rule left ).type_converter - self._link = _BinaryLink(sorted(self._shared_tags), self._finish) + self._link = _BinaryLink( + sorted(self._shared_tags), + self._finish, + ( + unique_on(left.unique_keys, self._shared_tags), + unique_on(right.unique_keys, self._shared_tags), + ), + ) def _check_settled_against_empty_inputs(self) -> None: """Refuse, when every input has closed, a run whose input with rows settled a @@ -957,6 +1330,8 @@ def _finish( for left_name, right_name in self._rename.items(): joined = Join._merge_source_columns(joined, left_name, right_name) # pyright: ignore[reportPrivateUsage] # Join's one rule joined = Join._fold_source_column(joined, left_name) # pyright: ignore[reportPrivateUsage] # Join's one rule + # A merge of derived tokens has a recipe, so a type, of its own (ITL-1464). + output_types[left_name] = joined.schema.field(left_name).type for name in sorted(self._colliding): source_name = f"{constants.SOURCE_PREFIX}{name}" pairs = [(name, output_types[name])] @@ -1001,7 +1376,7 @@ def _finish( schema=schema, ) - def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: + def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: table = arrow_utils.append_to_system_tags( table, self._suffix(input_index, input_index) ) @@ -1009,21 +1384,24 @@ def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: table = table.rename_columns( [self._rename.get(c, c) for c in table.column_names] ) - result = self._link.push(input_index, table) - return [] if result is None else [result] + # A source-info column both inputs have becomes a list of both tokens: text. + table = source_tokens.materialize(table, self._in_both) + return self._link.push(input_index, table) - def _close(self, input_index: int) -> list[pa.Table]: - self._link.close(input_index) - return [] + def release(self) -> None: + self._link.release() + + def _close(self, input_index: int) -> Iterable[pa.Table]: + return self._link.close(input_index) class StreamingSemiJoin(StreamingJoinKernel): - """``SemiJoin`` on record batches: the left input streams. + """``SemiJoin`` on record batches: the right input's keys are held. - A left row is emitted as soon as its key is among the right rows seen so far; a left - row with no such match waits until a right row matches it or the right input closes, - when it is dropped. The right input's rows are held as keys only, while the left - input is open. With no tag shared by the inputs, every left row passes, as + Which left rows are kept is decided by the whole right input, of which only the + distinct keys are held. Left rows that arrive before it has ended are spooled without + keys and decided when it ends; the left rows after that are decided at once and not + held. With no tag shared by the inputs, every left row passes as it arrives, as ``static_process`` returns the left stream. Args: @@ -1037,81 +1415,87 @@ def __init__(self, operator: SemiJoin, inputs: Sequence[StreamProtocol]) -> None super().__init__(operator, inputs) left, right = inputs self._keys = list(SemiJoin._match_keys(left.keys()[0], right.keys()[0])) # pyright: ignore[reportPrivateUsage] # SemiJoin's one rule - # The left rows not decided yet, and the right rows' keys. - self._waiting: pa.Table | None = None + # The left rows not decided yet, spooled, and the distinct keys of the right rows. + self._waiting = _Side(self._keys, _ROW[0], constant_key=False) self._right_frames: list[pl.DataFrame] = [] - self._right_frame: pl.DataFrame | None = None + # Whether Polars tells key values apart as its joins do (no nested key). + self._distinct: bool = not any( + pa.types.is_nested(self._layouts[1].field(name).type) for name in self._keys + ) @property def held_rows(self) -> int: - waiting = self._waiting.num_rows if self._waiting is not None else 0 - return waiting + sum(frame.height for frame in self._right_frames) + return self._waiting.rows + sum(frame.height for frame in self._right_frames) + + def release(self) -> None: + self._waiting.clear() + self._right_frames = [] def _right_keys(self) -> pl.DataFrame | None: - """The key frame of every right row held, or ``None`` with none.""" + """The key frame of the right rows held, or ``None`` with none.""" if not self._right_frames: return None - if self._right_frame is None: - self._right_frame = pl.concat(self._right_frames, rechunk=False) - self._right_frames = [self._right_frame] - return self._right_frame - - def _kept(self, left: pa.Table, right_keys: pl.DataFrame) -> pa.Array[Any]: - """Whether each left row's key is among ``right_keys``, as a boolean mask.""" - kept = polars_key_frame(left, self._keys, _ROW[0]).join( - right_keys, on=self._keys, how="semi" - ) - mask = np.zeros(left.num_rows, dtype=np.bool_) - mask[kept.get_column(_ROW[0]).to_numpy()] = True - return pa.array(mask) - - def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: + if len(self._right_frames) > 1: + self._right_frames = [pl.concat(self._right_frames, rechunk=False)] + return self._right_frames[0] + + def _matched( + self, left: pl.DataFrame, right_keys: pl.DataFrame + ) -> npt.NDArray[np.int64]: + """The left rows whose key is among ``right_keys``, by number.""" + kept = left.join(right_keys, on=self._keys, how="semi") + return kept.get_column(_ROW[0]).to_numpy().astype(np.int64) + + def _push(self, input_index: int, table: pa.Table) -> Iterable[pa.Table]: if not self._keys: return [table] if input_index == 0 else [] - if input_index == 0: - right_keys = self._right_keys() - if right_keys is None: - kept = pa.array(np.zeros(table.num_rows, dtype=np.bool_)) - else: - kept = self._kept(table, right_keys) - if not self._closed[1]: - # A left row whose key holds a top-level null never matches. - undecided = table.filter( - pc.and_(pc.invert(kept), _has_whole_key(table, self._keys)) - ) - if undecided.num_rows: - self._waiting = ( - undecided - if self._waiting is None - else pa.concat_tables([self._waiting, undecided]) - ) - return [table.filter(kept)] - # A right batch: only its keys, and only rows whose keys hold no top-level null - # (the sync path drops those: such a key never matches). - keys = table.select(self._keys) - keys = keys.filter(_has_whole_key(keys, self._keys)) - if not keys.num_rows: + # A row whose key holds a top-level null matches nothing, on either side. + table = table.filter(_has_whole_key(table, self._keys)) + if not table.num_rows: return [] - frame = polars_key_frame(keys, self._keys) - if not self._closed[0]: - self._right_frames.append(frame) - self._right_frame = None - if self._waiting is None: + if input_index == 1: + self._hold_right(table) return [] - kept = self._kept(self._waiting, frame) - decided = self._waiting.filter(kept) - remaining = self._waiting.filter(pc.invert(kept)) - self._waiting = remaining if remaining.num_rows else None - return [decided] + if self._closed[1]: + return self._decided(table) + self._waiting.spool(table) + return [] - def _close(self, input_index: int) -> list[pa.Table]: + def _decided(self, table: pa.Table) -> Iterator[pa.Table]: + """The left rows of ``table`` whose key is among the right rows'.""" + right_keys = self._right_keys() + if right_keys is None: + return + kept = np.zeros(table.num_rows, dtype=np.bool_) + kept[self._matched(self._waiting.key_frame(table), right_keys)] = True + decided = table.filter(pa.array(kept)) + for start in range(0, decided.num_rows, PAIRS_PER_BATCH): + yield decided.slice(start, PAIRS_PER_BATCH) + + def _hold_right(self, table: pa.Table) -> None: + """Hold the keys of right rows, each once.""" + if self._closed[0] and not self._waiting.rows: + return # no left row to decide + frame = polars_key_frame(table.select(self._keys), self._keys) + held = self._right_keys() + if self._distinct: + frame = frame.unique() + if held is not None: + frame = frame.join(held, on=self._keys, how="anti") + if frame.height: + self._right_frames.append(frame) + + def _close(self, input_index: int) -> Iterator[pa.Table]: if input_index == 0: - # No left row will arrive: the right keys can match nothing new. - self._right_frames, self._right_frame = [], None - else: - # No right row will arrive: the undecided left rows never match. - self._waiting = None - return [] + if self._closed[1] or not self._waiting.rows: + # No left row is left to decide. + self._right_frames = [] + return + for table in self._waiting.replay(): + yield from self._decided(table) + self._waiting.clear() + if self._closed[0]: + self._right_frames = [] # The occurrence-number column of a Rejoin key frame, and the prefix of the other side's @@ -1140,40 +1524,6 @@ def _with_system_tags(table: pa.Table, keys: Sequence[str]) -> pa.Table: return table.filter(_has_whole_key(table, keys)) -def _take_rows(table: pa.Table, rows: np.ndarray[Any, np.dtype[np.int64]]) -> pa.Table: - """The rows of ``table`` with these numbers, in this order, without combining chunks. - - Arrow's ``take`` on a chunked column concatenates its chunks first, a copy of the - whole column. Here only the chunks that hold a wanted row are read: each one's rows - are taken from it alone, and the small result is put in the order asked for. - - Args: - table: A table, of any number of chunks. - rows: Row numbers in ``table``. - - Returns: - The rows, as one chunk. - """ - batches = table.to_batches() - if len(batches) <= 1: - return table.take(pa.array(rows, pa.int64())) - lengths = np.fromiter((b.num_rows for b in batches), np.int64, len(batches)) - starts = np.concatenate([np.zeros(1, np.int64), np.cumsum(lengths)[:-1]]) - chunks = np.searchsorted(starts, rows, side="right") - 1 - order = np.argsort(chunks, kind="stable") - sorted_rows, sorted_chunks = rows[order], chunks[order] - edges = np.flatnonzero(np.diff(sorted_chunks)) + 1 - parts: list[pa.Table] = [] - for group in np.split(np.arange(len(sorted_rows)), edges): - chunk = int(sorted_chunks[group[0]]) - local = sorted_rows[group] - starts[chunk] - parts.append( - pa.Table.from_batches([batches[chunk]]).take(pa.array(local, pa.int64())) - ) - taken = pa.concat_tables(parts).combine_chunks() - return taken.take(pa.array(np.argsort(order, kind="stable"), pa.int64())) - - def _occurrences(frame: pl.DataFrame, among: Sequence[str]) -> pl.DataFrame: """Number each row among the rows before it equal to it in ``among`` (0, 1, ...). @@ -1186,85 +1536,6 @@ def _occurrences(frame: pl.DataFrame, among: Sequence[str]) -> pl.DataFrame: ) -class _Remaining: - """An input's rows not matched yet, with a key frame and a mask of removed rows. - - Removing a row only clears its mask bit; the rows are compacted when the removed - ones are the majority, so a batch never copies the whole table. - - Args: - columns: The shared columns of the key frame (system tags first). - row: The row-number column. - """ - - def __init__(self, columns: Sequence[str], row: str) -> None: - self.columns: list[str] = list(columns) - self.row: str = row - self.closed: bool = False - self.schema: pa.Schema | None = None - self._tables: list[pa.Table] = [] - self._frames: list[pl.DataFrame] = [] - self._alive: list[np.ndarray[Any, np.dtype[np.bool_]]] = [] - self._table: pa.Table | None = None - self._frame: pl.DataFrame | None = None - self.size: int = 0 - self.rows: int = 0 - - def append(self, table: pa.Table) -> None: - """Hold ``table``'s rows.""" - if not table.num_rows: - return - frame = polars_key_frame(table, self.columns, self.row) - self._frames.append(frame.with_columns(pl.col(self.row) + self.size)) - self._tables.append(table) - self._alive.append(np.ones(table.num_rows, dtype=np.bool_)) - self._table, self._frame = None, None - self.size += table.num_rows - self.rows += table.num_rows - - def table(self) -> pa.Table: - """Every row appended and not compacted away, numbered as in ``frame``.""" - if self._table is None: - self._table = pa.concat_tables(self._tables) - self._tables = [self._table] - return self._table - - def frame(self) -> pl.DataFrame: - """The key frame of the rows not removed, in the order they arrived.""" - if self._frame is None: - frame = pl.concat(self._frames, rechunk=False) - alive = np.concatenate(self._alive) - self._frames, self._alive = [frame], [alive] - self._frame = frame.filter(pl.Series(alive)) - return self._frame - - def remove(self, rows: np.ndarray[Any, np.dtype[np.int64]]) -> None: - """Remove the rows with these numbers (each held and not removed yet).""" - if not len(rows): - return - self.frame() - alive = self._alive[0] - alive[rows] = False - self.rows -= len(rows) - self._frame = None - if self.rows * 2 < self.size: - self._compact() - - def _compact(self) -> None: - """Drop the removed rows and number the rest from 0.""" - alive = np.concatenate(self._alive) - table = self.table().filter(pa.array(alive)) - self.clear() - self.append(table) - - def clear(self) -> None: - """Drop every row held.""" - self._tables, self._frames, self._alive = [], [], [] - self._table, self._frame = None, None - self.size = 0 - self.rows = 0 - - class _RejoinLink: """One step of ``Rejoin``: a symmetric match of two sides on every shared column. @@ -1284,9 +1555,9 @@ def __init__( self.system: list[str] = list(system) self.others: list[str] = list(others) self.shared: list[str] = [*system, *others] - self.sides: tuple[_Remaining, _Remaining] = ( - _Remaining(self.shared, _ROW[0]), - _Remaining(self.shared, _ROW[1]), + self.sides: tuple[_Side, _Side] = ( + _Side(self.shared, _ROW[0], constant_key=False), + _Side(self.shared, _ROW[1], constant_key=False), ) self._finish: Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table] = finish # The shared columns other than system tags in which rows of one origin row @@ -1325,8 +1596,6 @@ def push(self, side: int, table: pa.Table) -> pa.Table | None: The output rows of the matched pairs, or ``None`` when there is none. """ this, other = self.sides[side], self.sides[1 - side] - if this.schema is None: - this.schema = table.schema table = _with_system_tags(table, self.system) if not table.num_rows: return None @@ -1335,57 +1604,40 @@ def push(self, side: int, table: pa.Table) -> pa.Table | None: result = None unmatched = np.ones(table.num_rows, dtype=np.bool_) if other.rows: - held = _occurrences(other.frame(), self.shared) + held = _occurrences(other.held_frame(), self.shared) pairs = frame.join( held, on=[*self.shared, _OCCURRENCE], how="inner", nulls_equal=True ) if pairs.height: - mine = pairs.get_column(row).to_numpy() - theirs = pairs.get_column(other_row).to_numpy() + mine = pairs.get_column(row).to_numpy().astype(np.int64) + theirs = pairs.get_column(other_row).to_numpy().astype(np.int64) unmatched[mine] = False - tables = (table, other.table()) if side == 0 else (other.table(), table) - rows = (mine, theirs) if side == 0 else (theirs, mine) - result = self._pairs(*tables, *rows) + taken = (table.take(pa.array(mine, pa.int64())), other.take(theirs)) + result = self._pairs(*(taken if side == 0 else taken[::-1])) other.remove(theirs) rest = table.filter(pa.array(unmatched)) if not unmatched.all() else table if rest.num_rows and other.rows and self.others: self._note_differing(rest, other, side) if not other.closed: - this.append(rest) + this.append(rest, this.key_frame(rest)) return result - def _pairs( - self, - left: pa.Table, - right: pa.Table, - left_rows: np.ndarray[Any, np.dtype[np.int64]], - right_rows: np.ndarray[Any, np.dtype[np.int64]], - ) -> pa.Table: - """The matched pairs as ``Rejoin._rejoin_pair`` builds them, by row number. - - Values are taken from the chunks that hold them (``_take_rows``): no held - table is copied. - """ - left_taken = _take_rows(left, left_rows) - right_taken = _take_rows(right, right_rows) + def _pairs(self, left: pa.Table, right: pa.Table) -> pa.Table: + """The matched pairs as ``Rejoin._rejoin_pair`` builds them, from their rows.""" names: list[str] = [] arrays: list[Any] = [] for name in left.column_names: names.append(name) - arrays.append(left_taken.column(name)) + arrays.append(left.column(name)) for name in right.column_names: if name not in left.column_names: names.append(name) - arrays.append(right_taken.column(name)) - assert self.sides[0].schema is not None - assert self.sides[1].schema is not None + arrays.append(right.column(name)) return self._finish( - pa.Table.from_arrays(arrays, names=names), - self.sides[0].schema, - self.sides[1].schema, + pa.Table.from_arrays(arrays, names=names), left.schema, right.schema ) - def _note_differing(self, rest: pa.Table, other: _Remaining, side: int) -> None: + def _note_differing(self, rest: pa.Table, other: _Side, side: int) -> None: """Note the shared columns in which unmatched rows of one origin row differ. One more join, of the arriving rows that matched nothing on the system tags only @@ -1402,7 +1654,7 @@ def _note_differing(self, rest: pa.Table, other: _Remaining, side: int) -> None: return origin = [*self.system, _OCCURRENCE] mine = _occurrences(polars_key_frame(rest, self.shared, row), self.system) - theirs = _occurrences(other.frame(), self.system).select( + theirs = _occurrences(other.held_frame(), self.system).select( [*origin, *(pl.col(name).alias(_OTHER + name) for name in names)] ) pairs = mine.select([*origin, *names]).join(theirs, on=origin, how="inner") @@ -1439,7 +1691,7 @@ class StreamingRejoin(StreamingJoinKernel): occurrence numbers of the remaining rows. That is O(held rows) per batch, as in the ``Join`` kernels, plus O(m log m) to take the m pairs it makes from the held chunks (``_take_rows``: one vectorized chunk lookup and one sort for all of them), never by - copying a whole held table; a compaction copies the remaining rows when half of + copying a whole held table; a compaction copies the remaining keys when half of those held were removed. A long run of one-row batches against a large buffer is quadratic in the rows. @@ -1537,6 +1789,10 @@ def __init__(self, operator: Rejoin, inputs: Sequence[StreamProtocol]) -> None: def held_rows(self) -> int: return sum(link.held_rows for link in self._links) + def release(self) -> None: + for link in self._links: + link.release() + def _link_finish( self, shared_tags: set[str] ) -> Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table]: @@ -1566,6 +1822,8 @@ def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: """ if not self._links: return [table] + # Rejoin compares shared source-info columns by value: text. + table = source_tokens.materialize(table) table = _with_context(table, self._contexts[input_index]) position = self._position[input_index] step, side = (0, 0) if position == 0 else (position - 1, 1) @@ -1624,3 +1882,147 @@ def _close(self, input_index: int) -> list[pa.Table]: ) ) return [] + + +async def run_kernel( + make_kernel: Callable[[Sequence[StreamProtocol]], StreamingJoinKernel], + inputs: Sequence[RecordBatchInput], + output: RecordBatchOutput, +) -> None: + """Run a join kernel over an operator's channels (``async_execute_batches``). + + Every input is read at once and to its end, whatever the others do: the inputs may + be two readers of one upstream, which a wait would block, and an input's read error + must be met. Each input reads ahead until it holds ``PUSH_ROWS`` rows + (its producer's last batch whole, whatever its size) and waits, and the + output's batches are sent one at a time, so a slow reader of the output holds the + join back. + + The kernel's rows and files are let go at a normal end, a failure and a + cancellation. Channels end as in ``StaticOutputOperatorPod.async_execute_batches``. + + Args: + make_kernel: Makes the kernel from the input streams (the descriptions). + inputs: The operator's input channels, in order. + output: The channel the result's record batches are sent into. + """ + readers: list[asyncio.Task[None]] = [] + kernel: StreamingJoinKernel | None = None + try: + # An input read already cannot be given whole: refused before anything is read. + claims = [channel.reserve() for channel in inputs] + kernel = make_kernel([channel.stream for channel in inputs]) + changed = asyncio.Event() + ahead = [_ReadAhead(changed) for _ in inputs] + readers = [ + asyncio.create_task(buffer.fill(channel, claim)) + for buffer, channel, claim in zip(ahead, inputs, claims) + ] + open_inputs = set(range(len(inputs))) + while open_inputs: + changed.clear() + progressed = False + for index in sorted(open_inputs): + batches, ended = ahead[index].drain() + for batch in _push_sizes(batches): + progressed = True + for result in kernel.iter_push(index, batch): + await _send(output, result) + # The readers get a turn also when nothing was sent. + await asyncio.sleep(0) + if ended: + progressed = True + await readers[index] # raises what ended it, if anything did + open_inputs.discard(index) + for result in kernel.iter_close(index): + await _send(output, result) + if not progressed: + _ = await changed.wait() + except BaseException as error: + output.fail(error) + for reader in readers: + _ = reader.cancel() + _ = await asyncio.gather(*readers, return_exceptions=True) + await close_inputs(inputs, error) + raise + finally: + if kernel is not None: + kernel.release() + await finish_operator(inputs, output) + + +async def _send(output: RecordBatchOutput, batch: pa.RecordBatch) -> None: + """Send a batch and give every other task a turn, also when the send did not wait. + + A cancellation, or a reader that closes, is met between two batches, however many a + replay gives. + """ + await output.send(batch) + await asyncio.sleep(0) + + +class _ReadAhead: + """The record batches one input delivered and the join has not pushed yet. + + Args: + changed: Set when a batch arrives or the input ends. + """ + + def __init__(self, changed: asyncio.Event) -> None: + self._changed: asyncio.Event = changed + self._room: asyncio.Event = asyncio.Event() + self._batches: list[pa.RecordBatch] = [] + self._rows: int = 0 + self._ended: bool = False + + async def fill(self, channel: RecordBatchInput, claim: object) -> None: + """Read ``channel`` to its end, waiting while ``PUSH_ROWS`` rows or more are unread.""" + try: + _ = channel.reserve(claim) + async for batch in carried_batches(channel): + if not batch.num_rows: + continue + self._batches.append(_without_token_lists(batch)) + self._rows += batch.num_rows + self._changed.set() + while self._rows >= PUSH_ROWS: + self._room.clear() + _ = await self._room.wait() + finally: + self._ended = True + self._changed.set() + + def drain(self) -> tuple[list[pa.RecordBatch], bool]: + """Take the batches read, and whether the input has ended after them.""" + batches, self._batches, self._rows = self._batches, [], 0 + self._room.set() + return batches, self._ended + + +def _without_token_lists(batch: pa.RecordBatch) -> pa.RecordBatch: + """``batch`` with derived token lists as text, which a kernel takes and can spool.""" + lists = [ + field.name + for field in batch.schema + if isinstance(field.type, source_tokens.MemberTokenType) + ] + if not lists: + return batch + table = source_tokens.materialize(pa.Table.from_batches([batch]), lists) + return table.combine_chunks().to_batches()[0] + + +def _push_sizes(batches: Sequence[pa.RecordBatch]) -> Iterator[pa.RecordBatch]: + """``batches`` put under one another and cut to at most ``PUSH_ROWS`` rows. + + Args: + batches: Record batches of one input, in the order they arrived. + """ + if len(batches) == 1: + # As delivered: a batch of its own is what the kernel checks. + table = pa.Table.from_batches(batches) + else: + table = concatenate_batches(batches) + if table is not None: + for start in range(0, table.num_rows, PUSH_ROWS): + yield from table.slice(start, PUSH_ROWS).combine_chunks().to_batches() diff --git a/src/orcapod/core/operators/tag_by.py b/src/orcapod/core/operators/tag_by.py index 911fefc36..5b043e7a1 100644 --- a/src/orcapod/core/operators/tag_by.py +++ b/src/orcapod/core/operators/tag_by.py @@ -7,6 +7,7 @@ from typing_extensions import override +from orcapod.core.unique_keys import UniqueKeys from orcapod.core.operators.base import UnaryOperator from orcapod.core.data_tags import require_taggable_type, stream_data_tags from orcapod.core.streams import ArrowTableStream @@ -73,12 +74,18 @@ class TagBy(UnaryOperator): column name, or one holding ``::``. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). PROVISIONAL: ClassVar[bool] = True # Data-tags (ITL-1023): handled; this operator makes them. DATA_TAGS_ISSUE: ClassVar[str | None] = None + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys (``core/unique_keys``): tags are only added.""" + return stream.unique_keys + def __init__(self, columns: str | Iterable[str], **kwargs: Any) -> None: names = _tag_by_names(columns) schema_utils.require_names_not_meta(names) @@ -209,13 +216,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ tag_columns, _ = stream.keys() # The context column too, so each row keeps its own data context key. - table = stream.as_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) return ArrowTableStream( table, diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 3e94bbe12..71888ab47 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -29,7 +29,7 @@ from orcapod.core.streams.record_batch_input import InputChannel from orcapod.errors import UpstreamFailedError from orcapod.system_constants import constants -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens if TYPE_CHECKING: from orcapod.protocols.core_protocols import StreamProtocol @@ -429,6 +429,10 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: expected = declared.field(column.name) carried = arrow_utils.normalize_to_large_types(expected.type) if column.name.startswith(constants.SOURCE_PREFIX): + if source_tokens.is_derived(column.type): + if column.metadata: + return f"column {column.name!r} carries field metadata" + continue if not _is_token_type(column.type): return f"column {column.name!r} is {column.type}, not a token type" if column.metadata or not column.type.equals( diff --git a/src/orcapod/core/row_spool.py b/src/orcapod/core/row_spool.py new file mode 100644 index 000000000..18fa0be22 --- /dev/null +++ b/src/orcapod/core/row_spool.py @@ -0,0 +1,585 @@ +"""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. Derived +source-info tokens (``utils/source_tokens.py``) are written as ``source_tokens.Shelf`` +says: the ids of a list's members once a file, and only those the file's rows read. + +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 + +from orcapod.utils import source_tokens + +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.bytes: int = held_bytes(table) + self.path: str | None = None + self.shelf: source_tokens.Shelf = source_tokens.Shelf(()) + + 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.bytes + 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 spill(self) -> None: + """Write the rows in memory to a file, so that none stays in memory. + + Raises: + ValueError: If the spool is closed. + RuntimeError: In a process other than the one that made the spool. + OSError: If they cannot be written; the rows then stay in memory. + """ + self._require_owner() + with self._lock: + self._require_usable() + if self._in_memory: + self._spill() + + def _add(self, segment: _Segment) -> None: + self._segments.append(segment) + self._starts = None + if segment.table is not None: + self._in_memory += segment.bytes + + 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), segment.shelf, 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), segment.shelf, 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.bytes + 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] + # The derived columns first: put together, every one of them would have + # the ids of all the members of its own (ITL-1464). + shelf = source_tokens.Shelf.of(tables) + table = pa.concat_tables([_as_storage(t, shelf) for t in tables]) + merged = _Segment(run[0].start, table.combine_chunks()) + merged.shelf = shelf + 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(s.bytes for s in run) + 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 = 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 held_bytes(table: pa.Table) -> int: + """The bytes ``table`` holds, what its derived lists share counted once.""" + lists = [ + name + for name in source_tokens.derived_columns(table.schema) + if isinstance(table.schema.field(name).type, source_tokens.MemberTokenType) + ] + shared = table.select(lists).get_total_buffer_size() if lists else 0 + return table.drop_columns(lists).nbytes + shared + + +def _owned(table: pa.Table) -> pa.Table: + """``table`` as one chunk over buffers of its own size, copied only if needed. + + Derived lists of tokens keep only the ids their rows read, shared by the lists that + have the same. + """ + table = table.combine_chunks() + derived = source_tokens.derived_columns(table.schema) + plain = table.drop_columns(list(derived)) + if plain.get_total_buffer_size() > 2 * plain.nbytes: + plain = plain.take(pa.array(np.arange(table.num_rows), pa.int64())) + if not derived: + return plain + shelf = source_tokens.Shelf.of([table]) + shelved = shelf.shelve(table) + for index, name in enumerate(plain.column_names): + position = shelved.schema.get_field_index(name) + shelved = shelved.set_column(position, plain.field(index), plain.column(index)) + return shelf.restore(shelved.combine_chunks(), table.schema) + + +def _as_storage(table: pa.Table, shelf: source_tokens.Shelf) -> pa.Table: + """``table`` with each extension column as its storage, no field metadata. + + Derived token columns are written as ``shelf`` says. 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 + table = shelf.shelve(table.combine_chunks()).combine_chunks() + for column in table.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, shelf: source_tokens.Shelf, 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 + table = table.combine_chunks() + for name, column in zip(table.column_names, table.columns, strict=True): + array = column.chunk(0) + index = schema.get_field_index(name) + kind = schema.field(index).type if index >= 0 else column.type + if isinstance(kind, pa.BaseExtensionType): + array = pa.ExtensionArray.from_storage(kind, array) + columns.append(array) + wrapped = pa.Table.from_arrays(columns, names=table.column_names) + return shelf.restore(wrapped, schema) diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index f05485472..ffe089a72 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -91,7 +91,9 @@ class ArrowTableSource(RootSource): SOURCE_KIND: ClassVar[str] = "arrow_table" # The version of this kind's implementation, in the kind part (ITL-1425). SOURCE_VERSION: ClassVar[int] = 1 + KEY_COLUMNS_CHECKED: ClassVar[bool] = True TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 07221924c..20c7eb83c 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -1,18 +1,25 @@ from __future__ import annotations import warnings -from collections.abc import Callable +from collections.abc import Callable, Generator from typing import TYPE_CHECKING, Any, ClassVar, TypeVar from orcapod import contexts +from orcapod.core.exact_class import reads_as_its_class +from orcapod.core.unique_keys import NO_UNIQUE_KEYS, UniqueKeys, certificate from orcapod.config import OrcapodConfig +from orcapod.core.streams.carried import carried_table from orcapod.core.streams.base import ( StreamBase, - reads_as_its_class, typed_arrow_schemas, typed_zero_row_table, ) from orcapod.errors import SourceNameWarning, SourceVersionWarning +from orcapod.core.streams.preview import ( + PreviewRequest, + refuse_without_compute_all, + slices_of, +) from orcapod.core.streams.view import StreamView from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import ColumnConfig, Condition, ContentHash, Schema @@ -389,6 +396,32 @@ def row_limit(self) -> int | None: """The resolved key columns of the record ids, in key order; ``()`` for the position. Every concrete source sets it in ``__init__``.""" + KEY_COLUMNS_CHECKED: ClassVar[bool] = False + """Whether every read of the source refuses a repeated key (ITL-1464). + + Declared ``True`` only by the library source kinds whose rows all pass + ``SourceStreamBuilder``, which names each row by its key columns and refuses a + repeat, each on its own class: read for the exact class only, never inherited, and + for an instance with no member replaced. + """ + + @property + def unique_keys(self) -> UniqueKeys: + """The key columns, when they are checked and all are tags (``core/unique_keys``). + + Two rows that agree on the key columns under the joins' equality have one record + id, which is a function of the values (a key is never a float). + """ + kind = type(self) + if vars(kind).get("KEY_COLUMNS_CHECKED") is not True: + return NO_UNIQUE_KEYS + if not reads_as_its_class(self, kind): + return NO_UNIQUE_KEYS + key = frozenset(self._key_columns) + if not key or not key <= set(self.keys()[0]): + return NO_UNIQUE_KEYS + return certificate([key]) + _arrow_schemas_cache: "tuple[pa.Schema, pa.Schema] | None" = None @property @@ -537,6 +570,15 @@ def as_table( """Delegate to the underlying stream's as_table.""" return self._stream.as_table(columns=columns, all_info=all_info) + def _carried_from_stream(self, config: ColumnConfig) -> "pa.Table": + """``as_table`` above, derived token columns as they are (ITL-1464). + + What a source kind that reads through ``_stream`` declares as its + ``_carried_table`` (``core/streams/carried.py``). + """ + stream: StreamBase = getattr(self, "_stream") # noqa: B009 # set by each subclass + return carried_table(stream, config) + # ------------------------------------------------------------------------- # The start-of-run check (ITL-1102) # ------------------------------------------------------------------------- @@ -587,6 +629,20 @@ def _display_name(self) -> str: # The header names the class already; the name is the part that is the user's. return self.source_name + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Slices of the rows a source holds (``preview_batches``). + + A source of the library that holds its table (``_stream``) reads nothing. Any + other read of a whole source is refused unless ``compute_all`` was given. + """ + from orcapod.core.streams.arrow_table_stream import ArrowTableStream + + if not isinstance(getattr(self, "_stream", None), ArrowTableStream): + refuse_without_compute_all(self, request, "reads its rows whole") + yield from slices_of(self, request) + def head( self, n: int = 10, diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 55065699b..694c8b54d 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -3,7 +3,7 @@ import logging from datetime import datetime -from collections.abc import Iterator +from collections.abc import Generator, Iterator from typing import Any, ClassVar, TYPE_CHECKING import pyarrow as pa @@ -26,6 +26,7 @@ schema_requires_io, typed_zero_row_table, ) +from orcapod.core.streams.preview import PreviewRequest, refused from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -41,7 +42,12 @@ report_rows_of_other_data_contexts, with_data_context, ) -from orcapod.protocols.core_protocols import DataProtocol, SourceProtocol, TagProtocol +from orcapod.protocols.core_protocols import ( + DataProtocol, + SourceProtocol, + StreamProtocol, + TagProtocol, +) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.system_constants import SOURCE_DB_SCHEMA_VERSION, constants from orcapod.types import ColumnConfig, Schema @@ -701,6 +707,12 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: assert self._cached_stream is not None return self._cached_stream.iter_data() + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Refused: reading the source writes its cache.""" + raise refused(self, "writes its cache when it is read") + def as_table( self, *, diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index f39681d9e..095fcce76 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -280,6 +280,7 @@ class CSVSource(RootSource): SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 6c65bf64d..840462207 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -46,7 +46,9 @@ class DataFrameSource(RootSource): SOURCE_KIND: ClassVar[str] = "data_frame" # The version of this kind's implementation, in the kind part (ITL-1425). SOURCE_VERSION: ClassVar[int] = 1 + KEY_COLUMNS_CHECKED: ClassVar[bool] = True TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 86ea349d5..b50ad5e6a 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -84,6 +84,7 @@ class DBTableSource(RootSource): SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 239c00191..608c783ae 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -53,6 +53,7 @@ class DeltaTableSource(RootSource): SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1c4a57228..175a851bb 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -1,7 +1,8 @@ from __future__ import annotations import dataclasses -from collections.abc import Collection, Mapping +from contextlib import closing +from collections.abc import Collection, Generator, Mapping from datetime import datetime from typing import TYPE_CHECKING, Any, ClassVar @@ -23,6 +24,7 @@ normalize_record_id_columns, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.carried import carried_table from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -33,6 +35,12 @@ typed_arrow_schemas, typed_zero_row_table, ) +from orcapod.core.streams.preview import ( + PreviewRequest, + preview_batches, + refuse_without_compute_all, + slices_of, +) from orcapod.errors import InputValidationError from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema @@ -40,6 +48,7 @@ from orcapod.utils.provisional import provisional_class_name if TYPE_CHECKING: + from orcapod.protocols.core_protocols import StreamProtocol from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode @@ -589,13 +598,22 @@ def _build_derived_stream( return self._derive_from(table, tags_as_data), has_rows def _derive_from( - self, table: "pa.Table", tags_as_data: Mapping[str, str] + self, + table: "pa.Table", + tags_as_data: Mapping[str, str], + *, + first_row: int = 0, + seen_keys: dict[str, int] | None = None, ) -> ArrowTableStream: """Append the tag copies to the origin rows ``table`` and enrich it as a source. Args: table: Rows of the origin. tags_as_data: Maps a tag column of the origin to the name of its copy. + first_row: The position of the first row of ``table`` among the origin's + rows, when it is a later batch of them. + seen_keys: The keys of the earlier batches' rows + (``SourceStreamBuilder.build``); ``None`` for all the rows. """ for tag, name in tags_as_data.items(): # The copy is the tag's own Arrow column under a renamed field, so its @@ -611,6 +629,8 @@ def _derive_from( source_name=self.source_name, kind_part=self.kind_part(), record_id_columns=self._record_id_columns or (), + first_row=first_row, + seen_keys=seen_keys, ) return result.stream @@ -792,6 +812,49 @@ def head( head.for_stream(self, origin="stored"), total_rows=records.num_rows ) + @override + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """This source's first rows (``preview_batches``), read without keeping them. + + The rows it holds are sliced. Otherwise an origin source gives its rows through + its own preview, which refuses a source that would poll or write its cache + when read, so nothing is polled or written; each of its batches is derived as + it comes, so the origin reads no further than the rows a step above takes. An origin job node's stored + rows are read whole, only with ``compute_all``. Nothing read here is kept by + this source. + """ + self._note_provisional_identity_use() + if self._tags_as_data is not None and self._cached_stream is not None: + yield from slices_of(self._cached_stream, request) + return + if self._tags_as_data is None and self._cached_table is not None: + yield from slices_of(self._stream_over(self._cached_table), request) + return + if isinstance(self._origin, RootSource) and self._tags_as_data is not None: + # The derived rows are the origin's, one for one and in order: each batch + # the origin gives is derived as it comes, its positional record ids + # continuing from the rows before it and its keys checked against + # theirs, so a step above that stops reading stops the origin too. + first_row = 0 + seen_keys: dict[str, int] = {} + with closing(preview_batches(self._origin, request)) as batches: + for batch in batches: + rows = batch.as_table() + yield self._derive_from( + rows, + self._tags_as_data, + first_row=first_row, + seen_keys=seen_keys, + ) + first_row += rows.num_rows + return + refuse_without_compute_all(self, request, "reads its origin's rows whole") + records = self._origin_records() + rows = self._empty_origin_table() if records is None else records + yield from slices_of(self._stream_over(rows), request) + def _stream_over(self, table: "pa.Table") -> ArrowTableStream: """Return this source's stream over the origin rows ``table``.""" if self._tags_as_data is not None: @@ -812,3 +875,7 @@ def as_table( all_info: bool = False, ) -> "pa.Table": return self._get_stream().as_table(columns=columns, all_info=all_info) + + def _carried_table(self, config: ColumnConfig) -> "pa.Table": + """The source's table, derived token columns as they are (ITL-1464).""" + return carried_table(self._get_stream(), config) diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index fdf7c1f34..b7815e130 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -42,7 +42,9 @@ class DictSource(RootSource): SOURCE_KIND: ClassVar[str] = "dict" # The version of this kind's implementation, in the kind part (ITL-1425). SOURCE_VERSION: ClassVar[int] = 1 + KEY_COLUMNS_CHECKED: ClassVar[bool] = True TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index f18da3433..b624eec07 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -41,7 +41,9 @@ def _default_tag(element: Any, idx: int) -> dict[str, Any]: SOURCE_KIND: ClassVar[str] = "list" # The version of this kind's implementation, in the kind part (ITL-1425). SOURCE_VERSION: ClassVar[int] = 1 + KEY_COLUMNS_CHECKED: ClassVar[bool] = True TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index de4cd3e1e..a45a344b6 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -14,7 +14,7 @@ import functools import logging import threading -from collections.abc import Collection +from collections.abc import Generator, Collection from math import floor from typing import Any, ClassVar, Generic, TYPE_CHECKING, TypeVar, cast @@ -29,6 +29,7 @@ SourceStreamBuilder, normalize_record_id_columns, ) +from orcapod.core.streams.preview import PreviewRequest, refused from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -57,6 +58,7 @@ from polars._typing import FrameInitTypes from orcapod.core.streams.arrow_table_stream import ArrowTableStream + from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol from orcapod.types import Schema @@ -652,6 +654,12 @@ def iter_data(self): _ = self._sync_poll_and_commit() return self._get_combined_stream().iter_data() + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Refused: reading the source polls.""" + raise refused(self, "polls when it is read") + def as_table( self, *, diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index 58acc1f17..71f73f007 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -175,7 +175,9 @@ class PostgreSQLTableSource(DBTableSource): """Config type key and the kind in the source id's kind part (one vocabulary).""" SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" + KEY_COLUMNS_CHECKED: ClassVar[bool] = True TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = DBTableSource._carried_from_stream def __init__( self, 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/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 83eb6238d..374050ad5 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -11,12 +11,14 @@ from __future__ import annotations from datetime import datetime +from collections.abc import Generator from typing import TYPE_CHECKING, Any from typing_extensions import override from orcapod.core.sources.base import RootSource from orcapod.core.sources.source_ids import parse_source_id +from orcapod.core.streams.preview import PreviewRequest, preview_batches from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -35,7 +37,11 @@ import pyarrow as pa - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import ( + DataProtocol, + StreamProtocol, + TagProtocol, + ) class SourceProxy(RootSource): @@ -264,6 +270,12 @@ def _typed_zero_row_table(self) -> pa.Table | None: def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: return self._require_delegate().iter_data() + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """The bound source's (``preview_batches``).""" + yield from preview_batches(self._require_delegate(), request) + def as_table( self, *, diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 8d534e5a3..a07541beb 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -44,6 +44,7 @@ import os from collections.abc import AsyncIterator, Collection, Generator, Iterator, Mapping from concurrent.futures import ThreadPoolExecutor +from contextlib import closing from threading import Lock from types import TracebackType from typing import Any, ClassVar, NamedTuple, TYPE_CHECKING @@ -55,6 +56,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, @@ -62,7 +64,10 @@ row_identifiers, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream -from orcapod.core.streams.base import check_head_size +from orcapod.core.exact_class import reads_as_its_class +from orcapod.core.streams.carried import carried_table +from orcapod.core.streams.base import StreamBase, check_head_size +from orcapod.core.streams.preview import PreviewRequest from orcapod.core.streams.view import ViewStatus, StreamView from orcapod.databases.spiraldb_connector import ( SpiralDBConnector, @@ -79,7 +84,11 @@ if TYPE_CHECKING: from orcapod import contexts from orcapod.config import OrcapodConfig - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import ( + DataProtocol, + StreamProtocol, + TagProtocol, + ) DEFAULT_MAX_ROWS = 100_000 DEFAULT_BATCH_ROWS = 8_192 @@ -113,6 +122,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 +854,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 +873,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 +887,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 +898,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_stream``): the streams then hold null tokens. Raises: SourceTooLargeError: If the read would return, or returns, more than @@ -885,7 +924,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, @@ -910,14 +949,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, @@ -926,6 +964,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,31 +1001,37 @@ def as_table( all_info: bool = False, ) -> "pa.Table": """Scan the table and return its rows as one PyArrow table (all held in memory).""" - return self._whole_table( - self._batch_streams(), columns=columns, all_info=all_info - ) + config = ColumnConfig.handle_config(columns, all_info=all_info) + with_source_info = _reads_source_info(config) + return self._whole_stream( + self._batch_streams(with_source_info=with_source_info), + with_source_info=with_source_info, + ).as_table(columns=columns, all_info=all_info) + + def _carried_table(self, config: ColumnConfig) -> "pa.Table": + """Scan the table as ``as_table`` does, building no source-info text (ITL-1464).""" + return carried_table(self._whole_stream(self._batch_streams()), config) - def _whole_table( + def _whole_stream( self, streams: Iterator["ArrowTableStream"], *, - columns: ColumnConfig | dict[str, Any] | None, - all_info: bool, - ) -> "pa.Table": - """Return the rows of ``streams`` (batches of one read) as one table.""" + with_source_info: bool = True, + ) -> StreamBase: + """Return the rows of ``streams`` (batches of one read) as one stream.""" # One stream over all the rows, so that a whole-table option (sorting by - # tags) applies across batches. - enriched = {"source": True, "system_tags": True} - tables = [stream.as_table(columns=enriched) for stream in streams] + # tags) applies across batches. The source-info tokens are carried only for + # a result that shows or hashes them (ITL-1464). + enriched = {"source": with_source_info, "system_tags": True} + tables = [carried_table(stream, enriched) for stream in streams] if not tables: - return self._stream.as_table(columns=columns, all_info=all_info) - whole = ArrowTableStream( + return self._stream + return ArrowTableStream( table=pa.concat_tables(tables), tag_columns=self._tag_columns, system_tag_columns=self._system_tag_columns, data_tags=self._data_tags, ) - return whole.as_table(columns=columns, all_info=all_info) def _head( self, @@ -1016,11 +1061,9 @@ def _head( head_limit = n if limit is None else min(n, limit) asof = self._asof table = self._lookup_table() - rows = self._whole_table( - self._read_batches(table, asof=asof, limit=head_limit, max_rows=None), - columns=columns, - all_info=all_info, - ) + rows = self._whole_stream( + self._read_batches(table, asof=asof, limit=head_limit, max_rows=None) + ).as_table(columns=columns, all_info=all_info) if rows.num_rows < head_limit or head_limit == limit: return _Head(rows, True, rows.num_rows, False) bound, total = self._bounded_count(n, table) @@ -1125,11 +1168,67 @@ def head( ), ) + @override + def _reads_in_batches(self) -> bool: + return reads_as_its_class(self, SpiralDBTableSource) + + @override + def _batch_streams_of_rows(self) -> Generator[StreamProtocol, None, None]: + """One scan of the table, each batch shaped as ``as_table()`` shapes the whole + (``run()``, ITL-1464).""" + yield from self._shaped_batches(self._batch_streams()) + + @override + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """One scan, limited by SpiralDB when the rows wanted are known, else closed when + enough were read. ``max_rows`` holds only when every row is asked for.""" + if not reads_as_its_class(self, SpiralDBTableSource): + yield from super()._preview_batches(request) + return + limits = [n for n in (self._limit, request.limit) if n is not None] + yield from self._shaped_batches( + self._read_batches( + self._lookup_table(), + asof=self._asof, + limit=min(limits, default=None), + max_rows=self._max_rows if request.whole else None, + ) + ) + + def _shaped_batches( + self, batches: Generator[ArrowTableStream, None, None] + ) -> Generator[StreamProtocol, None, None]: + """``batches`` of one read, each shaped as ``as_table()`` shapes the whole; at + least one.""" + columns = {"source": True, "system_tags": True, "context": True} + read = False + with closing(batches) as streams: + for stream in streams: + read = True + yield ArrowTableStream( + carried_table(self._whole_stream(iter([stream])), columns), + tag_columns=self._tag_columns, + data_tags=self._data_tags, + data_context=self.data_context_key, + ) + if not read: + # No row: the typed table of none that ``as_table()`` gives, without a + # second scan. + yield ArrowTableStream( + carried_table(self._stream, columns), + tag_columns=self._tag_columns, + data_tags=self._data_tags, + data_context=self.data_context_key, + ) + def run(self) -> StreamView: - """Read the whole table into memory and return a ``StreamView`` of every row. + """Read every row the source reads and return a ``StreamView`` of them. - Does what ``as_table()`` does: one scan of every row the source reads (``where``, - ``limit``, ``max_rows`` and the pinned version applied), held in memory. The + One scan (``where``, ``limit``, ``max_rows`` and the pinned version applied), + read in batches: a large table (``RunSize``) gives a + bounded view (``BoundedStreamView``) and is not held. The source holds no rows, so every call scans again. ``head(n)`` and the notebook preview are the bounded read: they read only the first ``n`` rows. """ diff --git a/src/orcapod/core/sources/sqlite_table_source.py b/src/orcapod/core/sources/sqlite_table_source.py index eab59a821..8fb8aeb00 100644 --- a/src/orcapod/core/sources/sqlite_table_source.py +++ b/src/orcapod/core/sources/sqlite_table_source.py @@ -104,7 +104,9 @@ class SQLiteTableSource(DBTableSource): """Config type key and the kind in the source id's kind part (one vocabulary).""" SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" + KEY_COLUMNS_CHECKED: ClassVar[bool] = True TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = DBTableSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 5fbb8eb52..540fc1417 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -25,7 +25,6 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import RowIdentifierError from orcapod.logical_types.identifier import LogicalTypeIdentifierError -from orcapod.system_constants import constants from orcapod.types import ContentHash from orcapod.utils import arrow_utils, schema_utils from orcapod.utils.schema_utils import compute_source_schema_hash @@ -200,12 +199,22 @@ def key_column_type_allowed(arrow_type: pa.DataType) -> bool: ) -def row_identifiers(table: pa.Table, record_id_columns: Sequence[str]) -> list[str]: +def row_identifiers( + table: pa.Table, + record_id_columns: Sequence[str], + *, + first_row: int = 0, + seen: dict[str, int] | None = None, +) -> list[str]: """Return each row's identifier: its key, or its position when no key is named. Args: - table: The source's rows. + table: The source's rows, or a part of them read in batches. record_id_columns: The key columns, in key order; empty for position. + first_row: The position of the table's first row among the source's rows: 0 + for the whole table, the rows before it for a later batch. + seen: The keys of the rows before ``table``, by position, when it is a later + batch; the keys of its rows are added. ``None`` for the whole table. Returns: One identifier per row, in row order. @@ -216,7 +225,7 @@ def row_identifiers(table: pa.Table, record_id_columns: Sequence[str]) -> list[s or two rows have the same key. The message names the column or the key. """ if not record_id_columns: - return [positional_row_identifier(i) for i in range(table.num_rows)] + return [positional_row_identifier(first_row + i) for i in range(table.num_rows)] missing = [c for c in record_id_columns if c not in table.column_names] if missing: raise RowIdentifierError( @@ -243,9 +252,10 @@ def row_identifiers(table: pa.Table, record_id_columns: Sequence[str]) -> list[s "value outside years 1 to 9999, which a row identifier cannot write" ) from exc identifiers: list[str] = [] - seen: dict[str, int] = {} - for i in range(table.num_rows): - key = [(c, columns[c][i]) for c in record_id_columns] + seen = {} if seen is None else seen + for row in range(table.num_rows): + i = first_row + row + key = [(c, columns[c][row]) for c in record_id_columns] nulls = [c for c, value in key if value is None] if nulls: raise RowIdentifierError( @@ -393,6 +403,8 @@ def build( data_tags: Collection[str] = (), *, hash_in_key_order: bool = False, + first_row: int = 0, + seen_keys: dict[str, int] | None = None, ) -> SourceStreamResult: """Run the full enrichment pipeline. @@ -431,6 +443,13 @@ def build( (ITL-1272). The stream keeps the rows in the order given. Off by default: the rows are hashed in the order given, which the user may have chosen on purpose. Needs key columns and no ``source_id``. + first_row: The position of the table's first row among the source's + rows, when the table is a later batch of them (a preview reads a + source in batches): positional record ids continue from it. Needs + a ``source_name``, since a default one is a hash of the whole table. + seen_keys: The keys of the rows of the earlier batches, by position; + the keys of this table's rows are added, and a repeat is refused as + within one table (``row_identifiers``). Returns: SourceStreamResult with enriched stream and metadata. @@ -506,7 +525,14 @@ def build( # 3. The row identifiers (validates the key columns: a missing, null or # repeated key is refused here, before anything is hashed). - identifiers = row_identifiers(table, key_columns) + if (first_row or seen_keys is not None) and source_name is None: + raise ValueError( + "a table read in batches needs a source_name: a default one is a " + "hash of the whole table" + ) + identifiers = row_identifiers( + table, key_columns, first_row=first_row, seen=seen_keys + ) # 4. Compute schema hash from the tag/data Arrow schemas (ITL-640). # Nullable flags in the incoming table are trusted as-is — callers must @@ -590,6 +616,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. @@ -597,7 +624,8 @@ def attach_provenance( key's canonical JSON), and its source id is the source's name: the two system-tag columns. Each source-info value is ``::::`` (for example ``_source_amplitude`` - holds ``::row_3::amplitude``). A row keeps its record id wherever + holds ``::row_3::amplitude``), carried as a recipe over the two system + tags until its text is needed (``source_tokens``). A row keeps its record id wherever and however often it is read, as long as its identifier is the same (ITL-1154). @@ -611,19 +639,24 @@ 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], - ) + # The tokens say nothing the two system tags below and the column names do not: + # each is carried as that recipe, and its text is built when it is needed + # (``source_tokens``, ITL-1464). + if with_source_info: + table = arrow_utils.add_source_tokens( + table, + schema_hash, + 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..917115f60 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -2,7 +2,7 @@ import itertools import logging -from collections.abc import Collection, Iterator +from collections.abc import Collection, Generator, Iterator from typing import Any import pyarrow as pa @@ -15,15 +15,43 @@ StreamBase, check_head_size, ) +from orcapod.core.streams.preview import PreviewRequest, slices_of from orcapod.core.streams.view import StreamView from orcapod.protocols.core_protocols import PodProtocol, StreamProtocol, TagProtocol from orcapod.protocols.hashing_protocols import PipelineElementProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema, SourceInfoValue -from orcapod.utils import arrow_utils, schema_utils +from orcapod.utils import arrow_utils, schema_utils, source_tokens logger = logging.getLogger(__name__) +ROWS_PER_PART = 8192 +"""The rows whose source-info text ``iter_data`` builds at once (ITL-1464).""" + + +def _parts(rows: "pa.Table") -> Iterator[tuple[int, int]]: + """The row ranges ``iter_data`` builds at once: all rows, or bounded ones (ITL-1464). + + A table with derived tokens is cut so that a part holds at most ``ROWS_PER_PART`` + rows and, beyond one row, at most eight times as many tokens in a column of lists. + """ + if not rows.num_rows: + return + if not source_tokens.derived_columns(rows.schema): + yield 0, rows.num_rows + return + members = source_tokens.members_per_row(rows) + ends = None if members is None else members.cumsum() + start = 0 + while start < rows.num_rows: + end = min(start + ROWS_PER_PART, rows.num_rows) + if ends is not None: + before = int(ends[start - 1]) if start else 0 + fit = int(ends.searchsorted(before + 8 * ROWS_PER_PART, side="right")) + end = min(end, max(fit, start + 1)) + yield start, end + start = end + class ArrowTableStream(StreamBase): """ @@ -90,14 +118,18 @@ def __init__( # Dictionary-encoded columns are not currently supported (ITL-1264, # ITL-1277): every source and operator result becomes a stream here, so this # refuses them all, tags and data alike. - if found := schema_utils.dictionary_columns(table.schema): + # A derived token column is no column of these types: it is text to every reader. + shown = pa.schema( + [f for f in table.schema if not source_tokens.is_derived(f.type)] + ) + if found := schema_utils.dictionary_columns(shown): raise schema_utils.dictionary_columns_error( found, tag_columns, data_tags, system_tag_columns ) # Nor are columns of a type the schema hash rejects (a union, a list view, a # run-end-encoded type; developer, November 21, 2026, ITL-640): a stream's # identity is its Arrow schema hash, which cannot hold them. - if found := schema_utils.schema_hash_rejected_columns(table.schema): + if found := schema_utils.schema_hash_rejected_columns(shown): raise schema_utils.schema_hash_rejected_columns_error( found, tag_columns, data_tags, system_tag_columns ) @@ -351,6 +383,11 @@ def as_table( columns_config = ColumnConfig.handle_config(columns, all_info=all_info) return self._assemble_table(columns_config, limit=None) + def _carried_table(self, columns: ColumnConfig | dict[str, Any]) -> "pa.Table": + """The table with its derived token columns as they are (``carried_table``).""" + config = ColumnConfig.handle_config(columns) + return self._assemble_table(config, limit=None, carried=config.system_tags) + def head( self, n: int = 10, @@ -379,18 +416,64 @@ 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 _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Slices of the rows this stream holds (``preview_batches``).""" + yield from slices_of(self, request) + 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) def _assemble_table( - self, columns_config: ColumnConfig, limit: int | None + self, + columns_config: ColumnConfig, + limit: int | None, + *, + carried: bool = False, ) -> "pa.Table": """Return the stream's rows with the column groups of ``columns_config``. Args: columns_config: The column groups to include, and whether to sort by tags. limit: Assemble only the first ``limit`` rows; ``None`` for all of them. + carried: Leave a derived token column derived (``carried_table``), which + needs the system tags in the table; ``False`` gives its text. """ output_table = self._table data_context_table = self._data_context_table @@ -408,8 +491,8 @@ def hashes() -> pa.Array[Any]: [str(data.content_hash()) for _, data in rows], type=pa.large_string() ) - def shape(carried: "pa.Table") -> "pa.Table": - table_stack = (carried,) + def shape(rows: "pa.Table") -> "pa.Table": + table_stack = (rows,) if columns_config.context: table_stack += (data_context_table,) if columns_config.source: @@ -423,6 +506,8 @@ def shape(carried: "pa.Table") -> "pa.Table": # the system tags are asked for. The system tags stay in the table # through the sort: they break ties between equal tags. table = arrow_utils.sort_by_tag_columns(table, tuple(self._tag_columns)) + if not carried: + table = source_tokens.materialize(table) if not columns_config.system_tags: table = table.drop_columns(list(self._system_tag_columns)) return table @@ -454,42 +539,68 @@ 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. + for pair in self._build_rows(): + yield pair + + 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), + ) + # Derived tokens become text a part of the rows at a time (ITL-1464); a + # table with none is one part. + for start, end in _parts(rows): + part = source_tokens.materialize(rows.slice(start, end - start)) + # The part is prepared once for all of its rows (ITL-1348): building + # ``Tag(row)`` and ``Data(row)`` from one-row slices normalized every + # row three times and split its columns again. tags = ( - Tag.rows_of(rows.select(tag_columns), self.data_context) + Tag.rows_of(part.select(tag_columns), self.data_context) if tag_columns else None ) - for data in Data.rows_of(rows.select(data_columns), self.data_context): + for data in Data.rows_of(part.select(data_columns), self.data_context): # A fresh empty tag per row, so rows never share one object. tag = next(tags) if tags is not None else Tag({}) yield tag, data - cached_elements.append((tag, data)) - self._cached_elements = cached_elements - else: - yield from self._cached_elements - def __repr__(self) -> str: refs = f", data_tags={self._data_tags}" if self._data_tags else "" return ( diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 9f8b731f7..5fb5f6088 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1,7 +1,5 @@ from __future__ import annotations -import functools -import inspect import logging from abc import abstractmethod from collections import deque @@ -9,27 +7,33 @@ AsyncIterator, Callable, Collection, + Generator, Iterable, Iterator, Mapping, Sequence, ) -from contextlib import contextmanager +from contextlib import closing, contextmanager from contextvars import ContextVar from datetime import datetime -from typing import TYPE_CHECKING, Any, cast +from typing import ClassVar, TYPE_CHECKING, Any, cast import pandas as pd import polars as pl import pyarrow as pa +from orcapod.core.streams.carried import carried_table +from orcapod.core.unique_keys import NO_UNIQUE_KEYS, UniqueKeys from orcapod.core.base import TraceableBase from orcapod.core.data_tags import data_tag_names +from orcapod.core.streams.preview import PreviewRequest, preview_batches, refused from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, + BoundedStreamView, ViewStatus, StreamView, + WindowOfRows, default_note, preview_html, ) @@ -42,7 +46,7 @@ from orcapod.protocols.core_protocols.streams import RecordBatchInput from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Condition, Schema -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens if TYPE_CHECKING: from orcapod.types.explanation import Explanation @@ -53,35 +57,21 @@ logger = logging.getLogger(__name__) -def reads_as_its_class(obj: object, cls: type) -> bool: - """Whether ``obj`` is exactly ``cls`` and reads only through ``cls``'s own members. +def reads_in_batches(stream: object) -> bool: + """Whether ``run()`` reads ``stream``'s rows batch by batch (ITL-1464). - Exact, never by inspection of what a subclass overrides: ``type(obj) is cls``, and - ``obj`` holds no attribute of its own that shadows a method or a property of - ``cls`` (an ``iter_data`` replaced on the instance). A ``functools.cached_property`` - keeps its value in the instance by design and is not a shadow. A subclass, however - small, is never ``cls`` here (ITL-1347). + True for a source that reads its rows on demand and holds none, and for operators + applied batch by batch over one; decided by the kind of stream and its operators, + never by its rows. + """ + check = getattr(stream, "_reads_in_batches", None) + return bool(check()) if callable(check) else False - Args: - obj: The object to check. - cls: The class whose reading is proven. - Returns: - Whether ``obj`` reads as ``cls`` does. - """ - if type(obj) is not cls: - return False - own = getattr(obj, "__dict__", None) - if not own: - return True - missing = object() - for name in own: - member = inspect.getattr_static(cls, name, missing) - if member is missing or isinstance(member, functools.cached_property): - continue - if callable(member) or hasattr(type(member), "__get__"): - return False - return True +def batch_streams_of(stream: object) -> Generator[StreamProtocol, None, None]: + """The rows of a stream that ``reads_in_batches``, in order, one stream per batch: at + least one, with no row when there is none.""" + return cast("StreamBase", stream)._batch_streams_of_rows() # pyright: ignore[reportPrivateUsage] # shared by the stream kinds def system_tags_as_rows_give(table: pa.Table) -> bool: @@ -152,6 +142,11 @@ def short_stream_repr(stream: object) -> str: ) """The zero-row tables derived during one outermost ``typed_zero_row_table`` call.""" +_RUN_ZERO_ROWS: ContextVar[dict[int, tuple[object, pa.Table | None]] | None] = ( + ContextVar("_RUN_ZERO_ROWS", default=None) +) +"""The zero-row tables derived during one async run (``zero_rows_of_one_run``).""" + @contextmanager def shared_zero_row_memo() -> Iterator[None]: @@ -209,15 +204,34 @@ def typed_zero_row_table(stream: object) -> pa.Table | None: return typed_zero_row_table(stream) finally: _ZERO_ROW_MEMO.reset(token) - known = memo.get(id(stream)) - if known is not None and known[0] is stream: - return known[1] + for tables in (memo, _RUN_ZERO_ROWS.get()): + known = None if tables is None else tables.get(id(stream)) + if known is not None and known[0] is stream: + return known[1] table = _derive_zero_row_table(stream) # The stream is held with its table, so its id is not reused during the call. memo[id(stream)] = (stream, table) + run = _RUN_ZERO_ROWS.get() + if run is not None and table is not None: + run[id(stream)] = (stream, table) return table +@contextmanager +def zero_rows_of_one_run() -> Generator[None, None, None]: + """Derive each stream's zero-row table at most once inside this block (ITL-1464). + + For an async run, whose nodes each describe their inputs: without it every node + derives everything above it. Bindings and operators do not change during a run. A + stream that cannot type itself yet (a source not polled) is asked again. + """ + token = _RUN_ZERO_ROWS.set({}) + try: + yield + finally: + _RUN_ZERO_ROWS.reset(token) + + def typed_zero_row_input(stream: object) -> pa.Table | None: """Return ``stream``'s zero-row table as a pod reads it: in the large-normalized form. @@ -340,8 +354,18 @@ def row_built_provenance(table: pa.Table) -> pa.Table: changed = False for field, column in zip(table.schema, table.columns, strict=True): if field.name.startswith(constants.SOURCE_PREFIX): - kind = _source_info_value_type(field.type) - if kind != field.type: + # A derived token column stays derived: its text is what the rows give. + if isinstance(field.type, source_tokens.MemberTokenType): + kind = field.type.with_list_type( + _source_info_value_type(field.type.list_type) + ) + if kind != field.type: + column = source_tokens.retyped(column, kind) + elif source_tokens.is_derived(field.type): + kind = field.type + else: + kind = _source_info_value_type(field.type) + if kind != column.type: column = column.cast(kind) new_field = pa.field(field.name, kind, nullable=field.nullable) elif field.name.startswith(constants.SYSTEM_TAG_PREFIX): @@ -571,7 +595,7 @@ def _row_built_table(self) -> pa.Table: retyped as a row retypes it. Only a stream that holds such a column (a raw ``ArrowTableStream``) is read that way, and its reads have no effect. """ - table = self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + table = carried_table(self._stream, ZERO_ROW_INPUT_COLUMNS) if not system_tags_as_rows_give(table): from orcapod.core.operators.static_output_pod import ( StaticOutputOperatorPod, @@ -1386,6 +1410,19 @@ def index( return Index(column, i, out=out, fail_on_miss=fail_on_miss)(self, label=label) + DERIVES_UNIQUE_KEYS: ClassVar[bool] = False + """Whether ``unique_keys`` is derived for this class: read for the exact class only, + each declaring it, and only while no member is replaced on the instance + (``core/unique_keys``).""" + + @property + def unique_keys(self) -> UniqueKeys: + """The tag sets no two rows agree on (``core/unique_keys``). + + None by default: a stream that derives or checks them says so itself. + """ + return NO_UNIQUE_KEYS + def arrow_schema(self) -> pa.Schema: """The Arrow schema of the columns this stream passes between job nodes. @@ -1591,11 +1628,16 @@ def run(self) -> StreamView: The one way to compute any stream outside a job (developer, November 13, 2026, ITL-1081): ``head()`` and the notebook preview never compute a row (see - ``head``). ``run()`` does - exactly the work ``as_table()`` does, through the same code path and cache, so - a stream already computed is not computed again, and one whose inputs changed is - computed again. The view holds every row with the default column configuration; - its ``head``, ``tail`` and ``sort_by_tags`` choose what is shown. For other + ``head``). ``run()`` computes every row, in the order of ``as_table()``, with + every effect, and promises nothing about how the rows are produced or held + (developer, November 24, 2026, ITL-1464). A stream that keeps its computed rows + is not computed again, and one whose inputs changed is computed again. The view + has the default column configuration; + its ``head``, ``tail`` and ``sort_by_tags`` choose what is shown. The view holds + every row, except over a source that reads its rows on demand + (``reads_in_batches``): its rows, and those of operators applied batch by batch + over it, are read in batches, and a large result (``RunSize``) gives a + ``BoundedStreamView``. For other column groups, use ``as_table(columns=...)`` or ``head(columns=...)`` after ``run()``. On a stream that keeps its rows (a pod's or operator's output stream, a job node, a job's side-effect node included, an in-memory source) they read the @@ -1605,10 +1647,32 @@ def run(self) -> StreamView: Returns: A ``StreamView`` of all the rows ``as_table()`` returns, with status - ``ROWS``. + ``ROWS``; bounded as said above. """ + if self._reads_in_batches(): + return self._run_in_batches() return self._view_of_rows(self.as_table(), self._RUN_ORIGIN) + def _reads_in_batches(self) -> bool: + """See ``reads_in_batches``; a stream reads its rows whole unless it says.""" + return False + + def _batch_streams_of_rows(self) -> Generator[StreamProtocol, None, None]: + """See ``batch_streams_of``; asked only when ``_reads_in_batches``.""" + raise NotImplementedError(f"{type(self).__name__} has no rows in batches") + + def _run_in_batches(self) -> StreamView: + """The ``run()`` view of rows read batch by batch, in one read.""" + rows = WindowOfRows() + with closing(self._batch_streams_of_rows()) as batches: + for batch in batches: + rows.add(batch.as_table()) + complete = rows.complete + if complete is not None: + return self._view_of_rows(complete, self._RUN_ORIGIN) + first = self._view_of_rows(rows.first, self._RUN_ORIGIN) + return BoundedStreamView(first, rows.last, rows.total) + def _view_of_rows(self, table: "pa.Table", origin: str) -> StreamView: """Return the ``run()`` view of ``table``, every row of this stream.""" return StreamView.of_rows( @@ -1620,6 +1684,80 @@ def _view_of_rows(self, table: "pa.Table", origin: str) -> StreamView: display_all_rows=False, ) + def preview(self, n: int = 10, *, compute_all: bool = False) -> StreamView: + """Compute the first ``n`` rows, and only what they need; keep nothing (ITL-1464). + + ``head()`` never computes; ``preview()`` does. The rows are the first ``n`` of + ``as_table()``, without a cached pod's meta columns. A source reads no more than is needed (a limit, or batches until + enough rows have passed), an operator applied batch by batch takes batches, and a + function is called on one row after another until ``n`` rows have come out, so + **your functions run**, once per row they are needed for. Nothing is kept on any + stream and nothing is written: a pod with stored results reads them and stores + none, no post-run hook fires, and a second ``preview()`` computes again. Results + a stream already holds are used. + + A join, ``group_by``, ``batch``, ``polars_filter``, ``tag_by``, ``pick``, + ``index`` or an operator of your own needs its whole input. It is refused unless + ``compute_all`` is ``True``, which computes that step, and everything beneath it, + in full (and calls functions beneath it on every row), and keeps none of it. + + Refused always: a side-effect pod or a function that takes the invocation + context (it would act), a source whose read polls or writes a cache, and a node + of a pipeline or job (``run()`` it, or ``head()`` it after a run). + + Args: + n: The most rows to compute; at least 1. + compute_all: Allow steps that need their whole input. + + Returns: + A ``StreamView``: ``ROWS`` when these are all the rows of the stream, else + ``PARTIAL``. + + Raises: + TypeError: If ``n`` is not an ``int``. + ValueError: If ``n`` is less than 1. + PreviewRefusedError: If a step is refused, as said above; the message names + it. Without ``compute_all`` it is raised before any function is called. + """ + if isinstance(n, bool) or not isinstance(n, int): + raise TypeError( + f"preview() takes an int number of rows, got {type(n).__name__}" + ) + if n < 1: + raise ValueError(f"preview() takes at least 1 row, got {n}") + request = PreviewRequest(limit=n, compute_all=compute_all) + tables: list[pa.Table] = [] + rows = 0 + with closing(preview_batches(self, request)) as batches: + for batch in batches: + tables.append(batch.as_table()) + rows += tables[-1].num_rows + if rows >= n: + break + table = pa.concat_tables(tables).slice(0, n) + complete = rows < n + shown = table.num_rows + noun = "row" if shown == 1 else "rows" + return StreamView.of_rows( + self, + table, + tag_columns=self.keys()[0], + total_rows=shown if complete else None, + status=ViewStatus.ROWS if complete else ViewStatus.PARTIAL, + origin="computed", + description=( + f"preview: all {shown:,} {noun}" + if complete + else f"preview: first {shown:,} {noun} (run() computes every row)" + ), + ) + + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """This stream's rows for a preview (``preview_batches``): not given by default.""" + raise refused(self, "has no preview") + def head( self, n: int = 10, diff --git a/src/orcapod/core/streams/carried.py b/src/orcapod/core/streams/carried.py new file mode 100644 index 000000000..81c7f513b --- /dev/null +++ b/src/orcapod/core/streams/carried.py @@ -0,0 +1,64 @@ +"""Reading a stream's table with its derived token columns as they are (ITL-1464). + +``carried_table`` is how the library's own operators read their inputs: the table of +``as_table``, where a source-info column may be a recipe in place of its text +(``utils/source_tokens.py``). It is no part of a stream's interface. Only a stream whose +class is a library class that declares ``_carried_table`` itself, read as that class +(``reads_as_its_class``: no subclass, nothing replaced on the object), is read this way; +every other stream, a subclass with its own ``as_table`` or a user's stream, is read +through ``as_table`` and gives text. +""" + +from __future__ import annotations + +from collections.abc import AsyncIterator +from typing import Any + +import pyarrow as pa + +from orcapod.core.exact_class import reads_as_its_class + +CARRIED_TABLE = "_carried_table" +"""The method a library class declares when its table may hold derived columns.""" + + +def carried_table( + stream: Any, # pyright: ignore[reportExplicitAny] # a stream (the protocol would make an import cycle) + columns: Any, # pyright: ignore[reportExplicitAny] # as as_table +) -> pa.Table: + """``stream.as_table(columns=columns)``, derived token columns as they are. + + Args: + stream: The stream. + columns: The column groups, as for ``as_table``. + + Returns: + The table, for library code that passes it on; never for a user, a user's + operator or function, a store or a hash. + """ + kind = type(stream) + read: Any = vars(kind).get(CARRIED_TABLE) # pyright: ignore[reportExplicitAny] # a method + if read is None or not reads_as_its_class(stream, kind): + return stream.as_table(columns=columns) + return read(stream, columns) + + +CARRIED_BATCHES = "_carried_batches" +"""The method of the library's channel class whose batches may hold derived columns.""" + + +def carried_batches(channel: Any) -> AsyncIterator[pa.RecordBatch]: # pyright: ignore[reportExplicitAny] # a channel (its protocol would make an import cycle) + """The remaining record batches of a channel, derived token columns as they are. + + For library code that passes them on, as ``carried_table`` is for tables, and by the + same rule: only the library's own channel class, read as that class, is read this + way; any other channel is iterated and gives what it gives. + + Args: + channel: An input channel (``RecordBatchInput``). + """ + kind = type(channel) + read: Any = vars(kind).get(CARRIED_BATCHES) # pyright: ignore[reportExplicitAny] # a method + if read is None or not reads_as_its_class(channel, kind): + return aiter(channel) + return read(channel) diff --git a/src/orcapod/core/streams/preview.py b/src/orcapod/core/streams/preview.py new file mode 100644 index 000000000..f022fec63 --- /dev/null +++ b/src/orcapod/core/streams/preview.py @@ -0,0 +1,141 @@ +"""``stream.preview(n)``: the first rows of a stream, computing only what they need (ITL-1464). + +A preview reads a stream's rows as ``_preview_batches`` yields them, in the order of the +sync path, and stops at ``n``. Each kind of stream says how it gives its rows in batches +(a source reads a limit, an operator applied batch by batch takes its input's batches, a +function pod takes one row at a time); a stream that needs a whole input is refused unless +``compute_all`` was given. Nothing is kept on a stream, written to a database or +delivered. +""" + +from __future__ import annotations + +import dataclasses +from collections.abc import Generator +from contextlib import closing +from typing import TYPE_CHECKING, Any + +import pyarrow as pa + +from orcapod.errors import PreviewRefusedError + +if TYPE_CHECKING: + from orcapod.protocols.core_protocols import StreamProtocol + +FIRST_BATCH_ROWS = 1_024 +"""The rows of the first batch read when a step may drop rows; each next one doubles.""" + +PREVIEW_COLUMNS = {"source": True, "system_tags": True, "context": True} +"""The column groups a batch carries from step to step: every one but the hashes.""" + + +@dataclasses.dataclass(frozen=True) +class PreviewRequest: + """What a preview asks of a stream. + + Attributes: + limit: The most rows that can be used, or ``None`` when that is not known (a + step above may drop rows). A source reads no more. + compute_all: Whether a step that needs its whole input may be computed. + whole: Whether every row is asked for, by such a step. + kept: Each stream read in full by such steps with its batches, by identity: a + stream two branches share is computed once. The stream is held with its + batches: many are temporary (a step's result), and the identity of one that + was freed is given to another. Discarded with the preview. + """ + + limit: int | None + compute_all: bool = False + whole: bool = False + kept: dict[int, tuple[Any, list[StreamProtocol]]] = dataclasses.field( + default_factory=dict + ) + + def without_limit(self) -> PreviewRequest: + """The request to the input of a step that may drop rows.""" + return dataclasses.replace(self, limit=None) + + def of_every_row(self) -> PreviewRequest: + """The request to the inputs of a step that needs them whole.""" + return dataclasses.replace(self, limit=None, whole=True) + + +def preview_batches( + stream: Any, request: PreviewRequest +) -> Generator[StreamProtocol, None, None]: + """The rows of ``stream``, in order, as one stream per batch; at least one batch. + + Args: + stream: The stream, or anything else a step read as its input. + request: What is asked of it. + + Raises: + PreviewRefusedError: If the stream, or one beneath it, cannot be previewed. + """ + give = getattr(stream, "_preview_batches", None) + if give is None: + raise refused(stream, "has no preview") + if not request.whole: + with closing(give(request)) as batches: + yield from batches + return + if id(stream) not in request.kept: + with closing(give(request)) as batches: + request.kept[id(stream)] = (stream, list(batches)) + yield from request.kept[id(stream)][1] + + +def slices_of( + stream: Any, request: PreviewRequest +) -> Generator[StreamProtocol, None, None]: + """The rows of a stream that holds them (or reads them without effect), in slices. + + Args: + stream: A stream whose ``as_table`` computes nothing. + request: What is asked of it. + """ + from orcapod.core.data_tags import stream_data_tags + from orcapod.core.streams.arrow_table_stream import ArrowTableStream + + table: pa.Table = stream.as_table(columns=PREVIEW_COLUMNS) + size = table.num_rows if request.whole else request.limit or FIRST_BATCH_ROWS + end = table.num_rows if request.limit is None else request.limit + start = 0 + while True: + yield ArrowTableStream( + table.slice(start, min(size, end - start)), + tag_columns=stream.keys()[0], + data_tags=stream_data_tags(stream), + data_context=stream.data_context_key, + ) + start += size + size *= 2 + if start >= min(end, table.num_rows): + return + + +def refused(stream: Any, why: str) -> PreviewRefusedError: + """Return the error for a stream that cannot be previewed, naming it and the remedy.""" + return PreviewRefusedError( + f"preview() stopped at {type(stream).__name__}[{getattr(stream, 'label', '')}], " + f"which {why}. run() computes every row." + ) + + +def refuse_without_compute_all(stream: Any, request: PreviewRequest, why: str) -> None: + """Refuse a step that needs its whole input, unless ``compute_all`` was given. + + Args: + stream: The step's stream. + request: What is asked of it. + why: What the step needs, after the stream's name. + + Raises: + PreviewRefusedError: Unless ``request.compute_all``. + """ + if not request.compute_all: + raise PreviewRefusedError( + f"preview() stopped at {type(stream).__name__}[{stream.label}], which {why}. " + "preview(n, compute_all=True) computes that step in full, and keeps nothing; " + "run() computes every row and keeps what it computes." + ) diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py index c7919638b..266a36570 100644 --- a/src/orcapod/core/streams/record_batch_input.py +++ b/src/orcapod/core/streams/record_batch_input.py @@ -21,11 +21,12 @@ from collections.abc import AsyncIterator, Coroutine from typing import TYPE_CHECKING, Any, Protocol +import pyarrow as pa + from orcapod.channels import ChannelClosed +from orcapod.utils import source_tokens if TYPE_CHECKING: - import pyarrow as pa - from orcapod.protocols.core_protocols.streams import StreamProtocol SOURCE_BATCH_ROWS = 65_536 @@ -235,7 +236,19 @@ def _belong_to_caller(self) -> None: ) async def receive(self) -> pa.RecordBatch: - """Return the next Arrow record batch. + """Return the next Arrow record batch, its source-info tokens as text. + + The text of a derived token column (``utils/source_tokens.py``) is built here: a + recipe leaves the library in no batch. The rest is as ``_receive_carried``. + """ + batch = await self._receive_carried() + if not source_tokens.derived_columns(batch.schema): + return batch + table = source_tokens.materialize(pa.Table.from_batches([batch])) + return table.combine_chunks().to_batches()[0] + + async def _receive_carried(self) -> pa.RecordBatch: + """Return the next Arrow record batch, as it travels. A read that is cancelled while it waits closes the channel, as ``close`` does: a consumer that stops reading never holds its producer. @@ -357,7 +370,7 @@ async def _to_stream(self, claim: object) -> StreamProtocol: # imported by core/streams/base.py (a module-level import would be circular). from orcapod.core.operators.static_output_pod import ( ROW_BUILT_OUTPUT, - stream_from_batches, + stream_of_channel, ) self.reserve(claim) @@ -365,7 +378,18 @@ async def _to_stream(self, claim: object) -> StreamProtocol: if opened_on is not None and getattr(opened_on, ROW_BUILT_OUTPUT, False): await self.close() return opened_on - return stream_from_batches(self._stream, await self.collect()) + return await stream_of_channel(self) + + async def _carried_batches(self) -> AsyncIterator[pa.RecordBatch]: + """The remaining record batches as they travel (``carried_batches``).""" + while True: + try: + batch = await self._receive_carried() + except ChannelClosed: + if self._ended and not self._closed: + return + raise + yield batch async def collect(self) -> list[pa.RecordBatch]: """Read to the end and return every remaining record batch, in arrival order. diff --git a/src/orcapod/core/streams/view.py b/src/orcapod/core/streams/view.py index 699de9401..9b92cc4ee 100644 --- a/src/orcapod/core/streams/view.py +++ b/src/orcapod/core/streams/view.py @@ -20,6 +20,7 @@ import dataclasses import html import importlib +from collections import deque from collections.abc import Iterable, Sequence from dataclasses import dataclass from enum import Enum @@ -31,6 +32,7 @@ import pyarrow.compute as pc from typing_extensions import override +from orcapod.errors import BoundedViewError from orcapod.system_constants import constants @@ -112,6 +114,15 @@ def default_note(status: ViewStatus) -> str: # A view nobody cut to n rows (the view ``run()`` returns, or a sort of it) shows at most # this many rows: the first and the last half, with Polars' ellipsis row between. _DISPLAY_ROWS = 10 +# A ``run()`` that reads its rows batch by batch keeps every row of a result of at most +# ``RUN_VIEW_COMPLETE_ROWS`` rows and ``RUN_VIEW_COMPLETE_BYTES`` of values +# (``value_bytes``); of a larger one, the view has the first and the last +# ``RUN_VIEW_WINDOW_ROWS`` rows (ITL-1464). A result that fits in the two windows is +# always kept. Neither measure depends on the layout, so equal data is always treated +# alike, however its batches were cut (``RunSize``, the one place that decides it). +RUN_VIEW_COMPLETE_ROWS = 50_000 +RUN_VIEW_COMPLETE_BYTES = 64 * 1024 * 1024 +RUN_VIEW_WINDOW_ROWS = 1_000 _MAX_TEXT = 80 _TEXT_START = 56 _TEXT_END = 20 @@ -186,7 +197,8 @@ class StreamView: """Rows of a stream, and how they were obtained. ``head(n)`` on a stream returns a view of at most ``n`` readily available rows; - ``run()`` returns a view of all the computed rows. The view's ``head``, ``tail`` and + ``run()`` returns a view of all the computed rows (a ``BoundedStreamView``, which holds + only the ends, of a large result read in batches). The view's ``head``, ``tail`` and ``sort_by_tags`` return a new view of its own rows, with a header that says what they are; they never read, compute or change the stream. A view holds the columns it was made with: for other column groups (system tags, source info, context, content @@ -563,32 +575,30 @@ def _display_frame(self, text: bool = False) -> pl.DataFrame: never changed.""" columns_shown = self._display_columns() table = self.table.select([name for name, _ in columns_shown]) - rows = table.num_rows half = _DISPLAY_ROWS // 2 - # Only the rows the display shows are summarised; the others are left null, - # because Polars shows the first and last ``half`` of a long frame only. - shown = ( - table - if self._displays_every_row() - else pa.concat_tables([table.slice(0, half), table.slice(rows - half)]) - ) + # Only the rows the display shows are read: of a long view the first and the last + # ``half``, and one more between them, where Polars renders its ellipsis. The + # view of a job node may be a memory-mapped file (ITL-1464). + ends: list[pa.Table] = [] + if not self._displays_every_row(): + ends = [ + table.slice(0, half), + table.slice(half, 1), + table.slice(table.num_rows - half), + ] + table = pa.concat_tables(ends) + shown = pa.concat_tables([ends[0], ends[2]]) if ends else table columns = [] for name in table.column_names: summary = _summarise(shown.column(name)) if summary is None: columns.append(table.column(name)) - elif shown is table: - columns.append(pa.chunked_array([summary], type=pa.large_string())) - else: - columns.append( - pa.chunked_array( - [ - pa.array(summary[:half], type=pa.large_string()), - pa.nulls(rows - 2 * half, type=pa.large_string()), - pa.array(summary[half:], type=pa.large_string()), - ] - ) - ) + continue + if ends: + summary = [*summary[:half], None, *summary[half:]] + columns.append( + pa.chunked_array([pa.array(summary, type=pa.large_string())]) + ) names = list(table.column_names) if text: marked = [ @@ -603,6 +613,22 @@ def _display_frame(self, text: bool = False) -> pl.DataFrame: names = list(table.column_names) return pl.DataFrame(pa.table(columns, names=names)) + def _with_row_count(self, rendered: str) -> str: + """Return Polars' rendering of the display frame, naming the view's row count. + + The frame of a long view has one row more than the display shows. Polars names + the frame's shape before anything else it renders. + """ + if self._displays_every_row(): + return rendered + return rendered.replace( + f"shape: ({_DISPLAY_ROWS + 1:_}, ", f"shape: ({self._row_count():_}, ", 1 + ) + + def _row_count(self) -> int: + """The rows of the view, as its display names them.""" + return self.table.num_rows + def _displays_every_row(self) -> bool: """Whether the display shows every row: a view cut to ``n`` rows, or a short one.""" return self.display_all_rows or self.table.num_rows <= _DISPLAY_ROWS @@ -625,7 +651,7 @@ def _repr_html_(self) -> str: if self.table.num_columns: # Polars shortens strings to its own default length; show up to _MAX_TEXT. with pl.Config(fmt_str_lengths=_MAX_TEXT, tbl_rows=self._display_rows()): - frame_html = self._display_frame()._repr_html_() + frame_html = self._with_row_count(self._display_frame()._repr_html_()) columns = self._display_columns() names = _HeaderNames() names.feed(frame_html) @@ -654,7 +680,7 @@ def __str__(self) -> str: if self.table.num_columns: with pl.Config(fmt_str_lengths=_MAX_TEXT, tbl_rows=self._display_rows()): frame = self._display_frame(text=True) - frame_text = str(frame) + frame_text = self._with_row_count(str(frame)) columns = self._display_columns() rendered = _rendered_columns(_text_header_cells(frame_text), frame.columns) if rendered is not None: @@ -679,6 +705,293 @@ def __repr__(self) -> str: ) +@dataclass(frozen=True, repr=False) +class _EndsView(StreamView): + """The first and last rows of a longer view, displayed as that view is. + + ``table`` holds one row more than a long view shows, so Polars renders its ellipsis. + + Attributes: + shown_total: The row count of the whole view, named by the display. + """ + + shown_total: int = 0 + + @override + def _row_count(self) -> int: + return self.shown_total + + +class BoundedStreamView(StreamView): + """The view of a ``run()`` whose rows are not held (ITL-1464). + + It has the first and the last ``window_rows`` rows, the row count and the columns. + It is displayed as a view holding every row is. ``head(n)`` and ``tail(n)`` within + the window give the same views such a view gives. What needs rows it does not hold + (``table``, ``as_table()``, ``as_polars_df()``, ``sort_by_tags()``, a longer + ``head`` or ``tail``) raises ``BoundedViewError``, which names the stream's own + method: a part is never given as the whole, and a view never reads or computes. + + Attributes: + window_rows: The rows held at each end. + """ + + def __init__( # pyright: ignore[reportMissingSuperCall] # the parent's would set ``table`` + self, first: StreamView, last: pa.Table, total_rows: int + ) -> None: + """Make the view. + + Args: + first: A view of the first rows, named as the stream's view is named. + last: The last rows, as many as ``first`` has. + total_rows: The row count of the whole. + """ + # ``table`` is deliberately not set: reading it reaches ``__getattr__``. + for field in dataclasses.fields(StreamView): + if field.name != "table": + object.__setattr__(self, field.name, getattr(first, field.name)) + object.__setattr__(self, "total_rows", total_rows) + object.__setattr__( + self, "_first", dataclasses.replace(first, total_rows=total_rows) + ) + object.__setattr__(self, "_last", last) + + def __getattr__(self, name: str) -> Any: + if name == "table": + raise self._refused("its table") + raise AttributeError(f"{type(self).__name__!r} has no attribute {name!r}") + + def _refused(self, what: str) -> BoundedViewError: + """Return the error for ``what``, which needs rows the view does not hold.""" + return BoundedViewError( + f"{what} needs every row, and this view of {self._total():,} rows holds only " + f"the first and the last {self.window_rows:,}: run() does not keep a result " + f"of more than {RUN_VIEW_COMPLETE_ROWS:,} rows, or " + f"{_size(RUN_VIEW_COMPLETE_BYTES)} of values, read in batches. Ask the " + "stream for its rows: stream.as_table(), stream.as_polars_df() or iteration " + "(stream.as_table(columns={'sort_by_tags': True}) sorts them)." + ) + + def _total(self) -> int: + return cast(int, self.total_rows) + + def _held(self) -> tuple[StreamView, pa.Table]: + values = vars(self) + return cast("StreamView", values["_first"]), cast(pa.Table, values["_last"]) + + @property + def window_rows(self) -> int: + """The rows held at each end.""" + return self._held()[1].num_rows + + @override + def __len__(self) -> int: + return self._total() + + @override + def __eq__(self, other: object) -> bool: + return self is other + + @override + def __hash__(self) -> int: + return id(self) + + @override + def as_table(self) -> pa.Table: + raise self._refused("as_table()") + + @override + def as_polars_df(self) -> pl.DataFrame: + raise self._refused("as_polars_df()") + + @override + def sort_by_tags(self) -> StreamView: + # A view with no tag column is returned as it is, as every view is. + if not self.tag_columns: + return self + raise self._refused("sort_by_tags()") + + @override + def head(self, n: int = 10) -> StreamView: + _check_row_count(n) + if n > self.window_rows: + raise self._refused(f"head({n})") + return dataclasses.replace(self._held()[0].head(n), display_all_rows=True) + + @override + def tail(self, n: int = 10) -> StreamView: + _check_row_count(n) + if n > self.window_rows: + raise self._refused(f"tail({n})") + first, last = self._held() + whole = dataclasses.replace( + first, table=last, start=self._total() - last.num_rows + ) + return whole.tail(n) + + @override + def for_stream( + self, stream: Any, *, origin: str | None = None, note: str | None = None + ) -> StreamView: + first, last = self._held() + return BoundedStreamView( + first.for_stream(stream, origin=origin, note=note), last, self._total() + ) + + def _ends(self) -> _EndsView: + """The rows the display shows, worded and counted as the whole.""" + first, last = self._held() + half = _DISPLAY_ROWS // 2 + values = { + f.name: getattr(first, f.name) for f in dataclasses.fields(StreamView) + } + values["table"] = pa.concat_tables( + [first.table.slice(0, half + 1), last.slice(last.num_rows - half)] + ) + values["description"] = first._describe_rows(self._total()) + values["display_all_rows"] = False + return _EndsView(**values, shown_total=self._total()) + + @override + def header(self) -> str: + return self._ends().header() + + @override + def _repr_html_(self) -> str: + return self._ends()._repr_html_() + + @override + def __str__(self) -> str: + return str(self._ends()) + + @override + def __repr__(self) -> str: + return ( + f"StreamView({self.kind}[{self.label}], status={self.status.value}, " + f"rows={self._total()})" + ) + + +def value_bytes(column: Any) -> int: + """Return the bytes of the values of ``column``, whatever its layout. + + A fixed-width value counts its width (a null too), a string or binary value its + bytes, a list the values in it and 8 bytes, a struct its fields. Offsets, validity, + chunks and the buffers behind a slice are not counted, so equal values always count + the same, in one chunk or many. + + Args: + column: An Arrow array or chunked array. + """ + if isinstance(column, pa.ChunkedArray): + return sum(value_bytes(chunk) for chunk in column.chunks) + kind = column.type + if isinstance(kind, pa.BaseExtensionType): + return value_bytes(column.storage) + if pa.types.is_map(kind): + entry = pa.struct([("key", kind.key_type), ("value", kind.item_type)]) + return value_bytes(column.cast(pa.list_(entry))) + if ( + pa.types.is_list(kind) + or pa.types.is_large_list(kind) + or pa.types.is_fixed_size_list(kind) + ): + return 8 * len(column) + value_bytes(column.flatten()) + if pa.types.is_struct(kind): + # ``flatten`` gives each field with the struct's own nulls, so a value under a + # null struct, which is no value, is not counted. + return sum(value_bytes(field) for field in column.flatten()) + if pa.types.is_null(kind): + return 0 + try: + return len(column) * ((kind.bit_width + 7) // 8) + except ValueError: # a variable-width type: string or binary + return int(pc.sum(pc.binary_length(column)).as_py() or 0) + + +class RunSize: + """The size of a result, and whether ``run()`` keeps every row of it.""" + + def __init__(self) -> None: + self.rows: int = 0 + self.bytes: int = 0 + + def add(self, table: pa.Table) -> None: + """Count the next rows (with the default columns).""" + self.rows += table.num_rows + # Once the rows alone decide, the values need not be measured. + if self.rows <= RUN_VIEW_COMPLETE_ROWS: + self.bytes += sum(value_bytes(column) for column in table.columns) + + @property + def is_kept(self) -> bool: + """Whether a result of this size is kept.""" + return self.rows <= 2 * RUN_VIEW_WINDOW_ROWS or ( + self.rows <= RUN_VIEW_COMPLETE_ROWS + and self.bytes <= RUN_VIEW_COMPLETE_BYTES + ) + + +class WindowOfRows: + """Collects the tables of a stream's rows, batch by batch: all rows of a result + ``RunSize`` says is kept, else the first and the last + ``RUN_VIEW_WINDOW_ROWS``. The window is copied, so no batch stays alive behind it. + """ + + def __init__(self) -> None: + self._size: RunSize = RunSize() + self._all: list[pa.Table] | None = [] + self._first: list[pa.Table] = [] + self._last: deque[pa.Table] = deque() + + def add(self, table: pa.Table) -> None: + """Take the next rows. + + Args: + table: The rows; every table of a stream has the same schema. + """ + missing = RUN_VIEW_WINDOW_ROWS - min(self.total, RUN_VIEW_WINDOW_ROWS) + if missing and table.num_rows: + self._first.append(_copied(table.slice(0, missing))) + if table.num_rows: + end = max(table.num_rows - RUN_VIEW_WINDOW_ROWS, 0) + self._last.append(_copied(table.slice(end))) + held = sum(part.num_rows for part in self._last) + while held - self._last[0].num_rows >= RUN_VIEW_WINDOW_ROWS: + held -= self._last.popleft().num_rows + self._size.add(table) + if self._all is not None: + self._all.append(table) + if not self._size.is_kept: + self._all = None + + @property + def total(self) -> int: + """The rows taken so far.""" + return self._size.rows + + @property + def complete(self) -> pa.Table | None: + """Every row, or ``None`` when there are too many (or nothing was taken).""" + return pa.concat_tables(self._all) if self._all else None + + @property + def first(self) -> pa.Table: + """The first rows.""" + return pa.concat_tables(self._first) + + @property + def last(self) -> pa.Table: + """The last rows.""" + rows = pa.concat_tables(list(self._last)) + return rows.slice(max(rows.num_rows - RUN_VIEW_WINDOW_ROWS, 0)) + + +def _copied(table: pa.Table) -> pa.Table: + """Return ``table``'s rows in buffers of their own, every value bit for bit.""" + return table.take(pa.array(range(table.num_rows), pa.int64())) + + def _mark_columns( frame_html: str, columns: Sequence[tuple[str, str]], diff --git a/src/orcapod/core/unique_keys.py b/src/orcapod/core/unique_keys.py new file mode 100644 index 000000000..757090d53 --- /dev/null +++ b/src/orcapod/core/unique_keys.py @@ -0,0 +1,166 @@ +"""Uniqueness certificates: the tag sets no two rows of a stream agree on (ITL-1464). + +A *unique key* of a stream is a set of its tags such that no two of its rows agree on all +of them, under the joins' equality of values (NaN equals NaN, ``-0.0`` equals ``0.0``). A +stream's certificate is a set of unique keys (``StreamProtocol.unique_keys``); the empty +set certifies nothing. A join uses it to let a row go once it has matched, so a wrong +certificate would lose rows: every rule here certifies only what is certain. + +A source certifies its key columns when it checks them on every read, and they are all +tags. Every other stream derives its certificate from its inputs' by the rule its pod's +class declares, at the time it is asked: nothing is stored on a stream, and nothing here +enters a hash, an identity, a config, a stored row or equality. A rule is read from the +pod's exact class, and only for a pod and a stream that are exactly their classes, with +no member replaced on the instance (``reads_as_its_class``): a subclass or a customized +instance may give other rows, so it certifies nothing. A stream class takes part by +declaring ``DERIVES_UNIQUE_KEYS`` itself. +""" + +from __future__ import annotations + +from collections.abc import Generator, Iterable, Mapping, Sequence +from contextlib import contextmanager +from contextvars import ContextVar +from typing import Protocol + +from orcapod.core.exact_class import reads_as_its_class + +UniqueKeys = frozenset[frozenset[str]] + +NO_UNIQUE_KEYS: UniqueKeys = frozenset() + +MAX_UNIQUE_KEYS = 8 +"""How many unique keys a certificate keeps (a join's keys combine pairwise).""" + +_MEMO: ContextVar[dict[int, tuple[object, UniqueKeys]] | None] = ContextVar( + "_UNIQUE_KEYS_MEMO", default=None +) +"""The certificates derived during one outermost call: a graph of diamonds reaches one +stream by many ways.""" + + +def certificate(keys: Iterable[Iterable[str]]) -> UniqueKeys: + """``keys`` as a certificate: no key that holds another one, at most a few. + + Args: + keys: Unique keys. + """ + sets = sorted({frozenset(key) for key in keys}, key=lambda k: (len(k), sorted(k))) + kept: list[frozenset[str]] = [] + for key in sets: + if not any(other <= key for other in kept): + kept.append(key) + return frozenset(kept[:MAX_UNIQUE_KEYS]) + + +def unique_on(keys: UniqueKeys, columns: Iterable[str]) -> bool: + """Whether a stream certified with ``keys`` has no two rows agreeing on ``columns``.""" + names = frozenset(columns) + return any(key <= names for key in keys) + + +def renamed_keys( + keys: UniqueKeys, renames: Mapping[str, str], dropped: Iterable[str] = () +) -> UniqueKeys: + """``keys`` after tags are renamed, all at once, and some dropped. + + Args: + keys: Unique keys. + renames: The new name of each renamed tag. + dropped: The tags that are gone; a name in it may also be another tag's new one. + """ + gone = frozenset(dropped) + return certificate( + {renames.get(name, name) for name in key} for key in keys if not key & gone + ) + + +def joined_keys( + left: UniqueKeys, right: UniqueKeys, shared: Iterable[str] +) -> UniqueKeys: + """The certificate of an inner join on ``shared`` tags. + + A joined row is named by a key of each side. When one side is unique on the shared + tags, a row of the other side is in at most one joined row, so that side's keys stay. + + Args: + left: The left side's unique keys. + right: The right side's unique keys. + shared: The tags matched on. + """ + names = frozenset(shared) + keys: set[frozenset[str]] = {a | b for a in left for b in right} + if unique_on(right, names): + keys |= left + if unique_on(left, names): + keys |= right + return certificate(keys) + + +def derives_unique_keys(stream: object) -> bool: + """Whether a stream's class takes part, and the stream is exactly of it. + + Args: + stream: A stream. + """ + kind = type(stream) + if vars(kind).get("DERIVES_UNIQUE_KEYS") is not True: + return False + return reads_as_its_class(stream, kind) + + +class _HasKeys(Protocol): + """What the certificate needs of the stream it is of.""" + + def keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: ... + + +def derived_keys( + pod: object, upstreams: Sequence[object], stream: _HasKeys +) -> UniqueKeys: + """The certificate of ``stream``, the result of ``pod`` over ``upstreams``. + + The pod's class declares its rule as a method ``derive_unique_keys(*upstreams)``. + Nothing is certified without one on the exact class, or when the pod or the stream is + not exactly its class (module docstring). + + Args: + pod: The producing pod. + upstreams: Its inputs. + stream: Its result, whose tags the keys must be among. + """ + rule = vars(type(pod)).get("derive_unique_keys") + if rule is None or not reads_as_its_class(pod, type(pod)): + return NO_UNIQUE_KEYS + if not derives_unique_keys(stream): + return NO_UNIQUE_KEYS + memo = _MEMO.get() + token = None + if memo is None: + memo = {} + token = _MEMO.set(memo) + try: + found = memo.get(id(stream)) + if found is None: + tags = frozenset(stream.keys()[0]) + keys = certificate(k for k in rule(pod, *upstreams) if k <= tags) + # The stream is kept beside its keys: an id is its own only while it lives. + found = memo[id(stream)] = (stream, keys) + return found[1] + finally: + if token is not None: + _MEMO.reset(token) + + +@contextmanager +def unique_keys_of_one_run() -> Generator[None, None, None]: + """Derive each stream's certificate at most once inside this block. + + For an async run, whose joins each ask their inputs'. Bindings, operators and cache + modes do not change during a run. + """ + token = _MEMO.set({}) + try: + yield + finally: + _MEMO.reset(token) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 6ae7f757c..20b4421b1 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -27,6 +27,7 @@ import pyarrow as pa import pyarrow.compute as pc +from orcapod.utils import source_tokens from orcapod.databases._pending_commits import PendingCommit, PendingCommits from orcapod.databases.utils import ( coerce_record_id, @@ -438,6 +439,7 @@ def add_records( ) -> None: """Add multiple records to the pending batch.""" self._validate_record_path(record_path) + source_tokens.refuse_derived(records.schema) if records.num_rows == 0: return diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index c88b322d8..e369b1735 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -63,7 +63,7 @@ TypeIdentityError, UnstorableColumnError, ) -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: @@ -2747,6 +2747,7 @@ def add_records( ValueError: If any record IDs already exist and skip_duplicates=False """ self._validate_record_path(record_path) + source_tokens.refuse_derived(records.schema) if records.num_rows == 0: return diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 2ccb4d696..92b270874 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -9,6 +9,7 @@ import pyarrow as pa import pyarrow.compute as pc +from orcapod.utils import source_tokens from orcapod.databases._pending_commits import PendingCommit, PendingCommits from orcapod.databases._row_index import KeyIndex, compact_tail, matching_rows from orcapod.databases.utils import ( @@ -242,6 +243,7 @@ def add_records( flush: bool = False, ) -> None: self._validate_record_path(record_path) + source_tokens.refuse_derived(records.schema) if records.num_rows == 0: return diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 7720e7980..2c6652663 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -1267,6 +1267,21 @@ def __str__(self) -> str: ) +class PreviewRefusedError(ValueError): + """A ``preview()`` would need more than the rows it shows, or would have an effect. + + The message names the stream it stopped at (ITL-1464). + """ + + +class BoundedViewError(ValueError): + """What was asked of a view needs rows the view does not hold (ITL-1464). + + Raised by the view of a ``run()`` whose result is too large to be kept; ask the + stream itself for its rows. + """ + + class ProvenanceInconsistencyError(ValueError): """What a job holds and what its databases store disagree about a row's provenance. diff --git a/src/orcapod/hashing/arrow_hashers.py b/src/orcapod/hashing/arrow_hashers.py index cf520d9f8..800086a68 100644 --- a/src/orcapod/hashing/arrow_hashers.py +++ b/src/orcapod/hashing/arrow_hashers.py @@ -18,6 +18,7 @@ from orcapod.logical_types.identifier import LogicalTypeIdentifierError from orcapod.hashing.visitors import SemanticHashingVisitor from orcapod.logical_types.canonical_form import storage_form_schema +from orcapod.utils import source_tokens from orcapod.utils.arrow_utils import normalize_extension_columns from orcapod.types import ContentHash @@ -231,6 +232,7 @@ def hash_schema(self, schema: "pa.Schema") -> ContentHash: column that keeps the identifier, so ``hash_schema(table.schema)`` is not the schema inside ``hash_table(table)``, and nothing may rely on it. """ + source_tokens.refuse_derived(schema) schema = storage_form_schema(schema) include_meta = has_extension_metadata(schema) or has_extension_type(schema) if include_meta: @@ -329,6 +331,7 @@ def _digest( Returns: The starfix digest (version prefix included). """ + source_tokens.refuse_derived(table.schema) if isinstance(table, pa.RecordBatch): table = pa.Table.from_batches([table]) diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 9edd1614e..cbfe4668a 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -15,10 +15,13 @@ import uuid import warnings from collections import defaultdict -from collections.abc import Callable, Coroutine +from collections.abc import AsyncGenerator, Callable, Coroutine from typing import TYPE_CHECKING, Any, Literal, TypeVar from orcapod.channels import BroadcastChannel, Channel +from orcapod.core.job_edges import EDGE_BATCHES, EdgeReader, EdgeWriter +from orcapod.core.streams.base import zero_rows_of_one_run +from orcapod.core.unique_keys import unique_keys_of_one_run from orcapod.errors import ( OrcapodDatabaseError, OrcapodDatabaseWriteError, @@ -237,22 +240,27 @@ async def _run_async( node_output_channels: dict[Any, Channel | BroadcastChannel] = {} edge_readers: dict[tuple[Any, Any], Any] = {} + def edge_buffer(node: Any) -> int: + """Items an edge holds: few when they may be record batches.""" + batches = is_source_node(node) or is_operator_node(node) + return min(buf, EDGE_BATCHES) if batches else buf + for node, downstreams in out_edges.items(): if len(downstreams) == 1: - ch = Channel(buffer_size=buf) + ch = Channel(buffer_size=edge_buffer(node)) node_output_channels[node] = ch - edge_readers[(node, downstreams[0])] = ch.reader + edge_readers[(node, downstreams[0])] = EdgeReader(ch.reader) else: - bch = BroadcastChannel(buffer_size=buf) + bch = BroadcastChannel(buffer_size=edge_buffer(node)) node_output_channels[node] = bch for ds in downstreams: - edge_readers[(node, ds)] = bch.add_reader() + edge_readers[(node, ds)] = EdgeReader(bch.add_reader()) # Terminal nodes need sink channels terminal_channels: list[Channel] = [] for node in topo_order: if node not in node_output_channels: - ch = Channel(buffer_size=buf) + ch = Channel(buffer_size=edge_buffer(node)) node_output_channels[node] = ch terminal_channels.append(ch) @@ -263,13 +271,16 @@ async def _run_async( collectors[node] = [] # Launch all nodes concurrently - async with asyncio.TaskGroup() as tg: + async with _task_group() as tg: for node in topo_order: writer = node_output_channels[node].writer if materialize_results: collector = collectors[node] writer = _CollectingWriter(writer, collector) + else: + # Takes a node's rows as record batches too (ITL-1464). + writer = EdgeWriter(writer) if held_rows is not None and node in held_rows: # Not run: the rows of its current run feed its successors. Its @@ -361,9 +372,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=( @@ -657,8 +671,19 @@ def create_data_logger(self, tag: Any, data: Any) -> Any: return NoOpLogger() +@contextlib.asynccontextmanager +async def _task_group() -> AsyncGenerator[asyncio.TaskGroup, None]: + """The run's task group, whose nodes share the descriptions they derive.""" + with zero_rows_of_one_run(), unique_keys_of_one_run(): + async with asyncio.TaskGroup() as group: + yield group + + async def _drain(reader: Any) -> None: """Read ``reader`` to its end, keeping nothing.""" + if isinstance(reader, EdgeReader): + await reader.discard() + return async for _ in reader: pass 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/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index c8c72abd6..b12a458a6 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -217,6 +217,15 @@ def arrow_types_declared(self) -> bool: """ ... + @property + def unique_keys(self) -> frozenset[frozenset[str]]: + """The tag sets no two rows of the stream agree on; empty certifies nothing. + + Derived from the inputs when asked, never stored; in no hash, identity, config, + stored row or equality (``orcapod.core.unique_keys``, ITL-1464). + """ + ... + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """ Generates explicit iterator over (tag, data) pairs in the stream. @@ -280,7 +289,9 @@ def as_table( def run(self) -> "StreamViewProtocol": """Compute the whole stream and return a view of all its rows. - Does the work ``as_table()`` does, through the same path and cache; a job node + Every row is computed, with every effect; nothing is promised about how the + rows are produced or held (ITL-1464), and the view of a large result may hold + only its ends (``BoundedStreamView``). A job node runs as it does in a job. Every stream has it, with no argument: it is the one way to compute a stream outside a job (ITL-1081). ``head()`` and the notebook preview never compute a row. @@ -290,6 +301,19 @@ def run(self) -> "StreamViewProtocol": """ ... + def preview( + self, n: int = 10, *, compute_all: bool = False + ) -> "StreamViewProtocol": + """Compute the first ``n`` rows and only what they need, keeping nothing. + + User functions are called; nothing is stored and nothing has an effect. A step + that needs its whole input is refused unless ``compute_all`` (ITL-1464). + + Returns: + StreamView: The first ``n`` rows of ``as_table()``. + """ + ... + def head( self, n: int = 10, diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 071aa82ac..874f91758 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -13,11 +13,12 @@ import datetime import logging from collections.abc import Callable, Collection, Iterator, Sequence -from typing import TYPE_CHECKING, Any, Literal, cast +from typing import ClassVar, TYPE_CHECKING, Any, Literal, cast import pyarrow as pa from typing_extensions import override +from orcapod.core.unique_keys import UniqueKeys, derived_keys from orcapod.core.base import TraceableBase from orcapod.core.nodes.staleness import RunHoldingNode from orcapod.core.nodes.function_node import ( @@ -129,6 +130,8 @@ class SideEffectPodStream(StreamBase): No invocation log is written in standalone mode (``pipeline_run_id=None``). """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def __init__( self, side_effect_pod: SideEffectPod, @@ -139,6 +142,11 @@ def __init__( self._input_stream = input_stream super().__init__(**kwargs) + @property + def unique_keys(self) -> UniqueKeys: + """The tag sets no two rows agree on, derived from the inputs' (``core/unique_keys``).""" + return derived_keys(self.producer, self.upstreams, self) + @property def producer(self) -> SideEffectPod: # type: ignore[override] return self._pod @@ -620,6 +628,10 @@ class SideEffectPod(TraceableBase): data_context: Optional data context override. """ + def derive_unique_keys(self, stream: StreamProtocol) -> UniqueKeys: + """The input's unique keys: each row comes from one input row, its tags kept.""" + return stream.unique_keys + def __init__( self, fn: Callable, @@ -908,6 +920,8 @@ class SideEffectNode(StreamBase): label: Optional display label. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + node_type = "side_effect" def __init__( @@ -924,6 +938,11 @@ def __init__( # StreamBase interface # ------------------------------------------------------------------ + @property + def unique_keys(self) -> UniqueKeys: + """The tag sets no two rows agree on, derived from the inputs' (``core/unique_keys``).""" + return derived_keys(self.producer, self.upstreams, self) + @property def producer(self) -> SideEffectPod | None: # type: ignore[override] """The node's pod; ``None`` for a node loaded from a saved file (ITL-1094).""" @@ -1086,6 +1105,8 @@ class SideEffectJobNode(RunHoldingNode, SideEffectNode): label: Optional display label. """ + DERIVES_UNIQUE_KEYS: ClassVar[bool] = True + def __init__( self, side_effect_pod: SideEffectPod, diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 86ac58283..f017b3190 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -1,15 +1,24 @@ from __future__ import annotations import hashlib +import itertools import json from collections import defaultdict -from collections.abc import Callable, Iterator, Mapping, Collection, Sequence +from collections.abc import ( + Callable, + Collection, + Iterable, + Iterator, + Mapping, + Sequence, +) from typing import Any, TYPE_CHECKING, cast import pyarrow as pa from orcapod.system_constants import constants from orcapod.types import ColumnConfig, SourceInfoValue +from orcapod.utils import source_tokens if TYPE_CHECKING: from orcapod.logical_types.identifier import LogicalTypeIdentifier @@ -1464,10 +1473,17 @@ def append_to_system_tags(table: "pa.Table", value: str) -> "pa.Table": else c for c in table.column_names } - return table.rename_columns(column_name_map) + # A derived token column keeps reading the columns it read (ITL-1464). + return source_tokens.rename_read_columns( + table.rename_columns(column_name_map), column_name_map + ) + + +_FOLD_PART = 4096 +"""How many members ``fold_system_tag_values`` digests at once.""" -def fold_system_tag_values(values: Sequence[Any], *, label: str) -> str: +def fold_system_tag_values(values: Iterable[Any], *, label: str) -> str: """Fold a group's system-tag values into one scalar: ``"