diff --git a/changelog.d/ITL-1485.md b/changelog.d/ITL-1485.md new file mode 100644 index 000000000..06928d436 --- /dev/null +++ b/changelog.d/ITL-1485.md @@ -0,0 +1,8 @@ +### Changed + +- A `SpiralDBTableSource` keeps the rows of its last preview (at most 10,000 rows and + 64 MiB). Showing it again, with fewer rows or other columns, makes no call to SpiralDB; it + reads again only for more rows than it read, or after a source check (a job run or + `check_for_new_data()`) moved the version it reads. A preview shows the version the source + last checked, as before. `as_table()`, `as_df()` and `run()` still read the table every + time. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 4f6b04177..4d6484180 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -424,6 +424,17 @@ by tags` when the source reads no more than that, or `10 matching rows read, sor says `first 10 rows of about 63,349`. Tag columns come first, and the line above the table names them. To see more rows, use `as_df()` with a `limit=` or `where=` source. +**A preview is kept.** The source keeps the rows of its last preview, so looking at it again +makes no call to SpiralDB: `head()` again, `head(5)` after `head(10)`, other columns +(`all_info=True`) or the sorted order are shown from the rows already read. It reads again +only when you ask for more rows than it read (it then reads them from the start), or when the +version it reads has moved. A source reads one version of its table, the one it had when the +source was built (or the `asof=` you gave), and only a source check moves it: running a job +over the source, or `check_for_new_data()`. So a preview shows the version the source last +checked; run the job (or check the source) to see newer rows. A preview of more than 10,000 +rows, or 64 MiB, is shown but not kept; `as_table()`, `as_df()` and `run()` read the table +every time, as before. + **Restrictions are not part of identity.** `where`, `limit` and `asof` choose rows of the same table, so two sources on one table have the same `source_id` and `content_hash` whatever their restrictions, and a row's result is computed once and shared. One diff --git a/docs/dev/specs/itl-1485-kept-preview.md b/docs/dev/specs/itl-1485-kept-preview.md new file mode 100644 index 000000000..29fa76407 --- /dev/null +++ b/docs/dev/specs/itl-1485-kept-preview.md @@ -0,0 +1,112 @@ +# ITL-1485: a source keeps its preview + +Developer, November 26, 2026: "sources should actually cache their preview and use the +system very much like that of the stream's staleness check to see if their preview is stale +OR if user is requesting a preview that cannot be achieved with what's been cached, ONLY +THEN it should bust the cache and stream again (minimally) from the source to form the +preview." + +## What a preview reads today + +Only two kinds of source read anything for `head()` (and the notebook preview, which is +`head()`): `SpiralDBTableSource`, and a `DerivedSource` over a job node (its stored rows, +read whole and not kept). Every other source holds its rows (a slice), delegates +(`SourceProxy`, a `DerivedSource` over a source, a source job node) or reads nothing +(`PollingSource` before a poll, `CachedSource` before its first read). + +A SpiralDB source's `head()` on `main`, every time, on the fake: open the table by name, +open the dataset's schema table, the snapshot's `schema()`, one scan limited to `n` rows; +the first one also counts the keys (the count is then remembered per version by the +connector). A preview of an unchanged table repeats all of it. + +What the source already knows for free: it reads one pinned version (`_asof`), set when it +is built or by a given `asof`, and moved only by `check_for_new_data` (a run's source check). +Between two moves every read returns the rows of one immutable snapshot. So whether a kept +preview is still the source's preview needs no call at all: it is if it was read at the +version, restriction and table the source reads now. + +## The design + +1. **What is kept.** One record on the source object: the rows of the last preview that + read rows, with every column group (tags, data, system tags, source info, context), as + one stream; the number of rows the read asked for and whether it returned fewer (then it + holds every row the source reads); the total and counted bound the header shows; and the + key it was read under: the pinned version, the condition, the limit. +2. **When it is used.** `head(n)` with the same key, and `n` at most the rows it holds or + the record holds every row. Any `columns` / `all_info` / `sort_by_tags` is answered from + it (they are projections of the kept columns; sorting sorts the first `n` rows read, as + on `main`). No service call is made. The view is the one `main` returns. +3. **When it reads again.** Another key (a run's check moved the version; a `where()` copy + starts with none), or more rows than it holds. It then reads `n` rows from the start, as + on `main`, and the new record replaces the old one. +4. **"Changed" per kind.** SpiralDB: the pinned version, held in memory; the check costs + nothing. A live change of the table is seen only after a run's check moves the version, + exactly as `main`'s preview (which reads the pinned version) sees it. Sources that hold + their rows: nothing to keep. `PollingSource`: unchanged, never polls. +5. **Restriction.** The key holds the condition and the limit: kept rows belong to one + restriction. `where()` returns a copy, which keeps nothing. +6. **A job.** A run's source check that takes in a new version moves the pin, so the next + preview reads. A run that finds nothing leaves the kept preview in use. Rebinding binds + another source object, with its own record; nothing is kept on a node or a slot. +7. **No identity changes.** Nothing kept enters a hash, a config, a stored path or a + stored table. + +## Decisions + +Approved as recommended by the coordinator on the developer's behalf (November 26, +2026). + + +- **D1. Scope: SpiralDB only.** Recommended. A `DerivedSource` over a job node also reads + on every preview (its whole stored table); its change signal would be the node's modified + time, which misses another process writing the same store. Follow-up issue, not this PR. +- **D2. Reading more rows: read `n` from the start, not only the missing ones.** + Recommended. A SpiralDB scan has no offset, and "after this key" over a composite key + needs an `or`/`>` predicate the source does not build (the `where()` path is being + changed by ITL-998). The second read costs what `main` pays for every preview. +- **D3. Memory bound: keep a preview of at most 10,000 rows and 64 MiB** (the Arrow + buffers of the kept table, every column group); a larger `head(n)` is read and shown, + not kept. The default preview is 10 rows. Rows can be wide (a list, binary or library + value column holds any number of bytes per row), so the row bound alone does not bound + memory: 10,000 rows of a 1 MB array column are 10 GB. The byte bound does. It counts + every buffer the kept table references (`get_total_buffer_size`), not its values' + bytes: a scan's limit slices a batch, and a slice keeps the whole batch's buffers, so + rows that hold more than their values are first copied out (review of af670090). +- **D4. A closed source keeps nothing.** `close()` drops the record, so a closed source's + `head()` raises as on `main`. Recommended. +- **D5. A table dropped and created again, or a schema-table change, is not seen by a kept + preview** (on `main` the preview's lookup raises). It is seen by the next run's check, + read or uncached preview. Consistent with `main`: a preview already shows the version + the source last checked (the version moves only by a run's source check). The docs say + so: a preview shows the version the source last checked; run the job (or check the + source) to see newer rows. +- **D6. Full reads (`as_table`, `iter_data`, `run()`) neither use nor fill the record.** + Recommended: they keep `main`'s "every read scans again"; a run's rows are a job's + business. The computed `preview(n)` of ITL-1464 (#571, not merged) can answer a source's + preview from the record later. +- **D7. The total is kept with the rows** (amended after the reviews of af670090, + 854bbf94 and 0a9ccfeb; decided on the developer's behalf: "a repeated preview of an + unchanged source takes no time"). A read whose rows are not every row the source reads + counts the table's keys, as on `main`, at the same version and through the same handle, + to the largest bound a preview answered from its rows counts to, and keeps the count. + A read of every row a condition chose knows its total and counts nothing (never waits + for a count); the first smaller preview answered from its rows counts once, as `main` + does for that preview, and the count is kept with the rows. Every other preview the + record answers makes no call. A record is kept only while the source still reads its + version, condition and limit, so a late read of an older version never replaces a + newer record. Each chunk of each column is copied out only when it is a real slice + (its buffers hold over 1 MiB beyond its values), after the row bound is checked. +- **One version, one read, a closed source** (review of af670090). The pinned version + is read once per preview: the rows, the count and the record's key are all of it, so a + source check that moves the version during a preview neither mixes versions nor keeps + rows under the new one. A source closed during a preview keeps nothing, and a closed + source's preview raises before it looks at a record. + +## Tests (fake SpiralDB, by SDK call counts) + +A second preview makes no service call; `head(5)` after `head(10)` none; other columns and +`sort_by_tags` none; `head(20)` after `head(10)` reads 20; a table written to and a run's +check (sync `job.run()` and `run_async()`) make the next preview read the new rows; a run +that finds nothing does not; a `where()` copy reads its own; a given `asof` keeps its +record; `close()` drops it; a 3-row table answers any `n`; a preview over 10,000 rows is not +kept; every view equals `main`'s for the same arguments. diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 8d534e5a3..5f5c32923 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -85,6 +85,13 @@ DEFAULT_BATCH_ROWS = 8_192 # The most rows a notebook display of the source reads. PREVIEW_ROWS = 10 +# A preview's rows are kept for the next preview when they are at most this many rows and +# bytes (the Arrow buffers of every column group): rows can be wide (a list, a binary or a +# library value), so the row bound alone does not bound the memory kept (ITL-1485). +PREVIEW_KEPT_ROWS = 10_000 +PREVIEW_KEPT_BYTES = 64 * 2**20 +# Bytes a kept preview's buffers may hold beyond its values before they are copied out. +_SLICE_SLACK = 2**20 def _is_positive_int(value: object) -> bool: @@ -92,6 +99,61 @@ def _is_positive_int(value: object) -> bool: return isinstance(value, int) and not isinstance(value, bool) and value >= 1 +def _compact(rows: "pa.Table") -> "pa.Table": + """Return ``rows`` with each sliced chunk copied into buffers of its own. + + A scan's limit slices its last batch, and a slice keeps the batch's whole buffers: + one small row beside a large one would keep the large one. Each chunk of each + column is judged on its own: one whose buffers hold more than ``_SLICE_SLACK`` bytes + beyond its values is a real slice and is copied (a whole chunk's last offset, which + ``nbytes`` leaves out, is a few bytes); every other chunk is kept as it is. Rows + whose values do not fit ``PREVIEW_KEPT_BYTES`` are returned as they are (they are + not kept). + """ + if rows.nbytes > PREVIEW_KEPT_BYTES: + return rows + columns: list[pa.ChunkedArray[Any]] = [] # pyright: ignore[reportExplicitAny] # any column + copied = False + for column in rows.columns: + chunks: list[pa.Array[Any]] = [] # pyright: ignore[reportExplicitAny] # any column + for chunk in column.chunks: + if chunk.get_total_buffer_size() > chunk.nbytes + _SLICE_SLACK: + chunk = chunk.take(pa.array(range(len(chunk)), pa.int64())) + copied = True + chunks.append(chunk) + columns.append(pa.chunked_array(chunks, type=column.type)) + if not copied: + return rows + return pa.Table.from_arrays(columns, schema=rows.schema) + + +def _merged(held: _KeptPreview, new: _KeptPreview) -> _KeptPreview: + """Return one record of ``held`` and ``new``, two reads under one key: the larger + rows, with every count either knows that still holds for them. + + Both reads are of one version, condition and limit, so the rows of the smaller are + the first rows of the larger. A count is ``None``, exact (at most its + ``counted_to``), or "more than ``counted_to``"; an exact count holds for any rows, + and a "more" count for rows whose bound is no larger. + """ + larger, smaller = ( + (held, new) + if held.complete + and not new.complete + or held.complete == new.complete + and held.asked >= new.asked + else (new, held) + ) + if larger.table_rows is not None or smaller.table_rows is None: + return larger + if ( + smaller.table_rows <= smaller.counted_to + or smaller.counted_to >= larger.counted_to + ): + return dataclasses.replace(larger, table_rows=smaller.table_rows) + return larger + + class _Head(NamedTuple): """The first rows of a source, and what is known of how many rows it reads. @@ -194,6 +256,37 @@ def spiraldb_table_address( return address +@dataclasses.dataclass(frozen=True) +class _KeptPreview: + """The rows of a source's last preview and the size it showed (ITL-1485). + + Everything here is of one read at one pinned version, so a preview under ``key`` of + no more rows (or of any number when ``complete``) is answered from it with no call + to SpiralDB, its total included. + + Attributes: + key: The pinned version, condition and limit the rows were read under. + rows: The rows read, with their system tags and source info; ``None`` for none. + asked: The most rows the read asked for. + complete: Whether the read returned every row the source reads. + table_rows: The table's row count at that version, counted to at most + ``counted_to + 1`` (so more than ``counted_to`` means "more"); ``None`` + when it was not counted. + counted_to: The largest bound a preview answered from these rows counts to. + """ + + key: tuple[int | None, Condition, int | None] + rows: "pa.Table | None" + asked: int + complete: bool + table_rows: int | None + counted_to: int + + def answers(self, key: tuple[int | None, Condition, int | None], n: int) -> bool: + """Whether a preview of ``n`` rows under ``key`` is these rows' first ``n``.""" + return key == self.key and (self.complete or n <= self.asked) + + class SpiralDBTableSource(RootSource): """A read-only Source over a table in a SpiralDB dataset, read in batches. @@ -207,12 +300,16 @@ class SpiralDBTableSource(RootSource): sends it in batches whose sizes follow its stored fragments (they cannot be chosen); the source hands each on in slices of at most ``batch_rows`` rows, so iterating holds one SpiralDB batch, and the slice being processed, at a time. - ``as_table`` and the dataframe methods hold every row they return. Nothing is - cached: every read scans again. + ``as_table`` and the dataframe methods hold every row they return. They keep + nothing: every read scans again. Display. ``head(n)`` and the notebook display (its ``head()``) read only the first ``n`` rows (``PREVIEW_ROWS``, 10, by default), in one scan to which ``max_rows`` does - not apply, and the header says how many rows the table has. + not apply, and the header says how many rows the table has. The source keeps the + rows of its last preview (at most ``PREVIEW_KEPT_ROWS`` rows and + ``PREVIEW_KEPT_BYTES`` bytes) and answers a preview of no more rows, of any columns, + from them without a call to SpiralDB, until a source check moves the version it + reads (ITL-1485): a preview shows the version the source last checked. Identity. The source is identified by where the table is, never by its rows. The default ``source_id`` is ``spiraldb_table_v1:..@ "SpiralDBTableSource": the data context and config, the condition (immutable) and limit, the tuples of tag, data-tag and key columns and the pinned version. Copied: the ``tags_as_data`` and ``overrides`` mappings. Reset: the content and pipeline - hash caches (they are recomputed, equal, on first use). Each source owns + hash caches (they are recomputed, equal, on first use) and the kept preview. + Each source owns a connector that holds the same SDK client and can be closed independently. The modified time is carried over until ``_apply_restriction`` moves it. A SpiralDB source holds no rows it read. @@ -611,6 +710,8 @@ def _copy(self) -> "SpiralDBTableSource": duplicate._connection_lock = Lock() duplicate._content_hash_cache = {} duplicate._pipeline_hash_cache = {} + # A copy is restricted further: the rows this source kept are not its preview. + duplicate._kept_preview = None return duplicate def _apply_restriction(self, condition: Condition) -> None: @@ -714,6 +815,7 @@ def close(self) -> None: require_same_process(self._pid) # before a lock inherited by a fork with self._connection_lock: self._closed = True + self._kept_preview = None if self._connection is not None: self._connection.close() self._connection = None @@ -974,14 +1076,30 @@ def _whole_table( all_info: bool, ) -> "pa.Table": """Return the rows of ``streams`` (batches of one read) as one table.""" - # One stream over all the rows, so that a whole-table option (sorting by - # tags) applies across batches. + return self._shown(self._read_rows(streams), columns=columns, all_info=all_info) + + @staticmethod + def _read_rows(streams: Iterator["ArrowTableStream"]) -> "pa.Table | None": + """Return the rows of ``streams`` (batches of one read), with their system tags + and source info, as one table; ``None`` when no batch came.""" enriched = {"source": True, "system_tags": True} tables = [stream.as_table(columns=enriched) for stream in streams] - if not tables: + return pa.concat_tables(tables) if tables else None + + def _shown( + self, + rows: "pa.Table | None", + *, + columns: ColumnConfig | dict[str, Any] | None, + all_info: bool, + ) -> "pa.Table": + """Return ``rows`` (as ``_read_rows`` returns them) with ``columns``.""" + if rows is None: return self._stream.as_table(columns=columns, all_info=all_info) + # One stream over all the rows, so that a whole-table option (sorting by + # tags) applies across batches. whole = ArrowTableStream( - table=pa.concat_tables(tables), + table=rows, tag_columns=self._tag_columns, system_tag_columns=self._system_tag_columns, data_tags=self._data_tags, @@ -1003,32 +1121,136 @@ def _head( size is the table's row count, counted from its keys up to ``max_rows`` (at most 100,000) rows; above that it is unknown. + The rows of the last preview and the size it counted are kept (ITL-1485): a + preview under the same pinned version, condition and limit, of no more rows + than were read (or of any number when every row was read), is answered from + them with no call to SpiralDB. + Args: n: The most rows to read. columns: Column configuration, as for ``as_table``. all_info: Include all column groups, as for ``as_table``. + + Raises: + RuntimeError: If the source is closed. """ if not self._preview_reads_rows: schema_only = self._stream.as_table(columns=columns, all_info=all_info) bound, total = self._bounded_count(PREVIEW_ROWS) return _Head(schema_only, False, total, True, bound) + require_same_process(self._pid) # before a lock inherited by a fork + with self._connection_lock: + if self._closed: + raise RuntimeError("SpiralDBTableSource is closed") + kept = self._kept_preview limit = self._limit head_limit = n if limit is None else min(n, limit) - asof = self._asof - table = self._lookup_table() - rows = self._whole_table( - self._read_batches(table, asof=asof, limit=head_limit, max_rows=None), - columns=columns, - all_info=all_info, - ) + # The version is read once: the rows, the count and the key are all of it. + key = (self._asof, self._condition, limit) + if kept is None or not kept.answers(key, head_limit): + kept = self._read_preview(key, head_limit) + first = kept.rows + if first is not None and first.num_rows > head_limit: + first = first.slice(0, head_limit) + rows = self._shown(first, columns=columns, all_info=all_info) if rows.num_rows < head_limit or head_limit == limit: return _Head(rows, True, rows.num_rows, False) - bound, total = self._bounded_count(n, table) - if limit is not None and self._condition.is_empty: + bound = self._count_bound(n) + condition = key[1] + if bound is None: + bound, total = n, None + elif kept.complete and condition.is_empty: + # Every row the source reads was read, and with no condition they are the + # table's first rows: all of them when fewer than the limit came back. + whole = 0 if kept.rows is None else kept.rows.num_rows + every_row = limit is None or whole < limit + total = whole if every_row and whole <= bound else None + else: + # Counted to counted_to + 1 >= bound + 1: by the read when its rows were not + # all the source reads, else by the first preview that needs it. + counted = kept.table_rows + if counted is None: + counted = self._lookup_table().count_rows( + asof=kept.key[0], at_most=kept.counted_to + 1 + ) + kept = dataclasses.replace(kept, table_rows=counted) + if ( + self._kept_preview is not None + and self._kept_preview.key == kept.key + ): + self._keep(kept) + total = None if counted > bound else counted + if limit is not None and condition.is_empty: total = limit if total is None and limit <= bound else total total = None if total is None else min(limit, total) return _Head(rows, True, total, True, bound) + def _read_preview( + self, key: tuple[int | None, Condition, int | None], head_limit: int + ) -> _KeptPreview: + """Read the first ``head_limit`` rows under ``key``, and the table's row count a + preview of them or of fewer rows shows; keep them when they are small enough. + + The rows and the count are read at the version in ``key``, through one handle. + Counting is needed only when a preview answered from these rows shows the + table's row count: when they are not every row the source reads (this preview + then needs it, as on main). A read of every row a condition chose knows its + total and counts nothing; the first smaller preview answered from its rows + counts, as on main, and keeps the count. The record is kept only while the + source is open and still reads the version, condition and limit of ``key``. + """ + asof, condition, limit = key + table = self._lookup_table() + read = self._read_rows( + self._read_batches(table, asof=asof, limit=head_limit, max_rows=None) + ) + count = 0 if read is None else read.num_rows + complete = count < head_limit or head_limit == limit + # The row bound first: rows that will not be kept are neither copied nor counted. + keep = count <= PREVIEW_KEPT_ROWS + if keep and read is not None: + read = _compact(read) + keep = read.get_total_buffer_size() <= PREVIEW_KEPT_BYTES + counted_to = self._count_bound(count) + table_rows: int | None = None + if counted_to is not None and not complete: + # This preview shows the table's row count, as on main. A preview that read + # every matching row knows its total and counts nothing: a smaller preview + # answered from its rows counts then (``_head``). + table_rows = table.count_rows(asof=asof, at_most=counted_to + 1) + kept = _KeptPreview( + key=key, + rows=read, + asked=head_limit, + complete=complete, + table_rows=table_rows, + counted_to=counted_to or 0, + ) + if keep: + self._keep(kept) + return kept + + def _keep(self, kept: _KeptPreview) -> None: + """Keep ``kept`` as the source's preview while the source is open and still + reads its version, condition and limit: a late read of an older version never + replaces a newer record, and a record of the same key never discards what the + kept one knows (``_merged``).""" + with self._connection_lock: + current = (self._asof, self._condition, self._limit) + if not self._closed and current == kept.key: + held = self._kept_preview + if held is not None and held.key == kept.key: + kept = _merged(held, kept) + self._kept_preview = kept + + def _count_bound(self, shown: int) -> int | None: + """Return how far a preview showing ``shown`` rows counts the table's rows, or + ``None`` when it counts none (``_bounded_count``).""" + if shown > DEFAULT_MAX_ROWS: + return None + allowed = min(self._max_rows or DEFAULT_MAX_ROWS, DEFAULT_MAX_ROWS) + return max(allowed, shown) + def _bounded_count( self, shown: int, table: SpiralDBTable | None = None ) -> tuple[int, int | None]: @@ -1042,10 +1264,9 @@ def _bounded_count( shown: The rows the preview shows. table: The handle resolved for this read; looked up when not given. """ - if shown > DEFAULT_MAX_ROWS: + bound = self._count_bound(shown) + if bound is None: return shown, None - allowed = min(self._max_rows or DEFAULT_MAX_ROWS, DEFAULT_MAX_ROWS) - bound = max(allowed, shown) handle = self._lookup_table() if table is None else table total = handle.count_rows(asof=self._asof, at_most=bound + 1) return bound, (None if total > bound else total) diff --git a/tests/test_core/sources/test_spiraldb_kept_preview.py b/tests/test_core/sources/test_spiraldb_kept_preview.py new file mode 100644 index 000000000..fc83a08f8 --- /dev/null +++ b/tests/test_core/sources/test_spiraldb_kept_preview.py @@ -0,0 +1,834 @@ +"""A SpiralDB source keeps its preview (ITL-1485), counted in SDK calls on the fake. + +A source reads one pinned version, moved only by its source check (a run's), so the rows +of its last preview are its preview for as long as the version, the condition and the +limit are those it read under. A second preview makes no SDK call; a preview that asks for +more rows than are kept, or one after the version moved, reads again. +""" + +from __future__ import annotations + +import collections +from collections.abc import Callable, Iterator +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.core.sources import spiraldb_table_source as spiral_module +from orcapod.core.streams.view import StreamView +from orcapod.databases import InMemoryArrowDatabase +from orcapod.databases.spiraldb_schema_table import SCHEMA_TABLE +from orcapod.operators import SelectColumns +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.sources import SpiralDBTableSource +from tests.test_databases import fake_spiral_sdk + +_PROJECT = "kept-preview" +# Two key columns (tags) and two data columns. +_SCHEMA = pa.schema( + [ + pa.field("subject", pa.large_string(), nullable=False), + pa.field("k", pa.int64(), nullable=False), + pa.field("x", pa.int64(), nullable=False), + pa.field("y", pa.large_string(), nullable=True), + ] +) +_KEYS = pa.schema([_SCHEMA.field("subject"), _SCHEMA.field("k")]) + + +def _rows(ks: list[int]) -> pa.Table: + return pa.table( + { + "subject": [f"s{k % 2}" for k in ks], + "k": ks, + "x": [10 * k for k in ks], + "y": [f"v{k}" for k in ks], + }, + schema=_SCHEMA, + ) + + +def _table() -> Any: # pyright: ignore[reportExplicitAny] # the fake's table + return fake_spiral_sdk.ExternalProject(_PROJECT).table("default.t") + + +@pytest.fixture +def calls( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> Iterator[collections.Counter[str]]: + """A fake project with table ``default.t`` of 30 rows; counts every SDK call on it. + + Counted: "lookup" (open by name), "by_id" (open a version by id), "open_schemas" + (open the dataset's schema table), "schema" (a snapshot's schema), "scan" (rows) + and "count" (keys), and every read of the schema table's rows ("read_schemas"). + """ + counts: collections.Counter[str] = collections.Counter() + + def name_label(args: tuple[Any, ...], kwargs: Any) -> str: # pyright: ignore[reportExplicitAny] + return "open_schemas" if args[3] == SCHEMA_TABLE else "lookup" + + def handle_label(user: str) -> Callable[..., str]: + def label(args: tuple[Any, ...], kwargs: Any) -> str: # pyright: ignore[reportExplicitAny] + if args[0]._table["name"] == SCHEMA_TABLE: + return f"{user}_schemas" + columns = args[1] if len(args) > 1 else kwargs.get("columns") + return "count" if user == "scan" and columns else user + + return label + + counted: dict[tuple[type, str], Callable[..., str]] = { + (fake_spiral_sdk.FakeClient, "keyed_table"): name_label, + (fake_spiral_sdk.FakeClient, "keyed_table_by_id"): lambda a, k: "by_id", + (fake_spiral_sdk.FakeKeyedTable, "schema"): handle_label("schema"), + (fake_spiral_sdk.FakeKeyedTable, "scan"): handle_label("scan"), + } + for (cls, name), label_of in counted.items(): + original: Callable[..., Any] = getattr(cls, name) # pyright: ignore[reportExplicitAny] + + def wrapper( + *args: Any, # pyright: ignore[reportExplicitAny] # passed through + _original: Callable[..., Any] = original, # pyright: ignore[reportExplicitAny] + _label_of: Callable[..., str] = label_of, + **kwargs: Any, # pyright: ignore[reportExplicitAny] + ) -> Any: # pyright: ignore[reportExplicitAny] + counts[_label_of(args, kwargs)] += 1 + return _original(*args, **kwargs) + + monkeypatch.setattr(cls, name, wrapper) + with fake_spiral_sdk.install(tmp_path / "spiral"): + table = fake_spiral_sdk.ExternalProject(_PROJECT).create_table( + "default.t", key_schema=_KEYS + ) + table.write(_rows(list(range(30)))) + table.record(_SCHEMA) + counts.clear() + yield counts + + +def _source(**kwargs: Any) -> SpiralDBTableSource: # pyright: ignore[reportExplicitAny] # options + return SpiralDBTableSource(project_id=_PROJECT, table_name="t", **kwargs) + + +def _scans() -> list[int | None]: + """The limits of the row scans made since the log was last cleared.""" + return [record.limit for record in fake_spiral_sdk.scan_log] + + +def _same_view(kept: StreamView, fresh: StreamView) -> None: + """``kept`` is the view a source keeping nothing gives for the same arguments.""" + assert kept.table.equals(fresh.table, check_metadata=True) + assert kept.description == fresh.description + assert kept.total_rows == fresh.total_rows + assert kept.total_is_estimate == fresh.total_is_estimate + assert kept.tag_columns == fresh.tag_columns + assert kept.status == fresh.status + + +def _fresh(**kwargs: Any) -> SpiralDBTableSource: # pyright: ignore[reportExplicitAny] # options + """A new source: its first preview reads as ``main`` does, keeping nothing yet.""" + return _source(**kwargs) + + +# Every argument form a preview takes: the columns asked for and the order shown. +_COLUMN_FORMS: list[dict[str, Any]] = [ # pyright: ignore[reportExplicitAny] + {}, + {"all_info": True}, + {"columns": {"sort_by_tags": True}}, + {"columns": {"source": True, "system_tags": True}}, + {"columns": {"context": True, "sort_by_tags": True}}, +] + + +@pytest.mark.parametrize("tag_only", [True, ()], ids=["plain_tags", "data_tags"]) +def test_a_second_preview_makes_no_call( + calls: collections.Counter[str], tag_only: bool | tuple[str, ...] +) -> None: + source = _source(tag_only_columns=tag_only) + calls.clear() + first = source.head() + assert calls["scan"] == 1 + calls.clear() + second = source.head() + assert calls == {} + _same_view(second, first) + # The notebook preview is the same head: no call either. + html = source._repr_html_() + assert calls == {} + assert html == _fresh(tag_only_columns=tag_only)._repr_html_() + + +@pytest.mark.parametrize("form", range(len(_COLUMN_FORMS))) +def test_other_columns_and_fewer_rows_are_answered_from_the_kept_rows( + calls: collections.Counter[str], form: int +) -> None: + source = _source(tag_only_columns=("subject",)) + _ = source.head(12) + calls.clear() + for n in (12, 5, 1, 0): + kept = source.head(n, **_COLUMN_FORMS[form]) + assert calls == {}, n + fresh = _fresh(tag_only_columns=("subject",)).head(n, **_COLUMN_FORMS[form]) + calls.clear() + _same_view(kept, fresh) + + +def test_more_rows_than_kept_reads_again_once(calls: collections.Counter[str]) -> None: + source = _source(tag_only_columns=True) + _ = source.head(10) + fake_spiral_sdk.scan_log.clear() + calls.clear() + more = source.head(20) + # One read of the 20 rows from the start (a SpiralDB scan has no offset). + assert _scans() == [20] + assert calls["scan"] == 1 + _same_view(more, _fresh(tag_only_columns=True).head(20)) + calls.clear() + _ = source.head(15) + _ = source.head(20) + assert calls == {} + + +def test_a_source_whose_rows_are_all_kept_answers_any_size( + calls: collections.Counter[str], +) -> None: + source = _source(tag_only_columns=True) + _ = source.head(50) # all 30 rows + calls.clear() + for n in (100, 30, 31, 10_000): + _same_view(source.head(n), _fresh(tag_only_columns=True).head(n)) + calls.clear() + _ = source.head(n) + assert calls == {} + + +def test_a_changed_table_is_shown_after_the_source_check( + calls: collections.Counter[str], +) -> None: + source = _source(tag_only_columns=True) + before = source.head(40) + assert before.total_rows == 30 + _table().write(_rows([100, 101])) + calls.clear() + # The source reads its pinned version until it is checked: the kept rows are it. + unchecked = source.head(40) + assert calls == {} + _same_view(unchecked, before) + assert source.check_for_new_data() + calls.clear() + after = source.head(40) + assert calls["scan"] == 1 + assert after.total_rows == 32 + assert 100 in after.table["k"].to_pylist() + calls.clear() + _ = source.head(40) + assert calls == {} + + +@pytest.mark.parametrize("orchestrator", [None, AsyncPipelineOrchestrator]) +def test_a_job_run_that_takes_in_new_data_makes_the_next_preview_read( + calls: collections.Counter[str], + orchestrator: type[AsyncPipelineOrchestrator] | None, +) -> None: + source = _source(tag_only_columns=True) + job = PipelineJob(name="kept-preview", database=InMemoryArrowDatabase()) + with job: + SelectColumns(["subject", "k", "x"])(source, label="read") + runner = orchestrator() if orchestrator is not None else None + _ = source.head() + # A run that finds nothing new leaves the kept preview in use. + _ = job.run(orchestrator=runner) + calls.clear() + _ = source.head() + assert calls == {} + # A run that takes in a new version: the next preview reads it. + _table().write(_rows([-2])) + _ = job.run(orchestrator=runner) + calls.clear() + after = source.head() + assert calls["scan"] == 1 + assert -2 in after.table["k"].to_pylist() + calls.clear() + _ = source.head() + assert calls == {} + + +def test_a_restricted_copy_keeps_its_own_preview( + calls: collections.Counter[str], +) -> None: + source = _source(tag_only_columns=True) + whole = source.head() + restricted = source.where(subject="s1") + calls.clear() + seen = restricted.head() + assert calls["scan"] == 1 + assert set(seen.table["subject"].to_pylist()) == {"s1"} + _same_view(seen, _fresh(tag_only_columns=True).where(subject="s1").head()) + calls.clear() + _ = restricted.head(3) + _same_view(source.head(), whole) + assert calls == {} + + +@pytest.mark.parametrize("limit", [3, 12]) +def test_a_limited_source_keeps_its_preview( + calls: collections.Counter[str], limit: int +) -> None: + source = _source(tag_only_columns=True, limit=limit) + _ = source.head() + calls.clear() + # Up to the limit, or fewer rows than were read. + for n in (10, 2, 20) if limit == 3 else (10, 2): + kept = source.head(n) + assert calls == {}, n + fresh = _fresh(tag_only_columns=True, limit=limit).head(n) + calls.clear() + _same_view(kept, fresh) + + +def test_a_given_version_keeps_its_preview(calls: collections.Counter[str]) -> None: + source = _source(tag_only_columns=True, asof=_table().last_modified_at()) + first = source.head() + _table().write(_rows([300])) + assert not source.check_for_new_data() + calls.clear() + _same_view(source.head(), first) + assert calls == {} + + +def test_a_closed_source_keeps_nothing(calls: collections.Counter[str]) -> None: + source = _source(tag_only_columns=True) + _ = source.head() + source.close() + with pytest.raises(RuntimeError, match="closed"): + _ = source.head() + + +def test_a_preview_over_the_row_bound_is_not_kept( + calls: collections.Counter[str], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(spiral_module, "PREVIEW_KEPT_ROWS", 5) + source = _source(tag_only_columns=True) + _ = source.head(6) + calls.clear() + _ = source.head(6) + assert calls["scan"] == 1 + _ = source.head(5) # kept: 5 rows + calls.clear() + _ = source.head(5) + _ = source.head(2) + assert calls == {} + + +def test_a_preview_over_the_byte_bound_is_not_kept( + calls: collections.Counter[str], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(spiral_module, "PREVIEW_KEPT_BYTES", 1) + source = _source(tag_only_columns=True) + _ = source.head() + calls.clear() + _ = source.head() + assert calls["scan"] == 1 + + +def test_full_reads_neither_use_nor_fill_the_kept_preview( + calls: collections.Counter[str], +) -> None: + source = _source(tag_only_columns=True) + _ = source.as_table() + calls.clear() + _ = source.head() + assert calls["scan"] == 1 + calls.clear() + assert source.as_table().num_rows == 30 + assert calls["scan"] == 1 + + +def test_an_empty_restriction_keeps_its_preview( + calls: collections.Counter[str], +) -> None: + source = _source(tag_only_columns=True).where(subject="nobody") + first = source.head() + assert first.table.num_rows == 0 + calls.clear() + _same_view(source.head(), first) + assert calls == {} + + +# Option sets whose header total is worked out differently: a cap below the rows read, +# a limit above and below them, a condition. +_OPTIONS: dict[str, dict[str, Any]] = { # pyright: ignore[reportExplicitAny] + "small_cap": {"max_rows": 5}, + "small_cap_limit": {"max_rows": 5, "limit": 8}, + "limit_above_rows": {"limit": 40}, + "where": {"where": {"subject": "s1"}}, + "where_limit": {"where": {"subject": "s1"}, "limit": 4}, + # Two conditions, a tag and a data column, in both orders (CodeRabbit, 62db6a1a). + "where_two": {"where": {"subject": "s1", "x": 30}}, + "where_two_reversed": {"where": {"x": 30, "subject": "s1"}}, +} + + +@pytest.mark.parametrize("options", sorted(_OPTIONS)) +@pytest.mark.parametrize("first", [10, 50]) +def test_every_kept_view_is_the_view_a_fresh_read_gives( + calls: collections.Counter[str], options: str, first: int +) -> None: + source = _source(tag_only_columns=True, **_OPTIONS[options]) + _ = source.head(first) + counts = 0 + for n in (first, 7, 3, 0): + calls.clear() + kept = source.head(n) + # Every preview the kept record answers reads no row. The one call: after a + # read of every row a condition chose (its total exact, so not counted then), + # the first smaller preview counts the table, once (round 3 of the review). + assert "scan" not in calls, n + assert set(calls) <= {"lookup", "open_schemas", "schema", "count"}, n + counts += calls["count"] + _same_view(kept, _fresh(tag_only_columns=True, **_OPTIONS[options]).head(n)) + calls.clear() + _ = source.head(n) + assert calls == {}, n + assert counts <= (1 if "where" in _OPTIONS[options] else 0) + + +@pytest.mark.parametrize( + ("options", "first", "then"), + [ + # The cap below both previews: each counts to its own bound on main. + ({"max_rows": 5}, {"n": 10}, {"n": 7, "columns": {"sort_by_tags": True}}), + # A condition read whole: the table's count is shown by the smaller preview. + ({"where": {"subject": "s1"}}, {"n": 40}, {"n": 10}), + ], + ids=["small_cap_sorted", "where_whole_then_fewer"], +) +def test_a_smaller_preview_makes_no_call( + calls: collections.Counter[str], + options: dict[str, Any], # pyright: ignore[reportExplicitAny] + first: dict[str, Any], # pyright: ignore[reportExplicitAny] + then: dict[str, Any], # pyright: ignore[reportExplicitAny] +) -> None: + """Codex review of af670090, finding 5: the total is kept with the rows.""" + source = _source(tag_only_columns=True, **options) + _ = source.head(**first) + calls.clear() + kept = source.head(**then) + # A read of every matching row counted nothing (round 3): the first smaller + # preview counts once; no row is read. + assert calls["scan"] == 0 + assert calls["count"] == (1 if "where" in options else 0) + _same_view(kept, _fresh(tag_only_columns=True, **options).head(**then)) + calls.clear() + _ = source.head(**then) + assert calls == {} + + +@pytest.fixture +def after_the_read( + monkeypatch: pytest.MonkeyPatch, +) -> Callable[[Callable[[], None]], None]: + """Run an action once, when the next scan of rows has handed out its last batch: + a preview paused after reading, before it keeps anything.""" + action: list[Callable[[], None]] = [] + original = fake_spiral_sdk.FakeReader.read_next_batch + + def read_next_batch(self: fake_spiral_sdk.FakeReader) -> pa.RecordBatch: + try: + return original(self) + except StopIteration: + record = self._record # pyright: ignore[reportPrivateUsage] # the fake's + if ( + action + and record.columns is None + and SCHEMA_TABLE not in (record.identifier) + ): + action.pop()() + raise + + monkeypatch.setattr(fake_spiral_sdk.FakeReader, "read_next_batch", read_next_batch) + return action.append + + +def test_a_source_closed_during_a_preview_keeps_and_serves_nothing( + calls: collections.Counter[str], + after_the_read: Callable[[Callable[[], None]], None], +) -> None: + """Codex review of af670090, finding 3.""" + source = _source(tag_only_columns=True) + after_the_read(source.close) + _ = source.head(40) + with pytest.raises(RuntimeError, match="closed"): + _ = source.head(40) + with pytest.raises(RuntimeError, match="closed"): + _ = source.head(5) + + +def test_a_check_during_a_preview_does_not_mix_versions( + calls: collections.Counter[str], + after_the_read: Callable[[Callable[[], None]], None], +) -> None: + """Codex review of af670090, finding 4: rows, total and key of one version.""" + source = _source(tag_only_columns=True) + + def new_first_key_and_check() -> None: + _table().write(_rows([-2])) + assert source.check_for_new_data() + + after_the_read(new_first_key_and_check) + during = source.head(10, columns={"sort_by_tags": True}) + # The rows and the total are those of the version the preview read. + assert -2 not in during.table["k"].to_pylist() + assert during.total_rows == 30 + # Nothing of the old version answers for the new one. + calls.clear() + after = source.head(10, columns={"sort_by_tags": True}) + assert calls["scan"] == 1 + assert -2 in after.table["k"].to_pylist() + assert after.total_rows == 31 + + +def test_the_memory_bound_counts_what_the_kept_rows_hold( + calls: collections.Counter[str], +) -> None: + """Codex review of af670090, finding 2: a small row sliced out of a batch with a + 65 MiB row beside it keeps only its own bytes.""" + huge = "z" * (65 * 2**20) + project = fake_spiral_sdk.ExternalProject(_PROJECT) + wide = project.create_table("default.wide", key_schema=_KEYS) + rows = _rows([0, 1]) + rows = rows.set_column(3, "y", pa.array(["small", huge], pa.large_string())) + wide.write(rows) + wide.record(_SCHEMA) + source = SpiralDBTableSource(_PROJECT, "wide", tag_only_columns=True) + first = source.head(1) + assert first.table["y"].to_pylist() == ["small"] + kept = source._kept_preview # pyright: ignore[reportPrivateUsage] # the bound's subject + assert kept is not None and kept.rows is not None + assert kept.rows.get_total_buffer_size() < 2**20 + calls.clear() + _same_view(source.head(1), first) + assert calls == {} + # A preview that holds the huge row itself is shown, not kept. + both = source.head(2) + assert both.table.num_rows == 2 + calls.clear() + _ = source.head(2) + assert calls["scan"] == 1 + + +# -------------------------------------------------------------------------------------- +# Round 2 of the review (854bbf94) + + +@pytest.fixture +def failing_counts(monkeypatch: pytest.MonkeyPatch) -> None: + """Every count of a table's keys fails, as a scan that times out does.""" + original = fake_spiral_sdk.FakeKeyedTable.scan + + def scan(self: fake_spiral_sdk.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any: # pyright: ignore[reportExplicitAny] + columns = args[0] if args else kwargs.get("columns") + if columns and SCHEMA_TABLE not in self._table["name"]: # pyright: ignore[reportPrivateUsage] # the fake's + raise fake_spiral_sdk.SpiralError("the count timed out") + return original(self, *args, **kwargs) + + monkeypatch.setattr(fake_spiral_sdk.FakeKeyedTable, "scan", scan) + + +def test_a_failing_count_never_fails_a_preview_that_read_every_row( + calls: collections.Counter[str], failing_counts: None +) -> None: + """Round 2, finding 1: the count is for later previews only.""" + source = _source(tag_only_columns=True, where={"subject": "s1"}) + seen = source.head(40) + assert seen.table.num_rows == 15 + assert seen.total_rows == 15 + assert not seen.total_is_estimate + # Its rows are kept without a count (round 3): the same preview makes no call. + calls.clear() + _same_view(source.head(40), seen) + assert calls == {} + # A smaller preview needs the table's count, as on main, and its failure is its + # own; the kept rows stay. + with pytest.raises(fake_spiral_sdk.SpiralError, match="timed out"): + _ = source.head(10) + calls.clear() + _same_view(source.head(40), seen) + assert calls == {} + + +def test_a_source_closed_before_the_count_still_answers_the_preview( + calls: collections.Counter[str], + after_the_read: Callable[[Callable[[], None]], None], +) -> None: + """Round 2, finding 1: closed after the row scan, before the count.""" + source = _source(tag_only_columns=True, where={"subject": "s1"}) + after_the_read(source.close) + seen = source.head(40) + assert seen.table.num_rows == 15 + with pytest.raises(RuntimeError, match="closed"): + _ = source.head(40) + + +def test_rows_over_the_keep_bound_are_not_counted( + calls: collections.Counter[str], monkeypatch: pytest.MonkeyPatch +) -> None: + """Round 2, finding 1: never count for a record that will not be kept.""" + monkeypatch.setattr(spiral_module, "PREVIEW_KEPT_ROWS", 10) + source = _source(tag_only_columns=True, where={"subject": "s1"}) + calls.clear() + seen = source.head(40) + assert seen.table.num_rows == 15 + assert "count" not in calls + + +def test_a_late_preview_of_an_old_version_does_not_replace_a_newer_one( + calls: collections.Counter[str], + after_the_read: Callable[[Callable[[], None]], None], +) -> None: + """Round 2, finding 2.""" + source = _source(tag_only_columns=True) + newer: list[StreamView] = [] + + def move_and_preview() -> None: + _table().write(_rows([-2])) + assert source.check_for_new_data() + newer.append(source.head(10)) + + after_the_read(move_and_preview) + older = source.head(10) + assert -2 not in older.table["k"].to_pylist() + assert -2 in newer[0].table["k"].to_pylist() + calls.clear() + _same_view(source.head(10), newer[0]) + assert calls == {} + + +def test_rows_over_the_row_bound_are_never_copied( + calls: collections.Counter[str], monkeypatch: pytest.MonkeyPatch +) -> None: + """Round 2, finding 3: the row bound is checked before any copy.""" + monkeypatch.setattr(spiral_module, "PREVIEW_KEPT_ROWS", 5) + copied: list[int] = [] + original = spiral_module._compact # pyright: ignore[reportPrivateUsage] # the subject + + def compact(rows: pa.Table) -> pa.Table: + copied.append(rows.num_rows) + return original(rows) + + monkeypatch.setattr(spiral_module, "_compact", compact) + _ = _source(tag_only_columns=True).head(6) + assert copied == [] + + +def test_rows_that_are_not_a_slice_are_not_copied() -> None: + """Round 2, finding 3: a whole large-string column (whose last offset ``nbytes`` + leaves out) is kept as it is; a slice of a larger batch is copied out.""" + whole = pa.table({"s": pa.array(["a" * 100] * 1000, pa.large_string())}) + assert whole.get_total_buffer_size() > whole.nbytes + assert spiral_module._compact(whole) is whole # pyright: ignore[reportPrivateUsage] # the subject + sliced = pa.table( + {"s": pa.array(["a", "z" * (2 * 2**20)], pa.large_string())} + ).slice(0, 1) + compacted = spiral_module._compact(sliced) # pyright: ignore[reportPrivateUsage] # the subject + assert compacted is not sliced + assert compacted.equals(sliced) + assert compacted.get_total_buffer_size() < 2**10 + + +# -------------------------------------------------------------------------------------- +# Round 3 of the review (0a9ccfeb) + + +def test_a_preview_that_read_every_matching_row_counts_nothing( + calls: collections.Counter[str], +) -> None: + """Round 3, finding 1: its total is exact, so it never waits for a count. The + first smaller preview answered from its rows counts once, as main does, and keeps + the count.""" + options: dict[str, Any] = {"where": {"subject": "s1"}} # pyright: ignore[reportExplicitAny] + source = _source(tag_only_columns=True, **options) + calls.clear() + seen = source.head(40) + assert seen.table.num_rows == 15 + assert "count" not in calls + calls.clear() + fewer = source.head(10) + assert "scan" not in calls + _same_view(fewer, _fresh(tag_only_columns=True, **options).head(10)) + calls.clear() + _same_view(source.head(10), fewer) + _ = source.head(3) + assert calls == {} + + +def test_unsliced_chunks_are_never_copied() -> None: + """Round 3, finding 2: many whole one-row chunks over many large-binary columns + hold a few bytes each beyond their values; together they are not a slice.""" + columns = { + f"c{i}": pa.chunked_array( + [pa.array([b"v"], pa.large_binary()) for _ in range(8192)] + ) + for i in range(17) + } + whole = pa.table(list(columns.values()), names=list(columns)) + assert whole.get_total_buffer_size() > whole.nbytes + 2**20 + assert spiral_module._compact(whole) is whole # pyright: ignore[reportPrivateUsage] # the subject + + +def test_only_a_sliced_column_is_copied() -> None: + """Round 3, finding 2: a real slice in one column copies that column only.""" + big = pa.array([b"a" * (3 * 2**20)], pa.large_binary()) + sliced = pa.array([b"s", b"z" * (2 * 2**20)], pa.large_binary()).slice(0, 1) + rows = pa.table({"whole": big, "sliced": sliced}) + compacted = spiral_module._compact(rows) # pyright: ignore[reportPrivateUsage] # the subject + assert compacted.equals(rows) + assert compacted.schema.equals(rows.schema, check_metadata=True) + # The whole column keeps its buffers; the slice holds only its own bytes. + kept_whole = compacted.column("whole").chunks[0].buffers()[2] + given_whole = rows.column("whole").chunks[0].buffers()[2] + assert kept_whole is not None + assert given_whole is not None + assert kept_whole.address == given_whole.address + assert compacted.column("sliced").chunk(0).get_total_buffer_size() < 2**10 + + +def test_a_late_store_of_the_same_key_keeps_what_is_known( + calls: collections.Counter[str], + after_the_read: Callable[[Callable[[], None]], None], +) -> None: + """Verification of b18ce0e7: a cold filtered head(40) paused before it keeps its + rows; head(50) keeps the same 15 rows; head(10) counts and keeps the total; the + late head(40) keeps the same key and must not erase the count.""" + options: dict[str, Any] = {"where": {"subject": "s1"}} # pyright: ignore[reportExplicitAny] + source = _source(tag_only_columns=True, **options) + + def others_first() -> None: + assert source.head(50).table.num_rows == 15 + _ = source.head(10) + + after_the_read(others_first) + late = source.head(40) + assert late.table.num_rows == 15 + calls.clear() + fewer = source.head(5) + assert calls == {} + _same_view(fewer, _fresh(tag_only_columns=True, **options).head(5)) + calls.clear() + _ = source.head(50) + assert calls == {} + + +# -------------------------------------------------------------------------------------- +# CodeRabbit review of 62db6a1a: a restriction of several conditions + + +# Each restriction holds two conditions; its forms give them in both orders, as a +# mapping, as keywords and as two chained ``where()`` calls. +_TWO_CONDITIONS: dict[str, dict[str, Any]] = { # pyright: ignore[reportExplicitAny] + "tag_and_data": {"subject": "s1", "x": 30}, + "two_data": {"x": 50, "y": "v5"}, + "two_tags": {"subject": "s0", "k": 4}, +} + + +def _restricted( + source: SpiralDBTableSource, + conditions: dict[str, Any], # pyright: ignore[reportExplicitAny] + form: str, +) -> SpiralDBTableSource: + items = list(conditions.items()) + if form == "mapping": + return source.where(dict(items)) + if form == "mapping_reversed": + return source.where(dict(reversed(items))) + if form == "keywords_reversed": + return source.where(**dict(reversed(items))) + first, second = items if form == "chained" else list(reversed(items)) + return source.where(dict([first])).where(dict([second])) + + +_FORMS = [ + "mapping", + "mapping_reversed", + "keywords_reversed", + "chained", + "chained_reversed", +] + + +@pytest.mark.parametrize("form", _FORMS) +@pytest.mark.parametrize("conditions", sorted(_TWO_CONDITIONS)) +@pytest.mark.parametrize("tag_only", [True, ()], ids=["plain_tags", "data_tags"]) +def test_a_restriction_of_two_conditions_keeps_its_preview_in_any_order( + calls: collections.Counter[str], + tag_only: bool | tuple[str, ...], + conditions: str, + form: str, +) -> None: + """Two conditions, given in any order and form, are one restriction: its kept + preview is the view a fresh source of the same form gives (the header names the + conditions in the order given, as on ``main``), its rows are those of the first + order, and a second preview makes no call.""" + given = _TWO_CONDITIONS[conditions] + + def fresh() -> SpiralDBTableSource: + return _restricted(_source(tag_only_columns=tag_only), given, form) + + source = fresh() + reference = _source(tag_only_columns=tag_only).where(**given) + assert source.condition == reference.condition + calls.clear() + seen = source.head(10) + assert calls["scan"] == 1 + assert seen.table.num_rows == 1 + assert seen.table.equals(reference.head(10).table, check_metadata=True) + calls.clear() + for n in (10, 1, 0): + kept = source.head(n, columns={"source": True, "system_tags": True}) + assert "scan" not in calls, n + _same_view(kept, fresh().head(n, columns={"source": True, "system_tags": True})) + calls.clear() + _ = source.head(n) + assert calls == {}, n + + +@pytest.mark.parametrize("orchestrator", [None, AsyncPipelineOrchestrator]) +@pytest.mark.parametrize("reversed_order", [False, True], ids=["given", "reversed"]) +def test_a_job_over_a_source_of_two_conditions_keeps_and_renews_its_preview( + calls: collections.Counter[str], + orchestrator: type[AsyncPipelineOrchestrator] | None, + reversed_order: bool, +) -> None: + """A run that finds nothing new leaves the kept preview of a two-condition + restriction in use; a run that takes in a new version makes the next preview read + it, on the sync and the async path.""" + conditions = {"subject": "s1", "y": "v7"} + if reversed_order: + conditions = dict(reversed(list(conditions.items()))) + source = _source(tag_only_columns=True, where=conditions) + job = PipelineJob(name="kept-preview-two", database=InMemoryArrowDatabase()) + with job: + SelectColumns(["subject", "k", "x"])(source, label="read") + runner = orchestrator() if orchestrator is not None else None + assert source.head().table["k"].to_pylist() == [7] + _ = job.run(orchestrator=runner) + calls.clear() + _ = source.head() + assert calls == {} + # A new row that matches both conditions (k = 107 is odd: subject "s1"). + _table().write( + pa.table( + {"subject": ["s1"], "k": [107], "x": [1070], "y": ["v7"]}, schema=_SCHEMA + ) + ) + _ = job.run(orchestrator=runner) + calls.clear() + after = source.head() + assert calls["scan"] == 1 + assert set(after.table["k"].to_pylist()) == {7, 107} + calls.clear() + _ = source.head() + assert calls == {} diff --git a/tests/test_core/sources/test_spiraldb_table_source_streaming.py b/tests/test_core/sources/test_spiraldb_table_source_streaming.py index 2b91d9b74..d61ec830f 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_streaming.py +++ b/tests/test_core/sources/test_spiraldb_table_source_streaming.py @@ -718,7 +718,8 @@ def test_a_sorted_head_sorts_only_the_rows_it_read(self, project): unsorted_head = source.head() sorted_head = source.head(columns={"sort_by_tags": True}) - assert self._scan_limits() == [10, 10] + # One read: the sorted head is the kept rows of the first, sorted (ITL-1485). + assert self._scan_limits() == [10] read = cast(list[int], unsorted_head.table.column("timestamp").to_pylist()) assert read == [10, 20, 30, 40, 50, 1, 2, 3, 4, 5] assert sorted_head.table.column("timestamp").to_pylist() == sorted(read)