From 611f72c981cc06ab2663fe131a83e1c7365cefdb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:15:39 -0800 Subject: [PATCH 1/5] docs(dev): views design for ITL-1464 Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-views.md | 120 +++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 docs/dev/specs/itl-1464-views.md diff --git a/docs/dev/specs/itl-1464-views.md b/docs/dev/specs/itl-1464-views.md new file mode 100644 index 000000000..0bc211408 --- /dev/null +++ b/docs/dev/specs/itl-1464-views.md @@ -0,0 +1,120 @@ +# `run()`, its view and `preview(n)` without a full table (ITL-1464, track VIEWS) + +Status: draft for approval, November 25, 2026, 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 row-by-row operators (`ROW_BY_ROW`, and `Filter`) over a +source that reads in batches. 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 **64 MiB** (all column groups). 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. + +## 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 2,177,155 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. +- 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 | 64 MiB of result (as L2), 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: 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, 2,177,155 rows of the gaze shape, before and after, for the source, a rename, a + `drop_nulls` and a `filter`. From f37442e78f5149d543d3aca919ab8502d7e3f5b5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:33:00 -0800 Subject: [PATCH 2/5] perf(streams): bounded view for run() over an on-demand source (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1464.md | 10 + docs/concepts/streams.md | 28 +- docs/dev/specs/itl-1464-views.md | 38 +- src/orcapod/core/operators/add_tags.py | 1 + .../core/operators/column_selection.py | 8 + src/orcapod/core/operators/drop_nulls.py | 1 + src/orcapod/core/operators/filter.py | 1 + src/orcapod/core/operators/mappers.py | 3 + .../core/operators/static_output_pod.py | 138 +++++ .../core/sources/spiraldb_table_source.py | 37 +- src/orcapod/core/streams/base.py | 64 ++- src/orcapod/core/streams/view.py | 240 ++++++++- src/orcapod/errors.py | 8 + .../protocols/core_protocols/streams.py | 4 +- .../streams/test_bounded_run_view.py | 471 ++++++++++++++++++ 15 files changed, 1025 insertions(+), 27 deletions(-) create mode 100644 changelog.d/ITL-1464.md create mode 100644 tests/test_core/streams/test_bounded_run_view.py diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md new file mode 100644 index 000000000..be50b516d --- /dev/null +++ b/changelog.d/ITL-1464.md @@ -0,0 +1,10 @@ +### Changed + +- `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 (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. diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index 40c13de07..0ecf17a1b 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,13 +210,30 @@ 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 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 row count, 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. What `run()` does on each kind of object: @@ -223,7 +241,7 @@ 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 | | 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-views.md b/docs/dev/specs/itl-1464-views.md index 0bc211408..dd54dd169 100644 --- a/docs/dev/specs/itl-1464-views.md +++ b/docs/dev/specs/itl-1464-views.md @@ -1,6 +1,7 @@ # `run()`, its view and `preview(n)` without a full table (ITL-1464, track VIEWS) -Status: draft for approval, November 25, 2026, against `origin/main` 0d1e017c. Companion of +Status: V1 to V12 approved by the coordinator, November 25, 2026 (V2, V3 and V8 flagged for +the developer); the bounded view is implemented, `preview(n)` is not. 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. @@ -16,8 +17,11 @@ Outside a job, only `SpiralDBTableSource` reads its rows on demand and holds non 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 row-by-row operators (`ROW_BY_ROW`, and `Filter`) over a -source that reads in batches. Joins, `GroupBy`, `Batch`, `PolarsFilter` and function pods +**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 @@ -28,7 +32,8 @@ end the chain: they compute as today. 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 **64 MiB** (all column groups). A result that ends +2. Result batches are kept whole up to **50,000 rows** (all column groups; counted in rows, + not bytes, 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 @@ -38,7 +43,9 @@ end the chain: they compute as today. `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. +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 @@ -96,9 +103,9 @@ never computes. | 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 | 64 MiB of result (as L2), first and last 1,000 rows; constants, no config yet | +| V4 | Threshold and window | approved at 64 MiB; implemented as 50,000 rows (bytes differ with the batches and with what is already held), 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: keeping one table per step is the cost being removed; each `run()`s by itself | +| 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 | @@ -118,3 +125,20 @@ never computes. - The refusals; `head` after `run`; staleness after the source moves. - Memory, 2,177,155 rows of the gaze shape, before and after, for the source, a rename, a `drop_nulls` and a `filter`. + +## Measured + +`run()` of a synthetic SpiralDB table shaped as one session of gaze (2,177,155 rows, 13 +columns, 248 MiB of Arrow data; the diagnosis's table), 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. diff --git a/src/orcapod/core/operators/add_tags.py b/src/orcapod/core/operators/add_tags.py index 9af218e81..583a51192 100644 --- a/src/orcapod/core/operators/add_tags.py +++ b/src/orcapod/core/operators/add_tags.py @@ -122,6 +122,7 @@ class AddTags(UnaryOperator): # 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 __init__(self, tags: Mapping[str, TagConstant], **kwargs: Any): diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index cbc6570b8..ff312854d 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -60,6 +60,7 @@ class SelectTagColumns(UnaryOperator): # 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 __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): @@ -199,6 +200,7 @@ class SelectDataColumns(UnaryOperator): # 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 __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): @@ -355,6 +357,7 @@ class DropTagColumns(UnaryOperator): # 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 __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): @@ -499,6 +502,7 @@ class DropDataColumns(UnaryOperator): # 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 __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): @@ -881,6 +885,8 @@ class DropColumns(_TagAndDataColumnsOperator): be dropped: a stream needs at least one data column. """ + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True + _verb: ClassVar[str] = "drop" def _removed(self, columns: Collection[str]) -> list[str]: @@ -905,6 +911,8 @@ class SelectColumns(_TagAndDataColumnsOperator): named: a stream needs at least one data column. """ + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True + _verb: ClassVar[str] = "select" def _removed(self, columns: Collection[str]) -> list[str]: diff --git a/src/orcapod/core/operators/drop_nulls.py b/src/orcapod/core/operators/drop_nulls.py index 1e7840935..3ad35f7b1 100644 --- a/src/orcapod/core/operators/drop_nulls.py +++ b/src/orcapod/core/operators/drop_nulls.py @@ -93,6 +93,7 @@ class DropNulls(UnaryOperator): # 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 __init__( diff --git a/src/orcapod/core/operators/filter.py b/src/orcapod/core/operators/filter.py index e5a4fa1a8..dd341ae58 100644 --- a/src/orcapod/core/operators/filter.py +++ b/src/orcapod/core/operators/filter.py @@ -82,6 +82,7 @@ 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 + BATCHES_GIVE_THE_WHOLE: ClassVar[bool] = True # Its identity is not frozen with data context v1 (ITL-1374). PROVISIONAL: ClassVar[bool] = True diff --git a/src/orcapod/core/operators/mappers.py b/src/orcapod/core/operators/mappers.py index fa89ec4a5..0a8d684b7 100644 --- a/src/orcapod/core/operators/mappers.py +++ b/src/orcapod/core/operators/mappers.py @@ -94,6 +94,7 @@ class MapData(UnaryOperator): # 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 __init__( @@ -371,6 +372,7 @@ class MapTags(UnaryOperator): # 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 __init__( @@ -667,6 +669,7 @@ class MapColumns(UnaryOperator): # 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 __init__( diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f829d44a5..6179a5066 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -5,6 +5,7 @@ import logging from abc import abstractmethod from collections.abc import ( + Generator, AsyncIterator, Collection, Iterable, @@ -12,6 +13,7 @@ Mapping, Sequence, ) +from contextlib import closing from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, cast @@ -43,6 +45,8 @@ from orcapod.utils.provisional import note_provisional_use, provisional_class_name from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( + batch_streams_of, + reads_in_batches, ZERO_ROW_INPUT_COLUMNS, StreamBase, check_head_size, @@ -53,6 +57,8 @@ row_built_columns, ) from orcapod.core.streams.view import ( + RUN_VIEW_COMPLETE_ROWS, + BoundedStreamView, STALE_NOTE, default_note, ViewStatus, @@ -117,6 +123,16 @@ 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). + """ + OUTPUT_SCHEMA_IS_INPUT_SCHEMA: ClassVar[bool] = False """Whether the output has exactly its single input's columns and Arrow types. @@ -1832,6 +1848,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. @@ -1887,6 +1906,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 +2053,96 @@ 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 type(self._pod).__dict__.get("BATCHES_GIVE_THE_WHOLE") is True + 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 of at most ``RUN_VIEW_COMPLETE_ROWS`` rows 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 = [] + rows = 0 + 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 + rows += result.as_table().num_rows + if kept is not None: + kept.append(result) + if rows > RUN_VIEW_COMPLETE_ROWS: + kept = None + yield result + if kept: + self._cached_stream = ( + # Its input unchanged, as a read keeps it: reads nothing. + self._pod.static_process(*self._upstreams) + if handed_on + else joined_batches(kept) + ) + self._cached_time = datetime.now(timezone.utc) + self._kept_states = kept_states + self._run_window = None + + 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 result of more than ``RUN_VIEW_COMPLETE_ROWS`` rows 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, *, @@ -2089,6 +2199,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 +2268,32 @@ def __repr__(self) -> str: ) +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( + [ + batch.as_table( + columns={"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.""" diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 6312a677f..316ac347d 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 @@ -62,7 +63,7 @@ row_identifiers, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream -from orcapod.core.streams.base import check_head_size +from orcapod.core.streams.base import check_head_size, reads_as_its_class from orcapod.core.streams.view import ViewStatus, StreamView from orcapod.databases.spiraldb_connector import ( SpiralDBConnector, @@ -79,7 +80,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 @@ -1122,11 +1127,33 @@ 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).""" + with closing(self._batch_streams()) as streams: + for stream in streams: + yield ArrowTableStream( + self._whole_table( + iter([stream]), + columns={"source": True, "system_tags": True, "context": True}, + all_info=False, + ), + 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 table of more than ``RUN_VIEW_COMPLETE_ROWS`` rows 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/streams/base.py b/src/orcapod/core/streams/base.py index 9f8b731f7..c3296bec4 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -9,12 +9,13 @@ 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 @@ -28,8 +29,10 @@ 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, ) @@ -84,6 +87,22 @@ def reads_as_its_class(obj: object, cls: type) -> bool: return True +def reads_in_batches(stream: object) -> bool: + """Whether ``run()`` reads ``stream``'s rows batch by batch (ITL-1464). + + 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 + + +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.""" + 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: """Whether every system-tag column is what the row rebuild gives: non-null text. @@ -1591,11 +1610,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 result of more than + ``RUN_VIEW_COMPLETE_ROWS`` rows 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 +1629,36 @@ 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(): + view = self._run_in_batches() + if view is not None: + return view 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 | None: + """The ``run()`` view of rows read batch by batch; ``None`` for no batch.""" + 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) + if rows.total == 0: + return None + 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( diff --git a/src/orcapod/core/streams/view.py b/src/orcapod/core/streams/view.py index 699de9401..373c76216 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,12 @@ 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; of a larger one, the view has the first and the last +# ``RUN_VIEW_WINDOW_ROWS`` rows (ITL-1464). Counted in rows, so equal data is always +# treated alike, however its batches were cut. +RUN_VIEW_COMPLETE_ROWS = 50_000 +RUN_VIEW_WINDOW_ROWS = 1_000 _MAX_TEXT = 80 _TEXT_START = 56 _TEXT_END = 20 @@ -603,6 +611,10 @@ 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, which names its row count.""" + return rendered + 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 +637,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 +666,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 +691,230 @@ 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 _with_row_count(self, rendered: str) -> str: + # Polars names the frame's shape before anything else it renders. + return rendered.replace( + f"shape: ({self.table.num_rows:_}, ", f"shape: ({self.shown_total:_}, ", 1 + ) + + +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 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()})" + ) + + +class WindowOfRows: + """Collects the tables of a stream's rows, batch by batch: all rows of a result of + at most ``RUN_VIEW_COMPLETE_ROWS`` rows, 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.total: int = 0 + 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.total += table.num_rows + if self._all is not None: + self._all.append(table) + if self.total > RUN_VIEW_COMPLETE_ROWS: + self._all = None + + @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/errors.py b/src/orcapod/errors.py index 7720e7980..492f411ad 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -1267,6 +1267,14 @@ def __str__(self) -> str: ) +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/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index c8c72abd6..ad079e67e 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -280,7 +280,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. diff --git a/tests/test_core/streams/test_bounded_run_view.py b/tests/test_core/streams/test_bounded_run_view.py new file mode 100644 index 000000000..c6462d038 --- /dev/null +++ b/tests/test_core/streams/test_bounded_run_view.py @@ -0,0 +1,471 @@ +"""``run()`` over a source read on demand: batches, and a bounded view (ITL-1464). + +The differential compares the batch-wise result with the result of the operators over the +whole input (``as_table()`` of a stream that was never run), for every column group. Runs +against the disk-backed fake of the SpiralDB client. +""" + +from __future__ import annotations + +import pickle +import uuid +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import polars as pl +import pyarrow as pa +import pytest + +from orcapod import col, function_pod +from orcapod.core.operators import DropNulls, MapData +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams import base, view as view_module +from orcapod.core.streams.view import BoundedStreamView, StreamView, WindowOfRows +from orcapod.errors import BoundedViewError, RowIdentifierError, SourceTooLargeError +from orcapod.sources import SpiralDBTableSource +from orcapod.streams import ViewStatus +from tests.test_databases import fake_spiral_sdk + +_PROJECT = "sample" +_KEYS = pa.schema( + [pa.field("subject", pa.string()), pa.field("timestamp", pa.uint64())] +) + + +def _rows(n: int) -> pa.Table: + """``n`` rows: two keys, data with nulls, strings longer than the display shows.""" + return pa.table( + { + "subject": [f"m{i * 3 // max(n, 1)}" for i in range(n)], + "timestamp": pa.array(range(n), pa.uint64()), + "amplitude": pa.array( + [None if i % 7 == 3 else i + 0.5 for i in range(n)], pa.float32() + ), + "note": [f"{i:04d}" + "a" * (200 if i % 5 == 0 else 3) for i in range(n)], + "trace": pa.array( + [[float(i)] * (i % 4) for i in range(n)], pa.list_(pa.float64()) + ), + "flag": [i % 2 == 0 for i in range(n)], + } + ) + + +@pytest.fixture() +def source(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """Make a source of ``n`` rows (default 40), scanned 6 rows per batch.""" + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 6) + with fake_spiral_sdk.install(tmp_path / "spiral"): + + def make(n: int = 40, **kwargs: Any) -> SpiralDBTableSource: + name = f"event_{n}" + project = fake_spiral_sdk.ExternalProject(_PROJECT) + try: + return SpiralDBTableSource(_PROJECT, name, **kwargs) + except Exception: # noqa: BLE001 - not made yet + project.create_table(f"default.{name}", key_schema=_KEYS).write( + _rows(n) + ) + return SpiralDBTableSource(_PROJECT, name, **kwargs) + + yield make + + +@pytest.fixture() +def small_limits(monkeypatch: pytest.MonkeyPatch) -> None: + """A result of more than 20 rows is bounded, with a window of 12 rows.""" + monkeypatch.setattr(view_module, "RUN_VIEW_COMPLETE_ROWS", 20) + monkeypatch.setattr(view_module, "RUN_VIEW_WINDOW_ROWS", 12) + import orcapod.core.operators.static_output_pod as pods + + monkeypatch.setattr(pods, "RUN_VIEW_COMPLETE_ROWS", 20) + + +CHAINS: dict[str, Callable[[Any], Any]] = { + "source": lambda s: s, + "drop_nulls": lambda s: s.drop_nulls(["amplitude", "note"]), + "drop_nulls_all": lambda s: s.drop_nulls(), + "filter": lambda s: s.filter(col("amplitude") >= 5.0, flag=True), + "filter_none_left": lambda s: s.filter(col("amplitude") >= 1e6), + "map_data": lambda s: s.map_data({"note": "text", "amplitude": "uv"}), + "map_tags": lambda s: s.map_tags({"timestamp": "t", "subject": "who"}), + "map_columns": lambda s: s.map_columns({"timestamp": "t", "note": "text"}), + "add_tags": lambda s: s.add_tags(cohort="A", run=3), + "select_tags": lambda s: s.select_tag_columns(["timestamp"]), + "select_data": lambda s: s.select_data_columns(["note", "amplitude"]), + "select_data_pass_through": lambda s: s.select_data_columns(list(s.keys()[1])), + "drop_tags": lambda s: s.drop_tag_columns(["subject", "timestamp"]), + "drop_data": lambda s: s.drop_data_columns(["trace", "note"]), + "select": lambda s: s.select_columns("timestamp", "note", "flag"), + "drop": lambda s: s.drop_columns("subject", "trace"), + "several": lambda s: ( + s.drop_nulls(["amplitude"]) + .filter(flag=True) + .map_data({"note": "text"}) + .add_tags(cohort="A") + .drop_columns("trace") + ), +} + +CONFIGS: list[dict[str, Any]] = [ + {}, + {"source": True, "system_tags": True}, + {"context": True}, + {"content_hash": True}, + {"sort_by_tags": True}, + {"all_info": True}, +] + + +def _same(left: pa.Table, right: pa.Table) -> None: + assert left.schema.equals(right.schema, check_metadata=True) + assert left.equals(right) + + +@pytest.mark.parametrize("tag_only", [True, False, ["timestamp"]]) +@pytest.mark.parametrize("batch_rows", [1, 5, 8192]) +@pytest.mark.parametrize("name", list(CHAINS)) +def test_the_batches_give_the_whole( + source: Any, name: str, batch_rows: int, tag_only: Any +) -> None: + """Rows, order, types, nullability, tokens, record ids and row hashes are those of + the operators over the whole input; the kept result is the one a read keeps.""" + + def stream() -> Any: + if name == "map_columns" and tag_only is not True: + pytest.skip("MapColumns takes no data-tags yet (ITL-1022)") + return CHAINS[name](source(batch_rows=batch_rows, tag_only_columns=tag_only)) + + whole = stream() + ran = stream() + assert base.reads_in_batches(ran) + view = ran.run() + assert type(view) is StreamView + _same(view.as_table(), whole.as_table()) + for config in CONFIGS: + _same(ran.as_table(columns=config), whole.as_table(columns=config)) + assert ran.keys() == whole.keys() + assert ran.content_hash() == whole.content_hash() + assert [(t.as_dict(all_info=True), d.content_hash()) for t, d in ran] == [ + (t.as_dict(all_info=True), d.content_hash()) for t, d in whole + ] + + +@pytest.mark.parametrize("name", list(CHAINS)) +def test_a_small_run_shows_what_the_whole_shows(source: Any, name: str) -> None: + """Header, text and HTML of a small result are those of a view of the whole.""" + ran = CHAINS[name](source(tag_only_columns=True)) + view = ran.run() + whole = CHAINS[name](source(tag_only_columns=True)) + expected = whole._view_of_rows(whole.as_table(), whole._RUN_ORIGIN) # pyright: ignore[reportPrivateUsage] # the view as it was built before + assert view.header() == expected.header() + assert str(view) == str(expected) + assert view._repr_html_() == expected._repr_html_() + assert ran.head(3).header() == whole.head(3).header() + assert ran.head(3).table.equals(whole.head(3).table) + assert ran._repr_html_() == whole._repr_html_() + + +def test_a_run_of_at_most_the_limit_is_kept_and_reads_once(source: Any) -> None: + """A small result is kept at every step of the chain: no second scan.""" + first = source().drop_nulls(["amplitude"]) + out = first.map_data({"note": "text"}) + fake_spiral_sdk.scan_log.clear() + view = out.run() + scans = len(fake_spiral_sdk.scan_log) + assert out.as_table().equals(view.as_table()) + assert out.run().as_table().equals(view.as_table()) + assert first.head(2).status is ViewStatus.ROWS + assert len(first.as_table()) == len(view) + assert len(fake_spiral_sdk.scan_log) == scans + + +# --------------------------------------------------------------------------- +# The bounded view +# --------------------------------------------------------------------------- + + +def _bounded_and_complete(stream: Any) -> tuple[BoundedStreamView, StreamView]: + view = stream.run() + assert isinstance(view, BoundedStreamView) + table = stream.as_table() + return view, stream._view_of_rows(table, stream._RUN_ORIGIN) # the complete view + + +@pytest.mark.usefixtures("small_limits") +@pytest.mark.parametrize("n", [33, 40, 1200]) +@pytest.mark.parametrize("name", ["source", "map_data", "drop_nulls", "several"]) +def test_a_bounded_view_is_displayed_as_the_complete_one( + source: Any, name: str, n: int +) -> None: + """Header, legend, shape line and rows, in text and HTML.""" + chain = CHAINS[name] + if name == "several" and n < 100: + pytest.skip("leaves fewer rows than the limit") + view, complete = _bounded_and_complete(chain(source(n))) + assert view.header() == complete.header() + assert str(view) == str(complete) + assert view._repr_html_() == complete._repr_html_() + assert repr(view) == repr(complete) + assert view.total_rows == complete.total_rows == len(view) == len(complete) + assert view.status is complete.status + assert view.tag_columns == complete.tag_columns + assert view.data_tag_columns == complete.data_tag_columns + + +@pytest.mark.usefixtures("small_limits") +def test_head_and_tail_within_the_window_are_the_complete_views(source: Any) -> None: + """Rows and header; and the cuts and sorts of those.""" + view, complete = _bounded_and_complete(source().map_data({"note": "text"})) + for n in (0, 1, 5, 12): + for cut in ("head", "tail"): + mine, theirs = getattr(view, cut)(n), getattr(complete, cut)(n) + assert type(mine) is StreamView + _same(mine.as_table(), theirs.as_table()) + assert mine.header() == theirs.header() + assert str(mine) == str(theirs) + assert mine.sort_by_tags().header() == theirs.sort_by_tags().header() + assert view.head(8).tail(3).header() == complete.head(8).tail(3).header() + assert view.tail(8).head(3).header() == complete.tail(8).head(3).header() + + +@pytest.mark.usefixtures("small_limits") +@pytest.mark.parametrize( + "ask", + [ + lambda v: v.as_table(), + lambda v: v.as_polars_df(), + lambda v: v.table, + lambda v: v.sort_by_tags(), + lambda v: v.head(13), + lambda v: v.tail(13), + ], + ids=["as_table", "as_polars_df", "table", "sort_by_tags", "head", "tail"], +) +def test_what_needs_rows_not_held_is_refused( + source: Any, ask: Callable[[Any], Any] +) -> None: + """A part is never given as the whole; the error names the stream's method.""" + view = source().run() + with pytest.raises(BoundedViewError, match=r"stream\.as_table\(\)"): + ask(view) + + +@pytest.mark.usefixtures("small_limits") +def test_a_bounded_view_checks_the_number_of_rows(source: Any) -> None: + """As a complete view does, before the window.""" + view = source().run() + with pytest.raises(TypeError): + view.head(True) + with pytest.raises(ValueError, match="negative"): + view.tail(-1) + with pytest.raises(AttributeError): + _ = view.no_such_member + assert len(pickle.loads(pickle.dumps(view))) == len(view) + + +@pytest.mark.usefixtures("small_limits") +@pytest.mark.parametrize("n", [19, 20, 21]) +def test_the_limit_is_counted_in_rows_whatever_the_batches(source: Any, n: int) -> None: + """Equal data gives the same kind of view: however cut, run again, or already read.""" + for batch_rows in (1, 7, 8192): + stream = source(n, batch_rows=batch_rows).map_data({"note": "text"}) + bounded = n > 20 + assert isinstance(stream.run(), BoundedStreamView) is bounded + assert isinstance(stream.run(), BoundedStreamView) is bounded + _ = stream.as_table() # the stream now holds every row + assert isinstance(stream.run(), BoundedStreamView) is bounded + assert ( + isinstance(source(n, batch_rows=batch_rows).run(), BoundedStreamView) + is bounded + ) + + +@pytest.mark.usefixtures("small_limits") +def test_head_after_a_large_run_shows_the_window(source: Any) -> None: + """Default columns, within the window, while the inputs are unchanged.""" + stream = source().drop_nulls(["amplitude"]) + view = stream.run() + fake_spiral_sdk.scan_log.clear() + assert stream.head(3).table.equals(view.head(3).table) + assert stream.head(3).header() == view.head(3).header() + assert "first 10 of 34 computed rows, then sorted by tags" in stream._repr_html_() + assert stream.head(3, columns={"source": True}).status is ViewStatus.NOT_COMPUTED + assert stream.head(13).status is ViewStatus.NOT_COMPUTED + assert fake_spiral_sdk.scan_log == [] + stream.clear_cache() + assert stream.head(3).status is ViewStatus.NOT_COMPUTED + + +@pytest.mark.usefixtures("small_limits") +def test_head_after_the_source_moved_shows_no_old_rows(source: Any) -> None: + """The window is not shown once an input changed.""" + root = source() + stream = root.map_data({"note": "text"}) + _ = stream.run() + fake_spiral_sdk.ExternalProject(_PROJECT).table("default.event_40").write( + _rows(41).slice(40) + ) + assert root.check_for_new_data() + assert stream.head(3).status is ViewStatus.NOT_COMPUTED + assert len(stream.run()) == 41 + + +@pytest.mark.usefixtures("small_limits") +def test_reads_after_a_large_run_give_every_row(source: Any) -> None: + """``as_table()`` and iteration read again; a bounded run keeps no rows.""" + stream = CHAINS["several"](source(200)) + assert isinstance(stream.run(), BoundedStreamView) + whole = CHAINS["several"](source(200)) + _same(stream.as_table(), whole.as_table()) + assert len(list(stream)) == whole.as_table().num_rows + + +# --------------------------------------------------------------------------- +# Errors +# --------------------------------------------------------------------------- + + +class _Refusing(DropNulls): + """Reads its input, then raises when there are rows.""" + + BATCHES_GIVE_THE_WHOLE = True + + def unary_static_process(self, stream: Any) -> Any: + if stream.as_table().num_rows: + raise RuntimeError("the operator refused") + return super().unary_static_process(stream) + + +def test_max_rows_holds_for_the_whole_read(source: Any) -> None: + """The read is refused as ``as_table()`` refuses it; no view is returned.""" + for make in ( + lambda: source(max_rows=30), + lambda: source(max_rows=30, where={"flag": True}, limit=25), + ): + stream = make().map_data({"note": "text"}) + try: + expected: object = len(make().as_table()) + except SourceTooLargeError as error: + expected = str(error) + try: + found: object = len(stream.run()) + except SourceTooLargeError as error: + found = str(error) + assert found == expected + late = source(max_rows=10, where={"flag": True}) + with pytest.raises(SourceTooLargeError): + _ = late.drop_nulls().run() + assert len(late.drop_nulls().head()) == 0 + + +def test_a_late_source_error_is_raised_as_a_whole_read_raises_it( + source: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """Also before an operator's own error on an earlier batch.""" + root = source(batch_rows=6) + original = SpiralDBTableSource._key_tokens # pyright: ignore[reportPrivateUsage] # a failing row, late + + def failing(self: Any, table: pa.Table) -> list[str]: + if 30 in table.column("timestamp").to_pylist(): + raise RowIdentifierError("a null key, late") + return original(self, table) + + monkeypatch.setattr(SpiralDBTableSource, "_key_tokens", failing) + for stream in (root.map_data({"note": "text"}), _Refusing(["amplitude"])(root)): + with pytest.raises(RowIdentifierError, match="late"): + _ = stream.as_table() + with pytest.raises(RowIdentifierError, match="late"): + _ = stream.run() + assert stream.head().status is ViewStatus.NOT_COMPUTED + + +def test_an_operator_error_keeps_nothing(source: Any) -> None: + """The operator's error is raised, and nothing is shown after it.""" + stream = _Refusing(["amplitude"])(source()) + with pytest.raises(RuntimeError, match="refused"): + _ = stream.run() + assert stream.head().status is ViewStatus.NOT_COMPUTED + + +# --------------------------------------------------------------------------- +# What is not read in batches +# --------------------------------------------------------------------------- + + +class _Subclass(MapData): + """A subclass may change what an operator does: it declares batches itself.""" + + +def test_only_declared_operators_over_an_on_demand_source_are_batched( + source: Any, +) -> None: + """Everything else computes as before, and its view holds every row.""" + + @function_pod(output_keys="double") + def double(amplitude: float) -> float: + return 2 * amplitude + + root = source() + held = ArrowTableSource(_rows(40), tag_columns=["subject"]) + clean = root.drop_nulls(["amplitude"]) + for stream in ( + held, + held.drop_nulls(), + _Subclass({"note": "text"})(root), + clean.polars_filter(pl.col("flag")), + clean.group_by("subject"), + clean.batch(4), + clean.join(held.select_data_columns(["flag"]).map_data({"flag": "f"})), + double.pod(clean), + MapData({"double": "d"})(double.pod(clean)), + ): + assert not base.reads_in_batches(stream) + assert not isinstance(stream, SpiralDBTableSource) + assert "BATCHES_GIVE_THE_WHOLE" not in vars(_Subclass) + assert StaticOutputOperatorPod.BATCHES_GIVE_THE_WHOLE is False + + +# --------------------------------------------------------------------------- +# The window +# --------------------------------------------------------------------------- + + +def _column(kind: pa.DataType, rows: int) -> pa.Array[Any]: + if kind == pa.uuid(): + storage = pa.array([uuid.UUID(int=i).bytes for i in range(rows)], pa.binary(16)) + return pa.ExtensionArray.from_storage(pa.uuid(), storage) + return pa.array([None if i % 5 == 4 else i for i in range(rows)], pa.int64()).cast( + kind + ) + + +@pytest.mark.parametrize("cut", [1, 3, 8, 50]) +def test_the_window_is_the_first_and_last_rows( + monkeypatch: pytest.MonkeyPatch, cut: int +) -> None: + """Whatever the batches, for every kind of column; and it holds no batch.""" + monkeypatch.setattr(view_module, "RUN_VIEW_COMPLETE_ROWS", 20) + monkeypatch.setattr(view_module, "RUN_VIEW_WINDOW_ROWS", 8) + table = pa.table( + { + "i": _column(pa.int64(), 50), + "half": _column(pa.float32(), 50).cast(pa.float16()), + "text": _column(pa.large_string(), 50), + "uuid": _column(pa.uuid(), 50), + "decimal": _column(pa.decimal256(30, 2), 50), + "lists": pa.array([[i] * (i % 3) for i in range(50)]), + "structs": pa.array([{"a": i, "b": [str(i)]} for i in range(50)]), + "maps": pa.array( + [[(i, "x")] for i in range(50)], pa.map_(pa.int64(), pa.string()) + ), + } + ) + window = WindowOfRows() + for start in range(0, 50, cut): + window.add(table.slice(start, cut)) + assert window.total == 50 + assert window.complete is None + _same(window.first, table.slice(0, 8)) + _same(window.last, table.slice(42)) From d57d26e9cb997318785490b45c072fc87f5679b7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:43:20 -0800 Subject: [PATCH 3/5] docs(dev): round the measured sizes in the views spec Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-views.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/dev/specs/itl-1464-views.md b/docs/dev/specs/itl-1464-views.md index dd54dd169..19301738d 100644 --- a/docs/dev/specs/itl-1464-views.md +++ b/docs/dev/specs/itl-1464-views.md @@ -54,7 +54,7 @@ the window. | Member | Bounded view | |---|---| -| `total_rows`, schema, `status`, `header()` | as the complete view: `all 2,177,155 rows` | +| `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 | @@ -123,13 +123,13 @@ never computes. 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, 2,177,155 rows of the gaze shape, before and after, for the source, a rename, a +- 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 shaped as one session of gaze (2,177,155 rows, 13 -columns, 248 MiB of Arrow data; the diagnosis's table), peak resident memory, one process +`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 | From 2da7b22f2ef65d9f579dbc9067347af206d430c6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:15:53 -0800 Subject: [PATCH 4/5] fix(streams): see every change beneath a chain that keeps nothing; scan an empty source once (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-views.md | 10 ++ .../core/operators/static_output_pod.py | 26 +++- .../core/sources/spiraldb_table_source.py | 14 +- src/orcapod/core/streams/base.py | 13 +- src/orcapod/core/streams/view.py | 3 +- .../streams/test_bounded_run_view.py | 145 ++++++++++++++++++ 6 files changed, 197 insertions(+), 14 deletions(-) diff --git a/docs/dev/specs/itl-1464-views.md b/docs/dev/specs/itl-1464-views.md index 19301738d..fb1904979 100644 --- a/docs/dev/specs/itl-1464-views.md +++ b/docs/dev/specs/itl-1464-views.md @@ -142,3 +142,13 @@ per row: 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. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 6179a5066..5149cf697 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -2101,10 +2101,8 @@ def _batch_streams_of_rows(self) -> Generator[StreamProtocol, None, None]: yield result if kept: self._cached_stream = ( - # Its input unchanged, as a read keeps it: reads nothing. - self._pod.static_process(*self._upstreams) - if handed_on - else joined_batches(kept) + # 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 @@ -2332,10 +2330,30 @@ 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 + + def _upstream_states( upstreams: tuple[StreamProtocol, ...], ) -> tuple[tuple[str, object], ...]: diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 316ac347d..d67578527 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -1135,18 +1135,30 @@ def _reads_in_batches(self) -> bool: 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).""" + columns = {"source": True, "system_tags": True, "context": True} + read = False with closing(self._batch_streams()) as streams: for stream in streams: + read = True yield ArrowTableStream( self._whole_table( iter([stream]), - columns={"source": True, "system_tags": True, "context": True}, + columns=columns, all_info=False, ), 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( + self._stream.as_table(columns=columns), + tag_columns=self._tag_columns, + data_tags=self._data_tags, + data_context=self.data_context_key, + ) def run(self) -> StreamView: """Read every row the source reads and return a ``StreamView`` of them. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index c3296bec4..79d23ca7f 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -99,7 +99,8 @@ def reads_in_batches(stream: object) -> bool: 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.""" + """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 @@ -1632,9 +1633,7 @@ def run(self) -> StreamView: ``ROWS``; bounded as said above. """ if self._reads_in_batches(): - view = self._run_in_batches() - if view is not None: - return view + return self._run_in_batches() return self._view_of_rows(self.as_table(), self._RUN_ORIGIN) def _reads_in_batches(self) -> bool: @@ -1645,8 +1644,8 @@ 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 | None: - """The ``run()`` view of rows read batch by batch; ``None`` for no batch.""" + 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: @@ -1654,8 +1653,6 @@ def _run_in_batches(self) -> StreamView | None: complete = rows.complete if complete is not None: return self._view_of_rows(complete, self._RUN_ORIGIN) - if rows.total == 0: - return None first = self._view_of_rows(rows.first, self._RUN_ORIGIN) return BoundedStreamView(first, rows.last, rows.total) diff --git a/src/orcapod/core/streams/view.py b/src/orcapod/core/streams/view.py index 373c76216..204948373 100644 --- a/src/orcapod/core/streams/view.py +++ b/src/orcapod/core/streams/view.py @@ -194,7 +194,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 diff --git a/tests/test_core/streams/test_bounded_run_view.py b/tests/test_core/streams/test_bounded_run_view.py index c6462d038..db86dced5 100644 --- a/tests/test_core/streams/test_bounded_run_view.py +++ b/tests/test_core/streams/test_bounded_run_view.py @@ -167,6 +167,14 @@ def test_a_small_run_shows_what_the_whole_shows(source: Any, name: str) -> None: assert ran._repr_html_() == whole._repr_html_() +def test_a_pass_through_run_scans_once(source: Any) -> None: + """An operator that hands its input on keeps its input, without a second scan.""" + stream = CHAINS["select_data_pass_through"](source()) + fake_spiral_sdk.scan_log.clear() + assert len(stream.run()) == 40 + assert len(fake_spiral_sdk.scan_log) == 1 + + def test_a_run_of_at_most_the_limit_is_kept_and_reads_once(source: Any) -> None: """A small result is kept at every step of the chain: no second scan.""" first = source().drop_nulls(["amplitude"]) @@ -312,6 +320,143 @@ def test_head_after_the_source_moved_shows_no_old_rows(source: Any) -> None: assert len(stream.run()) == 41 +def _change_rows(name: str, rows: pa.Table) -> None: + fake_spiral_sdk.ExternalProject(_PROJECT).table(f"default.{name}").write(rows) + + +def _changes_source(root: Any, _steps: list[Any]) -> None: + changed = ( + _rows(40).slice(0, 1).set_column(2, "amplitude", pa.array([1e6], pa.float32())) + ) + _change_rows("event_40", changed) + assert root.check_for_new_data() + + +def _clears_the_intermediate(_root: Any, steps: list[Any]) -> None: + steps[0].clear_cache() + + +def _reruns_an_operator(_root: Any, steps: list[Any]) -> None: + steps[0].producer._update_modified_time() + + +_UPSTREAM_CHANGES = [_changes_source, _clears_the_intermediate, _reruns_an_operator] + +_READS_BEFORE: dict[str, Callable[[Any, list[Any]], None]] = { + "nothing": lambda root, steps: None, + "ran_the_intermediate": lambda root, steps: steps[0].run(), + "read_the_intermediate": lambda root, steps: steps[0].as_table(), +} + + +@pytest.mark.usefixtures("small_limits") +@pytest.mark.parametrize("change", _UPSTREAM_CHANGES) +@pytest.mark.parametrize("before", list(_READS_BEFORE)) +@pytest.mark.parametrize("when", ["before_run", "after_run"]) +@pytest.mark.parametrize("depth", [1, 3]) +@pytest.mark.parametrize("small", [True, False], ids=["retained", "window"]) +def test_no_result_is_shown_or_read_after_an_upstream_change( + source: Any, change: Any, before: str, when: str, depth: int, small: bool +) -> None: + """Review of PR 560 (blocker): an intermediate that kept nothing hid a change. + + The last step keeps its complete (small) result or its window, over intermediates + above the limit; a change of the source, a cleared intermediate or a modified + operator is seen by ``head``, the preview, ``as_table()``, ``run()`` and a step + over it, also when the intermediate was run or read on its own. + """ + root = source() + + def build(over: Any) -> list[Any]: + steps = [over.map_data({"note": "text"})] + for i in range(depth - 1): + steps.append(steps[-1].add_tags({f"extra_{i}": i})) + if small: + steps.append(steps[-1].filter(col("amplitude") >= 1e5)) + else: + steps.append(steps[-1].map_data({"text": "words"})) + return steps + + steps = build(root) + last = steps[-1] + over_last = last.add_tags(cohort="A") + if when == "before_run": + _ = _READS_BEFORE[before](root, steps) + assert isinstance(last.run(), BoundedStreamView) is not small + _ = over_last.run() + if when == "after_run": + _ = _READS_BEFORE[before](root, steps) + assert last.head(1).status is ViewStatus.ROWS # not a change + assert over_last.head(1).status is ViewStatus.ROWS + + change(root, steps) + + for stream in (over_last, last): + assert stream.head(1).status is ViewStatus.NOT_COMPUTED or small + if small: + assert "computed rows" not in stream.head(1).header() + assert "computed: no rows" not in stream.head(1).header() + assert "then sorted by tags" not in stream._repr_html_() + fresh = build(source()) + _same(last.as_table(), fresh[-1].as_table()) + _same(over_last.as_table(), fresh[-1].add_tags(cohort="A").as_table()) + assert len(last.run()) == len(fresh[-1].as_table()) + assert over_last.run().total_rows == len(fresh[-1].as_table()) + + +@pytest.mark.usefixtures("small_limits") +@pytest.mark.parametrize("change", _UPSTREAM_CHANGES) +def test_every_step_over_a_shared_intermediate_sees_a_change( + source: Any, change: Any +) -> None: + """Two branches, a function pod and a join over one intermediate that kept nothing.""" + + @function_pod(output_keys="double") + def double(amplitude: float | None) -> float: + return 2 * (amplitude or 0.0) + + def build(over: Any) -> tuple[list[Any], list[Any]]: + shared = over.map_data({"note": "text"}) + one = shared.filter(col("amplitude") >= 1e5) + two = shared.add_tags(cohort="A").filter(col("amplitude") >= 30.0) + joined = one.map_data( + {"amplitude": "a", "text": "b", "trace": "c", "flag": "d"} + ).join(two) + grouped = two.group_by("subject") + return [shared], [one, two, double.pod(two), joined, grouped] + + root = source(tag_only_columns=True) + shared, ends = build(root) + for stream in (*shared, *ends): + _ = stream.run() + change(root, shared) + _, fresh = build(source(tag_only_columns=True)) + for stream, expected in zip(ends, fresh, strict=True): + _same(stream.as_table(), expected.as_table()) + + +@pytest.mark.parametrize("name", list(CHAINS)) +@pytest.mark.parametrize("restriction", [{"subject": "absent"}, None]) +def test_a_read_of_no_rows_scans_once(source: Any, name: str, restriction: Any) -> None: + """Review of PR 560: an empty source was scanned twice; its result is typed the same.""" + n = 40 if restriction else 1 + kwargs: dict[str, Any] = {"tag_only_columns": True, "where": restriction} + if restriction is None: + kwargs["where"] = {"timestamp": 7} + whole = CHAINS[name](source(n, **kwargs)) + ran = CHAINS[name](source(n, **kwargs)) + fake_spiral_sdk.scan_log.clear() + view = ran.run() + assert len(fake_spiral_sdk.scan_log) == 1 + assert view.total_rows == 0 + assert view.status is ViewStatus.ROWS + _same(view.as_table(), whole.as_table()) + for config in CONFIGS: + _same(ran.as_table(columns=config), whole.as_table(columns=config)) + expected = whole._view_of_rows(whole.as_table(), whole._RUN_ORIGIN) + assert str(view) == str(expected) + + @pytest.mark.usefixtures("small_limits") def test_reads_after_a_large_run_give_every_row(source: Any) -> None: """``as_table()`` and iteration read again; a bounded run keeps no rows.""" From 19e1bfed3cbfa3b854bb58e9725f6a5d5a32ff5e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:51:06 -0800 Subject: [PATCH 5/5] fix(streams): ask each stream's state once; bound a kept run() result by its values (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1464.md | 2 +- docs/concepts/streams.md | 7 +- docs/dev/specs/itl-1464-views.md | 10 +- .../core/operators/static_output_pod.py | 45 +++++-- .../core/sources/spiraldb_table_source.py | 2 +- src/orcapod/core/streams/base.py | 4 +- src/orcapod/core/streams/view.py | 87 +++++++++++-- .../streams/test_bounded_run_view.py | 122 ++++++++++++++++-- 8 files changed, 242 insertions(+), 37 deletions(-) diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md index be50b516d..996ee7dd7 100644 --- a/changelog.d/ITL-1464.md +++ b/changelog.d/ITL-1464.md @@ -2,7 +2,7 @@ - `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 (ITL-1464). The view then has the row count and the first and the + 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 diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index 0ecf17a1b..63f89939f 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -214,14 +214,15 @@ 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 is held, as everywhere else. A larger one is not: its view has +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 row count, so equal data +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`. @@ -241,7 +242,7 @@ 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 in batches (`head()` is the bounded read); every call reads again; a bounded view above 50,000 rows | +| 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-views.md b/docs/dev/specs/itl-1464-views.md index fb1904979..e7a6a7050 100644 --- a/docs/dev/specs/itl-1464-views.md +++ b/docs/dev/specs/itl-1464-views.md @@ -32,8 +32,9 @@ end the chain: they compute as today. 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** (all column groups; counted in rows, - not bytes, so equal data is treated alike however its batches are cut). A result that ends +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 @@ -103,7 +104,7 @@ never computes. | 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 | approved at 64 MiB; implemented as 50,000 rows (bytes differ with the batches and with what is already held), first and last 1,000 rows; constants, no config yet | +| 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 | @@ -152,3 +153,6 @@ its generation, its operator's modified time and the state of its own input, dow 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. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 5149cf697..1851b1ce5 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -14,6 +14,7 @@ Sequence, ) from contextlib import closing +from contextvars import ContextVar from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, cast @@ -57,8 +58,8 @@ row_built_columns, ) from orcapod.core.streams.view import ( - RUN_VIEW_COMPLETE_ROWS, BoundedStreamView, + RunSize, STALE_NOTE, default_note, ViewStatus, @@ -2066,8 +2067,8 @@ 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 of at most ``RUN_VIEW_COMPLETE_ROWS`` rows is kept, as a read keeps it; - a larger one is not. A current kept result is given as it is. + 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() @@ -2080,7 +2081,7 @@ def _batch_streams_of_rows(self) -> Generator[StreamProtocol, None, None]: return kept_states = _upstream_states(self._upstreams) kept: list[StreamProtocol] | None = [] - rows = 0 + size = RunSize() handed_on = True with closing(batch_streams_of(self._upstreams[0])) as batches: for batch in batches: @@ -2093,10 +2094,10 @@ def _batch_streams_of_rows(self) -> Generator[StreamProtocol, None, None]: pass raise handed_on = handed_on and result is batch - rows += result.as_table().num_rows + size.add(result.as_table()) if kept is not None: kept.append(result) - if rows > RUN_VIEW_COMPLETE_ROWS: + if not size.is_kept: kept = None yield result if kept: @@ -2112,7 +2113,7 @@ 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 result of more than ``RUN_VIEW_COMPLETE_ROWS`` rows is not held: the + 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. """ @@ -2354,8 +2355,34 @@ def _chain_state(stream: DynamicPodStream) -> 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/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index d67578527..efcfb4acc 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -1164,7 +1164,7 @@ def run(self) -> StreamView: """Read every row the source reads and return a ``StreamView`` of them. One scan (``where``, ``limit``, ``max_rows`` and the pinned version applied), - read in batches: a table of more than ``RUN_VIEW_COMPLETE_ROWS`` rows gives a + 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/streams/base.py b/src/orcapod/core/streams/base.py index 79d23ca7f..747d61607 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1619,8 +1619,8 @@ def run(self) -> StreamView: 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 result of more than - ``RUN_VIEW_COMPLETE_ROWS`` rows gives a ``BoundedStreamView``. For other + 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 diff --git a/src/orcapod/core/streams/view.py b/src/orcapod/core/streams/view.py index 204948373..ce5c333ec 100644 --- a/src/orcapod/core/streams/view.py +++ b/src/orcapod/core/streams/view.py @@ -115,10 +115,13 @@ def default_note(status: ViewStatus) -> str: # 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; of a larger one, the view has the first and the last -# ``RUN_VIEW_WINDOW_ROWS`` rows (ITL-1464). Counted in rows, so equal data is always -# treated alike, however its batches were cut. +# ``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 @@ -756,7 +759,8 @@ def _refused(self, what: str) -> BoundedViewError: 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 read in batches. Ask the " + 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)." ) @@ -861,14 +865,74 @@ def __repr__(self) -> str: ) +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 of - at most ``RUN_VIEW_COMPLETE_ROWS`` rows, else the first and the last + """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.total: int = 0 + self._size: RunSize = RunSize() self._all: list[pa.Table] | None = [] self._first: list[pa.Table] = [] self._last: deque[pa.Table] = deque() @@ -888,12 +952,17 @@ def add(self, table: pa.Table) -> None: 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.total += table.num_rows + self._size.add(table) if self._all is not None: self._all.append(table) - if self.total > RUN_VIEW_COMPLETE_ROWS: + 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).""" diff --git a/tests/test_core/streams/test_bounded_run_view.py b/tests/test_core/streams/test_bounded_run_view.py index db86dced5..7c6a81495 100644 --- a/tests/test_core/streams/test_bounded_run_view.py +++ b/tests/test_core/streams/test_bounded_run_view.py @@ -74,12 +74,9 @@ def make(n: int = 40, **kwargs: Any) -> SpiralDBTableSource: @pytest.fixture() def small_limits(monkeypatch: pytest.MonkeyPatch) -> None: - """A result of more than 20 rows is bounded, with a window of 12 rows.""" + """A result of more than 20 rows is bounded, with a window of 10 rows.""" monkeypatch.setattr(view_module, "RUN_VIEW_COMPLETE_ROWS", 20) - monkeypatch.setattr(view_module, "RUN_VIEW_WINDOW_ROWS", 12) - import orcapod.core.operators.static_output_pod as pods - - monkeypatch.setattr(pods, "RUN_VIEW_COMPLETE_ROWS", 20) + monkeypatch.setattr(view_module, "RUN_VIEW_WINDOW_ROWS", 10) CHAINS: dict[str, Callable[[Any], Any]] = { @@ -226,7 +223,7 @@ def test_a_bounded_view_is_displayed_as_the_complete_one( def test_head_and_tail_within_the_window_are_the_complete_views(source: Any) -> None: """Rows and header; and the cuts and sorts of those.""" view, complete = _bounded_and_complete(source().map_data({"note": "text"})) - for n in (0, 1, 5, 12): + for n in (0, 1, 5, 10): for cut in ("head", "tail"): mine, theirs = getattr(view, cut)(n), getattr(complete, cut)(n) assert type(mine) is StreamView @@ -246,8 +243,8 @@ def test_head_and_tail_within_the_window_are_the_complete_views(source: Any) -> lambda v: v.as_polars_df(), lambda v: v.table, lambda v: v.sort_by_tags(), - lambda v: v.head(13), - lambda v: v.tail(13), + lambda v: v.head(11), + lambda v: v.tail(11), ], ids=["as_table", "as_polars_df", "table", "sort_by_tags", "head", "tail"], ) @@ -300,7 +297,7 @@ def test_head_after_a_large_run_shows_the_window(source: Any) -> None: assert stream.head(3).header() == view.head(3).header() assert "first 10 of 34 computed rows, then sorted by tags" in stream._repr_html_() assert stream.head(3, columns={"source": True}).status is ViewStatus.NOT_COMPUTED - assert stream.head(13).status is ViewStatus.NOT_COMPUTED + assert stream.head(11).status is ViewStatus.NOT_COMPUTED assert fake_spiral_sdk.scan_log == [] stream.clear_cache() assert stream.head(3).status is ViewStatus.NOT_COMPUTED @@ -614,3 +611,110 @@ def test_the_window_is_the_first_and_last_rows( assert window.complete is None _same(window.first, table.slice(0, 8)) _same(window.last, table.slice(42)) + + +# --------------------------------------------------------------------------- +# Review of PR 560, round 2 +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("kept", [True, False], ids=["kept", "window"]) +@pytest.mark.parametrize("diamond", [False, True]) +def test_a_cached_preview_asks_each_stream_once( + source: Any, monkeypatch: pytest.MonkeyPatch, kept: bool, diamond: bool +) -> None: + """Blocker: the walk of upstream states was exponential in the depth of a chain.""" + import orcapod.core.operators.static_output_pod as pods + + if not kept: + monkeypatch.setattr(view_module, "RUN_VIEW_COMPLETE_ROWS", 20) + monkeypatch.setattr(view_module, "RUN_VIEW_WINDOW_ROWS", 10) + asked: list[int] = [] + original = pods._upstream_state # pyright: ignore[reportPrivateUsage] # counted + + def counted(stream: Any) -> Any: + asked.append(id(stream)) + return original(stream) + + def visits(depth: int) -> int: + stream: Any = source(40, tag_only_columns=True) + for i in range(depth): + stream = stream.map_data({f"note_{i}" if i else "note": f"note_{i + 1}"}) + if diamond and i % 4 == 3: + # Two branches over one stream, put together again by a join. + left = stream.select_data_columns([f"note_{i + 1}"]) + right = stream.drop_data_columns([f"note_{i + 1}"]) + stream = left.join(right) + _ = stream.run() + assert stream.head(1).status is ViewStatus.ROWS + asked.clear() + _ = stream.head(1) + return len(asked) + + monkeypatch.setattr(pods, "_upstream_state", counted) + # Each stream is asked at most once per outermost question, and head() asks twice + # at most: no growth beyond the number of streams. + assert visits(4) <= 2 * (4 + 3) + assert visits(12) <= 2 * (12 + 9) + assert visits(40) <= 2 * (40 + 30) + + +def test_value_bytes_do_not_depend_on_the_layout() -> None: + """Equal values count the same in any chunks, slices, or null slots' content.""" + from orcapod.core.streams.view import value_bytes + + cases: dict[str, tuple[pa.Array[Any], int]] = { + "int64": (pa.array([1, None, 3]), 24), + "bool": (pa.array([True, None, False]), 3), + "decimal": (pa.array([1, 2], pa.decimal128(5, 0)), 32), + "fixed_binary": (pa.array([b"ab", None], pa.binary(2)), 4), + "string": (pa.array(["a", None, "bcd"]), 4), + "large_string": (pa.array(["a", None, "bcd"], pa.large_string()), 4), + "binary": (pa.array([b"1234", None]), 4), + "null": (pa.nulls(4), 0), + "list": (pa.array([[1, 2], None, []]), 3 * 8 + 16), + "large_list": (pa.array([["ab"], None], pa.large_list(pa.string())), 18), + "fixed_list": (pa.array([[1, 2], [3, 4]], pa.list_(pa.int32(), 2)), 32), + "struct": (pa.array([{"a": 1, "b": "xy"}, {"a": 2, "b": None}]), 18), + "map": (pa.array([[("k", 1)], []], pa.map_(pa.string(), pa.int64())), 25), + "uuid": (_column(pa.uuid(), 3), 48), + } + for name, (array, expected) in cases.items(): + assert value_bytes(array) == expected, name + whole = pa.chunked_array([array]) + pieces = pa.chunked_array([array.slice(i, 1) for i in range(len(array))]) + assert value_bytes(whole) == value_bytes(pieces) == expected, name + # A value under a null struct or list slot is no value. + hidden = pa.StructArray.from_arrays( + [pa.array(["long hidden text", "x"])], ["a"], mask=pa.array([True, False]) + ) + assert value_bytes(hidden) == 1 + + +@pytest.mark.parametrize("batch_rows", [1, 7, 8192]) +@pytest.mark.parametrize("over", [False, True]) +def test_a_wide_result_is_bounded_by_its_values( + source: Any, monkeypatch: pytest.MonkeyPatch, batch_rows: int, over: bool +) -> None: + """Major: 50,000 wide rows were held. The limit is the same however data is cut.""" + from orcapod.core.streams.view import value_bytes + + monkeypatch.setattr(view_module, "RUN_VIEW_WINDOW_ROWS", 10) + chain = CHAINS["map_data"] + size = sum(value_bytes(c) for c in chain(source(40)).as_table().columns) + monkeypatch.setattr(view_module, "RUN_VIEW_COMPLETE_BYTES", size - int(over)) + stream = chain(source(40, batch_rows=batch_rows)) + for _ in range(2): + assert isinstance(stream.run(), BoundedStreamView) is over + _ = stream.as_table() + assert isinstance(stream.run(), BoundedStreamView) is over + + +def test_a_result_that_fits_in_the_windows_is_kept_however_wide( + source: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """Nothing would be saved, and a bounded view has rows the display leaves out.""" + monkeypatch.setattr(view_module, "RUN_VIEW_COMPLETE_BYTES", 0) + monkeypatch.setattr(view_module, "RUN_VIEW_WINDOW_ROWS", 20) + assert type(source(40).run()) is StreamView + assert isinstance(source(41).run(), BoundedStreamView)