diff --git a/changelog.d/ITL-1789.md b/changelog.d/ITL-1789.md new file mode 100644 index 000000000..89a4cf6a6 --- /dev/null +++ b/changelog.d/ITL-1789.md @@ -0,0 +1,75 @@ +### Added + +- `orcapod.SpiralDBEntry`, a reference to one entry of a SpiralDB table: the table's id, + the version read, the row's primary-key values, the column and the address of the + SpiralDB service (never a credential). Its logical type is `orcapod.spiraldb.entry`, + hashed by the content of the entry it names (label `spiraldb_entry_v1`), so an entry + that is the same in two table versions hashes alike. A function pod can reuse a stored + result after the source's pin moves when its other cache-key inputs also match. + `entry.read()` returns the entry as a + one-row `pyarrow.Table` from the version it names, and `entry.scan()` returns + spiral-sdk's scan of that one key and column. Both take an optional `client`; without + one they connect to the recorded service address with spiral-sdk's own sign-in, only + when this process reached that address through a `SpiralDBConnector` or SpiralDB + source it built (or its parent did, for a forked process); `SpiralDBEntry.prefetch` + refuses any other address the same way. The table `read()` returns is the caller's own. +- A job reads the entries a function node is about to hash together: one SpiralDB scan + per table version for the rows the node takes at once (at most 256 when an + asynchronous run executes; a load-only run takes its whole input), never one per row, and hashes + those rows from that batch; the references a function returns are read the same way + before its results are recorded (on the synchronous path one row at a time under + `fail_fast` or for a function that takes an invocation context to deliver side effects; + the asynchronous path reads the results that have arrived together, up to + 256, before it raises). A reference that + names a missing entry fails its row; any other error reading one stops the run. Entries + read are also kept in a cache for the process, per sign-in (up to a million hashes and + 512 MiB of values); a read through a given `client` neither uses nor fills it, and + computes no hash. +- `orcapod.errors.SpiralDBUntrustedServiceError` (a `PermissionError`), raised before any + client is made when a reference names a service address this process did not reach + through a connector or source it built. +- `orcapod.errors.SpiralDBEntryMissingError` (a `LookupError`), raised when the version a + reference names holds no row with its key, or the table or exactly that version can no + longer be opened. In a job it fails that input row under the node's error policy. + +### Changed + +- `ReadableChannel.take_ready(max_items)` is a required member of the channel protocol: + it returns the items already waiting, up to `max_items`, without waiting. A custom + readable channel must implement it (returning `[]` is allowed). The record-batch + input protocol has it too. + +### Fixed + +- `SpiralDBTableSource` no longer refuses a table that stores a column in a Vortex + encoding (such as `vortex.turboquant`), at the top level or as a struct field. Such a + column is presented as a column of `SpiralDBEntry` references with the same name and + position, and the scan does not read it. A struct column with an encoded field becomes + one reference to the whole struct column. Every other column reads as from the same + table without the encoded columns. An encoded column cannot be a tag or key column. + Orcapod checks the schema record when it prepares a snapshot and raises + `TableSchemaError` if the record's Vortex encoding metadata disagrees with the + service. Scans on an existing handle reuse that handle's prepared snapshot. +- When an observer fails on the next input of a synchronous batch, earlier results + are recorded and can still be loaded. If finishing the batch also fails, the + remaining held rows are reported as crashed and the original error propagates. + +### Known limitations + +- A source over `SpiralDBEntry` references built from in-memory data (`ArrowTableSource`, + `DictSource`, `ListSource` and the like), also references inside a list, has no + default source id, since the default would read every entry: it must be given a + `source_id`. +- A `SpiralDBEntry` is supported only as a column's type or inside `list[...]` there. As + a field of a user class (a dataclass, a pydantic model or an `orcapod.dataclass`, at + any depth) it is refused where the class is declared (`NestedTypeNotStorableError`), + and inside an Arrow struct or map column when the source is built + (`InputValidationError`). +- `read()` never falls back to a newer version when the recorded one is gone: it raises + `SpiralDBEntryMissingError` (ITL-1872). +- A cached result that names a missing entry stays stored, so the row keeps failing + on subsequent runs until that result is removed. +- `orcapod.spiraldb.entry` is provisional: its value hash and stored identity may change + in a later release, and using it issues `ProvisionalHashWarning`. +- Other stored extension types that are not Vortex encodings are still refused with + `InputValidationError`. diff --git a/docs/api/errors.md b/docs/api/errors.md index 506ae657c..38ca67b9c 100644 --- a/docs/api/errors.md +++ b/docs/api/errors.md @@ -140,6 +140,10 @@ These exceptions and warnings report storage, schema, and connector problems. ::: orcapod.errors.SpiralDBSignInError +::: orcapod.errors.SpiralDBEntryMissingError + +::: orcapod.errors.SpiralDBUntrustedServiceError + ## Feature availability and stability These exceptions and warnings report optional dependencies and features still in development. diff --git a/docs/api/types.md b/docs/api/types.md index afab565c4..a638450df 100644 --- a/docs/api/types.md +++ b/docs/api/types.md @@ -84,6 +84,10 @@ Core type definitions used throughout Orcapod. ::: orcapod.enable_file_hash_caching +## SpiralDB entries + +::: orcapod.SpiralDBEntry + ## Custom types and extensions ::: orcapod.dataclass diff --git a/docs/concepts/arrays.md b/docs/concepts/arrays.md index 744d1c201..df1202aab 100644 --- a/docs/concepts/arrays.md +++ b/docs/concepts/arrays.md @@ -58,8 +58,11 @@ for tag, data in scale.pod(source): The value hashes and stored identities of the library value types are provisional in v0.3: `numpy.ndarray`, `torch.Tensor`, and the pandas and polars `DataFrame` and `Series`. They are -provisional until the library value type audit (after 0.4.0rc1) and may change then. Every other type, and the hashing of everything -else in a pipeline, is unaffected. +provisional until the library value type audit (after 0.4.0rc1) and may change then. So are +references to SpiralDB entries, `orcapod.SpiralDBEntry` (see +[Columns stored in a Vortex encoding](sources.md#columns-stored-in-a-vortex-encoding)), and the +same warning names them, `orcapod.spiraldb.entry`. Every other type, and the hashing of +everything else in a pipeline, is unaffected. Using one of these types issues `orcapod.errors.ProvisionalHashWarning` once per type per process, on whichever use comes first: a value hashed, a source column of the type, a function diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index ffde56c6a..c4de4914a 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1054,7 +1054,8 @@ whose schema is known without a scan. #### The schema of a Spiral table SpiralDB reports every column as nullable, key columns included, and every field of a struct -column too, whatever nullability the data was written with; and it keeps no Arrow metadata. +column too, whatever nullability the data was written with; and it keeps no Arrow metadata +(except a Vortex encoding's, see [below](#columns-stored-in-a-vortex-encoding)). Orcapod therefore reads each table with a schema that is recorded in one more table of its dataset, `__orcapod_schemas__`: a row per table, with its column names, types, nullability at every depth and metadata. The name is reserved, and listings leave it out. @@ -1092,6 +1093,173 @@ which spiral-sdk does not read. Until their dataset is migrated they read as not schema that release read it with, so schemas, hashes and source ids stay the same ([the steps](https://github.com/metamorphic-labs/orcapod-python/blob/main/RELEASING.md#migrating-a-spiraldb-dataset-from-pyspiral)). +#### Columns stored in a Vortex encoding + +SpiralDB can store a column in an encoding of its own, such as `vortex.turboquant`, a lossy +quantized form of a float vector. SpiralDB reports such a column with its encoding's Arrow +extension name and parameters on the field, at the top level or on a field of a struct +column. Orcapod does not decode such a value, and does not copy it. It presents the column +as **references** to its entries, one per row: + +- The column keeps its name and position, and its type is `orcapod.SpiralDBEntry` (Arrow + extension `orcapod.spiraldb.entry`), never null. A struct column with an encoded field + becomes one reference column: the reference names the whole struct column, because + Orcapod puts no logical type inside a struct field. +- A reference names exactly one entry: the table's id (`table_id`), the version the source + read (`version`, the snapshot SpiralDB resolved the source's `pinned_version` to), the + row's primary-key values (`key`, the canonical JSON of the key columns in key order, the + form of a record ID), the column (`column`) and the address of the SpiralDB service the source read from (`service`, such + as `https://spiral.example.invalid`; never a credential). The entry it names may itself + hold a null. +- The scan does not read the encoded columns. Every other column, and every record ID, is + read exactly as from the same table without them. +- `entry.read()` returns the entry: a `pyarrow.Table` of one row and one column, the value + as SpiralDB stores it, with its encoding's extension name and parameters on the field. + It reads the table by its id at exactly the reference's version, so it returns the same + value whenever it is called. While the process still holds an entry it hashed or read + (a value is held up to a budget of 512 MiB, least recently used first), it is not read + again; otherwise it is read again at that version. The table returned is yours: + changing it changes nothing the process holds. `entry.scan()` returns spiral-sdk's + own scan of that one key and that one column, to use the SDK's functions on it. Both + take an optional `client` (a `spiral.Client`); without one they connect to the + reference's service address and sign in as spiral-sdk does (the `SPIRAL_*` environment + variables, or a saved `spiral login`), and never ask a person to sign in. A read through + a given `client` always goes to SpiralDB and computes no hash, and entries are held per + sign-in. +- A reference's service address is data, and can name any host. Without a `client`, + Orcapod signs in only to an address this process reached through a `SpiralDBConnector` + or a SpiralDB source it built (compared without regard to the case of the scheme and + host, a default port or a trailing `/`). Reading, scanning or hashing a reference to + any other address raises `orcapod.errors.SpiralDBUntrustedServiceError` before a client + is made or a credential taken (`SpiralDBEntry.prefetch` included): build a source of + that service first, or pass a client of it (`entry.read(client=...)`). A process forked + from one that reached an address trusts it too, as the same program with the same + credentials, but holds none of its parent's clients or entries. The address check controls + where Orcapod uses the worker's sign-in. Accept references only from producers you trust + to select data the worker can read, including the table, version, key, and column. +- When the version no longer holds a row with the key, or the table or that exact + version no longer exists, `entry.read()` raises `orcapod.errors.SpiralDBEntryMissingError` + (a `LookupError`) naming the reference; a newer version is never read in its place. + `entry.scan()` raises it only when the table or the version does not exist: the scan + is lazy, and for a key the version does not hold it yields no row, which its caller + must handle. A failure to reach the service or to sign in is not a missing entry: it + is raised as itself, by `read()`, `scan()` and hashing alike. +- A function pod over the source receives `SpiralDBEntry` objects, and can return one: it is + stored as the reference. An encoded column cannot be a tag or key column, and `where` + cannot name it. + + +```python +import orcapod as op +from orcapod import function_pod +from orcapod.sources import SpiralDBTableSource + +# The encoded cells and their block_0, norms, and count fields must be non-null. +# "rate" is a nullable plain column. +items = SpiralDBTableSource("my-project-123456", "items") + + +@function_pod(output_keys=("first_norm", "count")) +def summarize( + vector: op.SpiralDBEntry, embeddings: op.SpiralDBEntry, rate: float | None +) -> tuple[float, int]: + vector_value = vector.read().column("vector")[0].as_py() + embedding_value = embeddings.read().column("embeddings")[0].as_py() + if vector_value is None: + raise ValueError("vector must be non-null") + if embedding_value is None: + raise ValueError("embeddings must be non-null") + block = vector_value["block_0"] + if block is None: + raise ValueError("vector.block_0 must be non-null") + norm = block["norms"] + if norm is None: + raise ValueError("vector.block_0.norms must be non-null") + count = embedding_value["count"] + if count is None: + raise ValueError("embeddings.count must be non-null") + return norm * (1.0 if rate is None else rate), count + + +summaries = summarize.pod(items.select_data_columns(["vector", "embeddings", "rate"])) +``` + +This sample needs a SpiralDB service. The test suite runs it against a fake SpiralDB +(`test_the_documented_sample_runs` in +`tests/test_core/sources/test_spiraldb_table_source_encoded.py`). + +**A reference is hashed by its entry's content.** The hash of a reference is the hash of +the entry it names (its value, bit for bit, and its encoding's extension name and +parameters), not of the reference's fields. When a run's check (`check_for_new_data()`) +pins a newer table version, unchanged entry content keeps the same hash. The function pod +can reuse a stored result when all inputs used for cache lookup also match, including plain +inputs such as `rate`. References with equal content can reuse a result across different +keys, versions, or columns. If the result depends on a locator field such as `entry.key`, +pass that locator field as a separate plain input so it participates in cache lookup. +Hashing needs the content, so a job first reads the entries it is +about to hash, together: one SpiralDB scan per table version for the rows a function node +takes at once (all its input rows on the synchronous path and in a load-only run, +`run(load_only=True)`, on either path; when an asynchronous run executes, the rows that +have arrived, at most 256 at a time, so 257 rows waiting in one version take two scans, +of 256 and 1 keys), and hashes those rows from what that scan read. The +bound is per function-node batch, not per batch a source reads. The references a +function returns are read the same way before its results are recorded (each result's +hash is part of its record): one scan per table version for the results a node holds at +once. Synchronous runs can hold up to 256 results under `continue`. Under `fail_fast` +or for a function that takes an invocation context to deliver side effects, a synchronous +run finishes one row before computing the next. An asynchronous run reads up to 256 +results that have arrived under either policy. Under `fail_fast`, this can include +results computed beside a failing one. A row is reported as ended only +once its result is hashed and recorded. A node whose inputs hold no reference takes its +rows one by one, as before. The entries read also stay in a cache for the process, per sign-in (up to a +million hashes and 256 MiB charged for them, and 512 MiB of values, least recently used +first; each charged its key, its missing reason or its bytes with their field metadata). +An entry that is no longer held is read again on its own, at its version, when it is +hashed outside such a batch or read; when the process's sign-in cannot be told apart, +nothing is kept after the batch. Building the source, a plain read (`as_table()`, `iter_data()`), `head()` and +the preview read no entry; a read that asks for row hashes +(`as_table(columns={"content_hash": True})`) hashes the references, and so reads their +entries. + +Entries are kept per sign-in as Orcapod sees it when a read starts and ends: the +environment and the saved login. What a batch read serves only that sign-in: after a +change, an entry is read again under the new one. A kept entry is served without asking +the service again (a table version never changes), so a change of permissions under the +same sign-in is not seen while the process keeps it. Changing the sign-in while reads run in other threads of +the same process is not supported: spiral-sdk does not say which sign-in a client used, so +a read that saw the sign-in change and change back could keep what it read under the +earlier one. + +In a job, an entry that cannot be read (`SpiralDBEntryMissingError`) fails its own input +row, under the node's error policy (`continue` records it and goes on; `fail_fast` stops +the run); so does a returned reference whose entry cannot be read. Any other error (a +failed scan, a refused service address, a reference to a column the table's version does +not have, which concerns that reference only) stops the run, whatever the policy: for an input, +at the first row whose hash needs that entry, with the column named; for a returned +reference, at the row whose result names it. The run keeps results recorded before it +stops. On the asynchronous path, results reach the recorder in arrival order, so an +earlier input row can still be computing when a later row stops the run. + +**A source over references needs a source id.** A source built from a table, rows or +Python values that hold `SpiralDBEntry` references (an `ArrowTableSource`, `DictSource`, +`ListSource` and the like), also inside a list, has no default source id, because the +default hashes every value, which would read every entry: give it a `source_id`. The error +names the columns. + +**A reference lives in a column of its own.** A `SpiralDBEntry` is supported as a column's +type, and inside `list[...]` there. It is refused anywhere else: as a field of a dataclass, +a pydantic model or an `orcapod.dataclass` (at any depth, also in a list field), raised +where the class is declared for a source or a function pod +(`NestedTypeNotStorableError`, a `ValueError`); as a dict key or value or a tuple field, +as any logical type there; and inside an Arrow struct or map column, raised when the source +is built (`InputValidationError`). A class is stored and hashed as its fields are stored, +so a reference inside one would be hashed by its fields, not by its entry's content. + +References are [provisional](arrays.md#provisional-value-hashes): their value hash and stored +identity may change in a later release, and using them issues `ProvisionalHashWarning`. Any +other stored extension type that is not a Vortex encoding is still refused when the source +is built (`InputValidationError`). + ### `CachedSource`: a record id names one row A `CachedSource` (`source.cached(cache_database=...)`) keeps every row its wrapped source diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index e4ad91dcf..00047aac2 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -82,6 +82,7 @@ Hash labels: | `pandas_dataframe_v1` | the `pandas.DataFrame` value hash (§10) | `PANDAS_DATAFRAME_HASH_LABEL`, `hashing/pandas_value_hash.py` | | `pandas_series_v1` | the `pandas.Series` value hash (§10) | `PANDAS_SERIES_HASH_LABEL`, `hashing/pandas_value_hash.py` | | `torch_tensor_v1` | the torch tensor value hash (§8): the element digest, then `requires_grad`, the lazy conjugate and negative bits, the strides and the class | `TORCH_TENSOR_HASH_LABEL`, `logical_types/torch_type.py` | +| `spiraldb_entry_v1` | the SpiralDB entry reference value hash: starfix's strict digest of the entry's content as spiral-sdk returns it (one value with its Arrow field and metadata, under a fixed column name); the reference's table, version, key, column and service are not part of it (ITL-1789) | `SPIRALDB_ENTRY_HASH_LABEL`, `logical_types/spiraldb_entry_type.py` | | `polars_expr_v1` | the Polars expression hash (§1c) | `POLARS_EXPR_HASH_LABEL`, `hashing/semantic_hashing/polars_expr.py` | | `polars_dataframe_v1` | the Polars DataFrame value hash (§1e) | `PolarsDataFrameHandler.HASH_LABEL`, `hashing/semantic_hashing/builtin_handlers.py` | | `polars_series_v1` | the Polars Series value hash (§1e) | `PolarsSeriesHandler.HASH_LABEL`, `hashing/semantic_hashing/builtin_handlers.py` | @@ -391,6 +392,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | directory hasher | a directory tree | Merkle tree of SHA-256 entries, `directory_v1`; file leaves taken with their label. The handler verifies custom directory hashes against the library Merkle procedure. | `Directory` value hash | `hashing/directory_hashers.py:BasicDirectoryHasher.hash_directory`, `hashing/directory_hashers.py:_hash_dir`, `hashing/semantic_hashing/builtin_handlers.py:DirectoryHandler.handle`, `hashing/directory_hashers.py:verified_directory_hash`, `hashing/directory_hashers.py:canonical_directory_hash` | | array value hash | an array: element digest, then order, byte order, struct layout | SHA-256, `ndarray_v1` (the element digest is a step of the same algorithm) | `numpy.ndarray` value hash | `logical_types/numpy_type.py:array_value_digest`, `logical_types/array_format.py:array_digest_v1` | | tensor value hash | element digest, flags, strides, class | SHA-256, `torch_tensor_v1` | `torch.Tensor` value hash | `logical_types/torch_type.py:tensor_digest` | +| SpiralDB entry content hash | the content of the entry a `SpiralDBEntry` names, fetched from SpiralDB (one scan per service, table and version for many entries) | starfix strict digest, `spiraldb_entry_v1` | `SpiralDBEntry` value hash (into a hash: a cell token of an `orcapod.spiraldb.entry` column, a bare reference's hash); held for the batch being hashed and per process and sign-in in the entry cache (display only: an in-memory key) | `logical_types/spiraldb_entry_type.py:entry_content_hash`, `core/sources/spiraldb_entries.py:_fetch_group`, `core/sources/spiraldb_entries.py:cached_content_hash`, `hashing/semantic_hashing/builtin_handlers.py:SpiralDBEntryHandler.handle` | | pandas value hash | descriptor, `\0`, `b"arrow_ordered_v1:" + D`; inferred struct fields in `object` columns are sorted by name at every depth before computing `D` | SHA-256, `pandas_dataframe_v1` / `pandas_series_v1` | pandas value hash | `hashing/pandas_value_hash.py:pandas_frame_content_hash`, `hashing/pandas_value_hash.py:pandas_series_content_hash`, `hashing/labelled_hash.py:labelled_content_hash`, `hashing/semantic_hashing/builtin_handlers.py:PandasDataFrameHandler.digest`, `hashing/semantic_hashing/builtin_handlers.py:PandasSeriesHandler.digest` | | Polars value hash | descriptor, `\0`, starfix digest called directly (a step of this algorithm) | SHA-256, `polars_dataframe_v1` / `polars_series_v1` | Polars value hash | `logical_types/polars_type.py:_digest`, `logical_types/polars_type.py:_values_digest` | | Polars expression hash | the expression's canonical tree | SHA-256 of canonical JSON, `polars_expr_v1` | `PolarsFilter` identity (an operator that is not recommended) | `hashing/semantic_hashing/polars_expr.py:polars_expr_content_hash` | diff --git a/src/orcapod/__init__.py b/src/orcapod/__init__.py index 65f18ad89..7b406f303 100644 --- a/src/orcapod/__init__.py +++ b/src/orcapod/__init__.py @@ -58,6 +58,9 @@ from orcapod.logical_types.file_type import File from orcapod.logical_types.directory_type import Directory +# A reference to one entry of a SpiralDB table (ITL-1789) +from orcapod.logical_types.spiraldb_entry_type import SpiralDBEntry + # Extension registration API (ITL-473) from .extensions import OrcapodExtension, register_extension @@ -112,6 +115,8 @@ "Path", "UPath", "UUID", + # A reference to one entry of a SpiralDB table (ITL-1789) + "SpiralDBEntry", # Extension registration API (ITL-473) "OrcapodExtension", "register_extension", diff --git a/src/orcapod/channels.py b/src/orcapod/channels.py index 8111912f4..c6710ebaf 100644 --- a/src/orcapod/channels.py +++ b/src/orcapod/channels.py @@ -50,6 +50,14 @@ async def receive(self) -> T_co: """Receive next item. Raises ``ChannelClosed`` when done.""" ... + def take_ready(self, max_items: int) -> list[T_co]: + """Take the items already waiting, up to ``max_items``, without waiting. + + Items come in the order they were sent, after any ``receive`` before. An + empty list says only that nothing is waiting now: ``receive`` tells the end. + """ + ... + def __aiter__(self) -> AsyncIterator[T_co]: ... async def __anext__(self) -> T_co: ... @@ -117,6 +125,11 @@ async def receive(self) -> T: raise ChannelClosed() return item # type: ignore[return-value] + def take_ready(self, max_items: int) -> list[T]: + if self._channel._drained: + return [] + return _take_waiting(self._channel._queue, max_items) + def __aiter__(self) -> AsyncIterator[T]: return self @@ -133,6 +146,22 @@ async def collect(self) -> list[T]: return items +def _take_waiting(queue: asyncio.Queue[T | _Sentinel], at_most: int) -> list[T]: + """Take up to ``at_most`` items already in ``queue``, without waiting. + + The end-of-stream marker is put back where it was, so the next ``receive`` ends. + """ + items: list[T] = [] + while len(items) < at_most and not queue.empty(): + item = queue.get_nowait() + if isinstance(item, _Sentinel): + # Nothing follows the marker, and the queue has just made room for it. + queue.put_nowait(item) + break + items.append(item) + return items + + class _ChannelWriter(Generic[T]): """Concrete WritableChannel backed by a Channel.""" @@ -228,6 +257,9 @@ async def receive(self) -> T: raise ChannelClosed() return item # type: ignore[return-value] + def take_ready(self, max_items: int) -> list[T]: + return _take_waiting(self._queue, max_items) + def __aiter__(self) -> AsyncIterator[T]: return self diff --git a/src/orcapod/contexts/logical_types.json b/src/orcapod/contexts/logical_types.json index 5aa387a47..9a974aea5 100644 --- a/src/orcapod/contexts/logical_types.json +++ b/src/orcapod/contexts/logical_types.json @@ -14,6 +14,7 @@ "orcapod.pandas.series", "orcapod.polars.dataframe", "orcapod.polars.series", + "orcapod.spiraldb.entry", "orcapod.torch.tensor" ], "logical_type_registry": { @@ -40,6 +41,10 @@ "_class": "orcapod.logical_types.directory_type.LogicalDirectory", "_config": {} }, + { + "_class": "orcapod.logical_types.spiraldb_entry_type.LogicalSpiralDBEntry", + "_config": {} + }, { "_class": "orcapod.logical_types.numpy_type.LogicalNumpyArray", "_config": { @@ -174,6 +179,15 @@ } } ], + [ + { + "_type": "orcapod.logical_types.spiraldb_entry_type.SpiralDBEntry" + }, + { + "_class": "orcapod.hashing.semantic_hashing.builtin_handlers.SpiralDBEntryHandler", + "_config": {} + } + ], [ { "_type": "numpy.ndarray" diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index f60283ded..4c9ca53ff 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -18,13 +18,14 @@ import asyncio import contextlib +import functools import dataclasses import logging import sys import uuid from abc import abstractmethod from collections import Counter -from collections.abc import Callable, Iterator, Mapping, Sequence +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from datetime import datetime, timezone from functools import partial from typing import Any, Literal, NamedTuple, cast @@ -92,11 +93,13 @@ InputValidationError, PipelineJobRequiredError, OrcapodDatabaseError, + SpiralDBEntryMissingError, TypeIdentityError, OrcapodDatabaseWriteError, StoredTableSchemaError, UnstorableColumnError, ) +from orcapod.hashing.prefetch import prefetched_columns, prefetched_rows from orcapod.contexts.stored import ( StaleTables, keep_rows_of_data_context, @@ -113,7 +116,7 @@ commit_best_effort, database_write_path, keep_database_error, - database_error_of, + keep_run_error, ) from orcapod.protocols.core_protocols import ( FunctionPodProtocol, @@ -157,6 +160,61 @@ ) +_PREFETCH_ROWS = 256 +"""At most how many waiting input rows an async function node takes together, so +that what hashing them needs is fetched together (ITL-1789).""" + + +async def _with_waiting_rows( + channel: ReadableChannel[tuple[TagProtocol, DataProtocol]], + first: tuple[TagProtocol, DataProtocol], +) -> list[tuple[TagProtocol, DataProtocol]]: + """Return ``first`` and the rows that are waiting or that upstream sends at once. + + Rows already buffered are taken; then the event loop is given a turn while that + brings more, so an upstream that can send at once (a source, a chain of + operators) sends its rows into one batch. Nothing waits on a row that is not + ready. At most ``_PREFETCH_ROWS`` rows, in the order they were sent. + """ + batch = [first] + idle_turns = 0 + while len(batch) < _PREFETCH_ROWS and idle_turns < _IDLE_TURNS: + more = channel.take_ready(_PREFETCH_ROWS - len(batch)) + if more: + batch.extend(more) + idle_turns = 0 + else: + await asyncio.sleep(0) + idle_turns += 1 + return batch + + +_IDLE_TURNS = 4 +"""How many event-loop turns in a row that bring no row end a batch (each upstream hop +needs a turn to pass a row on).""" + + +class _DeferredRecord(NamedTuple): + """A pipeline record waiting for its result's hash (``FunctionJobNode._record_result``).""" + + output_data: DataProtocol + record: Callable[..., None] + + +class _HeldRow(NamedTuple): + """A row a sync run holds until its batch's results are hashed + (``FunctionJobNode._execute_fetching_outputs``).""" + + tag: TagProtocol + data: DataProtocol + instance_id: bytes + tag_out: TagProtocol + result: DataProtocol | None + # The index of its deferred pipeline record, or ``None``. + record: int | None + cached: bool + + def _pipeline_record_order( recorded_at: datetime, result_id: bytes ) -> tuple[datetime, bytes]: @@ -1552,6 +1610,10 @@ def __init__( self._results_in_order = False self._rows_since_commit = 0 self._commit_failed = False + # Pipeline records waiting for their outputs' hashes, while a sync run holds + # a batch whose outputs fetch; ``finish`` inside ``_execute_fetching_outputs`` + # records them and empties the list (ITL-1789). + self._deferred_records: list[_DeferredRecord] | None = None self.attach_databases( pipeline_database=pipeline_database, @@ -2205,12 +2267,15 @@ def _execute_load_only( ) tag_schema = input_stream.output_schema(columns={"system_tags": True})[0] ctx_obs.on_node_start(node_label, node_hash, tag_schema=tag_schema) - inputs = [ - (tag, data, self.compute_instance_id(tag, data)) - for tag, data in input_stream.iter_data() - ] - _ = self.get_cached_results(instance_ids=[eid for _, _, eid in inputs]) + inputs = self._input_entries(input_stream.iter_data()) + _ = self.get_cached_results( + instance_ids=[eid for _, _, eid in inputs if isinstance(eid, bytes)] + ) for tag, data, entry_id in inputs: + if isinstance(entry_id, SpiralDBEntryMissingError): + # No input hash, so nothing stored can be its result. + not_stored += 1 + continue entry = self._stored_entry(entry_id) if entry is None: not_stored += 1 @@ -2260,14 +2325,17 @@ async def _async_execute_load_only( columns={"system_tags": True} )[0] ctx_obs.on_node_start(node_label, node_hash, tag_schema=tag_schema) - inputs = [ - (tag, data, self.compute_instance_id(tag, data)) - async for tag, data in input_channel - ] - _ = self.get_cached_results(instance_ids=[eid for _, _, eid in inputs]) + inputs = await self._input_entries_of_channel(input_channel) + _ = self.get_cached_results( + instance_ids=[eid for _, _, eid in inputs if isinstance(eid, bytes)] + ) loaded_ids: list[bytes] = [] not_stored = 0 for tag, data, entry_id in inputs: + if isinstance(entry_id, SpiralDBEntryMissingError): + # No input hash, so nothing stored can be its result. + not_stored += 1 + continue entry = self._stored_entry(entry_id) if entry is None: not_stored += 1 @@ -2804,11 +2872,12 @@ def execute( output: list[tuple[TagProtocol, DataProtocol]] = [] try: # Collect upstream entries and resolve their instance ids. - upstream_entries: list[tuple[TagProtocol, DataProtocol, bytes]] = [ - (tag, data, self.compute_instance_id(tag, data)) - for tag, data in input_stream.iter_data() + upstream_entries = self._input_entries( + input_stream.iter_data(), stop_at_missing=error_policy == "fail_fast" + ) + instance_ids = [ + eid for _, _, eid in upstream_entries if isinstance(eid, bytes) ] - instance_ids = [eid for _, _, eid in upstream_entries] # Hot-load any already-computed results from DB into _cached_output_datas. # get_cached_results() is called for its side effect (populating the @@ -2822,69 +2891,102 @@ def execute( # successful computation), one per input: the node's rows afterwards. emitted_entry_ids: list[bytes] = [] failed_rows = 0 - for tag, data, instance_id in upstream_entries: - ctx_obs.on_data_start(node_label, tag, data) + if self._outputs_fetch(): + # The results' values fetch when hashed (ITL-1789): batches. + failed_rows = self._execute_fetching_outputs( + upstream_entries, + ctx_obs=ctx_obs, + node_label=node_label, + node_hash=node_hash, + error_policy=error_policy, + run_id=run_id, + output=output, + emitted_entry_ids=emitted_entry_ids, + ) + else: + for tag, data, instance_id in upstream_entries: + ctx_obs.on_data_start(node_label, tag, data) - if instance_id in self._cached_output_datas and not isinstance( - self._cached_output_datas[instance_id][1], EmptyData - ): - tag_out, result = self._cached_output_datas[instance_id] - ctx_obs.on_data_end(node_label, tag, data, result, cached=True) + if isinstance(instance_id, SpiralDBEntryMissingError): + # The row has no input hash: a failed row, as one whose function + # raised (ITL-1789). + logger.debug( + "Data execution failed in %s, skipping: %s", + node_label, + instance_id, + ) + if error_policy == "fail_fast": + with keep_run_error(instance_id, "Observer on_data_crash"): + ctx_obs.on_data_crash( + node_label, tag, data, instance_id + ) + with keep_run_error(instance_id, "Observer on_node_end"): + ctx_obs.on_node_end(node_label, node_hash) + raise instance_id + ctx_obs.on_data_crash(node_label, tag, data, instance_id) + failed_rows += 1 + continue + + if instance_id in self._cached_output_datas and not isinstance( + self._cached_output_datas[instance_id][1], EmptyData + ): + tag_out, result = self._cached_output_datas[instance_id] + ctx_obs.on_data_end(node_label, tag, data, result, cached=True) + emitted_entry_ids.append(instance_id) + if result is not None: + output.append((tag_out, result)) + continue + + pkt_logger = ctx_obs.create_data_logger(tag, data) + try: + tag_out, result = self._process_data_internal( + tag, + data, + logger=pkt_logger, + run_id=run_id, + instance_id=instance_id, + ) + except OrcapodDatabaseError as exc: + # A failed database read or write fails the run whatever the error + # policy: error_policy only decides about rows whose function + # raised. + exc.add_context(node_label=node_label, tag=tag.as_dict()) + with keep_database_error(exc, "Observer on_data_crash"): + ctx_obs.on_data_crash(node_label, tag, data, exc) + with keep_database_error(exc, "Observer on_node_end"): + ctx_obs.on_node_end(node_label, node_hash) + raise + except TypeIdentityError as exc: + # A stored row that cannot be decoded as its class is never + # skipped as a row failure, whatever the error policy (ITL-881). + with keep_database_error(exc, "Observer on_data_crash"): + ctx_obs.on_data_crash(node_label, tag, data, exc) + with keep_database_error(exc, "Observer on_node_end"): + ctx_obs.on_node_end(node_label, node_hash) + raise + except Exception as exc: + # Reported at the end of a job run (RunSummary, RowFailuresWarning), + # so one traceback per failed row is only for debugging. + logger.debug( + "Data execution failed in %s, skipping: %s", + node_label, + exc, + exc_info=True, + ) + ctx_obs.on_data_crash(node_label, tag, data, exc) + if error_policy == "fail_fast": + ctx_obs.on_node_end(node_label, node_hash) + raise + failed_rows += 1 + continue + + ctx_obs.on_data_end(node_label, tag, data, result, cached=False) emitted_entry_ids.append(instance_id) if result is not None: output.append((tag_out, result)) - continue - - pkt_logger = ctx_obs.create_data_logger(tag, data) - try: - tag_out, result = self._process_data_internal( - tag, - data, - logger=pkt_logger, - run_id=run_id, - instance_id=instance_id, - ) - except OrcapodDatabaseError as exc: - # A failed database read or write fails the run whatever the error - # policy: error_policy only decides about rows whose function - # raised. - exc.add_context(node_label=node_label, tag=tag.as_dict()) - with keep_database_error(exc, "Observer on_data_crash"): - ctx_obs.on_data_crash(node_label, tag, data, exc) - with keep_database_error(exc, "Observer on_node_end"): - ctx_obs.on_node_end(node_label, node_hash) - raise - except TypeIdentityError as exc: - # A stored row that cannot be decoded as its class is never - # skipped as a row failure, whatever the error policy (ITL-881). - with keep_database_error(exc, "Observer on_data_crash"): - ctx_obs.on_data_crash(node_label, tag, data, exc) - with keep_database_error(exc, "Observer on_node_end"): - ctx_obs.on_node_end(node_label, node_hash) - raise - except Exception as exc: - # Reported at the end of a job run (RunSummary, RowFailuresWarning), - # so one traceback per failed row is only for debugging. - logger.debug( - "Data execution failed in %s, skipping: %s", - node_label, - exc, - exc_info=True, + self._commit_or_end_node( + self._row_processed, ctx_obs, node_label, node_hash ) - ctx_obs.on_data_crash(node_label, tag, data, exc) - if error_policy == "fail_fast": - ctx_obs.on_node_end(node_label, node_hash) - raise - failed_rows += 1 - continue - - ctx_obs.on_data_end(node_label, tag, data, result, cached=False) - emitted_entry_ids.append(instance_id) - if result is not None: - output.append((tag_out, result)) - self._commit_or_end_node( - self._row_processed, ctx_obs, node_label, node_hash - ) self._commit_or_end_node( self._commit_at_node_end, ctx_obs, node_label, node_hash @@ -3009,6 +3111,302 @@ def _empty_data_cache_hit( ), ) + def _execute_fetching_outputs( + self, + upstream_entries: Sequence[ + tuple[TagProtocol, DataProtocol, bytes | SpiralDBEntryMissingError] + ], + *, + ctx_obs: Any, + node_label: str, + node_hash: str, + error_policy: str, + run_id: str | None, + output: list[tuple[TagProtocol, DataProtocol]], + emitted_entry_ids: list[bytes], + ) -> int: + """Run the rows of a sync run whose results' values fetch when hashed (a + function that returns SpiralDB entry references; ITL-1789). + + Each row starts, and its function runs and its result is stored, as on the + other path; its pipeline record (which holds its result's hash), its end and + its place in the node's rows wait until up to ``_PREFETCH_ROWS`` rows (cache + hits and repeats included) are held, whose results' references are then fetched together, one scan per + table version. The rows keep their input order. Under ``fail_fast`` each row + is finished before the next one runs. Side-effecting functions also finish + each row before delivering the next. A repeated input whose first occurrence is + still held ends with that occurrence's outcome. Only a result that names a + missing entry is a failed row; any other error raised while hashing a result + stops the run, after the rows held before it are finished. + + Returns: + How many rows failed. + """ + failed = 0 + finish_each_row = error_policy == "fail_fast" or self._delivers_side_effects + held: list[_HeldRow] = [] + pending_results: dict[bytes, _HeldRow] = {} + # The node's end is reported once, by whichever failure ends the run first. + node_ended = False + # The row whose database or identity error the run raises, while the rows held + # before it are finished: its crash is reported before the node's end. + fatal: tuple[TagProtocol, DataProtocol, Exception] | None = None + waiting_failure: tuple[TagProtocol, DataProtocol, Exception] | None = None + active_row: tuple[TagProtocol, DataProtocol] | None = None + finishing_after_error: Exception | None = None + + def end_node(run_error: Exception) -> None: + """Report the failed node's end once, preserving its error.""" + nonlocal node_ended + if node_ended: + return + node_ended = True + with keep_run_error(run_error, "Observer on_node_end"): + ctx_obs.on_node_end(node_label, node_hash) + + def crash(tag: TagProtocol, data: DataProtocol, exc: Exception) -> None: + """Report a failed row; raise under ``fail_fast`` (the caller re-raises + what this does not).""" + logger.debug( + "Data execution failed in %s, skipping: %s", + node_label, + exc, + exc_info=True, + ) + if error_policy == "fail_fast": + with keep_run_error(exc, "Observer on_data_crash"): + ctx_obs.on_data_crash(node_label, tag, data, exc) + end_node(exc) + raise exc + ctx_obs.on_data_crash(node_label, tag, data, exc) + + def run_error_for(exc: Exception) -> Exception: + """The error the run raises when ``exc`` ends it: the fatal row's, when + one waits (finishing the rows held before it raised), else ``exc``.""" + if fatal is not None: + return fatal[2] + return finishing_after_error if finishing_after_error is not None else exc + + def abort(aborted: Sequence[_HeldRow], exc: Exception) -> None: + """End the run for the observer: each started row held behind the failure + crashes with ``exc``, the waiting failed row with its own error, then + the node ends, once. An observer that raises cannot interrupt the reports + or replace the error the run raises.""" + nonlocal fatal, waiting_failure + run_error = run_error_for(exc) + for row in aborted: + with keep_run_error(run_error, "Observer on_data_crash"): + ctx_obs.on_data_crash(node_label, row.tag, row.data, exc) + waiting = fatal if fatal is not None else waiting_failure + if waiting is not None: + failed_tag, failed_data, failed_exc = waiting + fatal = None + waiting_failure = None + if isinstance(failed_exc, OrcapodDatabaseError): + with keep_run_error(run_error, "Adding row context"): + failed_exc.add_context( + node_label=node_label, tag=failed_tag.as_dict() + ) + with keep_run_error(run_error, "Observer on_data_crash"): + ctx_obs.on_data_crash( + node_label, failed_tag, failed_data, failed_exc + ) + end_node(run_error) + + def finish() -> None: + """Fetch the held results' references together, then record, end and + emit the held rows in order.""" + nonlocal failed + pending = self._deferred_records or [] + self._deferred_records = [] + rows = list(held) + held.clear() + pending_results.clear() + # The instances whose held result names a missing entry, with the error. + missing: dict[bytes, SpiralDBEntryMissingError] = {} + reported = 0 + prefetch = contextlib.ExitStack() + try: + _ = prefetch.enter_context( + prefetched_rows( + [record.output_data for record in pending], + self.data_context.type_converter, + self.data_context.semantic_hasher, + ) + ) + for index, row in enumerate(rows): + row_error = missing.get(row.instance_id) + if row.record is not None: + deferred = pending[row.record] + try: + deferred.record( + output_data_hash=deferred.output_data.content_hash() + ) + except SpiralDBEntryMissingError as exc: + # A repeat of this input fails with the same error. + missing[row.instance_id] = exc + row_error = exc + except OrcapodDatabaseError as exc: + with keep_run_error( + run_error_for(exc), "Adding row context" + ): + exc.add_context( + node_label=node_label, tag=row.tag.as_dict() + ) + raise + else: + self._cache_output_data( + row.instance_id, row.tag_out, row.result + ) + # A terminal callback that raises may have already reported. + reported = index + 1 + if row_error is not None: + crash(row.tag, row.data, row_error) + failed += 1 + continue + ctx_obs.on_data_end( + node_label, row.tag, row.data, row.result, cached=row.cached + ) + emitted_entry_ids.append(row.instance_id) + if row.result is not None: + output.append((row.tag_out, row.result)) + if not row.cached: + self._row_processed() + prefetch.close() + except Exception as exc: + with keep_run_error(run_error_for(exc), "Closing the output prefetch"): + prefetch.close() + abort(rows[reported:], exc) + raise + finally: + prefetch.close() + + def finish_before_crash( + tag: TagProtocol, data: DataProtocol, exc: Exception + ) -> None: + """Report this row after finishing, or during abort if finishing fails.""" + nonlocal waiting_failure + waiting_failure = (tag, data, exc) + try: + finish() + finally: + waiting_failure = None + crash(tag, data, exc) + + self._deferred_records = [] + try: + for tag, data, instance_id in upstream_entries: + ctx_obs.on_data_start(node_label, tag, data) + active_row = (tag, data) + if isinstance(instance_id, SpiralDBEntryMissingError): + # No input hash: a failed row (see ``execute``). + active_row = None + finish_before_crash(tag, data, instance_id) + failed += 1 + continue + pending_result = pending_results.get(instance_id) + cached_result = ( + (pending_result.tag_out, pending_result.result) + if pending_result is not None + else self._cached_output_datas.get(instance_id) + ) + if cached_result is not None and not isinstance( + cached_result[1], EmptyData + ): + tag_out, result = cached_result + held.append( + _HeldRow(tag, data, instance_id, tag_out, result, None, True) + ) + active_row = None + if finish_each_row or len(held) >= _PREFETCH_ROWS: + finish() + continue + pkt_logger = ctx_obs.create_data_logger(tag, data) + before = len(self._deferred_records) + try: + tag_out, result = self._process_data_internal( + tag, + data, + logger=pkt_logger, + run_id=run_id, + instance_id=instance_id, + ) + except (OrcapodDatabaseError, TypeIdentityError) as exc: + # The rows held before it are recorded first; this error is the + # one the run raises. When finishing them ends the run, this row's + # crash is reported there, before the node's end. + active_row = None + fatal = (tag, data, exc) + with keep_database_error(exc, "Finishing the rows held before it"): + finish() + if fatal is not None: + abort((), exc) + raise + except Exception as exc: + active_row = None + finish_before_crash(tag, data, exc) + failed += 1 + continue + record = before if len(self._deferred_records) > before else None + row = _HeldRow(tag, data, instance_id, tag_out, result, record, False) + held.append(row) + active_row = None + if record is not None: + pending_results[instance_id] = row + if finish_each_row or len(held) >= _PREFETCH_ROWS: + finish() + finish() + except Exception as exc: + if not node_ended: + # A failure outside row processing still owes the held rows their + # records and terminal events. A secondary failure cannot replace it. + finishing_after_error = exc + if active_row is not None: + waiting_failure = (*active_row, exc) + if held: + with keep_run_error(exc, "Finishing the held rows"): + finish() + if not node_ended: + abort((), exc) + raise + finally: + self._deferred_records = None + return failed + + def _record_result( + self, + output_data: DataProtocol, + record: Callable[..., None], + ) -> None: + """Record a result's pipeline row: now, or, while a sync run holds a batch + whose outputs fetch, once the batch's outputs are fetched together: ``finish`` + inside ``_execute_fetching_outputs`` records the held rows and empties the + list. + + Args: + output_data: The result, as hashed into the row (before fall-through). + record: ``_add_pipeline_record`` with every argument but + ``output_data_hash``. + """ + if self._deferred_records is None: + record(output_data_hash=output_data.content_hash()) + else: + self._deferred_records.append(_DeferredRecord(output_data, record)) + + def _outputs_fetch(self) -> bool: + """Whether hashing this node's results fetches what an output's values name (a + SpiralDB entry), from the function's declared outputs (``prefetched_columns``); + no graph is walked. A loaded node with no function computes nothing.""" + if self._function_pod is None: + return False + converter = self.data_context.type_converter + schema = converter.python_schema_to_arrow_schema( + self._function_pod.data_function.output_data_schema + ) + return bool( + prefetched_columns(schema, converter, self.data_context.semantic_hasher) + ) + def _process_data_internal( self, tag: TagProtocol, @@ -3021,7 +3419,8 @@ def _process_data_internal( """Core compute + persist + cache. Used by ``execute_data`` and ``execute``. - Stores result in ``_cached_output_datas`` keyed by instance_id. + Caches the result by instance id once its record is written, or immediately + when there is no pipeline record to write. Exceptions propagate to the caller — no error handling here. Args: @@ -3058,6 +3457,7 @@ def _process_data_internal( self._preflight_pipeline_write_schema() ephemeral_result = bool(self._node_config.is_result_ephemeral) + records_before = len(self._deferred_records or ()) if ephemeral_result: if self._ephemeral_cached_pod is None: @@ -3085,15 +3485,18 @@ def _process_data_internal( ) ) if self._pipeline_database is not None: - self._add_pipeline_record( - tag, - data, - instance_id, - data_record_id=output_data.datagram_uuid, - computed=result_computed, - is_ephemeral=not from_persistent, - output_data_hash=output_data.content_hash(), - run_id=run_id, + self._record_result( + output_data, + functools.partial( + self._add_pipeline_record, + tag, + data, + instance_id, + data_record_id=output_data.datagram_uuid, + computed=result_computed, + is_ephemeral=not from_persistent, + run_id=run_id, + ), ) elif self._cached_function_pod is not None: tag_out, output_data = self._cached_function_pod.process_data( @@ -3108,14 +3511,17 @@ def _process_data_internal( self._cached_function_pod.RESULT_COMPUTED_FLAG, False ) ) - self._add_pipeline_record( - tag, - data, - instance_id, - data_record_id=output_data.datagram_uuid, - computed=result_computed, - output_data_hash=output_data.content_hash(), - run_id=run_id, + self._record_result( + output_data, + functools.partial( + self._add_pipeline_record, + tag, + data, + instance_id, + data_record_id=output_data.datagram_uuid, + computed=result_computed, + run_id=run_id, + ), ) else: tag_out, output_data = self._function_pod.process_data( @@ -3127,13 +3533,19 @@ def _process_data_internal( # through onto it, as the pod does (ITL-1023). output_data = with_fall_through(self._function_pod, data, output_data) - # Store by instance id (the same for every result of one instance) and invalidate caches + if len(self._deferred_records or ()) == records_before: + self._cache_output_data(instance_id, tag_out, output_data) + + return tag_out, output_data + + def _cache_output_data( + self, instance_id: bytes, tag_out: TagProtocol, output_data: DataProtocol | None + ) -> None: + """Store the result in memory and invalidate its derived views.""" self._cached_output_datas[instance_id] = (tag_out, output_data) self._cached_output_table = None self._cached_content_hash_column = None - return tag_out, output_data - def get_cached_results( self, instance_ids: list[bytes] ) -> dict[bytes, tuple[TagProtocol, DataProtocol]]: @@ -3274,6 +3686,135 @@ async def _async_process_data_internal( return tag_out, output_data + def _prefetched_inputs( + self, rows: Sequence[DataProtocol] + ) -> contextlib.AbstractContextManager[None]: + """Fetch together what hashing ``rows`` needs; hash them inside the block + (ITL-1789). + + A value whose hash is the content of something stored elsewhere (a SpiralDB + entry) is fetched for all the rows at once, one SpiralDB scan per table + version, and the rows hashed one by one inside the block use what was fetched. + Placeholders hold nothing. + """ + return prefetched_rows( + [row for row in rows if not isinstance(row, EmptyData)], + self.data_context.type_converter, + self.data_context.semantic_hasher, + ) + + def _inputs_fetch(self, row: DataProtocol) -> bool: + """Whether hashing ``row`` fetches what a column's values name (a SpiralDB + entry): a column whose values are prefetched (``prefetched_columns``). Rows of + one stream share their schema.""" + return bool( + prefetched_columns( + row.arrow_schema(), + self.data_context.type_converter, + self.data_context.semantic_hasher, + ) + ) + + def _input_entries( + self, + rows: Iterable[tuple[TagProtocol, DataProtocol]], + *, + stop_at_missing: bool = False, + ) -> list[tuple[TagProtocol, DataProtocol, bytes | SpiralDBEntryMissingError]]: + """Return each input row with its instance id, in input order. + + Decided from the first row with a payload, as the async router decides: when + its hash fetches (``_inputs_fetch``), the rest of the input is read first, + under either policy, and the rows' entries fetched together + (``_instance_ids_of``); otherwise each row's + id is computed as the row arrives, before the next row is asked for, so an + error hashing a row is raised before anything after it is read (ITL-1789). + With ``stop_at_missing`` (a ``fail_fast`` run), the rows end at the first one + whose entry is missing: the run stops there, so no later row is hashed and no + later error can take its place; an error reading the input after that row is + not raised either, as the row-by-row path would never have read on. Otherwise + an error reading the input is raised after the rows read before it are hashed. + """ + entries: list[ + tuple[TagProtocol, DataProtocol, bytes | SpiralDBEntryMissingError] + ] = [] + rows = iter(rows) + fetching: bool | None = None + for tag, data in rows: + if fetching is None and not isinstance(data, EmptyData): + fetching = self._inputs_fetch(data) + if fetching: + pairs = [(tag, data)] + read_error: Exception | None = None + try: + pairs.extend(rows) + except Exception as exc: + read_error = exc + ids = self._instance_ids_of(pairs, stop_at_missing=stop_at_missing) + entries += [ + (pair_tag, pair_data, eid) + for (pair_tag, pair_data), eid in zip( + pairs[: len(ids)], ids, strict=True + ) + ] + stopped = stop_at_missing and any( + isinstance(eid, SpiralDBEntryMissingError) for eid in ids + ) + if read_error is not None and not stopped: + raise read_error + return entries + entries.append((tag, data, self.compute_instance_id(tag, data))) + return entries + + async def _input_entries_of_channel( + self, rows: ReadableChannel[tuple[TagProtocol, DataProtocol]] + ) -> list[tuple[TagProtocol, DataProtocol, bytes | SpiralDBEntryMissingError]]: + """The async form of ``_input_entries``, over a channel.""" + entries: list[ + tuple[TagProtocol, DataProtocol, bytes | SpiralDBEntryMissingError] + ] = [] + pairs: list[tuple[TagProtocol, DataProtocol]] = [] + fetching: bool | None = None + async for tag, data in rows: + if fetching is None and not isinstance(data, EmptyData): + fetching = self._inputs_fetch(data) + if fetching: + pairs.append((tag, data)) + else: + entries.append((tag, data, self.compute_instance_id(tag, data))) + entries += [ + (tag, data, eid) + for (tag, data), eid in zip( + pairs, self._instance_ids_of(pairs), strict=True + ) + ] + return entries + + def _instance_ids_of( + self, + pairs: Sequence[tuple[TagProtocol, DataProtocol]], + *, + stop_at_missing: bool = False, + ) -> list[bytes | SpiralDBEntryMissingError]: + """Return each row's instance id, its entries fetched together first. + + A row that names a SpiralDB entry its table version does not hold has no input + hash: its place holds the ``SpiralDBEntryMissingError``, which the caller treats + as that row's failure. Any other error raises, as from ``compute_instance_id``, + at the first row it concerns. With ``stop_at_missing``, the ids end at the first + missing entry: no later row is hashed. + """ + ids: list[bytes | SpiralDBEntryMissingError] = [] + with self._prefetched_inputs([data for _, data in pairs]): + for tag, data in pairs: + try: + ids.append(self.compute_instance_id(tag, data)) + except SpiralDBEntryMissingError as exc: + ids.append(exc) + if stop_at_missing: + break + return ids + def compute_instance_id( self, tag: TagProtocol, @@ -4755,6 +5296,11 @@ async def async_execute( # Whether the node has started for the observer and not yet ended. node_open = False + # When the results' values fetch when hashed (ITL-1789), the end events held + # until each result is hashed and recorded, by correlation key. + held_ends: dict[ + bytes, tuple[TagProtocol, DataProtocol, DataProtocol, bool] + ] = {} try: tag_schema = self._input_stream.output_schema( columns={"system_tags": True} @@ -4815,6 +5361,11 @@ async def async_execute( run_entry_ids: list[bytes] = [] # Rows whose function raised (error policy "continue"). failed_rows: list[int] = [0] + # When the results' values fetch when hashed (ITL-1789), their + # hashes are taken together in the record stage, and a row's end is + # reported only once its result is hashed and recorded: the end + # events held meanwhile, by correlation key. + outputs_fetch = self._outputs_fetch() def lookup_crashed( tag: TagProtocol, data: DataProtocol, exc: Exception @@ -4837,183 +5388,265 @@ def lookup_crashed( with keep_database_error(exc, "Observer on_data_crash"): ctx_obs.on_data_crash(node_label, tag, data, exc) return False + if error_policy == "fail_fast" and isinstance( + exc, SpiralDBEntryMissingError + ): + with keep_run_error(exc, "Observer on_data_crash"): + ctx_obs.on_data_crash(node_label, tag, data, exc) + return False ctx_obs.on_data_crash(node_label, tag, data, exc) if error_policy == "fail_fast": return False failed_rows[0] += 1 return True - async def route_inputs() -> None: - """Stage 1: send cache hits to output; stamp misses for computation.""" + async def route_one(tag: TagProtocol, data: DataProtocol) -> None: + """Send one input row: a cache hit to output, a miss to compute.""" try: - async for tag, data in input_channel: - instance_id = self.compute_instance_id(tag, data) - # A cached EmptyData is a result that is gone (an - # ephemeral result from an earlier run): compute the row - # again, as the sync path does (ITL-923). - if instance_id in cached_by_instance_id and not ( - isinstance( - cached_by_instance_id[instance_id][1], - EmptyData, - ) - ): - cached_tag, cached_data = cached_by_instance_id[ - instance_id - ] - ctx_obs.on_data_start(node_label, tag, data) - ctx_obs.on_data_end( - node_label, tag, data, cached_data, cached=True - ) - await output.send((cached_tag, cached_data)) - # Recorded once the output took the row, so the held - # order is the order downstream received (a parked - # send can resume after a later one). - run_entry_ids.append(instance_id) - elif isinstance(data, EmptyData): - # A placeholder whose instance is not stored: the - # result store answers by its input hash, nothing - # is computed and no pipeline row is written - # (``_empty_data_cache_hit``). A placeholder with - # no stored result is a failed row under the row - # failure policy, with the events of the sync path: - # the row starts before the lookup. - ctx_obs.on_data_start(node_label, tag, data) + instance_id = self.compute_instance_id(tag, data) + except SpiralDBEntryMissingError as exc: + # No input hash: a failed row (ITL-1789). + ctx_obs.on_data_start(node_label, tag, data) + if not lookup_crashed(tag, data, exc): + raise + return + # A cached EmptyData is a result that is gone (an + # ephemeral result from an earlier run): compute the row + # again, as the sync path does (ITL-923). + if instance_id in cached_by_instance_id and not ( + isinstance( + cached_by_instance_id[instance_id][1], + EmptyData, + ) + ): + cached_tag, cached_data = cached_by_instance_id[instance_id] + ctx_obs.on_data_start(node_label, tag, data) + ctx_obs.on_data_end( + node_label, tag, data, cached_data, cached=True + ) + await output.send((cached_tag, cached_data)) + # Recorded once the output took the row, so the held + # order is the order downstream received (a parked + # send can resume after a later one). + run_entry_ids.append(instance_id) + elif isinstance(data, EmptyData): + # A placeholder whose instance is not stored: the + # result store answers by its input hash, nothing + # is computed and no pipeline row is written + # (``_empty_data_cache_hit``). A placeholder with + # no stored result is a failed row under the row + # failure policy, with the events of the sync path: + # the row starts before the lookup. + ctx_obs.on_data_start(node_label, tag, data) + try: + found_tag, found = self._empty_data_cache_hit( + tag, data, instance_id + ) + except Exception as exc: + if not lookup_crashed(tag, data, exc): + raise + return + ctx_obs.on_data_end(node_label, tag, data, found, cached=False) + await output.send((found_tag, found)) + run_entry_ids.append(instance_id) + else: + self._preflight_pipeline_write_schema() + found = None + if is_ephemeral: + if instance_id not in persistent_lookups: try: - found_tag, found = self._empty_data_cache_hit( - tag, data, instance_id + persistent_lookups[instance_id] = ( + self._persistent_result_in_ephemeral_mode(data) ) except Exception as exc: + # The sync path makes this lookup + # inside the row, after its start: + # the same events here. + with keep_database_error( + exc + if isinstance( + exc, + ( + OrcapodDatabaseError, + TypeIdentityError, + ), + ) + else None, + "Observer on_data_start", + ): + ctx_obs.on_data_start(node_label, tag, data) if not lookup_crashed(tag, data, exc): raise - continue + return + found = persistent_lookups[instance_id] + correlation_key = uuid.uuid4().bytes + input_store[correlation_key] = ( + tag, + data, + instance_id, + ) + stamped_tag = tag.with_meta_columns( + **{_TAG_NODE_INPUT_REF: correlation_key} + ) + if found is not None: + # Not computed, stored in neither result store + # again: straight to the record stage. + ctx_obs.on_data_start(node_label, tag, data) + if outputs_fetch: + held_ends[correlation_key] = (tag, data, found, False) + else: ctx_obs.on_data_end( node_label, tag, data, found, cached=False ) - await output.send((found_tag, found)) - run_entry_ids.append(instance_id) - else: - self._preflight_pipeline_write_schema() - found = None - if is_ephemeral: - if instance_id not in persistent_lookups: - try: - persistent_lookups[instance_id] = ( - self._persistent_result_in_ephemeral_mode( - data - ) - ) - except Exception as exc: - # The sync path makes this lookup - # inside the row, after its start: - # the same events here. - with keep_database_error( - exc - if isinstance( - exc, - ( - OrcapodDatabaseError, - TypeIdentityError, - ), - ) - else None, - "Observer on_data_start", - ): - ctx_obs.on_data_start( - node_label, tag, data - ) - if not lookup_crashed(tag, data, exc): - raise - continue - found = persistent_lookups[instance_id] - correlation_key = uuid.uuid4().bytes - input_store[correlation_key] = ( - tag, - data, - instance_id, - ) - stamped_tag = tag.with_meta_columns( - **{_TAG_NODE_INPUT_REF: correlation_key} - ) - if found is not None: - # Not computed, stored in neither result store - # again: straight to the record stage. - ctx_obs.on_data_start(node_label, tag, data) - ctx_obs.on_data_end( - node_label, tag, data, found, cached=False - ) - persistent_hits.add(correlation_key) - await result_channel.writer.send( - (stamped_tag, found) - ) - continue - # The function takes the row without its - # fall-through columns (ITL-1023). - await compute_channel.writer.send( - ( - stamped_tag, - function_input(self._function_pod, data), - ) - ) + persistent_hits.add(correlation_key) + await result_channel.writer.send((stamped_tag, found)) + return + # The function takes the row without its + # fall-through columns (ITL-1023). + await compute_channel.writer.send( + ( + stamped_tag, + function_input(self._function_pod, data), + ) + ) + + async def route_inputs() -> None: + """Stage 1: send cache hits to output; stamp misses for computation.""" + try: + # Whether hashing a row fetches what its values name (a + # SpiralDB entry), decided from the first row with a payload. + fetching: bool | None = None + async for tag, data in input_channel: + if fetching is None and not isinstance(data, EmptyData): + fetching = self._inputs_fetch(data) + if not fetching: + await route_one(tag, data) + continue + # The rows already waiting are taken together, so what + # hashing them needs is fetched together (ITL-1789); each + # is then handled on its own, in arrival order. + batch = await _with_waiting_rows(input_channel, (tag, data)) + with self._prefetched_inputs([d for _, d in batch]): + for batch_tag, batch_data in batch: + await route_one(batch_tag, batch_data) finally: await compute_channel.writer.close() - async def record_and_forward() -> None: - """Stage 3: record pipeline entry, strip key, emit to output.""" - async for output_tag, output_data in result_channel.reader: - correlation_key = output_tag.get_meta_value(_TAG_NODE_INPUT_REF) - original_tag, input_data, instance_id = input_store.pop( - cast(bytes, correlation_key) + async def record_one( + output_tag: TagProtocol, output_data: DataProtocol + ) -> None: + """Record one result's pipeline entry, strip its key, emit it.""" + correlation_key = output_tag.get_meta_value(_TAG_NODE_INPUT_REF) + original_tag, input_data, instance_id = input_store.pop( + cast(bytes, correlation_key) + ) + result_computed = bool( + output_data.get_meta_value( + execution_pod.RESULT_COMPUTED_FLAG, False ) - result_computed = bool( - output_data.get_meta_value( - execution_pod.RESULT_COMPUTED_FLAG, False - ) + ) + held_end = held_ends.pop(cast(bytes, correlation_key), None) + # A held row ends, or crashes, with the input its start was + # reported with: the function's input for a computed row. + seen_tag, seen_input = ( + (held_end[0], held_end[1]) + if held_end is not None + else (original_tag, input_data) + ) + try: + output_hash = output_data.content_hash() + except Exception as exc: + # A result that names a missing entry: a failed row under + # the row failure policy, as on the sync path; any other + # error stops the run (ITL-1789). + persistent_hits.discard(cast(bytes, correlation_key)) + if isinstance( + exc, + ( + SpiralDBEntryMissingError, + OrcapodDatabaseError, + TypeIdentityError, + ), + ): + if not lookup_crashed(seen_tag, seen_input, exc): + raise + return + with keep_run_error(exc, "Observer on_data_crash"): + ctx_obs.on_data_crash(node_label, seen_tag, seen_input, exc) + raise + try: + self._add_pipeline_record( + original_tag, + input_data, + instance_id, + data_record_id=output_data.datagram_uuid, + computed=result_computed, + is_ephemeral=is_ephemeral + and correlation_key not in persistent_hits, + output_data_hash=output_hash, + run_id=run_id, ) - try: - self._add_pipeline_record( - original_tag, - input_data, - instance_id, - data_record_id=output_data.datagram_uuid, - computed=result_computed, - is_ephemeral=is_ephemeral - and correlation_key not in persistent_hits, - output_data_hash=output_data.content_hash(), - run_id=run_id, - ) - except OrcapodDatabaseError as exc: - # This runs outside the pod's per-row handler: name the - # node and row here. + except Exception as exc: + if isinstance(exc, OrcapodDatabaseError): exc.add_context( node_label=node_label, tag=original_tag.as_dict() ) - raise - persistent_hits.discard(cast(bytes, correlation_key)) - # The row's data-tag columns fall through onto the stored - # result, as on the sync path (ITL-1023). - # Not None: the result channel carries only results. - output_data = cast( - DataProtocol, - with_fall_through( - self._function_pod, input_data, output_data - ), - ) - # Update in-memory cache so iter_data() sees the result. - clean_tag = output_tag.drop_meta_columns( - _TAG_NODE_INPUT_REF, ignore_missing=True + if held_end is not None: + # The row's end was held for this record: it ends in a + # crash instead (ITL-1789). + with keep_run_error(exc, "Observer on_data_crash"): + ctx_obs.on_data_crash( + node_label, seen_tag, seen_input, exc + ) + raise + persistent_hits.discard(cast(bytes, correlation_key)) + if held_end is not None: + ctx_obs.on_data_end( + node_label, *held_end[:3], cached=held_end[3] ) - self._cached_output_datas[instance_id] = ( - clean_tag, - output_data, + # The row's data-tag columns fall through onto the stored + # result, as on the sync path (ITL-1023). + # Not None: the result channel carries only results. + output_data = cast( + DataProtocol, + with_fall_through(self._function_pod, input_data, output_data), + ) + # Update in-memory cache so iter_data() sees the result. + clean_tag = output_tag.drop_meta_columns( + _TAG_NODE_INPUT_REF, ignore_missing=True + ) + self._cached_output_datas[instance_id] = ( + clean_tag, + output_data, + ) + self._cached_output_table = None + self._cached_content_hash_column = None + # Commits every commit_every_rows rows inside a job (ITL-919); + # no await in between, so no other row interleaves. + self._row_processed() + await output.send((clean_tag, output_data)) + # Recorded once the output took the row (see route_inputs). + run_entry_ids.append(instance_id) + + async def record_and_forward() -> None: + """Stage 3: record pipeline entry, strip key, emit to output.""" + # When the results' values fetch when hashed (ITL-1789), the + # results waiting are taken together and their references + # fetched together, one scan per table version. + async for output_tag, output_data in result_channel.reader: + if not outputs_fetch: + await record_one(output_tag, output_data) + continue + batch = await _with_waiting_rows( + result_channel.reader, (output_tag, output_data) ) - self._cached_output_table = None - self._cached_content_hash_column = None - # Commits every commit_every_rows rows inside a job (ITL-919); - # no await in between, so no other row interleaves. - self._row_processed() - await output.send((clean_tag, output_data)) - # Recorded once the output took the row (see route_inputs). - run_entry_ids.append(instance_id) + with prefetched_rows( + [data for _, data in batch], + self.data_context.type_converter, + self.data_context.semantic_hasher, + ): + for batch_tag, batch_data in batch: + await record_one(batch_tag, batch_data) # Capture outer self so _NodeLabelObserver methods can # update FunctionJobNode state without shadowing with 'self'. @@ -5052,6 +5685,12 @@ def on_data_end( clean = tag.drop_meta_columns( _TAG_NODE_INPUT_REF, ignore_missing=True ) + key = tag.get_meta_value(_TAG_NODE_INPUT_REF, None) + if outputs_fetch and out is not None and key is not None: + # Reported by the record stage once the result is + # hashed and recorded (see ``held_ends``). + held_ends[key] = (clean, inp, out, cached) + return ctx_obs.on_data_end(node_label, clean, inp, out, cached=cached) if out is None: # The function filtered this item (returned None). @@ -5155,14 +5794,28 @@ def create_data_logger(self, tag: Any, data: Any) -> Any: except Exception as run_error: try: if node_open: + # Rows whose end was held for their record (ITL-1789) and never + # reached it end in a crash, before the node's end. + cause = ( + run_error.exceptions[0] + if isinstance(run_error, ExceptionGroup) + else run_error + ) + # Each crash report is isolated: an observer that raises is + # logged and noted on the run's error, every other held row and + # the node's end are still reported, and the run's own error is + # raised. + for held_tag, held_input, _, _ in list(held_ends.values()): + with keep_run_error(run_error, "Observer on_data_crash"): + ctx_obs.on_data_crash( + node_label, held_tag, held_input, cause + ) + held_ends.clear() # The node ends for the observer before it raises, as in execute; - # a failing observer must not replace a database error on its way out. - with keep_database_error( - database_error_of(run_error), "Observer on_node_end" - ): + # a failing observer must preserve the original run error. + with keep_run_error(run_error, "Observer on_node_end"): ctx_obs.on_node_end(node_label, node_hash) finally: - # Also when the observer raised instead, as execute commits then. self._commit_after_failure(run_error) # A run that raised defines no rows: the node reads as one with no # run, as on the sync path. diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 89f54667f..7c1189895 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -189,6 +189,13 @@ async def receive(self) -> tuple[TagProtocol, DataProtocol]: self._keep(item) return item + def take_ready(self, max_items: int) -> list[tuple[TagProtocol, DataProtocol]]: + """Take the rows already waiting in the wrapped reader, keeping them if needed.""" + items = self._reader.take_ready(max_items) + for item in items: + self._keep(item) + return items + def __aiter__(self) -> "_InputTap": return self diff --git a/src/orcapod/core/sources/spiraldb_entries.py b/src/orcapod/core/sources/spiraldb_entries.py new file mode 100644 index 000000000..8fab4cd68 --- /dev/null +++ b/src/orcapod/core/sources/spiraldb_entries.py @@ -0,0 +1,914 @@ +"""SpiralDB entry references: which columns become references, and reading one (ITL-1789). + +A SpiralDB table can store a column in a Vortex encoding (``vortex.turboquant``, a lossy +quantized vector, at the top level or as a field of a struct column). Orcapod neither +decodes nor copies such a value. ``SpiralDBTableSource`` presents the column as a +column of ``SpiralDBEntry`` references (``encoded_columns`` decides which columns, +``reference_column`` builds the references), and ``SpiralDBEntry.read`` reads the value +through spiral-sdk (``read_entry``). + +A reference's value hash is the hash of its entry's content. The entries of a batch are +fetched together (``prefetched_entries``: one scan per service, table and version, with +one key range per entry); the batch keeps its own outcomes while it is hashed, and a +process-wide cache (``_CACHE``), kept per sign-in, keeps entries' content hashes, or that +they are missing (``ENTRY_CACHE_HASHES``, ``ENTRY_CACHE_HASH_BYTES``), and the fetched +values as immutable bytes up to a byte budget (``ENTRY_CACHE_BYTES``), so ``read`` after +hashing returns the bytes that were hashed without another fetch while they are held. +A reference's own service address is signed in to only when this process reached it +through a connector or source it built (``client_for_service``). +""" + +from __future__ import annotations + +import copy +import datetime +import json +import os +from collections import OrderedDict +from collections.abc import Callable, Iterable, Iterator, Sequence +from contextlib import contextmanager +from contextvars import ContextVar +from threading import Lock +from typing import Any, NamedTuple, cast + +import pyarrow as pa + +from orcapod.core.sources.stream_builder import ( + require_live_logical_types, + row_identifiers, +) +from orcapod.databases.spiraldb_connector import ( + TableVersionNotFoundError, + client_for_service, + open_table_version, + require_trusted_service, + scan_keys, + scan_one_key, + sign_in_scope, +) +from orcapod.databases.spiraldb_schema_table import ( + VORTEX_EXTENSION_PREFIX, + vortex_encodings, +) +from orcapod.errors import SpiralDBEntryMissingError, TableSchemaError +from orcapod.logical_types.spiraldb_entry_type import ( + SPIRALDB_ENTRY_STORAGE, + LogicalSpiralDBEntry, + SpiralDBEntry, + entry_content_hash, +) +from orcapod.types import ContentHash + +_EXTENSION_NAME_KEY = b"ARROW:extension:name" + +_FRACTION_DIGITS = {"s": 0, "ms": 3, "us": 6, "ns": 9} + + +def encoded_columns(schema: pa.Schema) -> dict[str, tuple[str, ...]]: + """Return the top-level columns that hold a Vortex encoding, with their encodings. + + A column holds one when its field, or any field inside it (a struct field, a list + item), carries an Arrow extension name starting with ``vortex.``. Such a column is + presented whole as references: Orcapod puts no logical type inside a struct field. + + Args: + schema: The table's schema as SpiralDB reports it. + + Returns: + Column name to its sorted, distinct encoding names, in schema order. + """ + found: dict[str, tuple[str, ...]] = {} + for field in schema: + names = sorted( + { + name.decode("utf-8", errors="backslashreplace") + for _, name, _ in vortex_encodings(field) + } + ) + if names: + found[field.name] = tuple(names) + return found + + +def _without_encodings(field: pa.Field[Any]) -> pa.Field[Any]: + """Return ``field`` with the Vortex encodings' extension metadata removed, at any + depth; every other field, type and metadata unchanged.""" + metadata = dict(field.metadata or {}) + name = metadata.get(_EXTENSION_NAME_KEY) + if name is not None and name.startswith(VORTEX_EXTENSION_PREFIX): + metadata = {k: v for k, v in metadata.items() if not k.startswith(b"ARROW:")} + arrow_type = field.type + if pa.types.is_struct(arrow_type): + arrow_type = pa.struct( + [ + _without_encodings(arrow_type.field(i)) + for i in range(arrow_type.num_fields) + ] + ) + elif pa.types.is_large_list(arrow_type): + arrow_type = pa.large_list(_without_encodings(arrow_type.value_field)) + elif pa.types.is_list(arrow_type): + arrow_type = pa.list_(_without_encodings(arrow_type.value_field)) + elif pa.types.is_fixed_size_list(arrow_type): + arrow_type = pa.list_( + _without_encodings(arrow_type.value_field), arrow_type.list_size + ) + return pa.field(field.name, arrow_type, field.nullable, metadata or None) + + +def require_only_encodings(schema: pa.Schema, columns: Sequence[str]) -> None: + """Refuse an encoded column that also holds another stored logical type. + + Such a column is presented whole as references, so what else it holds is never + read; a stored logical type that is not a Vortex encoding is still refused, as in + any other column. + + Args: + schema: The table's schema as SpiralDB reports it. + columns: The encoded columns (``encoded_columns``). + + Raises: + TableSchemaError: If a Vortex encoding is wrapped by a dictionary. + InputValidationError: If one of ``columns`` holds a stored logical type other + than a Vortex encoding. + """ + fields = [schema.field(column) for column in columns] + for field in fields: + # A -1 path step denotes a dictionary's value type. + if any(-1 in path for path, _, _ in vortex_encodings(field)): + raise TableSchemaError( + f"Column {field.name!r} uses a dictionary-wrapped Vortex encoding, " + "which is not supported yet" + ) + require_live_logical_types( + pa.schema([_without_encodings(field) for field in fields]) + ) + + +def reference_field(name: str) -> pa.Field[Any]: + """Return the field a reference column has: ``orcapod.spiraldb.entry``, non-null. + + Args: + name: The column's name, the encoded column's own. + """ + return pa.field( + name, LogicalSpiralDBEntry().get_arrow_extension_type(), nullable=False + ) + + +def presented_schema(schema: pa.Schema, columns: Sequence[str]) -> pa.Schema: + """Return ``schema`` with each of ``columns`` replaced by its reference field. + + Every column keeps its name and position; every other field is unchanged. + + Args: + schema: The table's schema as SpiralDB reports it. + columns: The encoded columns (``encoded_columns``). + """ + replaced = set(columns) + return pa.schema( + [reference_field(f.name) if f.name in replaced else f for f in schema], + metadata=cast("dict[bytes | str, bytes | str] | None", schema.metadata), + ) + + +def reference_column( + keys: pa.Table, + primary_key: Sequence[str], + *, + table_id: str, + version: int, + column: str, + service: str, +) -> pa.ExtensionArray[Any]: + """Return one reference per row of ``keys`` to its entry of ``column``. + + Args: + keys: The rows read, with the primary-key columns. + primary_key: The table's primary-key columns, in key order. + table_id: SpiralDB's id of the table. + version: The table version the rows were read at. + column: The encoded column. + service: The address of the SpiralDB service the rows were read from. + + Returns: + The references, of the type ``reference_field`` gives, none null. + + Raises: + RowIdentifierError: If a key value is null or of a type that cannot name a row. + """ + tokens = row_identifiers(keys, primary_key) + storage = pa.StructArray.from_arrays( + [ + pa.array([table_id] * len(tokens), pa.large_string()), + pa.array([version] * len(tokens), pa.int64()), + pa.array(tokens, pa.large_string()), + pa.array([column] * len(tokens), pa.large_string()), + pa.array([service] * len(tokens), pa.large_string()), + ], + fields=[ + SPIRALDB_ENTRY_STORAGE.field(i) + for i in range(SPIRALDB_ENTRY_STORAGE.num_fields) + ], + ) + return pa.ExtensionArray.from_storage( + LogicalSpiralDBEntry().get_arrow_extension_type(), storage + ) + + +def _key_value(value: object, arrow_type: pa.DataType) -> pa.Array[Any]: + """Return a key value of an entry's key text as a one-element array of its type. + + The inverse of the key text's form (``row_identifiers``): a timestamp from its + ISO-8601 text as a count of its unit, a date from ``YYYY-MM-DD``, anything else as + it is. The caller checks the result gives the same text again. + + Raises: + ValueError: If the value is not of the form a key of that type has. + """ + if pa.types.is_timestamp(arrow_type) and isinstance(value, str): + unit = arrow_type.unit # pyright: ignore[reportAttributeAccessIssue] + text = value[:-1] if value.endswith("Z") else value + whole, _, fraction = text.partition(".") + moment = datetime.datetime.fromisoformat(whole) + seconds = (moment - datetime.datetime(1970, 1, 1)) // datetime.timedelta( + seconds=1 + ) + count = seconds * 10 ** _FRACTION_DIGITS[unit] + int(fraction or "0") + return pa.array([count], pa.int64()).cast(arrow_type) + if ( + pa.types.is_date32(arrow_type) or pa.types.is_date64(arrow_type) + ) and isinstance(value, str): + return pa.array([datetime.date.fromisoformat(value)], arrow_type) + return pa.array([value], arrow_type) + + +def _key_arrays( + entry: SpiralDBEntry, key_columns: Sequence[str], schema: pa.Schema +) -> list[pa.Array[Any]]: + """Return ``entry``'s key values as arrays of the table's key column types. + + Args: + entry: The reference. + key_columns: The table's primary-key columns, in key order. + schema: The table's schema at the entry's version. + + Raises: + ValueError: If the key text does not name the table's primary-key columns in + order, a value is not of its column's form, or the values do not give the + key text again (the key would not be exact). + """ + values = json.loads(entry.key) # pyright: ignore[reportAny] + if not isinstance(values, dict) or list(values) != list(key_columns): # pyright: ignore[reportUnknownArgumentType] + raise ValueError( + f"SpiralDB entry {entry!r}: the key does not name the table's primary-key " + f"columns {list(key_columns)} in order" + ) + arrays: list[pa.Array[Any]] = [] + for name in key_columns: + value: object = values[name] # pyright: ignore[reportUnknownVariableType] + try: + arrays.append(_key_value(value, schema.field(name).type)) + except (ValueError, TypeError, pa.ArrowException) as exc: + raise ValueError( + f"SpiralDB entry {entry!r}: key column {name!r} cannot hold {value!r}" + ) from exc + # The key is exact only if its values give the key text again. + rebuilt = row_identifiers(pa.table(dict(zip(key_columns, arrays))), key_columns) + if rebuilt != [entry.key]: + raise ValueError( + f"SpiralDB entry {entry!r}: the key reads back as {rebuilt[0]!r}, not as " + "given" + ) + return arrays + + +def _table_of(entry: SpiralDBEntry, client: Any) -> Any: # pyright: ignore[reportExplicitAny, reportAny] # SDK objects, untyped + """Open ``entry``'s table at its version, through ``client`` or its own service.""" + if client is None: + client = client_for_service(entry.service) # pyright: ignore[reportAny] + return open_table_version(client, entry.table_id, entry.version) # pyright: ignore[reportAny] + + +def scan_entry(entry: SpiralDBEntry, client: Any = None) -> Any: # pyright: ignore[reportExplicitAny, reportAny] # SDK objects, untyped + """Return spiral-sdk's scan of ``entry``: its one key and its one column. + + Args: + entry: The reference. + client: A ``spiral.Client``; ``None`` uses a client of the entry's service + (``client_for_service``). + + Raises: + SpiralDBSignInError: If ``client`` is ``None`` and spiral-sdk would have to + ask a person to sign in. + ValueError: If the key does not fit the table's primary key. + SpiralDBEntryMissingError: If the table or the entry's version does + not exist. (For a key the version does not hold, the scan yields no row.) + """ + try: + table = _table_of(entry, client) # pyright: ignore[reportAny] + except TableVersionNotFoundError as exc: + raise _missing(entry, str(exc)) from exc + key_columns = [str(c) for c in table.key_columns] # pyright: ignore[reportAny] + schema: pa.Schema = table.schema() # pyright: ignore[reportAny] + return scan_one_key(table, entry.column, _key_arrays(entry, key_columns, schema)) # pyright: ignore[reportAny] + + +ENTRY_CACHE_BYTES = 512 * 1024 * 1024 +"""How many bytes of fetched entry values the process keeps for ``read`` (512 MiB).""" + +ENTRY_VALUE_OVERHEAD = 1024 +"""What each held value is charged beyond its bytes and its key's text (its objects in +the cache), so that many small values do not exceed the budget unseen.""" + +ENTRY_CACHE_HASHES = 1_000_000 +"""How many entries' content hashes (or that they are missing) the process keeps. + +An entry evicted is fetched again at its exact version when it is next hashed outside a +batch (``prefetched_entries`` keeps a batch's own outcomes). +""" + +ENTRY_CACHE_HASH_BYTES = 256 * 1024 * 1024 +"""How many bytes the kept hashes may be charged (256 MiB): each its key's text, the +reason it is missing, and ``ENTRY_HASH_OVERHEAD``.""" + +ENTRY_HASH_OVERHEAD = 256 +"""What each kept hash is charged beyond its key's text and reason (its digest and the +cache's objects).""" + +_NO_ROW = "the table at version {version} holds no row with this key" + +_NO_COLUMN = ( + "SpiralDBEntry names column {column!r}, which the table at version {version} " + "does not have" +) + + +class _EntryKey(NamedTuple): + """What names one entry in the cache: the sign-in it was read with, and every field + of its reference.""" + + sign_in: object + service: str + table_id: str + version: int + key: str + column: str + + +def _entry_key(entry: SpiralDBEntry, sign_in: object) -> _EntryKey: + return _EntryKey( + sign_in, entry.service, entry.table_id, entry.version, entry.key, entry.column + ) + + +def _key_bytes(key: _EntryKey) -> int: + """The bytes of a cache key's variable-size text: the reference's text fields and + the sign-in's description.""" + return sum( + len(text.encode("utf-8", errors="replace")) + for text in (key.service, key.table_id, key.key, key.column, repr(key.sign_in)) + ) + + +class _Fetched(NamedTuple): + """What a fetch found for one entry: its value and content hash, or why there is + none.""" + + value: pa.Table | None + missing: str | None + content_hash: ContentHash | None = None + + @property + def known(self) -> ContentHash | str: + """The content hash, or the reason the entry is missing.""" + return ( + cast(ContentHash, self.content_hash) + if self.value is not None + else cast(str, self.missing) + ) + + +def _publisher(sign_in: object) -> Callable[[SpiralDBEntry, _Fetched], object]: + """Return how a fetch made under ``sign_in`` is kept: only while that sign-in is + still the current one, so a value read after the sign-in changed is never kept + under the earlier one (the client was taken under whichever was current).""" + + def publish(entry: SpiralDBEntry, found: _Fetched) -> object: + if sign_in_scope() != sign_in: + return None + return _CACHE.keep(_entry_key(entry, sign_in), found) + + return publish + + +def _freeze(value: pa.Table) -> bytes: + """Return ``value`` as Arrow IPC stream bytes: schema (with every field's metadata) + and buffers, in one immutable ``bytes``.""" + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, value.schema) as writer: + writer.write_table(value) + return sink.getvalue().to_pybytes() + + +def _thaw(frozen: bytes) -> pa.Table: + """Return the table ``_freeze`` gave ``frozen`` for. Its buffers are read-only + views of ``frozen`` (or new copies): writing to them cannot change what is held.""" + return pa.ipc.open_stream(pa.py_buffer(frozen)).read_all() + + +def _charge(frozen: bytes, key: _EntryKey) -> int: + """The bytes a held value is charged: its IPC bytes (schema and field metadata + included), its key's text and ``ENTRY_VALUE_OVERHEAD``.""" + return len(frozen) + _key_bytes(key) + ENTRY_VALUE_OVERHEAD + + +def _hash_charge(key: _EntryKey, known: ContentHash | str) -> int: + """The bytes a kept hash is charged: its key's text, the reason it is missing (if + so) and ``ENTRY_HASH_OVERHEAD``.""" + reason = ( + len(known.encode("utf-8", errors="replace")) if isinstance(known, str) else 0 + ) + return _key_bytes(key) + reason + ENTRY_HASH_OVERHEAD + + +class _EntryCache: + """The process-wide cache of fetched entries (``_CACHE``). + + Entries are kept per sign-in (``sign_in_scope``): what one sign-in read is never + given to another. ``hashes`` holds each fetched entry's content hash, or the reason + it is missing, least recently used first, at most ``ENTRY_CACHE_HASHES`` and within + ``ENTRY_CACHE_HASH_BYTES``; ``values`` the fetched values as immutable IPC bytes + (``_freeze``), least recently used first, within ``ENTRY_CACHE_BYTES``. A table + version never changes, so neither goes stale. + """ + + def __init__(self) -> None: + self.lock = Lock() + self.hashes: OrderedDict[_EntryKey, tuple[ContentHash | str, int]] = ( + OrderedDict() + ) + self.hash_bytes = 0 + self.values: OrderedDict[_EntryKey, tuple[bytes, int]] = OrderedDict() + self.value_bytes = 0 + + def keep(self, key: _EntryKey, fetched: _Fetched) -> ContentHash | str: + """Record what was fetched for ``key``; return its content hash, or the reason + it is missing.""" + value = fetched.value + known = fetched.known + charge = _hash_charge(key, known) + frozen = None + if value is not None: + # Frozen outside the lock; the value itself is never held. + frozen = _freeze(value) + with self.lock: + previous = self.hashes.pop(key, None) + if previous is not None: + self.hash_bytes -= previous[1] + if charge <= ENTRY_CACHE_HASH_BYTES: + self.hashes[key] = (known, charge) + self.hash_bytes += charge + while self.hashes and ( + len(self.hashes) > ENTRY_CACHE_HASHES + or self.hash_bytes > ENTRY_CACHE_HASH_BYTES + ): + _, (_, dropped) = self.hashes.popitem(last=False) + self.hash_bytes -= dropped + if frozen is None or key in self.values: + return known + size = _charge(frozen, key) + if size > ENTRY_CACHE_BYTES: + return known + self.values[key] = (frozen, size) + self.value_bytes += size + while self.value_bytes > ENTRY_CACHE_BYTES: + _, (_, dropped) = self.values.popitem(last=False) + self.value_bytes -= dropped + return known + + def known(self, key: _EntryKey) -> ContentHash | str | None: + """Return the held content hash of ``key``, the reason it is missing, or + ``None`` when nothing is held.""" + with self.lock: + found = self.hashes.get(key) + if found is None: + return None + self.hashes.move_to_end(key) + return found[0] + + def value(self, key: _EntryKey) -> pa.Table | None: + """Return a new table of the held value of ``key``, if any, as the most + recently used; the caller cannot change what is held (``_thaw``).""" + with self.lock: + held = self.values.get(key) + if held is None: + return None + self.values.move_to_end(key) + return _thaw(held[0]) + + def clear(self) -> None: + """Forget everything.""" + with self.lock: + self.hashes.clear() + self.hash_bytes = 0 + self.values.clear() + self.value_bytes = 0 + + +_CACHE = _EntryCache() + + +def _forget_in_child() -> None: + """In a forked child: start with an empty entry cache, under a new lock (a thread + of the parent may have held the old one).""" + _CACHE.lock = Lock() + _CACHE.clear() + + +if hasattr(os, "register_at_fork"): + os.register_at_fork(after_in_child=_forget_in_child) + + +def clear_entry_cache() -> None: + """Forget every fetched entry of this process: its hash and its value.""" + _CACHE.clear() + + +def _one_row(rows: pa.Table, column: str, index: int) -> pa.Table: + """Return row ``index`` of ``column`` as a one-row table with its own buffers. + + ``take`` copies the value, so a fetched entry never holds the whole scan's buffers; + the field (name, type, metadata) is the scan's. + """ + return pa.Table.from_arrays( + [rows.column(column).take([index])], + schema=pa.schema([rows.schema.field(column)]), + ) + + +def _fetch( + entries: Sequence[SpiralDBEntry], + client: Any, # pyright: ignore[reportExplicitAny] # an SDK client, untyped + found: Callable[[SpiralDBEntry, _Fetched], object], + *, + digest: bool = True, + failed: Callable[[SpiralDBEntry, Exception], object] | None = None, +) -> None: + """Fetch ``entries`` with one scan per (service, table, version). + + Each scan reads the key columns and every column asked for in that table version, + over one key range per distinct key; the rows are matched to the entries by their + key text. A table that is gone, or that holds no snapshot of exactly the version, + makes each entry of its group missing; the other groups are still fetched. + + Args: + entries: The references, all fetched (the cache is not consulted). + client: A ``spiral.Client`` for every group; ``None`` uses one per service + (``client_for_service``). + found: Called with each entry and what was found, as soon as its group is + fetched, so a later group's error does not lose an earlier group's. + digest: Whether to compute each value's content hash. + failed: Called with each entry and the error that fetching it raised (its + key does not fit its table or its column is not one of the table's, + or its group's client, table or scan failed); the other entries are + still fetched. ``None`` raises the first. + + Raises: + Exception: Without ``failed``, what fetching raised: ``ValueError`` if a key + does not fit its table or a column is not one of its columns, + ``SpiralDBUntrustedServiceError`` or + ``SpiralDBSignInError`` from the client, or the scan's own error. + """ + groups: dict[tuple[str, str, int], list[SpiralDBEntry]] = {} + for entry in entries: + groups.setdefault((entry.service, entry.table_id, entry.version), []).append( + entry + ) + for group in groups.values(): + try: + _fetch_group(group, client, found, digest=digest, failed=failed) + except Exception as exc: + if failed is None: + raise + for entry in group: + _ = failed(entry, exc) + + +def _fetch_group( + group: Sequence[SpiralDBEntry], + client: Any, # pyright: ignore[reportExplicitAny] # an SDK client, untyped + found: Callable[[SpiralDBEntry, _Fetched], object], + *, + digest: bool, + failed: Callable[[SpiralDBEntry, Exception], object] | None, +) -> None: + """Fetch the entries of one (service, table, version) with one scan (``_fetch``).""" + try: + table = _table_of(group[0], client) # pyright: ignore[reportAny] + except TableVersionNotFoundError as exc: + for entry in group: + _ = found(entry, _Fetched(None, str(exc))) + return + key_columns = [str(c) for c in table.key_columns] # pyright: ignore[reportAny] + schema: pa.Schema = table.schema() # pyright: ignore[reportAny] + keys: dict[str, list[pa.Array[Any]]] = {} + wanted: list[SpiralDBEntry] = [] + for entry in group: + if entry.column not in schema.names: + # Checked before the shared scan, so it fails this reference only. + exc = ValueError( + _NO_COLUMN.format(column=entry.column, version=entry.version) + ) + if failed is None: + raise exc + _ = failed(entry, exc) + continue + if entry.key not in keys: + try: + keys[entry.key] = _key_arrays(entry, key_columns, schema) + except ValueError as exc: + if failed is None: + raise + _ = failed(entry, exc) + continue + wanted.append(entry) + if not wanted: + return + columns = sorted({entry.column for entry in wanted}) + rows = scan_keys(table, key_columns + columns, list(keys.values())) + row_of = { + text: index + for index, text in enumerate( + row_identifiers(rows.select(key_columns), key_columns) + ) + } + for entry in wanted: + index = row_of.get(entry.key) + if index is None: + _ = found(entry, _Fetched(None, _NO_ROW.format(version=entry.version))) + continue + try: + value = _one_row(rows, entry.column, index) + fetched = _Fetched( + value, None, entry_content_hash(value) if digest else None + ) + except Exception as exc: + # This entry's own value: the other entries of the scan are unaffected. + if failed is None: + raise + _ = failed(entry, exc) + continue + _ = found(entry, fetched) + + +def prefetch_entries(entries: Iterable[SpiralDBEntry]) -> None: + """Fetch, together, the entries this process has not fetched yet, into the process + cache. + + One scan per (service, table, version), never one per entry. An entry whose key + does not fit its table, or whose fetch fails, is left for its own hash to raise. + Nothing is fetched when the current sign-in cannot be told apart + (``sign_in_scope``): nothing could be kept for it. + + Args: + entries: The references; repeats are fetched once. + + Raises: + SpiralDBUntrustedServiceError: If a reference names a service this process + did not reach, as ``read`` raises it: before any client is made. + """ + entries = list(entries) + for service in dict.fromkeys(entry.service for entry in entries): + require_trusted_service(service) + sign_in = sign_in_scope() + if sign_in is None: + return + todo = [ + entry + for entry in dict.fromkeys(entries) + if _CACHE.known(_entry_key(entry, sign_in)) is None + ] + if todo: + _fetch(todo, None, _publisher(sign_in), failed=lambda entry, exc: None) + + +_Outcome = ContentHash | str | Exception +"""What a batch knows of one entry: its content hash, the reason it is missing, or the +error fetching it raised.""" + + +class _Batch(NamedTuple): + """The outcomes fetched for a batch, and what they hold for: the sign-in they were + fetched under, the process that fetched them, and whether the block is still open + (one flag shared by every copy of the context, so a task that outlives the block + sees it closed).""" + + sign_in: object + outcomes: dict[SpiralDBEntry, _Outcome] + pid: int + open: list[bool] + + +def _batch_outcomes(sign_in: object) -> dict[SpiralDBEntry, _Outcome]: + """The outcomes of the batch being hashed, if they hold for ``sign_in`` in this + process now (``_Batch``); none otherwise.""" + batch = _BATCH.get() + if ( + batch is None + or not batch.open[0] + or batch.pid != os.getpid() + or batch.sign_in != sign_in + ): + return {} + return batch.outcomes + + +_BATCH: ContextVar[_Batch | None] = ContextVar( + "orcapod_spiraldb_entry_batch", default=None +) +"""The outcomes fetched for the batch being hashed (``prefetched_entries``).""" + + +def _detached(exc: Exception) -> Exception: + """Return ``exc`` without the tracebacks of it and of the errors it chains, so a + held error keeps no fetch's frames (and with them its scan) alive.""" + seen: set[int] = set() + todo: list[BaseException | None] = [exc] + while todo: + current = todo.pop() + if current is None or id(current) in seen: + continue + seen.add(id(current)) + current.__traceback__ = None + todo += [current.__cause__, current.__context__] + return exc + + +def _fresh(exc: Exception) -> Exception: + """A new raise of a held error: a copy with its chain, so raising it at every row + that hashes it never grows or changes the held one; the held one itself when it + cannot be copied.""" + try: + fresh = copy.copy(exc) + except Exception: # an error class that cannot be rebuilt from its state + return exc.with_traceback(None) + if type(fresh) is not type(exc) or fresh.args != exc.args: + return exc.with_traceback(None) + fresh.__cause__ = exc.__cause__ + fresh.__suppress_context__ = exc.__suppress_context__ + return fresh.with_traceback(None) + + +@contextmanager +def prefetched_entries(entries: Iterable[SpiralDBEntry]) -> Iterator[None]: + """Fetch ``entries`` together, and hash them from what was fetched while inside. + + One scan per (service, table, version) for every entry the process cache does not + hold. Inside the block, hashing one of ``entries`` takes its outcome from this + batch: its content hash, the reason it is missing (``SpiralDBEntryMissingError``), + or the error fetching it raised, raised where it is hashed, as hashing it alone + would raise it. An entry fetched before its group failed keeps what was found. + The batch keeps only outcomes, never values: it holds whatever the process cache + evicts meanwhile, and works when the sign-in cannot be told apart. Its outcomes + serve only the sign-in they were fetched under, in this process, while the block + is open: after a change of sign-in inside the block, in a forked child, or in a + task that hashes after the block closed, an entry is hashed as outside it, and a + nested batch inherits nothing. + Values are kept in the process cache (``read``) as ``prefetch_entries`` keeps them. + + Args: + entries: The references; repeats are fetched once. + """ + # The batch belongs to the process that starts preparing it: a fork while + # ``entries`` is consumed leaves the child a batch that serves it nothing. + pid = os.getpid() + sign_in = sign_in_scope() + batch: dict[SpiralDBEntry, _Outcome] = dict(_batch_outcomes(sign_in)) + todo: list[SpiralDBEntry] = [] + for entry in dict.fromkeys(entries): + if entry in batch: + continue + known = None if sign_in is None else _CACHE.known(_entry_key(entry, sign_in)) + if known is None: + todo.append(entry) + else: + batch[entry] = known + if todo: + publish = None if sign_in is None else _publisher(sign_in) + + def found(entry: SpiralDBEntry, fetched: _Fetched) -> None: + batch[entry] = fetched.known + if publish is not None: + _ = publish(entry, fetched) + + def failed(entry: SpiralDBEntry, exc: Exception) -> None: + _ = batch.setdefault(entry, _detached(exc)) + + _fetch(todo, None, found, failed=failed) + is_open = [True] + token = _BATCH.set(_Batch(sign_in, batch, pid, is_open)) + try: + yield + finally: + is_open[0] = False + _BATCH.reset(token) + + +def _missing(entry: SpiralDBEntry, reason: str) -> SpiralDBEntryMissingError: + return SpiralDBEntryMissingError(entry, reason) + + +def _one( + entry: SpiralDBEntry, + client: Any, # pyright: ignore[reportExplicitAny] # an SDK client, untyped + *, + digest: bool, + publish: Callable[[SpiralDBEntry, _Fetched], object] | None, +) -> _Fetched: + """Fetch ``entry`` alone; raise what fetching it raised.""" + result: list[_Fetched] = [] + + def found(fetched_entry: SpiralDBEntry, fetched: _Fetched) -> None: + result.append(fetched) + if publish is not None: + _ = publish(fetched_entry, fetched) + + _fetch([entry], client, found, digest=digest) + return result[0] + + +def cached_content_hash(entry: SpiralDBEntry) -> ContentHash: + """Return the content hash of ``entry``, fetching it if this process has not. + + Inside ``prefetched_entries`` of ``entry``, the batch's outcome is used while the + sign-in is the one it was fetched under. + + Raises: + SpiralDBEntryMissingError: If its version holds no row with its key, or the + table or that version does not exist. + SpiralDBUntrustedServiceError: If its service is not one this process reached. + ValueError: If its key does not fit the table's primary key, or the table + has no column of its name. + """ + sign_in = sign_in_scope() + known: _Outcome | None = _batch_outcomes(sign_in).get(entry) + if known is None: + key = None if sign_in is None else _entry_key(entry, sign_in) + known = None if key is None else _CACHE.known(key) + if known is None: + known = _one( + entry, + None, + digest=True, + publish=None if sign_in is None else _publisher(sign_in), + ).known + if isinstance(known, Exception): + raise _fresh(known) + if isinstance(known, str): + raise _missing(entry, known) + return known + + +def read_entry(entry: SpiralDBEntry, client: Any = None) -> pa.Table: # pyright: ignore[reportExplicitAny] # an SDK client, untyped + """Read ``entry``: one row, one column, as SpiralDB stores it at its version. + + Without ``client``, the value comes from the process cache while it holds it for the + current sign-in (the bytes that were hashed), else from SpiralDB at the entry's + version, never another. The table returned is the caller's own: changing it changes + nothing held. With ``client``, it is always read through that client; nothing is + taken from the cache or kept in it, and no content hash is computed. + + Args: + entry: The reference. + client: A ``spiral.Client``; ``None`` uses a client of the entry's service. + + Raises: + SpiralDBEntryMissingError: If its version holds no row with its key, or the + table or that version does not exist. + SpiralDBUntrustedServiceError: If ``client`` is ``None`` and the entry's service + is not one this process reached. + ValueError: If the key does not fit the table's primary key, or the table + has no column of its name. + """ + if client is not None: + found = _one(entry, client, digest=False, publish=None) + else: + sign_in = sign_in_scope() + key = None if sign_in is None else _entry_key(entry, sign_in) + value = None if key is None else _CACHE.value(key) + if value is not None: + return value + known = None if key is None else _CACHE.known(key) + if isinstance(known, str): + raise _missing(entry, known) + found = _one( + entry, + None, + digest=sign_in is not None, + publish=None if sign_in is None else _publisher(sign_in), + ) + if found.value is None: + raise _missing(entry, cast(str, found.missing)) + # A fetched value: the cache holds its own frozen copy, never this table. + return found.value diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index fd2d2fe96..9ea8923df 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -66,6 +66,12 @@ from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.base import RootSource, saved_tag_only_columns +from orcapod.core.sources.spiraldb_entries import ( + encoded_columns, + presented_schema, + reference_column, + require_only_encodings, +) from orcapod.core.sources.derived_source import validate_tags_as_data from orcapod.core.sources.provisional import warn_provisional_tags_as_data from orcapod.core.sources.source_ids import joined_location, location_source_name @@ -410,11 +416,18 @@ def __init__( "record_id_columns=[...]." ) self._table_id = table.table_id + # The service's address, which an entry reference records (ITL-1789). + self._service: str = self._connector().service_address() # The version every read scans is prepared now (its schema and schema # record), also a given older one, so a read makes no metadata call. schema = table.arrow_schema(asof=asof) require_source_column_names(schema.names) require_supported_nullable_types(schema) + # Columns stored in a Vortex encoding are presented as references to + # their entries, never read or decoded (ITL-1789). + self._encoded: tuple[str, ...] = tuple(encoded_columns(schema)) + require_only_encodings(schema, self._encoded) + self._primary_key: tuple[str, ...] = primary_key # One version for every read of this source object. A given version is # used as it is; a table that was never written has no version to pin. self._asof = asof if asof is not None else (table.version() or None) @@ -450,6 +463,40 @@ def __init__( f"columns {list(self._key_columns)}: {'; '.join(key_problems)}. A key " "column must hold strings, integers, booleans, timestamps or dates." ) + # A reference names its row by the table's primary key (ITL-1789), so with + # an encoded column the table needs a primary key, whatever + # record_id_columns says, and every primary-key column must form a key + # value. + if self._encoded and not primary_key: + raise ValueError( + f"{location}: table {table_name!r} has column(s) " + f"{list(self._encoded)} stored in a Vortex encoding, presented as " + "references that name their row by the primary key, but the table " + "has no primary key columns, so no reference could name its row. " + "record_id_columns names a source's rows, not a reference's." + ) + if self._encoded and ( + unreferable := [ + f"{c!r} has type {schema.field(c).type}" + for c in primary_key + if not key_column_type_allowed(schema.field(c).type) + ] + ): + raise ValueError( + f"{location}: table {table_name!r} has column(s) " + f"{list(self._encoded)} stored in a Vortex encoding, presented as " + "references that name their row by the primary key, which cannot " + f"name a row: {'; '.join(unreferable)}. A primary-key column must " + "hold strings, integers, booleans, timestamps or dates." + ) + if refused := sorted( + c for c in self._encoded if c in resolved_tags or c in self._key_columns + ): + raise ValueError( + f"{location}: table {table_name!r} column(s) {refused} are stored " + "in a Vortex encoding and are presented as references to their " + "entries (SpiralDBEntry), so they cannot be tag or key columns" + ) self._record_id_columns = given_key if self._source_name is None: self._source_name = location_source_name( @@ -462,9 +509,20 @@ def __init__( # A zero-row stream with the table's columns answers every schema question. self._builder = SourceStreamBuilder(self.data_context) + presented = presented_schema(schema, self._encoded) + # What a read scans: every column but the encoded ones (``None``: all). + self._read_columns: tuple[str, ...] | None = ( + tuple(n for n in schema.names if n not in self._encoded) + if self._encoded + else None + ) + # The table's own columns as SpiralDB reports them, which a check compares. + self._found_schema: pa.Schema = arrow_utils.drop_system_columns( + schema.empty_table() + ).schema try: template = self._builder.build( - schema.empty_table(), + presented.empty_table(), tag_columns=resolved_tags, source_name=self._source_name, kind_part=self.kind_part(), @@ -473,8 +531,15 @@ def __init__( except ValueError as exc: raise ValueError(f"{location}, table {table_name!r}: {exc}") from exc self._table_schema: pa.Schema = arrow_utils.drop_system_columns( - schema.empty_table() + presented.empty_table() ).schema + # The columns a read returns before the references are added. + self._scanned_schema: pa.Schema = pa.schema( + [f for f in self._table_schema if f.name not in self._encoded], + metadata=cast( + "dict[bytes | str, bytes | str] | None", self._table_schema.metadata + ), + ) if not requested.is_empty: try: self._apply_restriction(requested) @@ -529,6 +594,50 @@ def _check_tags_as_data( f"null. Key columns, which can be copied: {list(self._key_columns)}." ) + def _with_references( + self, rows: "pa.Table", version: int | None, columns: Collection[str] + ) -> "pa.Table": + """Return ``rows`` with a reference column for each of ``columns`` (ITL-1789). + + Each reference names its row's entry: the table id, ``version`` (the version + SpiralDB read, as it resolved the source's pin), the row's primary-key values + and the column. It takes the encoded column's position in the table's schema, + among the columns read. + + Args: + rows: The rows read, holding every primary-key column. + version: The version read. + columns: The encoded columns to add. + + Raises: + RowIdentifierError: If a primary-key value is null. + """ + if not columns: + return rows + if version is None: + raise ValueError( + f"SpiralDB table {self._qualified!r} returned rows without a version, " + "which a reference to its entries needs" + ) + # Each reference goes where its column is in the table's schema, among the + # columns read (a projected read reads only some). + position = 0 + for field in self._table_schema: + if field.name in columns: + reference = reference_column( + rows, + self._primary_key, + table_id=self._table_id, + version=version, + column=field.name, + service=self._service, + ) + rows = rows.add_column(position, field, reference) + position += 1 + elif field.name in rows.column_names: + position += 1 + return rows + def _with_tag_copies(self, table: "pa.Table") -> "pa.Table": """Return ``table`` with each ``tags_as_data`` copy appended, in mapping order. @@ -694,12 +803,18 @@ def _apply_restriction(self, condition: Condition) -> None: condition: The condition to add. Raises: - ValueError: If a column is not in the table, or a column must equal two - different values. + ValueError: If a column is not in the table, is a column of entry + references, or must equal two different values. TypeError: If the condition holds anything but equalities and ranges, a range names a column of another type, or a value is not of its column's type or does not fit it. """ + references = sorted(condition.columns & set(self._encoded)) + if references: + raise ValueError( + f"column(s) {references} are stored in a Vortex encoding and read as " + "SpiralDB entry references, which a condition cannot name" + ) check_restriction(condition, self._table_schema) combined = self._condition.combined(condition) # Again with the one in force: a column equals one value (ranges add up, and @@ -947,10 +1062,10 @@ def _check_table(self) -> bool: raw_schema = table.arrow_schema(asof=given, reuse_snapshot_of=self._handle) require_source_column_names(raw_schema.names) schema = arrow_utils.drop_system_columns(raw_schema.empty_table()).schema - if not schema.equals(self._table_schema, check_metadata=True): + if not schema.equals(self._found_schema, check_metadata=True): raise ValueError( f"SpiralDB table {self._qualified!r}: " - f"{_schema_difference(schema, self._table_schema)}. Build the " + f"{_schema_difference(schema, self._found_schema)}. Build the " "source again to read it as it is now." ) if given is not None: @@ -1091,21 +1206,38 @@ def _read_batches( seen = 0 # Keys must be unique across the whole read, not only within a slice. identifiers: set[str] = set() - expected_schema = self._table_schema + # What the scan returns: the table's columns (or ``table_columns``) without + # the encoded ones, whose references are added after (ITL-1789). A reference + # names its row by the primary key, which is scanned for it, and left out + # again when a projection did not ask for it. + references = [ + c for c in self._encoded if table_columns is None or c in table_columns + ] + expected_schema = self._scanned_schema + unasked: list[str] = [] if table_columns is not None: scanned = set(table_columns) + if references: + unasked = [c for c in self._primary_key if c not in scanned] + scanned |= set(unasked) expected_schema = pa.schema( - [f for f in self._table_schema if f.name in scanned], + [f for f in self._scanned_schema if f.name in scanned], metadata=cast( "dict[bytes | str, bytes | str] | None", - self._table_schema.metadata, + self._scanned_schema.metadata, ), ) + version = table.version_at(asof) if references else None + read_columns = ( + expected_schema.names + if table_columns is not None + else (None if self._read_columns is None else list(self._read_columns)) + ) for batch in table.scan_batches( where=None if self._condition.is_empty else self._condition, limit=scan_limit, asof=asof, - columns=None if table_columns is None else expected_schema.names, + columns=read_columns, ): for start in range(0, max(batch.num_rows, 1), self._batch_rows): raw = pa.Table.from_batches([batch.slice(start, self._batch_rows)]) @@ -1139,6 +1271,9 @@ def _read_batches( f"{sorted(repeated)[0]} appears in two rows; key values " "must be unique, so each row has its own identifier" ) + rows = self._with_references(rows, version, references) + if unasked: + rows = rows.drop_columns(unasked) rows = self._with_tag_copies(rows) if not rows.num_rows: continue diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index d3d2a3fdd..546e47ac3 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -34,6 +34,7 @@ EXTENSION_METADATA_KEY, EXTENSION_NAME_KEY, ) +from orcapod.hashing.prefetch import fetching_columns, prefetched_columns from orcapod.logical_types.identifier import LogicalTypeIdentifierError from orcapod.system_constants import constants from orcapod.types import ContentHash @@ -803,7 +804,8 @@ class SourceStreamResult: stream: ArrowTableStream schema_hash: str - table_hash: ContentHash + # ``None`` for a table whose hash would fetch values (ITL-1789): it is not hashed. + table_hash: ContentHash | None source_id: str source_name: str tag_columns: tuple[str, ...] @@ -972,20 +974,55 @@ def build( # 5. Compute table hash for data identity: the rows in the order given, or, # with ``hash_in_key_order``, in key order (ITL-1272). The stream keeps the - # rows in the order given either way. + # rows in the order given either way. A table whose hash would fetch values + # from elsewhere (SpiralDB entry references, ITL-1789) is not hashed: building + # a source fetches nothing, so such a table needs a given name. hasher = self._data_context.arrow_hasher - hashed = ( - arrow_utils.key_row_order(table, key_columns) - if hash_in_key_order - else table + fetching = fetching_columns( + table.schema, + self._data_context.type_converter, + self._data_context.semantic_hasher, ) - try: - table_hash = hasher.hash_table(hashed) - except ValueError as exc: - error = _unhashable_table_error(hasher, table, exc) - if error is None: - raise - raise error from exc + nested = sorted( + set(fetching) + - set( + prefetched_columns( + table.schema, + self._data_context.type_converter, + self._data_context.semantic_hasher, + ) + ) + ) + if nested: + raise InputValidationError( + f"column(s) {nested} hold SpiralDB entry references inside a struct, " + "a map or a user class: a reference is supported only as a column's " + "own type, or inside a list there (its hash is its entry's content, " + "which is fetched for a column's references). Hold the references in " + "a column of their own." + ) + table_hash: ContentHash | None = None + if fetching: + if source_name is None: + raise ValueError( + f"column(s) {fetching} hold SpiralDB entry references, whose hash " + "is their entries' content, read from SpiralDB: a source over them " + "has no default source id, so building it fetches nothing. Give " + "the source a source_id." + ) + else: + hashed = ( + arrow_utils.key_row_order(table, key_columns) + if hash_in_key_order + else table + ) + try: + table_hash = hasher.hash_table(hashed) + except ValueError as exc: + error = _unhashable_table_error(hasher, table, exc) + if error is None: + raise + raise error from exc # 6. Default name: the labelled table hash, at full length, after the kind # part (ITL-1425). A default built from a hash says which algorithm made it. @@ -996,6 +1033,7 @@ def build( ) kind, version = parse_kind_part(kind_part) if source_name is None: + assert table_hash is not None # a table without fetching columns source_name = hash_source_name(table_hash) source_id = build_source_id(kind, version, source_name) diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 289878f44..4ddb6cfb0 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -22,6 +22,7 @@ from orcapod.core.streams.view import StreamView from orcapod.errors import InputValidationError from orcapod.hashing.orcapod_table import OrcapodTable +from orcapod.hashing.prefetch import prefetched_rows from orcapod.protocols.core_protocols import PodProtocol, StreamProtocol, TagProtocol from orcapod.protocols.hashing_protocols import ( IdentityChains, @@ -646,9 +647,18 @@ def hashes() -> pa.Array[Any]: rows = self.iter_data() if limit is not None: rows = itertools.islice(rows, limit) - return pa.array( - [str(data.content_hash()) for _, data in rows], type=pa.large_string() - ) + datas = [data for _, data in rows] + # What hashing the rows needs is fetched together, and the rows are + # hashed from that batch (ITL-1789). + with prefetched_rows( + datas, + self.data_context.type_converter, + self.data_context.semantic_hasher, + ): + return pa.array( + [str(data.content_hash()) for data in datas], + type=pa.large_string(), + ) def shape(carried: "pa.Table") -> "pa.Table": table_stack = (carried,) diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py index 82cbdd3a9..cb6d184fc 100644 --- a/src/orcapod/core/streams/record_batch_input.py +++ b/src/orcapod/core/streams/record_batch_input.py @@ -295,6 +295,18 @@ async def receive(self) -> pa.RecordBatch: self._received += 1 return batch + def take_ready(self, max_items: int) -> list[pa.RecordBatch]: + """Take the record batches already waiting, without waiting: always none. + + The channel holds no batch of its own: each ``receive`` pulls the next one + from its feed. So nothing is waiting, and the channel's state is unchanged. + + Args: + max_items: The most batches to take. + """ + del max_items + return [] + def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: """Iterate over the remaining record batches, in arrival order.""" return self diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 0a40bf185..69198046b 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -47,6 +47,7 @@ SchemaTable, compared_columns, describe_difference, + vortex_encodings, ) from orcapod.databases.spiraldb_sign_in import require_sign_in, saved_login_path from orcapod.databases.spiraldb_writable_registry import register_writable_connector @@ -54,6 +55,7 @@ from orcapod.databases.store_table_names import is_spiral_lease_table_name from orcapod.errors import ( NullInNonNullableColumnError, + SpiralDBUntrustedServiceError, SpiralDBWriteNotSupportedError, TableSchemaError, UnrecordedTableSchemaWarning, @@ -429,11 +431,20 @@ def __init__(self, sdk: Any) -> None: def _forget_in_child() -> None: - """In a forked child: leave the parent's clients, kept rows and lock.""" + """In a forked child: leave the parent's clients, kept rows and locks. + + The clients held for references' services are left too, with their lock; the + trusted service addresses are kept (the child runs what its parent built), under a + new lock (ITL-1789). + """ global _clients, _kept_rows, _registry_lock + global _trusted_services_lock, _service_clients_lock _clients = WeakValueDictionary() _kept_rows = {} _registry_lock = Lock() + _trusted_services_lock = Lock() + _service_clients_lock = Lock() + _SERVICE_CLIENTS.clear() if hasattr(os, "register_at_fork"): @@ -497,6 +508,260 @@ def _kept_rows_for(api_url: str | None, project_id: str, dataset: str) -> KeptRo return _kept_rows.setdefault((api_url, project_id, dataset), KeptRows()) +def normalize_service_address(address: str) -> str: + """Return the form of a service address that two spellings of one address share. + + The scheme and host are lower-cased, a port that is the scheme's default is dropped + and a trailing ``/`` is removed; the rest is kept as written. + + Args: + address: A service address (an API URL). + """ + parts = urllib.parse.urlsplit(address.strip()) + scheme = parts.scheme.lower() + host = (parts.hostname or "").lower() + if ":" in host: + host = f"[{host}]" + try: + port = parts.port + except ValueError: + port = None + if port is not None and (scheme, port) not in (("https", 443), ("http", 80)): + host = f"{host}:{port}" + netloc = host + if parts.username is not None or parts.password is not None: + # An address with credentials in it is never one a connector reached. + netloc = f"{parts.netloc.rsplit('@', 1)[0]}@{host}" + return urllib.parse.urlunsplit( + (scheme, netloc, parts.path.rstrip("/"), parts.query, parts.fragment) + ) + + +_TRUSTED_SERVICES: set[str] = set() +"""The service addresses (normalized) this process reached through a connector or a +SpiralDB source it built: the only addresses a reference's own address may sign in to +(``client_for_service``).""" + +_trusted_services_lock = Lock() + + +def trust_service(address: str) -> None: + """Record that this process reached the service at ``address`` through a connector + or a source it built, so that a reference read from it may sign in to it. + + Args: + address: The service's address (its API URL). + """ + with _trusted_services_lock: + _TRUSTED_SERVICES.add(normalize_service_address(address)) + + +def forget_trusted_services() -> None: + """Forget every trusted address (``trust_service``) and the clients held for them.""" + with _trusted_services_lock: + _TRUSTED_SERVICES.clear() + clear_service_clients() + + +def require_trusted_service(address: str) -> None: + """Refuse to sign in to ``address`` unless this process reached it itself. + + A reference names the service it was read from; its address is data and can name + any host. Only an address this process reached through a ``SpiralDBConnector`` or a + SpiralDB source it built is signed in to with the process's own sign-in. + + Args: + address: The service's address (its API URL). + + Raises: + SpiralDBUntrustedServiceError: If this process reached no service at + ``address`` through a connector or source it built. + """ + with _trusted_services_lock: + trusted = normalize_service_address(address) in _TRUSTED_SERVICES + if not trusted: + raise SpiralDBUntrustedServiceError(address) + + +def client_for_service(service: str) -> Any: # pyright: ignore[reportExplicitAny] # an SDK client, untyped + """Return this process's spiral-sdk client of the service at ``service``. + + Only an address this process reached through a connector or source it built is + signed in to (``require_trusted_service``); the check comes before any client or + credential is taken. The client is the one the connectors of that address and + sign-in share (``_client_for``), held here, for that sign-in only, so that it + outlives them; one client per address is held, the latest sign-in's. Signed in as + spiral-sdk signs in (``SPIRAL_*`` environment variables, or a saved ``spiral + login``); it never asks a person to sign in. + + Args: + service: The service's address (its API URL). + + Raises: + SpiralDBUntrustedServiceError: If ``service`` is not a trusted address. + SpiralDBSignInError: If spiral-sdk would have to ask a person to sign in. + ImportError: If spiral-sdk is not installed. + """ + require_trusted_service(service) + address = normalize_service_address(service) + sign_in = _sign_in_key() + if sign_in is None: + # Whose sign-in it is cannot be told: nothing is held for a later call. The + # client is made for the address the trust check matched, not the spelling. + return _client_for({"server.url": address}).sdk # pyright: ignore[reportAny] + with _service_clients_lock: + held = _SERVICE_CLIENTS.get(address) + if ( + held is not None + and held[0] == sign_in + and held[1] == os.getpid() + and not held[2].health.failed + ): + return held[2].sdk # pyright: ignore[reportAny] + shared = _client_for({"server.url": address}) + if _sign_in_key() != sign_in: + # The sign-in changed meanwhile: whose client it is is not known. + return shared.sdk # pyright: ignore[reportAny] + with _service_clients_lock: + _SERVICE_CLIENTS[address] = (sign_in, os.getpid(), shared) + return shared.sdk # pyright: ignore[reportAny] + + +def sign_in_scope() -> object | None: + """Return what tells this process's current sign-in apart, holding no credential. + + Two calls return equal values while the sign-in (the environment and the saved + login) is unchanged; ``None`` when it cannot be told. + """ + return _sign_in_key() # pyright: ignore[reportAny] + + +_SERVICE_CLIENTS: dict[str, tuple[Any, int, _SharedClient]] = {} # pyright: ignore[reportExplicitAny] +"""The clients ``client_for_service`` holds: one per trusted address (normalized), with +the sign-in and the process that got it. A changed sign-in never reuses one; it replaces +it.""" + +_service_clients_lock = Lock() + + +def clear_service_clients() -> None: + """Forget the clients ``client_for_service`` made; the next call makes new ones.""" + with _service_clients_lock: + _SERVICE_CLIENTS.clear() + + +def service_address(client: Any) -> str: # pyright: ignore[reportExplicitAny] # an SDK client, untyped + """Return the address of the service ``client`` talks to (its API URL). + + spiral-sdk has no public accessor of it; the pinned version holds it on the + client's native handle, as ``_list_keyed_tables`` reads it. + """ + return str(client._native.api_url) # pyright: ignore[reportAny] # no public accessor + + +class TableVersionNotFoundError(LookupError): + """A table version that SpiralDB does not hold: the table is gone, or no snapshot + of it has exactly that version (ITL-1789).""" + + +def _reports_not_found(exc: BaseException) -> bool: + """Whether a spiral-sdk error says the resource does not exist, and nothing else. + + SpiralDB has no error class for it: its message names the missing resource, or, + when the service hides the body, only the status (404). + """ + text = str(exc).strip() + return text.startswith("resource not found:") or text.endswith("(status 404)") + + +def open_table_version(client: Any, table_id: str, version: int) -> Any: # pyright: ignore[reportExplicitAny] # SDK objects, untyped + """Return spiral-sdk's keyed table ``table_id`` at exactly ``version`` (ITL-1789). + + spiral-sdk's ``asof`` is a cutoff: it opens the newest snapshot not after it. The + snapshot opened must have ``version`` itself, or the version is not there. + + Args: + client: A ``spiral.Client``. + table_id: SpiralDB's id of the table. + version: The version. + + Raises: + TableVersionNotFoundError: If the table does not exist, or holds no snapshot of + exactly ``version``. + """ + with _service_call(f"open table {table_id} at version {version}"): + try: + _ignore_keyed_table_deprecation() + table = client.keyed_table_by_id(table_id, asof=version) # pyright: ignore[reportAny] + except sp.SpiralError as exc: + if not _reports_not_found(exc): + raise + raise TableVersionNotFoundError( + f"table {table_id} cannot be opened: {exc}" + ) from exc + opened = str(table.version_id) # pyright: ignore[reportAny] + if opened != str(version): + raise TableVersionNotFoundError( + f"table {table_id} has no version {version} (the snapshot at it is " + f"version {opened})" + ) + return table # pyright: ignore[reportAny] + + +def _key_range(key: Sequence[pa.Array[Any]]) -> Any: # pyright: ignore[reportExplicitAny] # an SDK object, untyped + """Return the key range of the one full key ``key``: both bounds that key, inclusive.""" + literals: list[Any] = [] + for array in key: + arrow_type = array.type + if pa.types.is_large_string(arrow_type): + literals.append(sp.literal(array[0].as_py(), pa.string())) + elif pa.types.is_large_binary(arrow_type): + literals.append(sp.literal(array[0].as_py(), pa.binary())) + elif pa.types.is_timestamp(arrow_type): + # As a count of the unit: the SDK takes no datetime between two of them. + literals.append(sp.literal(array.cast(pa.int64())[0].as_py(), arrow_type)) + else: + literals.append(sp.literal(array[0].as_py(), arrow_type)) + bound = sp.KeyBound(tuple(literals), True) + return sp.KeyRange(bound, bound) # pyright: ignore[reportAny] + + +def scan_one_key(table: Any, column: str, key: Sequence[pa.Array[Any]]) -> Any: # pyright: ignore[reportExplicitAny] # SDK objects, untyped + """Return spiral-sdk's scan of ``column`` over the key range of the one key ``key``. + + Args: + table: A keyed table (``open_table_version``). + column: The column read. + key: One single-element array per primary-key column, in key order, each of + its column's type as SpiralDB stores it. + """ + return table.scan([column], key_ranges=[_key_range(key)]) # pyright: ignore[reportAny] + + +def scan_keys( + table: Any, # pyright: ignore[reportExplicitAny] # an SDK table, untyped + columns: Sequence[str], + keys: Sequence[Sequence[pa.Array[Any]]], +) -> pa.Table: + """Read ``columns`` of the rows with the full keys ``keys``: ONE scan, many ranges. + + spiral-sdk reads several key ranges range after range ("replays ranges in supplied + order and retains overlaps", ``KeyedTable.scan`` in spiral-sdk 0.16.74), so the + keys must be distinct. A key the table does not hold reads no row. + + Args: + table: A keyed table (``open_table_version``). + columns: The columns read; the caller includes the key columns to tell the + rows apart. + keys: The distinct keys, each as in ``scan_one_key``. + """ + with _service_call(f"read {len(keys)} keys of table {table.resource_id}"): # pyright: ignore[reportAny] + scan = table.scan( # pyright: ignore[reportAny] + list(columns), key_ranges=[_key_range(key) for key in keys] + ) + return scan.to_table() # pyright: ignore[reportAny] + + class _NoRedirect(urllib.request.HTTPRedirectHandler): """Follows no redirect, so a token is never sent to another address.""" @@ -813,6 +1078,11 @@ def version(self) -> int: self._connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle return int(self._table.version_id) + def version_at(self, asof: int | None) -> int: + """The version a read with ``asof`` reads: the newest not after it (``None``: + the version at the lookup), as SpiralDB resolves it.""" + return int(self._at(asof).version_id) # pyright: ignore[reportAny] + def _at(self, asof: int | None) -> Any: """Return the SDK's handle of this same table at version ``asof``.""" self._connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle @@ -826,7 +1096,9 @@ def _at(self, asof: int | None) -> Any: self.table_id, asof, ) - self._versions[str(asof)] = opened + # Two reads that miss together keep the first handle stored, so every + # read of ``asof`` uses one snapshot (ITL-1789). + opened = self._versions.setdefault(str(asof), opened) return opened def scan_batches( @@ -1076,6 +1348,8 @@ def __init__( shared = _client_for(overrides) self._shared = shared self._client = client = shared.sdk + # References read through this connector may sign in to its service. + trust_service(service_address(client)) # Kept after close(): a read may end after it. self._health = health = shared.health self._pid = os.getpid() @@ -1126,6 +1400,11 @@ def _require_open(self) -> None: raise RuntimeError("SpiralDBConnector is closed") require_same_process(self._pid) + def service_address(self) -> str: + """Return the address (API URL) of the SpiralDB service this connector reads.""" + self._require_open() + return service_address(self._client) + def _writable_tables(self) -> SpiralDBTables | None: """The database tables, or ``None`` on a plain connector. @@ -1301,6 +1580,14 @@ def _recorded_schema( f"row in {SCHEMA_TABLE}: " f"{describe_difference(found, row.schema)}" ) + for reported_field, recorded_field in zip(found, row.schema, strict=True): + if tuple(vortex_encodings(reported_field)) != tuple( + vortex_encodings(recorded_field) + ): + raise TableSchemaError( + f"Vortex encoding metadata for column {reported_field.name!r} " + f"in version {table.version_id} differs from its row in {SCHEMA_TABLE}" + ) return row.schema def _reading( diff --git a/src/orcapod/databases/spiraldb_schema_table.py b/src/orcapod/databases/spiraldb_schema_table.py index 908cf8b1b..7d974fb52 100644 --- a/src/orcapod/databases/spiraldb_schema_table.py +++ b/src/orcapod/databases/spiraldb_schema_table.py @@ -1,7 +1,7 @@ """The schema table of a SpiralDB dataset (ITL-1186). -SpiralDB reports every top-level column and every struct field nullable and keeps no -Arrow metadata, and spiral-sdk reads no key-value metadata of a table. So the schemas of a +SpiralDB reports every top-level column and every struct field nullable, and +spiral-sdk reads no key-value metadata of a table. The schemas of a dataset's tables are kept in one keyed table beside them, ``__orcapod_schemas__``, written by ``scripts/migrate_spiral_schemas.py``. It is the assumed behaviour: a table that disagrees with its row is refused, and nothing else is consulted. @@ -24,7 +24,7 @@ import base64 import hashlib import json -from collections.abc import Callable, Iterable, Mapping +from collections.abc import Callable, Iterable, Iterator, Mapping from contextlib import AbstractContextManager from dataclasses import dataclass from functools import cached_property @@ -45,6 +45,7 @@ MARKER_KEY = "__complete__" FROM_RECORD = "record" FROM_SERVICE = "service" +VORTEX_EXTENSION_PREFIX = b"vortex." KEY_SCHEMA = pa.schema([pa.field("table_id", pa.large_string(), nullable=False)]) ROW_SCHEMA = pa.schema( @@ -92,6 +93,23 @@ def compared_columns(schema: pa.Schema) -> list[Any]: return [[f.name, _compared_type(f.type)] for f in schema] +def vortex_encodings( + field: pa.Field[Any], path: tuple[int, ...] = () +) -> Iterator[tuple[tuple[int, ...], bytes, bytes | None]]: + """Yield the relative field path, extension name and parameters of each encoding.""" + metadata = field.metadata or {} + name = metadata.get(b"ARROW:extension:name") + if name is not None and name.startswith(VORTEX_EXTENSION_PREFIX): + yield path, name, metadata.get(b"ARROW:extension:metadata") + arrow_type = field.type + if isinstance(arrow_type, pa.DictionaryType): + yield from vortex_encodings( + pa.field(field.name, arrow_type.value_type), (*path, -1) + ) + for index in range(arrow_type.num_fields): + yield from vortex_encodings(arrow_type.field(index), (*path, index)) + + def describe_difference(table: pa.Schema, recorded: pa.Schema) -> str: """Return how a table's columns differ from a recorded schema's, naming both.""" have = {f.name: _compared_type(f.type) for f in table} diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index f72432023..528462ca1 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -774,6 +774,62 @@ class SpiralDBSignInError(RuntimeError): """ +class SpiralDBUntrustedServiceError(PermissionError): + """A SpiralDB entry reference names a service this process did not reach itself. + + A reference's service address is data: it can name any host. Its entry is read, or + hashed, with the process's own sign-in only at an address this process reached + through a ``SpiralDBConnector`` or a SpiralDB source it built (ITL-1789). Raised + before any client is made or credential taken. To read from another service, pass + a client of it (``entry.read(client=...)``, ``entry.scan(client=...)``). + + Attributes: + service: The address the reference names. + """ + + def __init__(self, service: str) -> None: + """Create the error. + + Args: + service: The service address the reference names. + """ + self.service = service + super().__init__( + f"SpiralDB service {service!r} was not reached through a SpiralDBConnector " + "or a SpiralDB source built in this process, so it is not signed in to with " + "this process's sign-in. Build a source or connector of that service first, " + "or pass a client of it: entry.read(client=...)" + ) + + def __reduce__(self) -> tuple[object, ...]: + """Rebuild from the address (executors send errors across processes).""" + return (type(self), (self.service,), self.__dict__) + + +class SpiralDBEntryMissingError(LookupError): + """A SpiralDB entry reference names an entry its table version does not hold. + + The table at the reference's version has no row with its key, or that version cannot + be read any more (ITL-1789). Raised when the entry is hashed or read; a function + node counts it as a failed row under its error policy, as a row whose function + raised. + + Attributes: + entry: The reference (a ``SpiralDBEntry``). + reason: Why the entry cannot be read. + """ + + def __init__(self, entry: object, reason: str) -> None: + self.entry = entry + self.reason = reason + super().__init__(f"SpiralDB entry {entry!r}: {reason}") + + def __reduce__(self) -> tuple[object, ...]: + """Rebuild from the reference and reason (executors send errors across + processes); the state keeps notes added to it.""" + return (type(self), (self.entry, self.reason), self.__dict__) + + class UnrecordedTableSchemaWarning(UserWarning): """A SpiralDB table that holds rows has no row in its dataset's schema table. diff --git a/src/orcapod/hashing/arrow_hashers.py b/src/orcapod/hashing/arrow_hashers.py index acbe89117..77c16b613 100644 --- a/src/orcapod/hashing/arrow_hashers.py +++ b/src/orcapod/hashing/arrow_hashers.py @@ -1,5 +1,6 @@ from __future__ import annotations +from contextlib import nullcontext from typing import TYPE_CHECKING import pyarrow as pa @@ -14,8 +15,9 @@ has_extension_metadata, has_extension_type, ) -from orcapod.errors import MissingOptionalDependencyError +from orcapod.errors import MissingOptionalDependencyError, SpiralDBEntryMissingError from orcapod.logical_types.identifier import LogicalTypeIdentifierError +from orcapod.hashing.prefetch import prefetched_table from orcapod.hashing.visitors import SemanticHashingVisitor from orcapod.logical_types.canonical_form import storage_form_schema from orcapod.utils.arrow_utils import normalize_extension_columns @@ -140,64 +142,80 @@ def _process_table_columns(self, table: "pa.Table | pa.RecordBatch") -> "pa.Tabl new_columns: list[pa.Array | pa.ChunkedArray] = [] new_fields: list[pa.Field] = [] - for i, field in enumerate(table.schema): - # Short-circuit: columns that cannot contain semantic types skip - # the costly Python round-trip. Extension types must pass through - # so visit_extension can process them. - process_values = ( - isinstance(field.type, pa.ExtensionType) - or pa.types.is_struct(field.type) - or pa.types.is_list(field.type) - or pa.types.is_large_list(field.type) - or pa.types.is_fixed_size_list(field.type) - or pa.types.is_map(field.type) - ) - if not process_values and b"ARROW:extension:name" not in ( - field.metadata or {} - ): - new_columns.append(table.column(i)) - new_fields.append(field) - continue - - visitor = SemanticHashingVisitor( - self._type_converter, self._semantic_hasher - ) - - try: - # The hashed type is derived from the declared type alone, never - # from a row: nested nullability, field metadata and list item - # fields are kept, and a column hashes the same way whether it - # holds data, nulls or no rows (ITL-942 I). - # A value-hashed logical type keeps its identifier on the field, so - # it is part of the hash also when the column holds no value - # (ITL-967). - new_field = visitor.hashed_field(field) - column = table.column(i) - if process_values: - processed_data = [ - visitor.visit(field.type, value)[1] - for value in column.to_pylist() - ] - new_columns.append(pa.array(processed_data, type=new_field.type)) - else: - new_columns.append(column) - new_fields.append(new_field) - - except MissingOptionalDependencyError: - # A logical type whose library is not installed: raised as itself, - # naming the type and the package (the schema hash looks nothing up - # since ITL-640, so this is where such a column is first met). - raise - except LogicalTypeIdentifierError as exc: - # An identifier this installation cannot read: raised as itself, - # naming the column (met here first, as above). - if exc.column is not None: + # Values whose hash needs a fetch are fetched together, not one per cell, and + # hashed from that batch (ITL-1789); a one-row table's cell is fetched by its + # own hash. + batch = ( + prefetched_table(table, self._type_converter, self._semantic_hasher) + if table.num_rows > 1 + else nullcontext() + ) + with batch: + for i, field in enumerate(table.schema): + # Short-circuit: columns that cannot contain semantic types skip + # the costly Python round-trip. Extension types must pass through + # so visit_extension can process them. + process_values = ( + isinstance(field.type, pa.ExtensionType) + or pa.types.is_struct(field.type) + or pa.types.is_list(field.type) + or pa.types.is_large_list(field.type) + or pa.types.is_fixed_size_list(field.type) + or pa.types.is_map(field.type) + ) + if not process_values and b"ARROW:extension:name" not in ( + field.metadata or {} + ): + new_columns.append(table.column(i)) + new_fields.append(field) + continue + + visitor = SemanticHashingVisitor( + self._type_converter, self._semantic_hasher + ) + + try: + # The hashed type is derived from the declared type alone, never + # from a row: nested nullability, field metadata and list item + # fields are kept, and a column hashes the same way whether it + # holds data, nulls or no rows (ITL-942 I). + # A value-hashed logical type keeps its identifier on the field, so + # it is part of the hash also when the column holds no value + # (ITL-967). + new_field = visitor.hashed_field(field) + column = table.column(i) + if process_values: + processed_data = [ + visitor.visit(field.type, value)[1] + for value in column.to_pylist() + ] + new_columns.append( + pa.array(processed_data, type=new_field.type) + ) + else: + new_columns.append(column) + new_fields.append(new_field) + + except SpiralDBEntryMissingError as exc: + # A value whose content is gone: raised as itself, so a node fails + # that row under its error policy (ITL-1789). + exc.add_note(f"in column {field.name!r}") + raise + except MissingOptionalDependencyError: + # A logical type whose library is not installed: raised as itself, + # naming the type and the package (the schema hash looks nothing up + # since ITL-640, so this is where such a column is first met). raise - raise exc.for_column(field.name) from exc - except Exception as exc: - raise RuntimeError( - f"Failed to process column '{field.name}': {exc}" - ) from exc + except LogicalTypeIdentifierError as exc: + # An identifier this installation cannot read: raised as itself, + # naming the column (met here first, as above). + if exc.column is not None: + raise + raise exc.for_column(field.name) from exc + except Exception as exc: + raise RuntimeError( + f"Failed to process column '{field.name}': {exc}" + ) from exc intermediate = pa.table( new_columns, diff --git a/src/orcapod/hashing/prefetch.py b/src/orcapod/hashing/prefetch.py new file mode 100644 index 000000000..e88b976ff --- /dev/null +++ b/src/orcapod/hashing/prefetch.py @@ -0,0 +1,322 @@ +"""Fetching many cells' values together before they are hashed one by one (ITL-1789). + +Some value hashes need something fetched from elsewhere first: a ``SpiralDBEntry``'s hash +is the hash of its entry's content, read from SpiralDB. Hashing rows one by one would +fetch one value per row. A value handler that can fetch many values together implements +``PrefetchingHandlerProtocol``; rows are hashed one by one inside ``prefetched_rows`` +(rows) or ``prefetched_table`` (a table), which hands it every value of its columns at +once and keeps what was fetched for that batch while it is hashed. Prefetching changes +no hash. + +Only top-level columns are looked at: a column of such a logical type, or a native +container (``list[T]``, ``set[T]``) of one, at any depth. Such a value is refused +anywhere else (inside a struct, a user class or a map: ITL-1789). +""" + +from __future__ import annotations + +import json +from collections.abc import Iterator, Sequence +from contextlib import AbstractContextManager, ExitStack, contextmanager +from typing import TYPE_CHECKING, Any, Protocol, cast, runtime_checkable + +import pyarrow as pa + +from orcapod.logical_types.identifier import ( + arrow_type_identifier, + container_element_identifier, + declared_value_hash, +) + +if TYPE_CHECKING: + from orcapod.protocols.core_protocols import DataProtocol + from orcapod.protocols.hashing_protocols import SemanticHasherProtocol + from orcapod.logical_types.protocols import LogicalTypeProtocol + + +class ExtensionLookupProtocol(Protocol): + """What prefetching needs of a type converter: its logical types by extension name.""" + + def get_logical_type_by_arrow_extension_name( + self, arrow_extension_name: str + ) -> LogicalTypeProtocol | None: + """Return the registered logical type for ``arrow_extension_name``, or ``None``.""" + ... + + +@runtime_checkable +class PrefetchingHandlerProtocol(Protocol): + """A value handler that can fetch many values' inputs together (``prefetched``).""" + + def prefetched(self, values: Sequence[object]) -> AbstractContextManager[None]: + """Fetch what hashing ``values`` needs, together; inside the block, hashing + one of ``values`` uses what was fetched. + + Args: + values: Python values of the handler's type; a value it does not fetch + for is ignored. + + Returns: + A context manager: the batch lasts while it is entered. + """ + ... + + +class _Prefetching: + """A column whose values a handler prefetches: the handler and how to reach them.""" + + __slots__ = ("handler", "logical_type", "depth") + + def __init__( + self, handler: PrefetchingHandlerProtocol, logical_type: Any, depth: int + ) -> None: + self.handler = handler + self.logical_type = logical_type # pyright: ignore[reportAny] + # How many native container levels hold the values. + self.depth = depth + + +def _prefetching_handler( + extension_name: str, + type_converter: ExtensionLookupProtocol, + semantic_hasher: SemanticHasherProtocol, +) -> tuple[PrefetchingHandlerProtocol, Any] | None: + """Return the prefetching handler of the logical type ``extension_name`` and the + logical type, or ``None`` when its values are not prefetched.""" + logical_type = type_converter.get_logical_type_by_arrow_extension_name( + extension_name + ) + if logical_type is None or not isinstance(logical_type.python_type, type): + return None + handler = semantic_hasher.type_handler_registry.get_handler_for_type( + logical_type.python_type + ) + if not isinstance(handler, PrefetchingHandlerProtocol): + return None + return handler, logical_type + + +def _prefetching( + arrow_type: pa.DataType, + type_converter: ExtensionLookupProtocol, + semantic_hasher: SemanticHasherProtocol, +) -> _Prefetching | None: + """Return how a column of ``arrow_type`` is prefetched, or ``None`` if it is not. + + Only a column hashed by value is: one whose identifier declares a value hash (or, + with empty metadata, whose registered type does, as the hashing visitor reads it). + A column declared ``stored`` is hashed as stored and fetches nothing. Anything this + cannot resolve is not prefetched: hashing the column then resolves it and raises + what it raises. + """ + if not isinstance(arrow_type, pa.ExtensionType): + return None + try: + element = arrow_type_identifier(arrow_type) + depth = 0 + while (inner := container_element_identifier(element)) is not None: + element = inner + depth += 1 + found = _prefetching_handler(element.name, type_converter, semantic_hasher) + if found is None: + return None + declaration = declared_value_hash(element) + if declaration is None and element.metadata == b"": + declaration = declared_value_hash( + arrow_type_identifier(found[1].get_arrow_extension_type()) # pyright: ignore[reportAny] + ) + except Exception: + return None + if declaration in (None, "stored"): + return None + return _Prefetching(found[0], found[1], depth) + + +def _record_logical_names(arrow_type: pa.ExtensionType) -> Iterator[str]: + """Yield the extension names of the logical types an extension's metadata names in + an identity record (``{"logical": ";"}``, as a user class + records a field of a logical type), at any depth.""" + try: + record: object = json.loads(arrow_type.__arrow_ext_serialize__()) + except (ValueError, UnicodeDecodeError): + return + pending: list[object] = [record] + while pending: + item = pending.pop() + if isinstance(item, dict): + for key, value in cast("dict[str, object]", item).items(): + if key == "logical" and isinstance(value, str): + yield value.split(";", 1)[0] + else: + pending.append(value) + elif isinstance(item, list): + pending.extend(cast("list[object]", item)) + + +def _fetches( + arrow_type: pa.DataType, + type_converter: ExtensionLookupProtocol, + semantic_hasher: SemanticHasherProtocol, +) -> bool: + """Whether hashing a value of ``arrow_type`` fetches something, at any depth: the + type itself, a struct field, a list item, a map key or item, the storage of a + logical type, or a field a user class records in its identity.""" + if _prefetching(arrow_type, type_converter, semantic_hasher) is not None: + return True + if isinstance(arrow_type, pa.ExtensionType): + for name in _record_logical_names(arrow_type): + try: + if _prefetching_handler(name, type_converter, semantic_hasher): + return True + except Exception: + continue + return _fetches(arrow_type.storage_type, type_converter, semantic_hasher) + if isinstance(arrow_type, pa.MapType): + return _fetches( + arrow_type.key_type, type_converter, semantic_hasher + ) or _fetches(arrow_type.item_type, type_converter, semantic_hasher) + return any( + _fetches(arrow_type.field(index).type, type_converter, semantic_hasher) + for index in range(arrow_type.num_fields) + ) + + +class _Batches: + """The values to prefetch, gathered per handler over every column, so that each + handler is called once for all its columns (one fetch per table version, not per + column).""" + + def __init__(self) -> None: + self._values: dict[int, tuple[PrefetchingHandlerProtocol, list[object]]] = {} + + def add(self, handler: PrefetchingHandlerProtocol, values: list[object]) -> None: + self._values.setdefault(id(handler), (handler, []))[1].extend(values) + + @contextmanager + def prefetched(self) -> Iterator[None]: + with ExitStack() as stack: + for handler, values in self._values.values(): + if values: + _ = stack.enter_context(handler.prefetched(values)) + yield + + +def _flatten(values: list[Any], depth: int) -> list[Any]: + """Return the values ``depth`` list levels inside ``values``, nulls left out.""" + for _ in range(depth): + values = [item for value in values if value is not None for item in value] # pyright: ignore[reportAny] + return [value for value in values if value is not None] # pyright: ignore[reportAny] + + +@contextmanager +def prefetched_table( + table: pa.Table | pa.RecordBatch, + type_converter: ExtensionLookupProtocol, + semantic_hasher: SemanticHasherProtocol, +) -> Iterator[None]: + """Hand every prefetching handler all the values of its columns of ``table``; hash + the table inside the block. + + Args: + table: The table about to be hashed. + type_converter: The data context's type converter. + semantic_hasher: The data context's semantic hasher (its handler registry). + """ + batches = _Batches() + if table.num_rows: + for index, field in enumerate(table.schema): + found = _prefetching(field.type, type_converter, semantic_hasher) + if found is None: + continue + stored = _flatten(table.column(index).to_pylist(), found.depth) + try: + values = [ + found.logical_type.storage_to_python(value) # pyright: ignore[reportAny] + for value in stored + ] + except Exception: + # Not prefetched: hashing the column raises it, naming the column. + continue + batches.add(found.handler, values) + with batches.prefetched(): + yield + + +@contextmanager +def prefetched_rows( + rows: Sequence[DataProtocol], + type_converter: ExtensionLookupProtocol, + semantic_hasher: SemanticHasherProtocol, +) -> Iterator[None]: + """Hand every prefetching handler all the values of its columns in ``rows``; hash + the rows inside the block. + + The columns are found from the first row's Arrow schema (the rows of one stream + share it). + + Args: + rows: The data rows about to be hashed one by one, each holding its payload + (the caller leaves out a placeholder of a result that is gone). + type_converter: The data context's type converter. + semantic_hasher: The data context's semantic hasher (its handler registry). + """ + payloads = list(rows) + batches = _Batches() + if payloads: + for field in payloads[0].arrow_schema(): + found = _prefetching(field.type, type_converter, semantic_hasher) + if found is None: + continue + batches.add( + found.handler, + _flatten( + [row[field.name] for row in payloads if field.name in row], + found.depth, + ), + ) + with batches.prefetched(): + yield + + +def prefetched_columns( + schema: pa.Schema, + type_converter: ExtensionLookupProtocol, + semantic_hasher: SemanticHasherProtocol, +) -> list[str]: + """Return the top-level columns whose values are prefetched (``prefetched_rows``), + in name order: a column of a prefetching logical type, or a native container of + one. + + Args: + schema: The rows' schema. + type_converter: The data context's type converter. + semantic_hasher: The data context's semantic hasher (its handler registry). + """ + return sorted( + field.name + for field in schema + if _prefetching(field.type, type_converter, semantic_hasher) is not None + ) + + +def fetching_columns( + schema: pa.Schema, + type_converter: ExtensionLookupProtocol, + semantic_hasher: SemanticHasherProtocol, +) -> list[str]: + """Return the top-level columns whose values' hash fetches something, in name order. + + Hashing a table with such a column reads every value it names from elsewhere (a + SpiralDB entry's content). A column counts when such a value is anywhere inside + it (``_fetches``), though only top-level columns are prefetched. + + Args: + schema: The table's schema. + type_converter: The data context's type converter. + semantic_hasher: The data context's semantic hasher (its handler registry). + """ + return sorted( + field.name + for field in schema + if _fetches(field.type, type_converter, semantic_hasher) + ) diff --git a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py index a153ecc11..73e24b031 100644 --- a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py +++ b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py @@ -24,7 +24,8 @@ from __future__ import annotations import logging -from collections.abc import Iterable +from collections.abc import Iterable, Sequence +from contextlib import AbstractContextManager from typing import TYPE_CHECKING, Any from uuid import UUID @@ -61,6 +62,11 @@ POLARS_SERIES_EXTENSION_NAME, POLARS_SERIES_HASH_LABEL, ) +from orcapod.logical_types.spiraldb_entry_type import ( + SPIRALDB_ENTRY_EXTENSION_NAME, + SPIRALDB_ENTRY_HASH_LABEL, + SpiralDBEntry, +) from orcapod.types import ContentHash, Schema from orcapod.utils.canonical_type_names import canonical_type_name @@ -104,6 +110,55 @@ def handle(self, obj: Any, hasher: "SemanticHasherProtocol") -> Encoded: raise TypeError(f"UUIDHandler: expected uuid.UUID, got {type(obj)!r}") +class SpiralDBEntryHandler: + """Hasher for a ``SpiralDBEntry``: the content of the entry it names (ITL-1789). + + The hash is ``entry_content_hash`` of the entry's value as SpiralDB holds it, labelled + ``SPIRALDB_ENTRY_HASH_LABEL``; the reference's own fields (table, version, key, + column, service) are not part of it. A retained outcome for the current sign-in is + reused; otherwise the value is fetched (again after eviction or under another + sign-in). A node fetches the entries of many rows together through ``prefetched`` + first. + """ + + EXTENSION_NAME = SPIRALDB_ENTRY_EXTENSION_NAME + HASH_LABEL = SPIRALDB_ENTRY_HASH_LABEL + + def handle(self, obj: Any, hasher: "SemanticHasherProtocol") -> ContentHash: + """Return the content hash of the entry ``obj`` names. + + Args: + obj: A ``SpiralDBEntry``. + hasher: The semantic hasher (unused). + + Returns: + The entry's content hash. + + Raises: + TypeError: If ``obj`` is not a ``SpiralDBEntry``. + SpiralDBEntryMissingError: If the entry's version holds no row with its key. + """ + if isinstance(obj, SpiralDBEntry): + return obj.content_hash() + raise TypeError( + f"SpiralDBEntryHandler: expected SpiralDBEntry, got {type(obj)!r}" + ) + + def prefetched(self, values: Sequence[object]) -> AbstractContextManager[None]: + """Fetch the entries of ``values`` together; inside the block they are hashed + from that batch (``SpiralDBEntry.prefetched``). + + Args: + values: ``SpiralDBEntry`` references; anything else is left to ``handle``. + + Returns: + A context manager. + """ + return SpiralDBEntry.prefetched( + v for v in values if isinstance(v, SpiralDBEntry) + ) + + class BytesHandler: """Hasher for bytes and bytearray objects: the tagged value ``{"__type__": "bytes", "hex": ...}``. diff --git a/src/orcapod/logical_types/spiraldb_entry_type.py b/src/orcapod/logical_types/spiraldb_entry_type.py new file mode 100644 index 000000000..678389129 --- /dev/null +++ b/src/orcapod/logical_types/spiraldb_entry_type.py @@ -0,0 +1,402 @@ +"""orcapod.SpiralDBEntry: a reference to one entry of a SpiralDB table (ITL-1789). + +A SpiralDB table can store a column in an encoding of its own (a Vortex encoding, such +as ``vortex.turboquant``, a lossy quantized vector). Orcapod does not decode or copy such +a value: ``SpiralDBTableSource`` presents the column as references, one per row, and the +value is read through spiral-sdk when it is needed (``SpiralDBEntry.read``). + +A reference names exactly one entry of one version of the table: the table's id, the +version the source read, the row's primary-key values, the column and the address of the +SpiralDB service that holds it. It is stored as itself (``LogicalSpiralDBEntry``, +extension name ``orcapod.spiraldb.entry``). Those fields are provenance only: its value +hash is the hash of the entry's CONTENT (``entry_content_hash``, label +``SPIRALDB_ENTRY_HASH_LABEL``), fetched from SpiralDB when Orcapod hashes a data row that +holds it, never on a plain read. + +This module imports no spiral-sdk; ``read``, ``scan``, ``content_hash`` and ``prefetch`` +load the fetching code when called. +""" + +from __future__ import annotations + +from collections.abc import Iterable +from contextlib import AbstractContextManager +from typing import TYPE_CHECKING, Any + +import polars as pl +import pyarrow as pa + +from orcapod.logical_types.base_logical_type import BaseLogicalType +from orcapod.logical_types.identifier import version_metadata +from orcapod.logical_types.registry import ( + make_arrow_extension_type, + make_polars_extension_type, +) +from orcapod.hashing.starfix_digest import digest_library_value +from orcapod.types import ContentHash + +if TYPE_CHECKING: + from orcapod.logical_types.protocols import TypeConverterProtocol + + +SPIRALDB_ENTRY_EXTENSION_NAME = "orcapod.spiraldb.entry" +"""The Arrow extension name of a SpiralDB entry reference.""" + +SPIRALDB_ENTRY_HASH_LABEL = "spiraldb_entry_v1" +"""``ContentHash.method`` of ``entry_content_hash``: the single definition.""" + +_ENTRY_COLUMN = "entry" +"""The fixed name an entry's column is hashed under, so its column name does not count.""" + + +def entry_content_hash(entry_table: pa.Table) -> ContentHash: + """Return the value hash of an entry: the digest of its content (ITL-1789). + + The content is the one value spiral-sdk returns for the entry, with its Arrow field + (type, nullability and metadata, so a Vortex encoding's name and parameters count) + under a fixed column name: the column's own name, the table, the version, the key + and the service are not part of it. The digest is starfix's strict digest (every bit + counts), as for a library value. + + Args: + entry_table: The entry as read: one row, one column. + + Returns: + The hash, labelled ``SPIRALDB_ENTRY_HASH_LABEL``. + + Raises: + ValueError: If ``entry_table`` is not one row and one column. + """ + if entry_table.num_rows != 1 or entry_table.num_columns != 1: + raise ValueError( + "a SpiralDB entry is one row and one column, got " + f"{entry_table.num_rows} rows and {entry_table.num_columns} columns" + ) + field = entry_table.schema.field(0).with_name(_ENTRY_COLUMN) + content = pa.Table.from_arrays([entry_table.column(0)], schema=pa.schema([field])) + digest = digest_library_value( + content, include_metadata=True, ordered_columns=True, ordered_struct_fields=True + ) + return ContentHash(method=SPIRALDB_ENTRY_HASH_LABEL, digest=digest) + + +_IDENTIFIER_METADATA = version_metadata(1, SPIRALDB_ENTRY_HASH_LABEL) +"""Version 1 of the stored layout; the value hash is the entry's content hash.""" + +SPIRALDB_ENTRY_STORAGE = pa.struct( + [ + pa.field("table_id", pa.large_string(), nullable=False), + pa.field("version", pa.int64(), nullable=False), + pa.field("key", pa.large_string(), nullable=False), + pa.field("column", pa.large_string(), nullable=False), + pa.field("service", pa.large_string(), nullable=False), + ] +) +"""The stored layout: the five fields of ``SpiralDBEntry``, none of them nullable.""" + + +class SpiralDBEntry: + """A reference to one entry of a SpiralDB table, at one version of the table. + + ``SpiralDBTableSource`` gives one for each row of a column stored in an encoding + Orcapod does not read (a Vortex encoding). The reference names the version the source + read and the service that holds the table. Its fields are provenance only: its value + hash is the hash of the entry's content (``content_hash``), so two references to the + same bytes (at two versions of the table, say) hash alike, and an entry rewritten + under its key hashes apart. The content is fetched only when Orcapod hashes a data + row that holds the reference (a function node's input, a cached operator), never on + a plain read, ``head`` or preview; a node fetches the entries of its rows together + (``prefetch``), one SpiralDB scan per table version. Its fields are read-only; two + references are equal when their five fields are. + + It is a class of its own, not a dataclass, so that it is only ever the logical type + ``orcapod.spiraldb.entry``, never a user class. + + Args: + table_id: SpiralDB's own id of the table (``table_...``). + version: The table version the source read + (``SpiralDBTableSource.pinned_version``). + key: The row's primary-key values, in key order, as the canonical JSON Orcapod + uses for a row's key (``{"unit":"u1","time":1700000000}``; a timestamp or + date as ISO-8601 text). + column: The name of the top-level column. For a struct column with an encoded + field, the whole struct column. + service: The address of the SpiralDB service the source read (its API URL). It + is an address only, never a credential. + + Raises: + TypeError: If a field is not of its type (``str``, ``int``, ``str``, ``str``, + ``str``). + """ + + __slots__ = ("_table_id", "_version", "_key", "_column", "_service") + + def __init__( + self, table_id: str, version: int, key: str, column: str, service: str + ) -> None: + for name, value, kind in ( + ("table_id", table_id, str), + ("version", version, int), + ("key", key, str), + ("column", column, str), + ("service", service, str), + ): + if type(value) is not kind: + raise TypeError( + f"SpiralDBEntry: {name} must be a {kind.__name__}, got {value!r}" + ) + self._table_id: str = table_id + self._version: int = version + self._key: str = key + self._column: str = column + self._service: str = service + + @property + def table_id(self) -> str: + """SpiralDB's own id of the table.""" + return self._table_id + + @property + def version(self) -> int: + """The table version the source read.""" + return self._version + + @property + def key(self) -> str: + """The row's primary-key values as canonical JSON, in key order.""" + return self._key + + @property + def column(self) -> str: + """The top-level column.""" + return self._column + + @property + def service(self) -> str: + """The address of the SpiralDB service that holds the table.""" + return self._service + + def _fields(self) -> tuple[str, int, str, str, str]: + return (self._table_id, self._version, self._key, self._column, self._service) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SpiralDBEntry): + return NotImplemented + return self._fields() == other._fields() + + def __hash__(self) -> int: + return hash(self._fields()) + + def __repr__(self) -> str: + return ( + f"SpiralDBEntry(table_id={self._table_id!r}, version={self._version!r}, " + f"key={self._key!r}, column={self._column!r}, service={self._service!r})" + ) + + def __reduce__(self) -> tuple[type[SpiralDBEntry], tuple[str, int, str, str, str]]: + return (SpiralDBEntry, self._fields()) + + def scan(self, client: Any = None) -> Any: # pyright: ignore[reportExplicitAny, reportAny] # an SDK object, untyped + """Return spiral-sdk's scan of this entry: the one key, the one column. + + The table is opened by its id at exactly ``version``; the scan's key range is + the one primary key, so it holds at most one row. The scan is lazy: for a key + the version does not hold it yields no row, which the caller must handle. A failure + to reach the service, or to sign in, is not a missing entry: it propagates as + itself. + + Args: + client: A ``spiral.Client``. ``None`` (default) makes one for ``service`` + with spiral-sdk's own sign-in (``SPIRAL_*`` environment variables, or a + saved ``spiral login``); it never asks a person to sign in. + + Returns: + A ``spiral.tables.Scan``. + + Raises: + ImportError: If spiral-sdk is not installed (``orcapod[spiraldb]``). + SpiralDBEntryMissingError: If the table or its exact ``version`` does not + exist. + SpiralDBUntrustedServiceError: If ``client`` is ``None`` and ``service`` + is not one this process reached. + SpiralDBSignInError: If ``client`` is ``None`` and spiral-sdk would have + to ask a person to sign in. + ValueError: If the key does not fit the table's primary key. + """ + from orcapod.core.sources.spiraldb_entries import scan_entry + + return scan_entry(self, client) # pyright: ignore[reportAny] # an SDK object + + def read(self, client: Any = None) -> pa.Table: # pyright: ignore[reportExplicitAny] # an SDK client, untyped + """Read this entry, exactly the value its content hash was computed from. + + The value comes from this process's entry cache when the entry was fetched + before (to hash it, for example), else from SpiralDB at ``version``. It is never + read at another version. A failure to reach the service, or to sign in, is not a + missing entry: it propagates as itself. + + Args: + client: As for ``scan``. + + Returns: + A table of one row and one column, named ``column``, holding the value as + spiral-sdk returns it (a Vortex-encoded column keeps its Arrow extension + name and metadata on the field). + + Raises: + ImportError: If spiral-sdk is not installed (``orcapod[spiraldb]``). + SpiralDBEntryMissingError: If the table or its exact ``version`` does not + exist, or that version has no row with this key. + SpiralDBUntrustedServiceError: If ``client`` is ``None`` and ``service`` + is not one this process reached. + SpiralDBSignInError: If ``client`` is ``None`` and spiral-sdk would have + to ask a person to sign in. + """ + from orcapod.core.sources.spiraldb_entries import read_entry + + return read_entry(self, client) + + def content_hash(self) -> ContentHash: + """Return the hash of the entry's content (``entry_content_hash``). + + The entry is fetched when hashed, unless an outcome for it is retained for + the current sign-in (or the active batch): hashing reuses that outcome. A + miss, after the outcome was evicted or under another sign-in, fetches the + entry again (``prefetch`` fetches many entries together). A failure to + reach the service, or to sign in, is not a missing entry: it propagates as + itself. + + Raises: + SpiralDBEntryMissingError: If the table or its exact ``version`` does not + exist, or that version has no row with this key. + SpiralDBUntrustedServiceError: If ``service`` is not one this process + reached. + """ + from orcapod.core.sources.spiraldb_entries import cached_content_hash + + return cached_content_hash(self) + + @staticmethod + def prefetch(entries: Iterable[SpiralDBEntry]) -> None: + """Fetch the entries this process has not fetched yet, together. + + One SpiralDB scan per (service, table, version), with one key range per entry, + never one per entry. An entry the version does not hold is remembered as + missing: hashing it raises ``SpiralDBEntryMissingError``, for that row only. + Any other fetch error is left for the hash of the entry it concerns to raise. + + Args: + entries: The references. + + Raises: + SpiralDBUntrustedServiceError: If a reference names a service this process + did not reach through a connector or source it built, as ``read`` + raises it: before any client is made. + """ + from orcapod.core.sources.spiraldb_entries import prefetch_entries + + prefetch_entries(entries) + + @staticmethod + def prefetched(entries: Iterable[SpiralDBEntry]) -> AbstractContextManager[None]: + """Fetch ``entries`` together, and hash them from that batch inside the block. + + One SpiralDB scan per (service, table, version) for the entries the process + has not kept. Inside the ``with`` block, hashing one of ``entries`` uses what + this batch fetched (its content hash, that it is missing, or the error its + fetch raised, raised where it is hashed), whatever the process cache evicts + meanwhile. + + Args: + entries: The references. + + Returns: + A context manager. + """ + from orcapod.core.sources.spiraldb_entries import prefetched_entries + + return prefetched_entries(entries) + + +class LogicalSpiralDBEntry(BaseLogicalType): + """Logical type for ``SpiralDBEntry``: extension ``orcapod.spiraldb.entry``. + + Stored as a struct of the reference's five fields (``SPIRALDB_ENTRY_STORAGE``), + with metadata ``{"value_hash":"spiraldb_entry_v1","version":1}``: a reference is + hashed by its entry's content (``entry_content_hash``). Provisional (``provisional`` of ``contexts/logical_types.json``). + """ + + _arrow_ext_class = make_arrow_extension_type( + SPIRALDB_ENTRY_EXTENSION_NAME, SPIRALDB_ENTRY_STORAGE, _IDENTIFIER_METADATA + ) + _arrow_ext: pa.ExtensionType | None = None + _polars_ext_class = make_polars_extension_type( + SPIRALDB_ENTRY_EXTENSION_NAME, + SPIRALDB_ENTRY_STORAGE, + _IDENTIFIER_METADATA.decode(), + ) + _polars_ext: pl.BaseExtension | None = None + + logical_type_name: str = SPIRALDB_ENTRY_EXTENSION_NAME + python_type: type = SpiralDBEntry + + def get_arrow_extension_type(self) -> pa.ExtensionType: + """Return the Arrow extension type ``orcapod.spiraldb.entry``. + + Returns: + The one instance, over ``SPIRALDB_ENTRY_STORAGE``. + """ + if LogicalSpiralDBEntry._arrow_ext is None: + LogicalSpiralDBEntry._arrow_ext = LogicalSpiralDBEntry._arrow_ext_class() # pyright: ignore[reportCallIssue] # the synthesized class takes no arguments + return LogicalSpiralDBEntry._arrow_ext + + def get_polars_extension_type(self) -> pl.BaseExtension: + """Return the Polars extension type ``orcapod.spiraldb.entry``. + + Returns: + The one instance. + """ + if LogicalSpiralDBEntry._polars_ext is None: + LogicalSpiralDBEntry._polars_ext = LogicalSpiralDBEntry._polars_ext_class() # pyright: ignore[reportCallIssue] # the synthesized class takes no arguments + return LogicalSpiralDBEntry._polars_ext + + def python_to_storage( + self, value: Any, converter: TypeConverterProtocol | None = None + ) -> dict[str, object]: + """Return a reference's stored struct value. + + Args: + value: A ``SpiralDBEntry``. + converter: Ignored. Present for protocol conformance. + + Returns: + ``{"table_id": ..., "version": ..., "key": ..., "column": ..., + "service": ...}``. + """ + return { + "table_id": value.table_id, + "version": value.version, + "key": value.key, + "column": value.column, + "service": value.service, + } + + def storage_to_python( + self, storage_value: Any, converter: TypeConverterProtocol | None = None + ) -> SpiralDBEntry: + """Rebuild a reference from its stored struct value. + + Args: + storage_value: A mapping with the five fields. + converter: Ignored. Present for protocol conformance. + + Returns: + The ``SpiralDBEntry``. + """ + return SpiralDBEntry( + table_id=storage_value["table_id"], + version=storage_value["version"], + key=storage_value["key"], + column=storage_value["column"], + service=storage_value["service"], + ) diff --git a/src/orcapod/logical_types/user_class_identity.py b/src/orcapod/logical_types/user_class_identity.py index c18a9a0b8..5e7845ff0 100644 --- a/src/orcapod/logical_types/user_class_identity.py +++ b/src/orcapod/logical_types/user_class_identity.py @@ -500,7 +500,9 @@ def _type_token( _ = converter.register_python_class(annotation) # raises for unsupported types lt = converter.get_logical_type_for_python_type(annotation) if lt is not None: - return {"logical": logical_type_identifier(lt).text} + identifier = logical_type_identifier(lt) + _require_held_in_user_class(identifier.name, path) + return {"logical": identifier.text} return _class_token(annotation) if origin is not None: return { @@ -510,6 +512,37 @@ def _type_token( raise TypeError(f"Cannot build a type token for annotation {annotation!r}.") +def _require_held_in_user_class(extension_name: str, path: tuple[type, ...]) -> None: + """Refuse a SpiralDB entry reference as a field of a user class, at any depth. + + A reference's hash is its entry's content, fetched together for a column's values; + a reference inside a class would be hashed as its stored fields (the class is + stored and hashed as stored), so a moved pin would change the row's hash while + the entry's content did not (ITL-1789). A reference is supported as a column's + own type, or inside ``list[...]`` there. + + Raises: + NestedTypeNotStorableError: If ``extension_name`` is the reference type's and + ``path`` names the user class that holds it. + """ + from orcapod.logical_types.spiraldb_entry_type import ( + SPIRALDB_ENTRY_EXTENSION_NAME, + ) + from orcapod.semantic_types.nested_storage import NestedTypeNotStorableError + + if extension_name != SPIRALDB_ENTRY_EXTENSION_NAME or not path: + # No class encloses it: ``type_token`` of the type itself. + return + holder = path[-1].__qualname__ + raise NestedTypeNotStorableError( + f"{holder} declares a SpiralDBEntry inside a field: a SpiralDB entry reference " + "is supported only as a column's own type, or inside list[...] there, never " + "inside a user class, a dataclass, a pydantic model or another struct field " + "(its hash is its entry's content, which a class field would not hash). Hold " + "the reference in a column of its own." + ) + + def _class_token(cls: Any) -> str: """Return the type token of a class: its canonical name, builtins written bare.""" name = canonical_type_name(cls) diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 4345a33fd..ad7f8bc7a 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -673,6 +673,12 @@ async def receive(self) -> pa.RecordBatch: """ ... + def take_ready(self, max_items: int) -> list[pa.RecordBatch]: + """Take the record batches already waiting, up to ``max_items``, without + waiting (``ReadableChannel.take_ready``). An empty list says only that none is + waiting now: ``receive`` tells the end.""" + ... + def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: """Iterate over the remaining record batches, in arrival order.""" ... diff --git a/src/orcapod/protocols/semantic_types_protocols.py b/src/orcapod/protocols/semantic_types_protocols.py index 4116decc3..5703d2f96 100644 --- a/src/orcapod/protocols/semantic_types_protocols.py +++ b/src/orcapod/protocols/semantic_types_protocols.py @@ -63,6 +63,10 @@ def ensure_types_registered_for_schemas(self, *schemas: Schema) -> None: ... def get_logical_type(self, python_type: type) -> "LogicalTypeProtocol | None": ... + def get_logical_type_by_arrow_extension_name( + self, arrow_extension_name: str + ) -> "LogicalTypeProtocol | None": ... + def get_logical_type_for_python_type( self, annotation: Any ) -> "LogicalTypeProtocol | None": ... diff --git a/src/orcapod/utils/database_errors.py b/src/orcapod/utils/database_errors.py index b2b3ebc76..882a49149 100644 --- a/src/orcapod/utils/database_errors.py +++ b/src/orcapod/utils/database_errors.py @@ -97,6 +97,48 @@ def keep_database_error( note_callback_failure(database_error, during, failure) +@contextmanager +def keep_run_error(run_error: BaseException, during: str) -> Iterator[None]: + """Run a cleanup callback so that it cannot replace the run's own error. + + Used while a failed run reports its held rows' crashes before the node's end: an + ``Exception`` the block raises is logged and noted on the error the run carries + (its database error when it holds one, otherwise the first error inside it, which + an orchestrator raises out of a task group) and not + re-raised, so the next callback still runs and the caller's ``raise`` propagates + the original error. + + Args: + run_error: The error the run failed with, which the caller re-raises. + during: What the block runs, for the log and the note. + + Yields: + Nothing; the block runs inside the context. + """ + try: + yield + except Exception as failure: + logger.warning( + "%s raised while a failed run was reporting its end; the run's own " + + "error is raised instead: %s", + during, + failure, + exc_info=failure, + ) + carrier = database_error_of(run_error) or _first_leaf(run_error) + carrier.add_note( + f"{during} also raised while this error propagated: " + + f"{type(failure).__name__}: {failure}" + ) + + +def _first_leaf(error: BaseException) -> BaseException: + """Return ``error``, or the first error inside it when it is an exception group.""" + while isinstance(error, BaseExceptionGroup) and error.exceptions: + error = error.exceptions[0] + return error + + def database_write_path( database: ArrowDatabaseProtocol, record_path: tuple[str, ...] = () ) -> tuple[str, ...]: diff --git a/tests/test_channels/test_channels.py b/tests/test_channels/test_channels.py index 3542909c9..5a2c2c625 100644 --- a/tests/test_channels/test_channels.py +++ b/tests/test_channels/test_channels.py @@ -600,3 +600,102 @@ def test_resolve_concurrency_both_default(self, monkeypatch: pytest.MonkeyPatch) node = PodConfig() pipeline = PipelineConfig() assert resolve_concurrency(node, pipeline) == 4 + + +# --------------------------------------------------------------------------- +# take_ready: the items already waiting, without waiting (ITL-1789) +# --------------------------------------------------------------------------- + + +class TestTakeReady: + """``take_ready`` takes what is buffered, in order, up to a limit, never waits, and + leaves the end of the stream for ``receive`` to tell.""" + + @pytest.mark.asyncio + async def test_takes_waiting_items_in_order_up_to_the_limit(self) -> None: + ch = Channel[int](buffer_size=8) + for item in (1, 2, 3, 4, 5): + await ch.writer.send(item) + + assert ch.reader.take_ready(3) == [1, 2, 3] + assert await ch.reader.receive() == 4 + assert ch.reader.take_ready(10) == [5] + assert ch.reader.take_ready(10) == [] + + @pytest.mark.asyncio + async def test_leaves_the_end_for_receive(self) -> None: + ch = Channel[int](buffer_size=8) + for item in (1, 2): + await ch.writer.send(item) + await ch.writer.close() + + assert ch.reader.take_ready(10) == [1, 2] + assert ch.reader.take_ready(10) == [] + with pytest.raises(ChannelClosed): + await ch.reader.receive() + assert ch.reader.take_ready(10) == [] + + @pytest.mark.asyncio + async def test_a_close_found_with_a_full_queue_ends_after_the_items(self) -> None: + ch = Channel[int](buffer_size=2) + await ch.writer.send(1) + await ch.writer.send(2) + await ch.writer.close() # the queue is full: the close is recorded + + assert ch.reader.take_ready(10) == [1, 2] + with pytest.raises(ChannelClosed): + await ch.reader.receive() + + @pytest.mark.asyncio + async def test_makes_room_for_a_waiting_sender(self) -> None: + ch = Channel[int](buffer_size=2) + await ch.writer.send(1) + await ch.writer.send(2) + sender = asyncio.ensure_future(ch.writer.send(3)) + await asyncio.sleep(0) + assert not sender.done() + + assert ch.reader.take_ready(10) == [1, 2] + await asyncio.wait_for(sender, 1) + assert await ch.reader.receive() == 3 + + @pytest.mark.asyncio + async def test_broadcast_readers_take_their_own_items(self) -> None: + bc = BroadcastChannel[int](buffer_size=8) + first, second = bc.add_reader(), bc.add_reader() + for item in (1, 2, 3): + await bc.writer.send(item) + await bc.writer.close() + + assert first.take_ready(2) == [1, 2] + assert second.take_ready(10) == [1, 2, 3] + assert await first.receive() == 3 + for reader in (first, second): + with pytest.raises(ChannelClosed): + await reader.receive() + assert reader.take_ready(10) == [] + + +@pytest.mark.asyncio +async def test_an_operator_input_tap_takes_ready_rows_and_keeps_the_first() -> None: + """The operator job's input tap passes ``take_ready`` through and keeps the rows it + takes as ``receive`` does (ITL-1789).""" + from orcapod.core.datagrams import Data, Tag + from orcapod.core.nodes.operator_node import _InputTap # pyright: ignore[reportPrivateUsage] + from orcapod.sources import DictSource + + stream = DictSource( + [{"id": 1, "x": 10}, {"id": 2, "x": 20}], + tag_columns=["id"], + tag_only_columns=True, + source_id="rows", + ) + rows = list(stream.iter_data()) + ch = Channel[tuple[Tag, Data]](buffer_size=4) + for row in rows: + await ch.writer.send(row) # pyright: ignore[reportArgumentType] + tap = _InputTap(ch.reader, stream) # pyright: ignore[reportArgumentType] + + assert tap.take_ready(10) == rows + assert tap.rows == rows[:1] + assert tap.take_ready(10) == [] diff --git a/tests/test_channels/test_native_async_operators.py b/tests/test_channels/test_native_async_operators.py index 9f5da3a1e..37ceb89ea 100644 --- a/tests/test_channels/test_native_async_operators.py +++ b/tests/test_channels/test_native_async_operators.py @@ -1099,6 +1099,10 @@ async def collect(self) -> list[_Row]: """Read every remaining row from the wrapped channel.""" return await self._reader.collect() + def take_ready(self, max_items: int) -> list[_Row]: + """Take the rows already waiting in the wrapped channel.""" + return self._reader.take_ready(max_items) + @pytest.mark.parametrize("validated", [False, True], ids=["unknown", "validated"]) @pytest.mark.parametrize( @@ -1190,6 +1194,9 @@ async def __anext__(self) -> _Row: async def collect(self) -> list[_Row]: return [await self.receive()] + def take_ready(self, max_items: int) -> list[_Row]: + return [] + class _SignallingReader: """Reads a channel and sets ``waiting`` when the given receive call starts.""" @@ -1218,6 +1225,9 @@ async def __anext__(self) -> _Row: async def collect(self) -> list[_Row]: return [row async for row in self] + def take_ready(self, max_items: int) -> list[_Row]: + return self._reader.take_ready(max_items) + # Guards a wait that must end at once; a timeout means the operator hung. _HANG_GUARD_SECONDS = 10 diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 7ae3ba0c2..b5fd79d4b 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -2520,6 +2520,21 @@ async def write() -> None: run(write) +@pytest.mark.asyncio +async def test_take_ready_takes_nothing_and_leaves_the_channel_unread() -> None: + """An input channel pulls each batch from its feed on ``receive``: nothing is ever + waiting, and ``take_ready`` changes nothing (ITL-1789).""" + stream = source() + channel = stream.open_channel() + + assert channel.take_ready(10) == [] + assert channel.unread + assert sum(batch.num_rows for batch in await channel.collect()) == ( + stream.as_table().num_rows + ) + assert channel.take_ready(10) == [] + + # --- The token-shape rule on every batch sent (ITL-1845, in part ITL-1526) ----------- diff --git a/tests/test_contexts/test_data_context_v1.py b/tests/test_contexts/test_data_context_v1.py index 122f26aa9..70ab9a0bc 100644 --- a/tests/test_contexts/test_data_context_v1.py +++ b/tests/test_contexts/test_data_context_v1.py @@ -325,7 +325,8 @@ def test_logical_type_registration_is_unchanged_by_the_move() -> None: """The default context registers exactly what the single file registered before. The Polars value types were added afterwards (ITL-578), and ``OrcapodTable`` (a table - Orcapod built, hashed under the float rule; ITL-1179). + Orcapod built, hashed under the float rule; ITL-1179), and references to SpiralDB + entries (ITL-1789). """ context = contexts.create_registry().get_context() handlers = context.semantic_hasher.type_handler_registry @@ -344,6 +345,7 @@ def test_logical_type_registration_is_unchanged_by_the_move() -> None: "orcapod.hashing.orcapod_table.OrcapodTable=OrcapodTableHandler", "orcapod.logical_types.directory_type.Directory=DirectoryHandler", "orcapod.logical_types.file_type.File=FileHandler", + "orcapod.logical_types.spiraldb_entry_type.SpiralDBEntry=SpiralDBEntryHandler", "orcapod.types.Schema=SchemaHandler", "pandas.core.frame.DataFrame=PandasDataFrameHandler", "pandas.core.series.Series=PandasSeriesHandler", @@ -372,6 +374,7 @@ def test_logical_type_registration_is_unchanged_by_the_move() -> None: "orcapod.path", "orcapod.polars.dataframe", "orcapod.polars.series", + "orcapod.spiraldb.entry", "orcapod.upath", "orcapod.uuid", ] diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py new file mode 100644 index 000000000..239a7e77c --- /dev/null +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -0,0 +1,4001 @@ +"""SpiralDB columns stored in a Vortex encoding are presented as entry references (ITL-1789). + +A column stored as ``vortex.turboquant`` (a lossy quantized vector), at the top level or +as a field of a struct column, used to make ``SpiralDBTableSource`` refuse the whole +table. It is now presented as a column of ``SpiralDBEntry`` references: the scan does +not read it, every other column reads exactly as from a table without it, and +``SpiralDBEntry.read`` returns the stored value through spiral-sdk. + +The encoded field reproduces the layout SpiralDB reports for ``vortex.turboquant`` +(``ARROW:extension:name`` and base64 parameters over a struct of blocks of a norm and +codes) with synthetic values, through the disk-backed fake +(``tests/test_databases/fake_spiral_sdk.py``, rules ``vortex`` and ``key-range``). +""" + +from __future__ import annotations + +import asyncio +import contextlib +import datetime +import os +import warnings +from pathlib import Path +from collections.abc import Iterator +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import function_pod +from orcapod.core.sources import SpiralDBTableSource +from orcapod.errors import ( + InputValidationError, + ProvisionalHashWarning, + SpiralDBEntryMissingError, +) +from orcapod.invocation import InvocationContext +from orcapod.logical_types.provisional import reset_provisional_warnings +from orcapod.logical_types.spiraldb_entry_type import ( + LogicalSpiralDBEntry, + SpiralDBEntry, + entry_content_hash, +) +from orcapod.system_constants import constants +from orcapod.types import ContentHash +from tests.test_databases import fake_spiral_sdk + +_PROJECT = "test-project-123456" +_DIMENSIONS = 4 + +_ENCODING = { + b"ARROW:extension:name": b"vortex.turboquant", + b"ARROW:extension:metadata": b"CAkQBBgIICooAzIBQA==", +} +"""The field metadata SpiralDB reports for an encoded column (synthetic parameters).""" + +_STORAGE = pa.struct( + [ + pa.field( + "block_0", + pa.struct( + [ + pa.field("norms", pa.float32()), + pa.field( + "codes", + pa.list_(pa.field("item", pa.uint8(), False), _DIMENSIONS), + ), + ] + ), + ) + ] +) +"""The storage SpiralDB reports for a TurboQuant column of ``_DIMENSIONS`` dimensions.""" + +_TIMES = [ + datetime.datetime(2026, 1, 1, 12, 0, 1, tzinfo=datetime.timezone.utc), + datetime.datetime(2026, 1, 2, 0, 0, 0, 5, tzinfo=datetime.timezone.utc), + datetime.datetime(2026, 1, 1, 12, 0, 0, 123456, tzinfo=datetime.timezone.utc), +] +"""Key times; with ``_plain_rows``' units the rows are written in key order, which is +the order the table stores them in and the order of ``_encoded_values``.""" + + +def _encoded_values(seed: int) -> pa.StructArray: + """Return three synthetic encoded values: a norm and codes per row.""" + codes = pa.array( + [[(seed + row + i) % 256 for i in range(_DIMENSIONS)] for row in range(3)], + pa.list_(pa.field("item", pa.uint8(), False), _DIMENSIONS), + ) + norms = pa.array([1.5 + seed, 2.25 + seed, 0.125 + seed], pa.float32()) + block = pa.StructArray.from_arrays([norms, codes], fields=list(_STORAGE[0].type)) + return pa.StructArray.from_arrays([block], fields=list(_STORAGE)) + + +def _plain_rows() -> pa.Table: + """Return the rows every table here holds: two key columns and two data columns.""" + return pa.table( + { + "unit": pa.array(["u1", "u1", "u2"], pa.large_string()), + "time": pa.array(_TIMES, pa.timestamp("us", tz="UTC")), + "rate": pa.array([0.5, 1.5, 2.5], pa.float64()), + "label": pa.array(["a", "b", "c"], pa.large_string()), + } + ) + + +def _key_schema() -> pa.Schema: + """Return the composite primary key: a string and a zoned timestamp, in that order.""" + rows = _plain_rows() + return pa.schema([rows.schema.field("unit"), rows.schema.field("time")]) + + +def _make_tables() -> dict[str, Any]: + """Create ``encoded`` (with a top-level and a struct-field encoded column) and + ``plain`` (the same rows without them); return the encoded columns' stored values.""" + project = fake_spiral_sdk.ExternalProject(_PROJECT) + plain = project.create_table("default.plain", key_schema=_key_schema()) + plain.write(_plain_rows()) + encoded = project.create_table("default.encoded", key_schema=_key_schema()) + encoded.write(_plain_rows()) + top = _encoded_values(0) + encoded.write_encoded( + "vector", top, pa.field("vector", _STORAGE, metadata=_ENCODING) + ) + inner = _encoded_values(7) + holder = pa.StructArray.from_arrays( + [inner, pa.array([10, 20, 30], pa.int64())], + fields=[ + pa.field("model_a", _STORAGE, metadata=_ENCODING), + pa.field("count", pa.int64()), + ], + ) + encoded.write_encoded("embeddings", holder, pa.field("embeddings", holder.type)) + return {"vector": top, "embeddings": holder} + + +@pytest.fixture(autouse=True) +def fake_spiral(tmp_path: Path): + """Route every source in this module to a fresh fake SpiralDB.""" + with fake_spiral_sdk.install(tmp_path / "spiral"): + yield + + +@pytest.fixture +def stored() -> dict[str, Any]: + """The two tables, and the encoded columns' stored values.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return _make_tables() + + +def _source(name: str = "encoded", **kwargs: Any) -> SpiralDBTableSource: + """Return a source over table ``name``, warnings silenced.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return SpiralDBTableSource(_PROJECT, name, tag_only_columns=True, **kwargs) + + +@pytest.mark.parametrize("column", ["vector", "embeddings"]) +@pytest.mark.parametrize("change", ["missing", "name", "parameters"]) +def test_a_schema_record_cannot_hide_or_change_an_encoding( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch, column: str, change: str +) -> None: + """Reject a conflicting schema record even when the storage types agree.""" + from orcapod.databases.spiraldb_connector import SpiralDBConnector + from orcapod.databases.spiraldb_schema_table import ( + FROM_SERVICE, + SchemaRow, + SchemaTable, + ) + from orcapod.errors import TableSchemaError + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + connector = SpiralDBConnector(_PROJECT) + table = connector.lookup_table("encoded") + reported = table.arrow_schema() + field = reported.field(column) + encoded_field = field if column == "vector" else field.type.field("model_a") + metadata: dict[bytes | str, bytes | str] = {**_ENCODING} + if change == "missing": + metadata.clear() + elif change == "name": + metadata[b"ARROW:extension:name"] = b"vortex.other" + else: + metadata[b"ARROW:extension:metadata"] = b"changed" + changed = encoded_field.with_metadata(metadata) + if column == "embeddings": + changed = field.with_type(pa.struct([changed, field.type.field("count")])) + recorded = reported.set(reported.get_field_index(column), changed) + row = SchemaRow( + table.table_id, + "encoded", + tuple(table.key_columns), + recorded.serialize().to_pybytes(), + FROM_SERVICE, + table.version(), + ) + + def lookup(_self: SchemaTable, table_id: str) -> SchemaRow | None: + return row if table_id == row.table_id else None + + monkeypatch.setattr(SchemaTable, "row", lookup) + with connector: + assert sum(b.num_rows for b in table.scan_batches(columns=["rate"])) == 3 + with pytest.raises( + TableSchemaError, match=rf"Vortex encoding metadata.*{column}" + ): + connector.lookup_table("encoded").arrow_schema() + with pytest.raises(TableSchemaError, match=rf"Vortex encoding metadata.*{column}"): + _source() + fragment = Path(__file__).parents[3] / "changelog.d" / "ITL-1789.md" + assert "when it prepares a snapshot" in " ".join(fragment.read_text().split()) + + +def test_dictionary_wrapped_vortex_columns_report_an_unsupported_layout( + stored: dict[str, Any], +) -> None: + """Name the unsupported physical layout before presenting a source schema.""" + from orcapod.errors import TableSchemaError + + values = pa.StructArray.from_arrays( + [stored["vector"]], fields=[pa.field("encoded", _STORAGE, metadata=_ENCODING)] + ) + wrapped = pa.DictionaryArray.from_arrays( + pa.array([0, 1, 2], pa.int16()), values, ordered=True + ) + table = fake_spiral_sdk.ExternalProject(_PROJECT).table("default.encoded") + table.write_encoded("wrapped", wrapped, pa.field("wrapped", wrapped.type)) + + with pytest.raises(TableSchemaError, match=r"'wrapped'.*dictionary-wrapped"): + _source() + + +def _table(source: SpiralDBTableSource, **kwargs: Any) -> pa.Table: + """Return ``source.as_table`` with warnings silenced.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return source.as_table(**kwargs) + + +def _values(table: pa.Table, column: str) -> list[Any]: + """Return a column's values as Python values.""" + return list(table.column(column).to_pylist()) + + +def _entries(table: pa.Table, column: str) -> list[SpiralDBEntry]: + """Return a reference column's values as ``SpiralDBEntry`` objects.""" + return [LogicalSpiralDBEntry().storage_to_python(v) for v in _values(table, column)] + + +def _record_ids(table: pa.Table) -> list[Any]: + """Return the record-id system tag's values.""" + (name,) = [ + n + for n in table.column_names + if n.startswith(f"{constants.SYSTEM_TAG_PREFIX}record_id") + ] + return _values(table, name) + + +def test_encoded_columns_are_presented_as_references(stored: dict[str, Any]): + """A top-level encoded column and a struct column holding one are each one + ``SpiralDBEntry`` column, with their own names; the other columns keep their types.""" + source = _source() + plain = _source("plain") + + tags, data = source.output_schema() + plain_tags, plain_data = plain.output_schema() + + assert tags == plain_tags + assert data["vector"] is SpiralDBEntry + assert data["embeddings"] is SpiralDBEntry + assert {k: v for k, v in data.items() if v is not SpiralDBEntry} == dict(plain_data) + + +def test_other_columns_read_as_from_a_table_without_the_encoded_ones( + stored: dict[str, Any], +): + """Every other column, and every record id, equals the plain table's, in the same + order of rows.""" + rows = _table(_source(), all_info=True) + plain = _table(_source("plain"), all_info=True) + + for name in ("unit", "time", "rate", "label"): + assert rows.column(name).equals(plain.column(name)), name + assert rows.schema.field(name) == plain.schema.field(name), name + assert _record_ids(rows) == _record_ids(plain) + + +def test_each_reference_names_its_entry(stored: dict[str, Any]): + """A reference holds the table id, the pinned version, the row's primary key as + canonical JSON in key order, and the column.""" + source = _source() + rows = _table(source) + + # The rows come in key order: the references' keys follow it. + keys = [ + '{"unit":"u1","time":"2026-01-01T12:00:01.000000Z"}', + '{"unit":"u1","time":"2026-01-02T00:00:00.000005Z"}', + '{"unit":"u2","time":"2026-01-01T12:00:00.123456Z"}', + ] + for column in ("vector", "embeddings"): + references = _entries(rows, column) + assert [r.key for r in references] == keys + assert {r.table_id for r in references} == {source.table_id} + assert {r.version for r in references} == {source.pinned_version} + assert {r.column for r in references} == {column} + + +@pytest.mark.parametrize("column", ["vector", "embeddings"]) +def test_read_returns_the_stored_entry_exactly(stored: dict[str, Any], column: str): + """``read`` returns one row of the column as stored, its encoding's field + metadata included; a struct column is returned whole.""" + source = _source() + rows = _table(source) + plain_keys = list( + zip(*(_plain_rows().column(c).to_pylist() for c in ("unit", "time"))) + ) + + for entry, unit, time in zip( + _entries(rows, column), _values(rows, "unit"), _values(rows, "time") + ): + read = entry.read() + assert read.num_rows == 1 + assert read.column_names == [column] + expected = stored[column][plain_keys.index((unit, time))] + assert read.column(column)[0] == expected + if column == "vector": + assert read.schema.field(column).metadata == _ENCODING + else: + assert read.schema.field(column).type.field("model_a").metadata == _ENCODING + + +def test_the_scan_never_reads_the_encoded_columns(stored: dict[str, Any]): + """A read scans the other columns only; a table without encoded columns is + scanned whole, as before.""" + fake_spiral_sdk.scan_log.clear() + _table(_source()) + _table(_source("plain")) + + encoded_scan, plain_scan = fake_spiral_sdk.scan_log + assert encoded_scan.columns is not None + assert "vector" not in encoded_scan.columns + assert "embeddings" not in encoded_scan.columns + assert set(encoded_scan.columns) == {"unit", "time", "rate", "label"} + assert plain_scan.columns is None + + +def test_sync_and_async_reads_give_the_same_references(stored: dict[str, Any]): + """``iter_data`` and ``async_iter_data`` give the same references, as objects.""" + source = _source() + + async def collect() -> list[Any]: + return [pair async for pair in source.async_iter_data()] + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + sync = list(source.iter_data()) + asynchronous = asyncio.run(collect()) + + for column in ("vector", "embeddings"): + sync_refs = [data[column] for _, data in sync] + async_refs = [data[column] for _, data in asynchronous] + assert sync_refs == async_refs + assert all(isinstance(r, SpiralDBEntry) for r in sync_refs) + + +def test_a_function_pod_receives_the_reference_and_reads_it(stored: dict[str, Any]): + """A function pod over the source gets ``SpiralDBEntry`` objects, can read them, + and can return one, stored as a reference.""" + + @function_pod(output_keys=("norm", "same")) + def first_norm(vector: SpiralDBEntry) -> tuple[float, SpiralDBEntry]: + assert isinstance(vector, SpiralDBEntry) + value = vector.read().column("vector")[0].as_py() + return value["block_0"]["norms"], vector + + source = _source() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = first_norm.pod(source.select_data_columns(["vector"])).as_table() + + assert sorted(_values(result, "norm")) == [0.125, 1.5, 2.25] + assert result.schema.field("same").type.extension_name == "orcapod.spiraldb.entry" + + +def test_a_new_version_moves_every_reference(stored: dict[str, Any]): + """When ``check_for_new_data`` pins a newer version, every reference names it, + also for rows whose entry did not change (the price of an exact reference).""" + source = _source() + before = _entries(_table(source), "vector") + project = fake_spiral_sdk.ExternalProject(_PROJECT) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + project.table("default.encoded").write( + pa.table( + { + "unit": pa.array(["u9"], pa.large_string()), + "time": pa.array([_TIMES[2]], pa.timestamp("us", tz="UTC")), + "rate": pa.array([9.0], pa.float64()), + "label": pa.array(["z"], pa.large_string()), + } + ) + ) + assert source.check_for_new_data() + + after = _entries(_table(source), "vector") + + assert {e.version for e in after} == {source.pinned_version} + assert {e.version for e in before}.isdisjoint({e.version for e in after}) + assert {e.key for e in before} <= {e.key for e in after} + + +def test_an_encoded_column_cannot_be_a_tag(stored: dict[str, Any]): + """Naming an encoded column as a tag column is refused, naming the column.""" + with pytest.raises(ValueError, match=r"\['vector'\].*Vortex encoding"): + _source(tag_columns=["unit", "vector"]) + + +def test_a_condition_on_a_reference_column_is_refused(stored: dict[str, Any]): + """CodeRabbit on PR 680 (test line 340): ``where`` on a reference column is refused + with ``ValueError`` naming it, when the source is built and by ``where()``, before + the value's type is checked.""" + with pytest.raises(ValueError, match=r"\['vector'\].*entry references"): + _source(where={"vector": "x"}) + source = _source() + for value in ("x", 1.5): + with pytest.raises(ValueError, match=r"\['embeddings', 'vector'\]"): + source.where(vector=value, embeddings=value, rate=1.5) + + +def test_another_stored_extension_is_still_refused(): + """A column carrying a stored extension that is not a Vortex encoding is refused as + before (``InputValidationError``).""" + project = fake_spiral_sdk.ExternalProject(_PROJECT) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + table = project.create_table("default.other", key_schema=_key_schema()) + table.write(_plain_rows()) + table.write_encoded( + "blob", + pa.array([b"x", b"y", b"z"], pa.binary()), + pa.field( + "blob", + pa.binary(), + metadata={b"ARROW:extension:name": b"some.other.type"}, + ), + ) + with pytest.raises(InputValidationError, match="some.other.type"): + _source("other") + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.UnrecordedTableSchemaWarning") +def test_references_are_provisional(stored: dict[str, Any]): + """Reading a source with reference columns warns that their hash is provisional.""" + reset_provisional_warnings() + with pytest.warns(ProvisionalHashWarning, match="orcapod.spiraldb.entry"): + source = SpiralDBTableSource(_PROJECT, "encoded", tag_only_columns=True) + source.output_schema() + + +def test_read_of_a_missing_key_raises_lookup_error(stored: dict[str, Any]): + """A reference whose key the version does not hold reads no row: + ``SpiralDBEntryMissingError``, a ``LookupError``.""" + source = _source() + entry = _entries(_table(source), "vector")[0] + missing = SpiralDBEntry( + entry.table_id, + entry.version, + '{"unit":"u1","time":"2026-01-01T12:00:00.123456Z"}', + "vector", + entry.service, + ) + + with pytest.raises(SpiralDBEntryMissingError, match="holds no row") as raised: + missing.read() + assert isinstance(raised.value, LookupError) + assert raised.value.entry == missing + + +@pytest.mark.parametrize( + "key", + [ + '{"time":"2026-01-01T12:00:00.123456Z","unit":"u1"}', + '{"unit":"u1"}', + '{"unit":"u1","time":"2026-01-01T12:00:00.1234560Z"}', + '{"unit":1,"time":"2026-01-01T12:00:00.123456Z"}', + ], +) +def test_read_refuses_a_key_that_does_not_fit_the_primary_key( + stored: dict[str, Any], key: str +): + """A key in another order, missing a column, or not in the canonical form of its + column's type is refused before any scan.""" + source = _source() + entry = _entries(_table(source), "vector")[0] + fake_spiral_sdk.scan_log.clear() + + with pytest.raises(ValueError, match="SpiralDB entry"): + SpiralDBEntry( + entry.table_id, entry.version, key, "vector", entry.service + ).read() + assert fake_spiral_sdk.scan_log == [] + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_a_job_stores_references_and_computes_each_once( + stored: dict[str, Any], tmp_path: Path, orchestrator: str +): + """In a job (sync and async), a function pod over the references computes each row + once, stores the references it returns, and a second run computes nothing.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator + + calls: list[SpiralDBEntry] = [] + + @function_pod(output_keys=("norm", "same")) + def first_norm(vector: SpiralDBEntry) -> tuple[float, SpiralDBEntry]: + calls.append(vector) + return vector.read().column("vector")[0].as_py()["block_0"]["norms"], vector + + def run() -> PipelineJob: + job = PipelineJob(name="refs", database=DeltaTableDatabase(tmp_path / "db")) + with job: + first_norm.pod(_source().select_data_columns(["vector"]), label="norm") + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + if orchestrator == "async": + job.run(orchestrator=AsyncPipelineOrchestrator()) + else: + job.run() + return job + + job = run() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = job.nodes["norm"].as_table() + assert len(calls) == 3 + assert sorted(result.column("norm").to_pylist()) == [0.125, 1.5, 2.25] + same = _entries(result, "same") + assert sorted(same, key=lambda e: e.key) == sorted(calls, key=lambda e: e.key) + + calls.clear() + second = run() + assert calls == [] + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + again = second.nodes["norm"].as_table() + assert sorted(again.column("norm").to_pylist()) == [0.125, 1.5, 2.25] + + # CodeRabbit on 1e627fc (test line 476): each replayed norm stays with its own + # reference, compared as pairs sorted by the reference's key. + def pairs(table: Any) -> list[tuple[Any, Any]]: + return sorted( + zip(_entries(table, "same"), table.column("norm").to_pylist()), + key=lambda pair: pair[0].key, + ) + + assert pairs(again) == pairs(result) + + +def test_another_stored_type_beside_an_encoding_in_a_struct_is_refused(): + """CodeRabbit on PR 680 (spiraldb_entries.py:93): a struct column holding a Vortex + field and, in another field, a stored type that is not a Vortex encoding is refused + (``InputValidationError``), as that type is in any other column; it is not hidden + by the column becoming a reference.""" + project = fake_spiral_sdk.ExternalProject(_PROJECT) + inner = _encoded_values(3) + holder = pa.StructArray.from_arrays( + [inner, pa.array([b"x", b"y", b"z"], pa.binary())], + fields=[ + pa.field("model_a", _STORAGE, metadata=_ENCODING), + pa.field( + "blob", + pa.binary(), + metadata={b"ARROW:extension:name": b"some.other.type"}, + ), + ], + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + table = project.create_table("default.mixed", key_schema=_key_schema()) + table.write(_plain_rows()) + table.write_encoded("embeddings", holder, pa.field("embeddings", holder.type)) + + with pytest.raises(InputValidationError, match="some.other.type"): + _source("mixed") + + +def test_a_reference_over_a_date_key_reads_its_entry(): + """CodeRabbit on PR 680 (fake_spiral_sdk.py:783): a reference whose primary key is + a ``date32`` and a string reads its own entry (the key text's date is turned back + into the column's date).""" + project = fake_spiral_sdk.ExternalProject(_PROJECT) + rows = pa.table( + { + "day": pa.array( + [datetime.date(2026, 1, d) for d in (1, 2, 3)], pa.date32() + ), + "unit": pa.array(["u1", "u1", "u2"], pa.large_string()), + "rate": pa.array([0.5, 1.5, 2.5], pa.float64()), + "label": pa.array(["a", "b", "c"], pa.large_string()), + } + ) + values = _encoded_values(5) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + table = project.create_table( + "default.dated", + key_schema=pa.schema([rows.schema.field("day"), rows.schema.field("unit")]), + ) + table.write(rows) + table.write_encoded( + "vector", values, pa.field("vector", _STORAGE, metadata=_ENCODING) + ) + + entries = _entries(_table(_source("dated")), "vector") + + assert [e.key for e in entries] == [ + '{"day":"2026-01-01","unit":"u1"}', + '{"day":"2026-01-02","unit":"u1"}', + '{"day":"2026-01-03","unit":"u2"}', + ] + for index, entry in enumerate(entries): + assert entry.read().column("vector")[0] == values[index] + + +@pytest.mark.parametrize("limit", [None, 1]) +def test_a_projected_scan_filters_on_a_column_it_does_not_return(limit: int | None): + """CodeRabbit on PR 680 (spiraldb_connector.py:648): ``scan_batches(columns=...)`` + with an equality applied here (a ``float16`` column, which has no SDK literal) on a + column outside ``columns`` reads that column, filters, and returns only + ``columns``, as without a projection.""" + from orcapod.databases import SpiralDBConnector + from orcapod.types import Condition + + rows = pa.table( + { + "k": list(range(6)), + "h": pa.array([1.0, 2.0] * 3, pa.float64()).cast(pa.float16()), + "s": ["x", "y", "x", "y", "x", "y"], + } + ) + project = fake_spiral_sdk.ExternalProject(_PROJECT) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + project.create_table("default.half", key_schema=[("k", pa.int64())]).write(rows) + table = SpiralDBConnector(_PROJECT).lookup_table("half") + batches = list( + table.scan_batches( + where=Condition.of(h=2.0), limit=limit, columns=["k", "s"] + ) + ) + + found = pa.Table.from_batches(batches) + assert found.column_names == ["k", "s"] + assert found.column("k").to_pylist() == [1, 3, 5][:limit] + + +# -------------------------------------------------------------------------------------- +# The value hash is the entry's content, fetched together (ITL-1789, developer's D54). +# -------------------------------------------------------------------------------------- + + +def _entry_scans() -> list[fake_spiral_sdk.ScanRecord]: + """The scans that read entries: those with key ranges.""" + return [record for record in fake_spiral_sdk.scan_log if record.key_ranges] + + +def _write_row(unit: str, time: datetime.datetime) -> None: + """Upsert one more row into ``encoded``, giving the table a new version.""" + project = fake_spiral_sdk.ExternalProject(_PROJECT) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + project.table("default.encoded").write( + pa.table( + { + "unit": pa.array([unit], pa.large_string()), + "time": pa.array([time], pa.timestamp("us", tz="UTC")), + "rate": pa.array([9.0], pa.float64()), + "label": pa.array(["z"], pa.large_string()), + } + ) + ) + + +def _rewrite_vector(keep: list[bool], values: pa.Array[Any]) -> None: + """Write a new version of ``encoded``: the rows ``keep`` names, with ``vector`` + replaced by ``values``.""" + fake_spiral_sdk.ExternalProject(_PROJECT).table("default.encoded").rewrite_rows( + pa.array(keep), "vector", values + ) + + +def _rewrite_column(keep: list[bool], column: str, values: pa.Array[Any]) -> None: + """Write a new version of ``encoded``: the rows ``keep`` names, with ``column`` + replaced by ``values``.""" + fake_spiral_sdk.ExternalProject(_PROJECT).table("default.encoded").rewrite_rows( + pa.array(keep), column, values + ) + + +def _run(job: Any, orchestrator: str, error_policy: str = "continue") -> Any: + from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator + from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + if orchestrator == "async": + return job.run( + orchestrator=AsyncPipelineOrchestrator(error_policy=error_policy) # pyright: ignore[reportArgumentType] + ) + return job.run( + orchestrator=SyncPipelineOrchestrator(error_policy=error_policy) # pyright: ignore[reportArgumentType] + ) + + +def test_equal_content_at_two_versions_hashes_alike(stored: dict[str, Any]): + """An entry unchanged by a new version keeps its hash; an entry rewritten under + its key gets another; the reference's fields are in no hash.""" + source = _source() + before = _entries(_table(source), "vector") + _write_row("u9", _TIMES[2]) + assert source.check_for_new_data() + after = _entries(_table(source), "vector") + by_key = {e.key: e for e in after} + + for entry in before: + assert by_key[entry.key] != entry + assert by_key[entry.key].content_hash() == entry.content_hash() + assert len({e.content_hash() for e in after}) == len(after) + + _rewrite_vector([True] * 4, _encoded_values(5).take([0, 1, 2, 0])) + assert source.check_for_new_data() + rewritten = {e.key: e for e in _entries(_table(source), "vector")} + for entry in before: + assert rewritten[entry.key].content_hash() != entry.content_hash() + assert all( + h.method == "spiraldb_entry_v1" for h in (e.content_hash() for e in after) + ) + + +def test_reading_and_building_fetch_no_entry(stored: dict[str, Any]): + """Building the source, reading its rows (sync and async, with source info and + system tags), ``head`` and the schema make no entry scan: an entry is fetched only + where a data row is hashed. Asking for the rows' content hashes hashes them: one + scan for every row.""" + fake_spiral_sdk.scan_log.clear() + source = _source() + + async def collect() -> list[Any]: + return [pair async for pair in source.async_iter_data()] + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + _ = source.as_table(columns={"source": True, "system_tags": True}) + _ = list(source.iter_data()) + _ = asyncio.run(collect()) + _ = source.head() + _ = source.output_schema() + _ = source.content_hash() + _ = source.pipeline_hash() + + assert _entry_scans() == [] + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + hashed = source.as_table(columns={"content_hash": True}) + (scan,) = _entry_scans() + assert scan.key_ranges == 3 + assert hashed.num_rows == 3 + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_a_job_fetches_its_entries_with_one_scan_per_version( + stored: dict[str, Any], + tmp_path: Path, + orchestrator: str, + monkeypatch: pytest.MonkeyPatch, +): + """A function node over two reference columns fetches every entry of its rows with + ONE scan (both columns, one key range per row), never one per row; a second run + fetches nothing; after the pin moves, one more scan, and only the new row is + computed (the unchanged entries keep their hashes). The source hands its rows on in + one read batch here (see the next test for several).""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 100) + + calls: list[str] = [] + + @function_pod(output_keys=("norm", "count")) + def both(vector: SpiralDBEntry, embeddings: SpiralDBEntry) -> tuple[float, int]: + calls.append(vector.key) + norm = vector.read().column("vector")[0].as_py()["block_0"]["norms"] + count = embeddings.read().column("embeddings")[0].as_py()["count"] + return norm, count + + source = _source() + job = PipelineJob(name="refs", database=DeltaTableDatabase(tmp_path / "db")) + with job: + both.pod(source.select_data_columns(["vector", "embeddings"]), label="both") + + fake_spiral_sdk.scan_log.clear() + _run(job, orchestrator) + scans = _entry_scans() + assert len(calls) == 3 + assert len(scans) == 1 + assert scans[0].key_ranges == 3 + assert set(scans[0].columns or ()) == {"unit", "time", "vector", "embeddings"} + assert scans[0].version == source.pinned_version + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = job.nodes["both"].as_table() + assert sorted(result.column("count").to_pylist()) == [10, 20, 30] + + calls.clear() + fake_spiral_sdk.scan_log.clear() + _run(job, orchestrator) + assert calls == [] + assert _entry_scans() == [] + + # CodeRabbit on PR 680 (test line 722): the new row gets both encoded values, so + # it computes and stores its result, not only starts. + _write_row("u9", _TIMES[2]) + # A vector of its own (equal content would reuse a stored result, by design). + _rewrite_vector( + [True] * 4, + pa.concat_arrays([_encoded_values(0), _encoded_values(5).slice(0, 1)]), + ) + _rewrite_column([True] * 4, "embeddings", stored["embeddings"].take([0, 1, 2, 1])) + fake_spiral_sdk.scan_log.clear() + summary = _run(job, orchestrator) + scans = _entry_scans() + assert len(scans) == 1 + assert scans[0].key_ranges == 4 + assert calls == ['{"unit":"u9","time":"2026-01-01T12:00:00.123456Z"}'] + assert summary.nodes["both"].failed == 0 + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = job.nodes["both"].as_table() + assert sorted(result.column("count").to_pylist()) == [10, 20, 20, 30] + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_async_batches_follow_the_sources_read_batches( + stored: dict[str, Any], tmp_path: Path, orchestrator: str +): + """The sync node fetches all its rows' entries with one scan. The async node takes + together the rows that have arrived: at most one fetch per read batch its source + hands on (the fake's batches hold two rows: here two batches for three rows), so + never one per row.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + + @function_pod(output_keys=("norm",)) + def norm(vector: SpiralDBEntry) -> float: + return vector.read().column("vector")[0].as_py()["block_0"]["norms"] + + job = PipelineJob(name="batches", database=DeltaTableDatabase(tmp_path / "db")) + with job: + norm.pod(_source().select_data_columns(["vector"]), label="norm") + + assert fake_spiral_sdk.scan_batch_rows == 2 + fake_spiral_sdk.scan_log.clear() + _run(job, orchestrator) + + ranges = [s.key_ranges for s in _entry_scans()] + assert sum(ranges) == 3 + if orchestrator == "sync": + assert ranges == [3] + else: + assert len(ranges) <= 2 + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_rows_of_two_versions_take_one_scan_per_version( + stored: dict[str, Any], + tmp_path: Path, + orchestrator: str, + monkeypatch: pytest.MonkeyPatch, +): + """References of two table versions in one input (a source given them, with a + source id) are fetched with one scan per version: two scans for seven rows.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + from orcapod.sources import DictSource + + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 100) + + first = _entries(_table(_source()), "vector") + _write_row("u9", _TIMES[2]) + _rewrite_vector([True] * 4, _encoded_values(0).take([0, 1, 2, 0])) + second = _entries(_table(_source()), "vector") + assert {e.version for e in first} != {e.version for e in second} + rows: Any = [{"id": i, "vector": e} for i, e in enumerate([*first, *second])] + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + refs = DictSource( + rows, tag_columns=["id"], tag_only_columns=True, source_id="refs" + ) + + @function_pod(output_keys=("norm",)) + def norm(vector: SpiralDBEntry) -> float: + return vector.read().column("vector")[0].as_py()["block_0"]["norms"] + + job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "db")) + with job: + norm.pod(refs, label="norm") + + fake_spiral_sdk.scan_log.clear() + _run(job, orchestrator) + + scans = _entry_scans() + assert sorted(s.version for s in scans) == sorted( + {first[0].version, second[0].version} + ) + assert sorted(s.key_ranges for s in scans) == [3, 4] + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + assert job.nodes["norm"].as_table().num_rows == 7 + + +def _source_with_a_missing_entry() -> Any: + """A source of three references, the second naming a key its version lacks.""" + from orcapod.sources import DictSource + + entries = _entries(_table(_source()), "vector") + missing = SpiralDBEntry( + entries[0].table_id, + entries[0].version, + '{"unit":"u7","time":"2026-01-01T12:00:00.123456Z"}', + "vector", + entries[0].service, + ) + rows: Any = [ + {"id": 0, "vector": entries[0]}, + {"id": 1, "vector": missing}, + {"id": 2, "vector": entries[2]}, + ] + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return DictSource( + rows, tag_columns=["id"], tag_only_columns=True, source_id="refs" + ) + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_a_missing_entry_fails_its_row_only( + stored: dict[str, Any], tmp_path: Path, orchestrator: str +): + """Under ``continue``, a reference whose entry is missing is one failed row; the + other rows are computed, still with one scan.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + + calls: list[str] = [] + + @function_pod(output_keys=("norm",)) + def norm(vector: SpiralDBEntry) -> float: + calls.append(vector.key) + return vector.read().column("vector")[0].as_py()["block_0"]["norms"] + + job = PipelineJob(name="miss", database=DeltaTableDatabase(tmp_path / "db")) + with job: + norm.pod(_source_with_a_missing_entry(), label="norm") + + fake_spiral_sdk.scan_log.clear() + summary = _run(job, orchestrator) + + assert len(calls) == 2 + assert len(_entry_scans()) == 1 + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + assert job.nodes["norm"].as_table().num_rows == 2 + node = summary.nodes["norm"] + assert (node.computed, node.failed) == (2, 1) + assert isinstance(node.first_error, SpiralDBEntryMissingError) + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_a_missing_entry_stops_a_fail_fast_run( + stored: dict[str, Any], tmp_path: Path, orchestrator: str +): + """Under ``fail_fast``, the missing entry raises ``SpiralDBEntryMissingError``.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + + @function_pod(output_keys=("norm",)) + def norm(vector: SpiralDBEntry) -> float: + return vector.read().column("vector")[0].as_py()["block_0"]["norms"] + + job = PipelineJob(name="miss", database=DeltaTableDatabase(tmp_path / "db")) + with job: + norm.pod(_source_with_a_missing_entry(), label="norm") + + with pytest.raises(BaseException) as raised: + _run(job, orchestrator, error_policy="fail_fast") + + def chain(exc: BaseException) -> list[BaseException]: + found = [exc] + for inner in getattr(exc, "exceptions", ()): + found.extend(chain(inner)) + if exc.__cause__ is not None: + found.extend(chain(exc.__cause__)) + return found + + assert any(isinstance(e, SpiralDBEntryMissingError) for e in chain(raised.value)) + + +def test_read_after_hashing_fetches_nothing_more(stored: dict[str, Any]): + """``read`` returns the bytes that were hashed, from the process cache: no scan.""" + entries = _entries(_table(_source()), "vector") + SpiralDBEntry.prefetch(entries) + fake_spiral_sdk.scan_log.clear() + + values = [e.read() for e in entries] + hashes = [e.content_hash() for e in entries] + + assert _entry_scans() == [] + assert [v.column("vector")[0] for v in values] == [ + stored["vector"][i] for i in range(3) + ] + assert len(set(hashes)) == 3 + + +def test_read_never_reads_another_version(stored: dict[str, Any]): + """A reference reads its own version, also after the table changed: a deleted row + is still read at the version that held it, and a key its version never held is + missing although a later version holds it.""" + source = _source() + entries = _entries(_table(source), "vector") + _rewrite_vector([False, True, True], _encoded_values(9).take([1, 2])) + _write_row("u7", _TIMES[0]) + + assert entries[0].read().column("vector")[0] == stored["vector"][0] + later = SpiralDBEntry( + entries[0].table_id, + entries[0].version, + '{"unit":"u7","time":"2026-01-01T12:00:01.000000Z"}', + "vector", + entries[0].service, + ) + with pytest.raises(SpiralDBEntryMissingError): + later.read() + with pytest.raises(SpiralDBEntryMissingError): + later.content_hash() + + +def test_references_record_the_service_and_read_through_it( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """A reference records the address of the service its source read (the source's + ``server.url``), and ``read`` opens a client of that address unless given one.""" + from orcapod.databases import spiraldb_connector + + address = "https://spiral.example.invalid" + entries = _entries(_table(_source(overrides={"server.url": address})), "vector") + assert {e.service for e in entries} == {address} + + asked: list[str] = [] + real = spiraldb_connector.client_for_service + + def recording(service: str) -> Any: + asked.append(service) + return real(service) + + monkeypatch.setattr(spiraldb_connector, "client_for_service", recording) + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + monkeypatch.setattr(spiraldb_entries, "client_for_service", recording) + _ = entries[0].read() + assert asked == [address] + + given = fake_spiral_sdk.fake_module.Client() + opened: list[str] = [] + original = given.keyed_table_by_id + + def counting(table_id: str, **kwargs: Any) -> Any: + opened.append(table_id) + return original(table_id, **kwargs) + + given.keyed_table_by_id = counting # pyright: ignore[reportAttributeAccessIssue] + asked.clear() + _ = entries[1].read(client=given) + assert asked == [] + assert opened == [entries[1].table_id] + + +@pytest.mark.parametrize( + ("selected", "kwargs"), + [ + (["rate"], {}), + (["vector", "rate"], {}), + (["label", "embeddings", "vector"], {}), + # CodeRabbit on PR 680 (spiraldb_table_source.py:591): rows named by a column + # that is not the primary key; a reference still needs the primary key. + (["vector"], {"tag_columns": ["label"], "record_id_columns": "label"}), + ( + ["rate", "embeddings"], + {"tag_columns": ["label"], "record_id_columns": "label"}, + ), + (["rate"], {"tag_columns": ["label"], "record_id_columns": "label"}), + ], +) +def test_a_projected_read_places_the_references_as_the_whole_read( + stored: dict[str, Any], selected: list[str], kwargs: dict[str, Any] +): + """A read of some data columns (ITL-1776, merged into this PR) scans no encoded + column, and each reference it keeps is in its place with the whole read's values. + The primary key is scanned for the references when they are kept, and left out of + the result when the selection did not ask for it.""" + from orcapod import PipelineJob + from orcapod.core.streams.arrow_table_stream import pending_whole_read + from orcapod.databases import InMemoryArrowDatabase + + config = {"source": True, "system_tags": True} + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + with job: + _source(**kwargs).select_data_columns(selected, label="sel") + node = next(n for n in job.nodes.values() if n.node_type == "source") + whole = node.execute().as_table(columns=config) + fake_spiral_sdk.scan_log.clear() + read = pending_whole_read(node.execute(read_columns=selected)) + assert read is not None + narrowed = read.projected_table(selected, columns=config) + + assert narrowed is not None + tags = set(kwargs.get("tag_columns", ["unit", "time"])) + unread = [ + c + for c in ("unit", "time", "rate", "label", "vector", "embeddings") + if c not in selected and c not in tags + ] + expected = whole.drop_columns( + unread + [f"{constants.SOURCE_PREFIX}{c}" for c in unread] + ) + assert narrowed.schema.equals(expected.schema, check_metadata=True) + assert narrowed.equals(expected) + for record in fake_spiral_sdk.scan_log: + assert record.columns is not None + assert not {"vector", "embeddings"} & set(record.columns) + + +# -------------------------------------------------------------------------------------- +# Review of 96c8ae4 (CodeRabbit on PR 680): one test per finding. +# -------------------------------------------------------------------------------------- + + +def _store_folder(table_id: str) -> Path: + """The fake store's folder of one table (its versions are ``v.arrow``).""" + return Path(os.environ[fake_spiral_sdk._ROOT_ENV]) / table_id # pyright: ignore[reportPrivateUsage] + + +def _at_version(entry: SpiralDBEntry, version: int) -> SpiralDBEntry: + return SpiralDBEntry( + entry.table_id, version, entry.key, entry.column, entry.service + ) + + +def test_a_version_the_table_no_longer_holds_is_missing(stored: dict[str, Any]): + """CodeRabbit (spiraldb_connector.py:552): SpiralDB's ``asof`` is a cutoff. A + reference to a version that is gone (or never was) is missing, never read from the + snapshot before it, when read and when hashed.""" + entries = _entries(_table(_source()), "vector") + pinned = entries[0].version + _rewrite_vector([True] * 3, _encoded_values(3)) # pinned + 1 + _rewrite_vector([True] * 3, _encoded_values(4)) # pinned + 2 + (_store_folder(entries[0].table_id) / f"v{pinned + 1}.arrow").unlink() + + for gone in (_at_version(entries[0], pinned + 1), _at_version(entries[1], 999)): + with pytest.raises(SpiralDBEntryMissingError, match="has no version"): + gone.read() + with pytest.raises(SpiralDBEntryMissingError, match="has no version"): + gone.content_hash() + newest = _at_version(entries[0], pinned + 2) + assert newest.read().column("vector")[0] == _encoded_values(4)[0] + + +def test_a_dropped_table_makes_its_group_missing_and_others_fetch( + stored: dict[str, Any], +): + """CodeRabbit (spiraldb_entries.py:414): when one table of a prefetch is gone, its + entries are missing and the other table's entries are still fetched, in the same + prefetch; nothing more is scanned after.""" + kept = _entries(_table(_source()), "vector") + project = fake_spiral_sdk.ExternalProject(_PROJECT) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + doomed = project.create_table("default.doomed", key_schema=_key_schema()) + doomed.write(_plain_rows()) + doomed.write_encoded( + "vector", + _encoded_values(2), + pa.field("vector", _STORAGE, metadata=_ENCODING), + ) + gone = _entries(_table(_source("doomed")), "vector") + project.drop_table("default.doomed") + fake_spiral_sdk.scan_log.clear() + + SpiralDBEntry.prefetch([*gone, *kept]) + assert len(_entry_scans()) == 1 + fake_spiral_sdk.scan_log.clear() + assert len({e.content_hash() for e in kept}) == 3 + for entry in gone: + with pytest.raises(SpiralDBEntryMissingError, match="cannot be opened"): + entry.content_hash() + assert _entry_scans() == [] + + +def test_a_cache_cleared_during_a_fetch_does_not_make_an_entry_missing( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit (spiraldb_entries.py:494): the hash comes from what the fetch found, + not from reading the cache again, so a clear in between changes nothing.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entry = _entries(_table(_source()), "vector")[0] + real = spiraldb_entries._fetch # pyright: ignore[reportPrivateUsage] + + def fetch_then_clear(*args: Any, **kwargs: Any) -> Any: + found = real(*args, **kwargs) + spiraldb_entries.clear_entry_cache() + return found + + monkeypatch.setattr(spiraldb_entries, "_fetch", fetch_then_clear) + spiraldb_entries.clear_entry_cache() + assert entry.content_hash().method == "spiraldb_entry_v1" + + +def test_a_read_through_a_given_client_neither_uses_nor_fills_the_cache( + stored: dict[str, Any], +): + """CodeRabbit (spiraldb_entries.py:515): a read with ``client`` always asks + SpiralDB through it, also for an entry held; what it read is not kept for reads + without a client.""" + entries = _entries(_table(_source()), "vector") + given = fake_spiral_sdk.fake_module.Client() + SpiralDBEntry.prefetch(entries[:1]) + fake_spiral_sdk.scan_log.clear() + + assert entries[0].read(client=given).column("vector")[0] == stored["vector"][0] + _ = entries[1].read(client=given) + assert len(_entry_scans()) == 2 + fake_spiral_sdk.scan_log.clear() + _ = entries[1].content_hash() + assert len(_entry_scans()) == 1 + + +def test_entries_are_held_per_sign_in( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit (spiraldb_entries.py:515, spiraldb_connector.py:513): what one sign-in + fetched is not given to another, and the client held for a service is not reused + after the sign-in changed; the same sign-in shares both.""" + from orcapod.databases.spiraldb_connector import client_for_service + + entries = _entries(_table(_source()), "vector") + service = entries[0].service + first_client = client_for_service(service) + SpiralDBEntry.prefetch(entries) + fake_spiral_sdk.scan_log.clear() + _ = entries[0].read() + assert _entry_scans() == [] + assert client_for_service(service) is first_client + + monkeypatch.setenv("SPIRAL_EXAMPLE_OTHER_SIGN_IN", "1") + assert client_for_service(service) is not first_client + _ = entries[0].read() + _ = entries[1].content_hash() + assert len(_entry_scans()) == 2 + + +def test_hashes_held_are_bounded( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit (spiraldb_entries.py:338): at most ``ENTRY_CACHE_HASHES`` hashes are + held, least recently used first out; an entry let go is fetched again at its + version, with the same hash.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + monkeypatch.setattr(spiraldb_entries, "ENTRY_CACHE_HASHES", 2) + monkeypatch.setattr(spiraldb_entries, "ENTRY_CACHE_BYTES", 0) # no value held + entries = _entries(_table(_source()), "vector") + first = entries[0].content_hash() + _ = entries[1].content_hash() + _ = entries[2].content_hash() + assert len(spiraldb_entries._CACHE.hashes) == 2 # pyright: ignore[reportPrivateUsage] + fake_spiral_sdk.scan_log.clear() + assert entries[0].content_hash() == first + assert len(_entry_scans()) == 1 + + +def test_a_held_value_holds_its_own_buffers_only(stored: dict[str, Any]): + """CodeRabbit (spiraldb_entries.py:349): a value kept from a scan of many rows is a + copy of its one row, not a slice that keeps the scan's buffers; its field and bytes + are the scan's.""" + entries = _entries(_table(_source()), "vector") + SpiralDBEntry.prefetch(entries) + for index, entry in enumerate(entries): + value = entry.read() + # One row: a few bytes of values and validity, never the scan's buffers. + assert value.get_total_buffer_size() <= 2 * value.nbytes + assert value.schema.field("vector").metadata == _ENCODING + assert value.column("vector")[0] == stored["vector"][index] + + +def test_references_name_the_version_spiraldb_read(stored: dict[str, Any]): + """CodeRabbit (spiraldb_table_source.py:593): a source built with an ``asof`` that + is not itself a version names, in its references, the version SpiralDB resolved + it to, which reads the same entry later.""" + pinned = _entries(_table(_source()), "vector")[0].version + source = _source(asof=pinned + 50) + entries = _entries(_table(source), "vector") + assert {e.version for e in entries} == {pinned} + _rewrite_vector([True] * 3, _encoded_values(6)) # pinned + 1, under the asof + assert entries[0].read().column("vector")[0] == stored["vector"][0] + + +def test_reading_with_warnings_as_errors(stored: dict[str, Any]): + """CodeRabbit (spiraldb_connector.py:552): the SDK's keyed-table deprecation on + opening a version is ignored as for every other open, so ``read`` works with + warnings turned into errors.""" + entries = _entries(_table(_source()), "vector") + with warnings.catch_warnings(): + warnings.simplefilter("error") + warnings.filterwarnings("ignore", category=ProvisionalHashWarning) + assert entries[0].read().column("vector")[0] == stored["vector"][0] + + +def test_a_missing_entry_error_pickles_with_its_notes(stored: dict[str, Any]): + """CodeRabbit (errors.py:766): the error round-trips through pickle and copy with + its type, reference, reason, message and notes.""" + import copy + import pickle + + entry = _entries(_table(_source()), "vector")[0] + error = SpiralDBEntryMissingError(entry, "the table at version 1 holds no row") + error.add_note("in column 'vector'") + for back in (pickle.loads(pickle.dumps(error)), copy.deepcopy(error)): + assert type(back) is SpiralDBEntryMissingError + assert back.entry == entry + assert back.reason == error.reason + assert str(back) == str(error) + assert back.__notes__ == ["in column 'vector'"] + + +# -------------------------------------------------------------------------------------- +# Review of 6f629f3 (CodeRabbit on PR 680): the threads it left open. +# -------------------------------------------------------------------------------------- + + +def test_scan_of_a_gone_version_raises_the_missing_entry_error(stored: dict[str, Any]): + """CodeRabbit (thread on the ``scan()`` docs): ``scan()`` raises + ``SpiralDBEntryMissingError`` when the table or the version cannot be opened, as + documented; for a key its version does not hold, it yields no row.""" + entry = _entries(_table(_source()), "vector")[0] + with pytest.raises(SpiralDBEntryMissingError, match="has no version"): + _ = _at_version(entry, 999).scan() + absent = SpiralDBEntry( + entry.table_id, + entry.version, + '{"unit":"u7","time":"2026-01-01T12:00:01.000000Z"}', + "vector", + entry.service, + ) + assert absent.scan().to_table().num_rows == 0 + + +def test_a_sign_in_change_during_a_fetch_keeps_nothing( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit (sign-in isolation): a value fetched while the sign-in changed is not + kept under the earlier sign-in, for a prefetch, a hash and a read; the client is + not held for it either.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + from orcapod.databases import spiraldb_connector + + entries = _entries(_table(_source()), "vector") + calls = {"n": 0} + + def changing() -> object: + calls["n"] += 1 + return ("sign-in", calls["n"]) # a new sign-in on every look + + monkeypatch.setattr(spiraldb_entries, "sign_in_scope", changing) + SpiralDBEntry.prefetch(entries) + _ = entries[0].content_hash() + _ = entries[1].read() + assert len(spiraldb_entries._CACHE.hashes) == 0 # pyright: ignore[reportPrivateUsage] + assert len(spiraldb_entries._CACHE.values) == 0 # pyright: ignore[reportPrivateUsage] + + spiraldb_connector.clear_service_clients() + monkeypatch.setattr(spiraldb_connector, "_sign_in_key", changing) + _ = spiraldb_connector.client_for_service(entries[0].service) + assert spiraldb_connector._SERVICE_CLIENTS == {} # pyright: ignore[reportPrivateUsage] + + +def test_a_later_groups_error_keeps_the_earlier_groups( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit (async error policy detail): each group is kept as soon as it is + fetched, so when a later group's scan raises (a transport error), the earlier + group's entries are not fetched again. The error is left to the later entries' + own hashes (review S3 of fd64224: never raised by the prefetch itself).""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + first = _entries(_table(_source()), "vector") + later = [_at_version(e, e.version + 1) for e in first] + _rewrite_vector([True] * 3, _encoded_values(3)) + real = spiraldb_entries.scan_keys + scans = {"n": 0} + + def second_fails(*args: Any, **kwargs: Any) -> Any: + scans["n"] += 1 + if scans["n"] == 2: + raise ConnectionError("transport failed") + return real(*args, **kwargs) + + monkeypatch.setattr(spiraldb_entries, "scan_keys", second_fails) + SpiralDBEntry.prefetch([*first, *later]) + assert scans["n"] == 2 + monkeypatch.setattr(spiraldb_entries, "scan_keys", real) + fake_spiral_sdk.scan_log.clear() + assert len({e.content_hash() for e in first}) == 3 + assert _entry_scans() == [] + + +# -------------------------------------------------------------------------------------- +# Review of ea10790 (CodeRabbit on PR 680). +# -------------------------------------------------------------------------------------- + + +def test_each_held_value_is_charged_its_overhead( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit (spiraldb_entries.py:406): a held value is charged its bytes, its + key's text and ``ENTRY_VALUE_OVERHEAD``, so a budget of two small values holds + two, not all.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + from orcapod.databases import spiraldb_connector + + entries = _entries(_table(_source()), "vector") + sign_in = spiraldb_connector.sign_in_scope() + charges = [ + spiraldb_entries._charge( # pyright: ignore[reportPrivateUsage] + spiraldb_entries._freeze(e.read()), # pyright: ignore[reportPrivateUsage] + spiraldb_entries._entry_key(e, sign_in), # pyright: ignore[reportPrivateUsage] + ) + for e in entries + ] + assert all(c > spiraldb_entries.ENTRY_VALUE_OVERHEAD for c in charges) + spiraldb_entries.clear_entry_cache() + monkeypatch.setattr(spiraldb_entries, "ENTRY_CACHE_BYTES", max(charges) * 2) + SpiralDBEntry.prefetch(entries) + cache = spiraldb_entries._CACHE # pyright: ignore[reportPrivateUsage] + assert len(cache.values) == 2 + assert cache.value_bytes == sum(size for _, size in cache.values.values()) + assert cache.value_bytes <= max(charges) * 2 + + +def test_a_batch_keeps_outcomes_not_values(stored: dict[str, Any]): + """CodeRabbit (spiraldb_entries.py:533): a batch keeps each entry's content hash, + never its fetched value, while its rows are hashed.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entries = _entries(_table(_source()), "vector") + with SpiralDBEntry.prefetched(entries): + batch = spiraldb_entries._BATCH.get() # pyright: ignore[reportPrivateUsage] + assert batch is not None + assert set(batch.outcomes) == set(entries) + assert all(isinstance(v, ContentHash) for v in batch.outcomes.values()) + assert spiraldb_entries._BATCH.get() is None # pyright: ignore[reportPrivateUsage] + assert len({e.content_hash() for e in entries}) == 3 + + +# -------------------------------------------------------------------------------------- +# Independent review of fd64224 (PR 680). +# -------------------------------------------------------------------------------------- + + +def _elsewhere(entry: SpiralDBEntry, service: str) -> SpiralDBEntry: + """``entry`` with another service address.""" + return SpiralDBEntry( + entry.table_id, entry.version, entry.key, entry.column, service + ) + + +def _error_chain(exc: BaseException) -> list[BaseException]: + """``exc``, its causes and the members of an exception group, depth first.""" + found = [exc] + for inner in getattr(exc, "exceptions", ()): + found.extend(_error_chain(inner)) + if exc.__cause__ is not None: + found.extend(_error_chain(exc.__cause__)) + return found + + +@pytest.mark.parametrize( + "service", ["https://elsewhere.invalid", "http://api.fake.invalid"] +) +def test_a_service_this_process_never_reached_is_refused_before_signing_in( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch, service: str +): + """Review B1 of fd64224: a reference's address is data. ``read``, ``scan``, a hash + and a batch of hashes sign in only to an address this process reached through a + connector or source it built; any other is refused before a client is made or a + credential taken, telling to pass a client. A given client still reads it.""" + from orcapod.errors import SpiralDBUntrustedServiceError + + entries = _entries(_table(_source()), "vector") + others = [_elsewhere(e, service) for e in entries[:2]] + made: list[str | None] = [] + + class Recording(fake_spiral_sdk.FakeClient): + def __init__(self, **kwargs: Any) -> None: + made.append(kwargs.get("api_url")) + super().__init__(**kwargs) + + monkeypatch.setattr(fake_spiral_sdk.fake_module, "Client", Recording) + monkeypatch.setenv("SPIRAL_TOKEN", "synthetic-token") + for attempt in ( + lambda: others[0].read(), + lambda: others[0].scan(), + lambda: others[1].content_hash(), + ): + with pytest.raises(SpiralDBUntrustedServiceError, match=r"client=") as raised: + attempt() + assert raised.value.service == service + with SpiralDBEntry.prefetched(others): + for other in others: + with pytest.raises(SpiralDBUntrustedServiceError): + other.content_hash() + assert made == [] + + given = fake_spiral_sdk.FakeClient() + assert others[0].read(client=given).equals(entries[0].read(client=given)) + assert "Accept references only from producers you trust" in _source_guide() + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_a_job_over_references_to_an_untrusted_service_raises_at_its_row( + stored: dict[str, Any], tmp_path: Path, orchestrator: str +): + """Review B1 of fd64224: in a job, hashing such a reference raises the refusal + with its column named, as any error of the row hash; nothing is computed.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + from orcapod.errors import SpiralDBUntrustedServiceError + from orcapod.sources import DictSource + + entries = _entries(_table(_source()), "vector") + rows: Any = [ + {"id": i, "vector": _elsewhere(e, "https://elsewhere.invalid"), "n": i} + for i, e in enumerate(entries) + ] + source = DictSource(rows, tag_columns=["id"], tag_only_columns=True, source_id="x") + calls: list[int] = [] + + @function_pod(output_keys=("m",)) + def count(vector: SpiralDBEntry, n: int) -> int: + calls.append(n) + return n + + job = PipelineJob(name="far", database=DeltaTableDatabase(tmp_path / "db")) + with job: + count.pod(source, label="count") + with pytest.raises(BaseException) as raised: + _run(job, orchestrator) + chain = _error_chain(raised.value) + assert any(isinstance(e, SpiralDBUntrustedServiceError) for e in chain) + assert any("Failed to process column 'vector'" in str(e) for e in chain) + assert calls == [] + + +def test_an_address_is_trusted_in_any_spelling_and_one_client_is_held_per_address( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """Review B1 and S1 of fd64224: a trusted address is matched normalized (case of + scheme and host, the default port, a trailing slash), and the clients held for + references are one per trusted address, whatever sign-ins came and went.""" + from orcapod.databases import spiraldb_connector + + entries = _entries(_table(_source()), "vector") + spellings = [ + "HTTPS://API.FAKE.INVALID/", + "https://api.fake.invalid:443", + "https://Api.Fake.Invalid", + ] + for spelling in spellings: + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + spiraldb_entries.clear_entry_cache() + assert _elsewhere(entries[0], spelling).read().equals(entries[0].read()) + for token in ("one", "two", "three"): + monkeypatch.setenv("SPIRAL_TOKEN", token) + _ = spiraldb_connector.client_for_service(spellings[0]) + _ = spiraldb_connector.client_for_service(entries[0].service) + held = spiraldb_connector._SERVICE_CLIENTS # pyright: ignore[reportPrivateUsage] + assert list(held) == ["https://api.fake.invalid"] + + +@pytest.mark.parametrize("sign_in_known", [True, False]) +def test_a_reference_client_is_made_for_the_address_the_trust_check_matched( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch, sign_in_known: bool +): + """CodeRabbit on 1e627fc (spiraldb_connector.py:536): the client of a reference's + service is made for the normalized address the trust check matched, never for + the reference's own spelling, with and without a sign-in that can be told.""" + from orcapod.databases import spiraldb_connector + + _ = stored + _ = _source() # reaches the service: its address is trusted + real = spiraldb_connector._client_for # pyright: ignore[reportPrivateUsage] + asked: list[str | None] = [] + + def recording(overrides: Any) -> Any: + asked.append(dict(overrides or {}).get("server.url")) + return real(overrides) + + monkeypatch.setattr(spiraldb_connector, "_client_for", recording) + if not sign_in_known: + monkeypatch.setattr(spiraldb_connector, "_sign_in_key", lambda: None) + spiraldb_connector._SERVICE_CLIENTS.clear() # pyright: ignore[reportPrivateUsage] + _ = spiraldb_connector.client_for_service("HTTPS://API.FAKE.INVALID:443/") + assert asked == ["https://api.fake.invalid"] + + +def _write_into(value: pa.Table) -> int: + """Write zeros into every buffer of ``value`` that accepts writes; return how many + accepted.""" + written = 0 + for chunk in value.column(0).chunks: + pending: list[pa.Array[Any]] = [chunk] + while pending: + array = pending.pop() + for buffer in array.buffers(): + if buffer is not None and buffer.is_mutable and buffer.size: + memoryview(buffer).cast("B")[:] = bytes(buffer.size) + written += 1 + if isinstance(array, pa.StructArray): + pending.extend(array.field(i) for i in range(array.type.num_fields)) + elif isinstance(array, (pa.ListArray, pa.LargeListArray)): + pending.append(array.values) + return written + + +def test_what_read_returns_cannot_change_what_is_held(stored: dict[str, Any]): + """Review B3 of fd64224: ``read`` hands out the caller's own table. Writing into + every writable buffer of what a first (fetching) read and a later (cached) read + returned changes neither the next read nor the hash, on several entries.""" + entries = _entries(_table(_source()), "vector")[:2] + given = fake_spiral_sdk.FakeClient() + originals = [e.read(client=given) for e in entries] + hashes = [e.content_hash() for e in entries] # fetches and holds the values + for entry, original, hashed in zip(entries, originals, hashes): + _ = _write_into(entry.read()) + again = entry.read() + assert all(not b.is_mutable for b in again.column(0).chunks[0].buffers() if b) + assert again.equals(original) + assert entry_content_hash(again) == hashed == entry.content_hash() + + +def test_a_cold_read_returns_a_table_the_cache_does_not_share(stored: dict[str, Any]): + """Review B3 of fd64224: the first read fetches; writing into what it returned + changes nothing held.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entries = _entries(_table(_source()), "vector")[:2] + given = fake_spiral_sdk.FakeClient() + originals = [e.read(client=given) for e in entries] + spiraldb_entries.clear_entry_cache() + for entry in entries: + assert _write_into(entry.read()) > 0 + fake_spiral_sdk.scan_log.clear() + for entry, original in zip(entries, originals): + assert entry.read().equals(original) + assert entry_content_hash(original) == entry.content_hash() + assert _entry_scans() == [] + + +def _count_job(tmp_path: Path, source: Any) -> Any: + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + + @function_pod(output_keys=("n",)) + def size(vector: SpiralDBEntry, rate: float | None) -> int: + return len(vector.key) + int(rate or 0) + + job = PipelineJob(name="count", database=DeltaTableDatabase(tmp_path / "db")) + with job: + size.pod(source.select_data_columns(["vector", "rate"]), label="size") + return job + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +@pytest.mark.parametrize("condition", ["one_hash_held", "unknown_sign_in"]) +def test_a_batch_fetches_each_entry_once_whatever_the_cache_keeps( + stored: dict[str, Any], + tmp_path: Path, + orchestrator: str, + condition: str, + monkeypatch: pytest.MonkeyPatch, +): + """Review B5 of fd64224: a node's batch hashes its rows from what the batch + fetched, so a process cache that keeps one hash, or a sign-in that cannot be told + apart (nothing kept), still fetches each entry once: one scan for the sync node, + one per read batch for the async one, never one per row.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 100) + if condition == "one_hash_held": + monkeypatch.setattr(spiraldb_entries, "ENTRY_CACHE_HASHES", 1) + else: + monkeypatch.setattr(spiraldb_entries, "sign_in_scope", lambda: None) + job = _count_job(tmp_path, _source()) + fake_spiral_sdk.scan_log.clear() + summary = _run(job, orchestrator) + assert summary.nodes["size"].failed == 0 + assert [s.key_ranges for s in _entry_scans()] == [3] + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_references_a_function_returns_are_fetched_together( + stored: dict[str, Any], tmp_path: Path, orchestrator: str +): + """Review B5 of fd64224: the references a function returns are hashed into its + pipeline records; they are fetched together, one scan per table version (two + versions here), never one per row; the rows keep their order and a second run + fetches nothing.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + from orcapod.sources import DictSource + + entries = _entries(_table(_source()), "vector") + later = [_at_version(e, e.version + 1) for e in entries] + _rewrite_vector([True] * 3, _encoded_values(3)) + rows: Any = [ + {"id": i, "pick": i % 2, "slot": i // 2, "count": c} + for i, c in enumerate([3, 5, 1, 4, 0, 2]) + ] + plain = DictSource(rows, tag_columns=["id"], tag_only_columns=True) + + @function_pod(output_keys=("ref", "count")) + def pick(pick: int, slot: int, count: int) -> tuple[SpiralDBEntry, int]: + return (entries if pick else later)[slot], count + + job = PipelineJob(name="out", database=DeltaTableDatabase(tmp_path / "db")) + with job: + pick.pod(plain, label="pick") + fake_spiral_sdk.scan_log.clear() + summary = _run(job, orchestrator) + assert summary.nodes["pick"].failed == 0 + scans = _entry_scans() + assert sorted(s.key_ranges for s in scans) == [3, 3] + assert len({s.version for s in scans}) == 2 + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + table = job.nodes["pick"].as_table() + assert sorted(table.column("count").to_pylist()) == [0, 1, 2, 3, 4, 5] + fake_spiral_sdk.scan_log.clear() + _run(job, orchestrator) + assert _entry_scans() == [] + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +@pytest.mark.parametrize("error_policy", ["continue", "fail_fast"]) +def test_a_returned_reference_to_a_missing_entry_fails_its_row( + stored: dict[str, Any], tmp_path: Path, orchestrator: str, error_policy: str +): + """Review B5 of fd64224: a returned reference whose entry is missing fails its + row because its result cannot be hashed into the record. Under ``continue``, + all other rows are recorded. Under ``fail_fast``, sync records the prefix; + async raises the same error and may retain any subset of successful rows.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + from orcapod.sources import DictSource + + entries = _entries(_table(_source()), "vector") + missing = SpiralDBEntry( + entries[0].table_id, + entries[0].version, + '{"unit":"u7","time":"2026-01-01T12:00:00.123456Z"}', + "vector", + entries[0].service, + ) + returned = [entries[0], entries[2], missing, entries[1]] + rows: Any = [{"id": i, "slot": i, "count": 10 * i} for i in range(4)] + plain = DictSource(rows, tag_columns=["id"], tag_only_columns=True) + + @function_pod(output_keys=("ref", "count")) + def pick(slot: int, count: int) -> tuple[SpiralDBEntry, int]: + return returned[slot], count + + job = PipelineJob(name="out", database=DeltaTableDatabase(tmp_path / "db")) + with job: + pick.pod(plain, label="pick") + if error_policy == "fail_fast": + with pytest.raises(BaseException) as raised: + _run(job, orchestrator, error_policy) + assert any( + isinstance(e, SpiralDBEntryMissingError) for e in _error_chain(raised.value) + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + job.run(load_only=True) + table = job.nodes["pick"].as_table() + stored_ids = _values(table, "id") + if orchestrator == "sync": + assert sorted(stored_ids) == [0, 1] + else: + # Async records results in arrival order until the missing entry raises. + # Successful rows on either side of the failure may have reached it. + assert len(set(stored_ids)) == len(stored_ids) + assert set(stored_ids) <= {0, 1, 3} + assert _values(table, "count") == [10 * i for i in stored_ids] + assert _entries(table, "ref") == [returned[i] for i in stored_ids] + return + summary = _run(job, orchestrator, error_policy) + assert summary.nodes["pick"].failed == 1 + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + table = job.nodes["pick"].as_table() + assert sorted(table.column("count").to_pylist()) == [0, 10, 30] + if orchestrator == "sync": + assert table.column("count").to_pylist() == [0, 10, 30] + + +def test_held_values_and_hashes_are_charged_their_variable_size( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """Review S1 of fd64224: a held value is charged its field metadata (it is held + as IPC bytes with its schema), and a held hash its key's text and missing + reason, so the budgets bound them.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + from orcapod.databases import spiraldb_connector + + field = pa.field("value", pa.int64(), metadata={b"note": b"x" * 1024 * 1024}) + value = pa.Table.from_arrays([pa.array([1])], schema=pa.schema([field])) + entry = _entries(_table(_source()), "vector")[0] + key = spiraldb_entries._entry_key(entry, spiraldb_connector.sign_in_scope()) # pyright: ignore[reportPrivateUsage] + frozen = spiraldb_entries._freeze(value) # pyright: ignore[reportPrivateUsage] + assert spiraldb_entries._charge(frozen, key) > 1024 * 1024 # pyright: ignore[reportPrivateUsage] + assert spiraldb_entries._thaw(frozen).equals(value) # pyright: ignore[reportPrivateUsage] + + long_key = '{"unit":"' + "u" * 4096 + '"}' + small = spiraldb_entries._hash_charge(key, "gone") # pyright: ignore[reportPrivateUsage] + large = spiraldb_entries._hash_charge(key._replace(key=long_key), "gone" * 1000) # pyright: ignore[reportPrivateUsage] + assert large - small == (len(long_key) - len(key.key)) + (4000 - 4) + + spiraldb_entries.clear_entry_cache() + monkeypatch.setattr(spiraldb_entries, "ENTRY_CACHE_HASH_BYTES", small * 2) + cache = spiraldb_entries._CACHE # pyright: ignore[reportPrivateUsage] + found = spiraldb_entries._Fetched(None, "gone") # pyright: ignore[reportPrivateUsage] + for name in ("a", "b", "c"): + _ = cache.keep(key._replace(column=name), found) + assert [k.column for k in cache.hashes] == ["b", "c"] + assert cache.hash_bytes == sum(size for _, size in cache.hashes.values()) + _ = cache.keep(key._replace(key=long_key), found) + assert cache.hash_bytes <= small * 2 + + +def test_a_read_through_a_given_client_computes_no_digest( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """Review S2 of fd64224: a read through a given client returns the bytes only: + no content digest is computed, for several entries.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + real = spiraldb_entries.entry_content_hash + + def counting(value: pa.Table) -> Any: + calls.append(value.num_rows) + return real(value) + + monkeypatch.setattr(spiraldb_entries, "entry_content_hash", counting) + given = fake_spiral_sdk.FakeClient() + values = [e.read(client=given) for e in entries] + assert calls == [] + assert [v.num_rows for v in values] == [1, 1, 1] + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_a_fetch_error_propagates_as_from_the_row_hash( + stored: dict[str, Any], + tmp_path: Path, + orchestrator: str, + monkeypatch: pytest.MonkeyPatch, +): + """Review S3 of fd64224: a scan that fails during a batch's fetch raises where + the first row is hashed, wrapped with its column as the row hash wraps it, the + same as with no batch fetch; nothing is computed. Only a missing entry is a + failed row.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + def broken(*args: Any, **kwargs: Any) -> Any: + raise ValueError("synthetic scan failure") + + monkeypatch.setattr(spiraldb_entries, "scan_keys", broken) + outcomes: list[tuple[type, str, type]] = [] + for batched in (True, False): + if not batched: + + @contextlib.contextmanager + def unbatched(entries: Any) -> Any: + yield + + monkeypatch.setattr(spiraldb_entries, "prefetched_entries", unbatched) + job = _count_job(tmp_path / str(batched), _source()) + with pytest.raises(BaseException) as raised: + _run(job, orchestrator) + error = next( + e + for e in _error_chain(raised.value) + if "Failed to process column" in str(e) + ) + assert error.__cause__ is not None + outcomes.append((type(error), str(error), type(error.__cause__))) + assert outcomes[0] == outcomes[1] + assert outcomes[0] == ( + RuntimeError, + "Failed to process column 'vector': synthetic scan failure", + ValueError, + ) + + +def _source_guide() -> str: + """Read the published source guide from the checkout.""" + page = Path(__file__).parents[3] / "docs" / "concepts" / "sources.md" + return page.read_text() + + +def _run_documented_sample() -> dict[str, Any]: + """Run the SpiralDB reference sample against the fake service.""" + blocks = _source_guide().split("```python\n")[1:] + sample = next(b.split("```")[0] for b in blocks if "op.SpiralDBEntry" in b) + assert 'SpiralDBTableSource("my-project-123456", "items")' in sample + namespace: dict[str, Any] = {} + exec( # noqa: S102 # the documentation's own sample, against the fake + sample.replace('"my-project-123456", "items"', f'"{_PROJECT}", "encoded"'), + namespace, + ) + return namespace + + +@pytest.mark.parametrize( + ("column", "field_path"), + [ + ("vector", ("block_0",)), + ("vector", ("block_0", "norms")), + ("embeddings", ("count",)), + ], +) +def test_the_documented_sample_rejects_null_nested_fields( + stored: dict[str, Any], column: str, field_path: tuple[str, ...] +) -> None: + """Report the field that the example requires before using its value.""" + values = stored[column].to_pylist() + parent = values[0] + for field in field_path[:-1]: + parent = parent[field] + parent[field_path[-1]] = None + _rewrite_column([True] * 3, column, pa.array(values, stored[column].type)) + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + namespace = _run_documented_sample() + name = ".".join((column, *field_path)) + with pytest.raises(ValueError, match=rf"{name} must be non-null"): + namespace["summaries"].as_table() + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_the_documented_sample_runs( + stored: dict[str, Any], tmp_path: Path, orchestrator: str +): + """Review nit of fd64224: the live-only sample of the documentation (two + reference columns and a plain one, two outputs) runs against the fake, alone and + in a job, reading each entry it hashes with one scan.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + + _rewrite_column([True, True, True], "rate", pa.array([0.0, None, 2.5])) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + namespace = _run_documented_sample() + table = namespace["summaries"].as_table() + assert dict( + zip(_values(table, "count"), _values(table, "first_norm"), strict=True) + ) == { + 10: 0.0, + 20: 2.25, + 30: 0.3125, + } + + job = PipelineJob(name="doc", database=DeltaTableDatabase(tmp_path / "db")) + with job: + namespace["summarize"].pod( + namespace["items"].select_data_columns(["vector", "embeddings", "rate"]), + label="summarize", + ) + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + spiraldb_entries.clear_entry_cache() + fake_spiral_sdk.scan_log.clear() + summary = _run(job, orchestrator) + assert summary.nodes["summarize"].failed == 0 + assert sum(s.key_ranges for s in _entry_scans()) == 3 + + items = namespace["items"] + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + original = items.as_table() + original_version = items.pinned_version + before = {name: _entries(original, name) for name in ("vector", "embeddings")} + _rewrite_column([True, True, True], "rate", pa.array([1.0, None, 2.5])) + assert items.check_for_new_data() + updated = items.as_table() + updated_version = items.pinned_version + assert original_version is not None + assert updated_version is not None and updated_version > original_version + for name, entries in before.items(): + refreshed_entries = _entries(updated, name) + assert {entry.version for entry in entries} == {original_version} + assert {entry.version for entry in refreshed_entries} == {updated_version} + assert [entry.content_hash() for entry in entries] == [ + entry.content_hash() for entry in refreshed_entries + ] + refreshed = _run(job, orchestrator).nodes["summarize"] + result = job.nodes["summarize"].as_table() + assert (refreshed.computed, refreshed.reused) == (1, 2) + assert dict( + zip( + result.column("count").to_pylist(), + result.column("first_norm").to_pylist(), + strict=True, + ) + ) == {10: 1.5, 20: 2.25, 30: 0.3125} + + +@pytest.mark.parametrize("column", ["vector", "embeddings"]) +def test_the_documented_sample_explains_null_encoded_cells( + stored: dict[str, Any], column: str +) -> None: + """Reject a null decoded cell with the sample's column-specific error.""" + values = stored[column] + nullable = pa.array([None], type=values.type) + _rewrite_column([True] * 3, column, pa.concat_arrays([nullable, values.slice(1)])) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + with pytest.raises(ValueError, match=rf"{column} must be non-null"): + _run_documented_sample()["summaries"].as_table() + + +def test_a_locator_input_distinguishes_equal_entry_content( + stored: dict[str, Any], tmp_path: Path +) -> None: + """Pass the locator separately when it changes the result for equal content.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + from orcapod.sources import DictSource + + _rewrite_column([True] * 3, "vector", stored["vector"].take(pa.array([0, 0, 2]))) + entries = _entries(_table(_source()), "vector")[:2] + assert entries[0].key != entries[1].key + assert entries[0].content_hash() == entries[1].content_hash() + rows: Any = [ + {"id": i, "vector": entry, "locator": entry.key} + for i, entry in enumerate(entries) + ] + + @function_pod(output_keys="location") + def from_entry(vector: SpiralDBEntry) -> str: + return vector.key + + @function_pod(output_keys="location") + def from_locator(vector: SpiralDBEntry, locator: str) -> str: + assert vector.key == locator + return locator + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + source = DictSource( + rows, tag_columns=["id"], tag_only_columns=True, source_id="locator" + ) + job = PipelineJob(name="locator", database=DeltaTableDatabase(tmp_path / "db")) + with job: + from_entry.pod(source.select_data_columns(["vector"]), label="entry") + from_locator.pod(source, label="locator") + result = _run(job, "sync") + locations = job.nodes["locator"].as_table().sort_by("id") + assert result.nodes["entry"].computed == 1 + assert result.nodes["locator"].computed == 2 + assert _values(locations, "location") == [entry.key for entry in entries] + assert "pass that locator field as a separate plain input" in " ".join( + _source_guide().split() + ) + + +# -------------------------------------------------------------------------------------- +# CodeRabbit on 4ce0a09 (PR 680). +# -------------------------------------------------------------------------------------- + + +class _Events: + """An observer recording `` `` for every row event.""" + + def __init__(self) -> None: + self.events: list[str] = [] + + def contextualize(self, *args: Any) -> _Events: + return self + + def create_data_logger(self, *args: Any) -> None: + return None + + def __getattr__(self, name: str) -> Any: + if name in {"on_data_start", "on_data_end", "on_data_crash"}: + + def record(node: str, tag: Any, *args: Any, **kwargs: Any) -> None: + row = tag.as_dict().get("id") + self.events.append(f"{name.removeprefix('on_')} {node} {row}") + + return record + if name.startswith("on_"): + return lambda *args, **kwargs: None + raise AttributeError(name) + + def terminal(self, node: str) -> dict[str, list[str]]: + """Each row's end and crash events at ``node``, by row id.""" + out: dict[str, list[str]] = {} + for event in self.events: + kind, at, row = event.split(" ") + if at == node and kind in {"data_end", "data_crash"}: + out.setdefault(row, []).append(kind) + return out + + +def _missing_reference(entry: SpiralDBEntry) -> SpiralDBEntry: + """A reference to a key ``entry``'s version does not hold.""" + return SpiralDBEntry( + entry.table_id, + entry.version, + '{"unit":"u7","time":"2026-01-01T12:00:00.123456Z"}', + "vector", + entry.service, + ) + + +def _picking_job( + tmp_path: Path, returned: list[SpiralDBEntry], calls: list[int] +) -> Any: + """A job whose node ``pick`` returns ``returned[slot]`` for rows ``id = slot``, + recording the slots it is called with.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + from orcapod.sources import DictSource + + rows: Any = [{"id": i, "slot": i, "count": 10 * i} for i in range(len(returned))] + plain = DictSource(rows, tag_columns=["id"], tag_only_columns=True) + + @function_pod(output_keys=("ref", "count")) + def pick(slot: int, count: int) -> tuple[SpiralDBEntry, int]: + calls.append(slot) + return returned[slot], count + + job = PipelineJob(name="out", database=DeltaTableDatabase(tmp_path / "db")) + with job: + pick.pod(plain, label="pick") + return job + + +def _run_observed(job: Any, orchestrator: str, error_policy: str, events: _Events): + from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator + from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator + + cls = ( + AsyncPipelineOrchestrator + if orchestrator == "async" + else SyncPipelineOrchestrator + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return job.run( + orchestrator=cls(error_policy=error_policy), # pyright: ignore[reportArgumentType] + observer=events, # pyright: ignore[reportArgumentType] + ) + + +def test_a_repeated_input_does_not_reuse_a_result_that_failed_its_hash( + stored: dict[str, Any], tmp_path: Path +): + """CodeRabbit on 4ce0a09 (function_node.py:3151): an input given twice in one sync + run, whose result names a missing entry, fails at both occurrences: the second + does not take the first's result before it was hashed. Rows with a valid result + around them are recorded.""" + from orcapod.core.streams.arrow_table_stream import ArrowTableStream + + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + job = _picking_job(tmp_path, [entries[0], _missing_reference(entries[0])], calls) + node = job.nodes["pick"] + repeated = ArrowTableStream( + pa.table({"id": [1, 0, 1], "slot": [1, 0, 1], "count": [10, 0, 10]}), + tag_columns=["id"], + ) + events = _Events() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + output = node.execute(repeated, observer=events, error_policy="continue") # pyright: ignore[reportArgumentType] + rows = output.as_table() + assert rows.column("id").to_pylist() == [0] + assert events.terminal("pick") == { + "1": ["data_crash", "data_crash"], + "0": ["data_end"], + } + assert sorted(calls) == [0, 1] + + +def test_sync_cache_exposes_held_results_only_after_recording( + stored: dict[str, Any], tmp_path: Path +): + """An observer sees neither a valid nor a missing result before hashing.""" + entry = _entries(_table(_source()), "vector")[0] + calls: list[int] = [] + job = _picking_job(tmp_path, [entry, _missing_reference(entry), entry], calls) + node = job.nodes["pick"] + instances: dict[int, bytes] = {} + seen: dict[str, set[int]] = {} + + class ReadsCache(_Events): + """Record what the cache exposes during each row event.""" + + def snapshot(self, event: str) -> None: + """Read the results for every instance seen so far.""" + found = node.get_cached_results(list(instances.values())) + seen[event] = {row for row, eid in instances.items() if eid in found} + + def on_data_start(self, label: str, tag: Any, data: Any) -> None: + if label == "pick": + row = tag.as_dict()["id"] + instances[row] = node.compute_instance_id(tag, data) + self.snapshot(f"start {row}") + + def on_data_end(self, label: str, tag: Any, *args: Any, **kwargs: Any) -> None: + if label == "pick": + self.snapshot(f"end {tag.as_dict()['id']}") + + def on_data_crash(self, label: str, tag: Any, data: Any, exc: Any) -> None: + if label == "pick": + self.snapshot(f"crash {tag.as_dict()['id']}") + + summary = _run_observed(job, "sync", "continue", ReadsCache()) + assert summary.nodes["pick"].failed == 1 + assert seen == { + "start 0": set(), + "start 1": set(), + "start 2": set(), + "end 0": {0}, + "crash 1": {0}, + "end 2": {0, 2}, + } + + +def test_a_fatal_error_keeps_the_records_of_the_rows_held_before_it( + stored: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit on 4ce0a09 (function_node.py:3171): when a later row's database + write fails, the rows held before it are recorded first, and the run raises + that row's error; a load-only run then finds them.""" + from orcapod.core.nodes.function_node import FunctionJobNode + from orcapod.errors import OrcapodDatabaseError + + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + job = _picking_job(tmp_path, [entries[0], entries[1], entries[2]], calls) + real = FunctionJobNode._process_data_internal # pyright: ignore[reportPrivateUsage] + + def failing_third(self: Any, tag: Any, data: Any, **kwargs: Any) -> Any: + if tag.as_dict()["id"] == 2: + raise OrcapodDatabaseError("synthetic write failure") + return real(self, tag, data, **kwargs) + + monkeypatch.setattr(FunctionJobNode, "_process_data_internal", failing_third) + with pytest.raises(BaseException) as raised: + _run(job, "sync") + assert any("synthetic write failure" in str(e) for e in _error_chain(raised.value)) + monkeypatch.setattr(FunctionJobNode, "_process_data_internal", real) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + summary = job.run(load_only=True) + table = job.nodes["pick"].as_table() + assert sorted(table.column("id").to_pylist()) == [0, 1] + assert summary.nodes["pick"].failed == 0 + + +def test_fail_fast_stops_before_computing_the_row_after_a_failed_result( + stored: dict[str, Any], tmp_path: Path +): + """CodeRabbit on 4ce0a09 (function_node.py:3183): under ``fail_fast`` a sync run + hashes each result before the next row runs, so the first failure stops the run + before any later row is computed.""" + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + returned = [entries[0], _missing_reference(entries[0]), entries[1], entries[2]] + job = _picking_job(tmp_path, returned, calls) + with pytest.raises(BaseException) as raised: + _run(job, "sync", "fail_fast") + assert any( + isinstance(e, SpiralDBEntryMissingError) for e in _error_chain(raised.value) + ) + assert calls == [0, 1] + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_a_row_whose_result_names_a_missing_entry_has_one_terminal_event( + stored: dict[str, Any], tmp_path: Path, orchestrator: str +): + """CodeRabbit on 4ce0a09 (function_node.py:5263): a computed row whose result + names a missing entry is reported as a crash only, never also as ended; every + other row ends once.""" + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + returned = [entries[0], _missing_reference(entries[0]), entries[1], entries[2]] + job = _picking_job(tmp_path, returned, calls) + events = _Events() + summary = _run_observed(job, orchestrator, "continue", events) + assert summary.nodes["pick"].failed == 1 + assert events.terminal("pick") == { + "0": ["data_end"], + "1": ["data_crash"], + "2": ["data_end"], + "3": ["data_end"], + } + + +def test_a_stored_result_naming_a_missing_entry_has_one_terminal_event( + stored: dict[str, Any], tmp_path: Path +): + """CodeRabbit on 4ce0a09 (function_node.py:5206): in ephemeral mode, a result + the persistent store holds that names a missing entry is reported as a crash + only on the async path, never also as ended.""" + from orcapod.databases import InMemoryArrowDatabase + from orcapod.types import NodeConfig + + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + returned = [entries[0], _missing_reference(entries[0]), entries[1]] + job = _picking_job(tmp_path, returned, calls) + first = _run(job, "async") + assert first.nodes["pick"].failed == 1 + node = job.nodes["pick"] + node.node_config = NodeConfig(is_result_ephemeral=True) + node.set_ephemeral_database(InMemoryArrowDatabase()) + events = _Events() + calls.clear() + summary = _run_observed(job, "async", "continue", events) + assert 1 not in calls # its stored result answered it + assert summary.nodes["pick"].failed == 1 + assert events.terminal("pick") == { + "0": ["data_end"], + "1": ["data_crash"], + "2": ["data_end"], + } + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_a_fetch_error_hashing_a_result_stops_the_run( + stored: dict[str, Any], + tmp_path: Path, + orchestrator: str, + monkeypatch: pytest.MonkeyPatch, +): + """CodeRabbit on 4ce0a09 (function_node.py:5263): only a missing entry fails a + row; a scan that fails while a result's references are hashed stops the run, + also under ``continue``.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + job = _picking_job(tmp_path, [entries[0], entries[1], entries[2]], calls) + + def broken(*args: Any, **kwargs: Any) -> Any: + raise ValueError("synthetic scan failure") + + spiraldb_entries.clear_entry_cache() + monkeypatch.setattr(spiraldb_entries, "scan_keys", broken) + with pytest.raises(BaseException) as raised: + _run(job, orchestrator, "continue") + assert any("synthetic scan failure" in str(e) for e in _error_chain(raised.value)) + + +def test_a_later_failure_in_a_group_keeps_an_earlier_entrys_hash( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit on 4ce0a09 (spiraldb_entries.py:575) and on 836fb1f + (spiraldb_entries.py:588): when computing one entry's digest fails, that entry + alone raises inside the batch; the entries of its group before and after it keep + the hash they have alone.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entries = _entries(_table(_source()), "vector") + alone = [e.content_hash() for e in entries] + spiraldb_entries.clear_entry_cache() + real = spiraldb_entries.entry_content_hash + seen: list[int] = [] + + def second_fails(value: pa.Table) -> Any: + seen.append(1) + if len(seen) == 2: + raise ValueError("synthetic digest failure") + return real(value) + + monkeypatch.setattr(spiraldb_entries, "entry_content_hash", second_fails) + with SpiralDBEntry.prefetched(entries): + monkeypatch.setattr(spiraldb_entries, "entry_content_hash", real) + assert entries[0].content_hash() == alone[0] + with pytest.raises(ValueError, match="synthetic digest failure"): + entries[1].content_hash() + assert entries[2].content_hash() == alone[2] + + +def test_a_held_batch_error_keeps_no_traceback_and_is_raised_afresh( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit on 4ce0a09 (spiraldb_entries.py:698): a fetch error held for a batch + keeps no traceback (no fetch frames, no scan), and each hash raises a new error + of the same type and message, so the held one never grows.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entries = _entries(_table(_source()), "vector")[:2] + + def broken(*args: Any, **kwargs: Any) -> Any: + raise ValueError("synthetic scan failure") + + spiraldb_entries.clear_entry_cache() + monkeypatch.setattr(spiraldb_entries, "scan_keys", broken) + with SpiralDBEntry.prefetched(entries): + batch = spiraldb_entries._BATCH.get() # pyright: ignore[reportPrivateUsage] + assert batch is not None + held = [ + h for h in (batch.outcomes[e] for e in entries) if isinstance(h, ValueError) + ] + assert len(held) == len(entries) + assert all(h.__traceback__ is None for h in held) + raised: list[BaseException] = [] + for _ in range(2): + for entry in entries: + with pytest.raises(ValueError, match="synthetic scan failure") as error: + entry.content_hash() + raised.append(error.value) + assert all(h.__traceback__ is None for h in held) + assert all(r is not h for r in raised for h in held) + + +def test_a_batch_serves_only_the_sign_in_it_was_fetched_under( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit on 4ce0a09 (spiraldb_entries.py:745): after the sign-in changes + inside a batch, its outcomes are not used: hashing an entry fetches it again under + the new sign-in, and a batch nested under it inherits nothing.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entries = _entries(_table(_source()), "vector") + monkeypatch.setenv("SPIRAL_TOKEN", "first") + spiraldb_entries.clear_entry_cache() + with SpiralDBEntry.prefetched(entries): + fake_spiral_sdk.scan_log.clear() + first = [e.content_hash() for e in entries] + assert _entry_scans() == [] + monkeypatch.setenv("SPIRAL_TOKEN", "second") + assert entries[0].content_hash() == first[0] + assert [s.key_ranges for s in _entry_scans()] == [1] + fake_spiral_sdk.scan_log.clear() + with SpiralDBEntry.prefetched(entries[1:]): + assert [s.key_ranges for s in _entry_scans()] == [2] + monkeypatch.setenv("SPIRAL_TOKEN", "first") + fake_spiral_sdk.scan_log.clear() + assert [e.content_hash() for e in entries] == first + assert _entry_scans() == [] + + +@pytest.mark.parametrize("rows", [1, 3]) +def test_a_reference_that_cannot_be_read_names_its_column(rows: int): + """CodeRabbit on 4ce0a09 (arrow_hashers.py:153): a stored reference that is not a + valid reference raises naming its column, in a table of one row and of several + (whose references are gathered for a batch fetch first).""" + from orcapod.contexts import get_default_context + + good = { + "table_id": "t", + "version": 1, + "key": '{"k":1}', + "column": "v", + "service": "https://api.fake.invalid", + } + values = [{**good, "table_id": None}] + [good] * (rows - 1) + ext = LogicalSpiralDBEntry().get_arrow_extension_type() + storage = pa.array(values, type=ext.storage_type) + table = pa.table({"refs": pa.ExtensionArray.from_storage(ext, storage)}) + with pytest.raises(RuntimeError, match="Failed to process column 'refs'"): + get_default_context().arrow_hasher.hash_table(table) + + +def test_a_reference_column_declared_stored_is_not_prefetched(): + """CodeRabbit on 4ce0a09 (prefetch.py:217): only a column hashed by value is + prefetched; the same extension name declared ``stored`` is hashed as stored and + fetches nothing.""" + from orcapod.contexts import get_default_context + from orcapod.hashing.prefetch import prefetched_columns + from orcapod.logical_types.registry import make_arrow_extension_type + from orcapod.logical_types.spiraldb_entry_type import ( + SPIRALDB_ENTRY_EXTENSION_NAME, + SPIRALDB_ENTRY_STORAGE, + ) + + context = get_default_context() + live = LogicalSpiralDBEntry().get_arrow_extension_type() + as_stored = make_arrow_extension_type( + SPIRALDB_ENTRY_EXTENSION_NAME, + SPIRALDB_ENTRY_STORAGE, + b'{"value_hash":"stored","version":1}', + )() # pyright: ignore[reportCallIssue] + schema = pa.schema([("by_value", live), ("stored", as_stored), ("b", live)]) + found = prefetched_columns(schema, context.type_converter, context.semantic_hasher) + assert sorted(found) == ["b", "by_value"] + + +def test_a_forked_child_keeps_trust_but_no_client_cache_or_held_lock( + stored: dict[str, Any], +): + """CodeRabbit on 4ce0a09 (review body, fork hook): the hooks a forked child runs + give it new locks for the trusted addresses, the clients held for references and + the entry cache (a parent thread may have held any of them), keep the trusted + addresses, and hold no client and no entry of the parent.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + from orcapod.databases import spiraldb_connector as connector + + entries = _entries(_table(_source()), "vector")[:2] + _ = [e.content_hash() for e in entries] + _ = [e.read() for e in entries] + assert connector._SERVICE_CLIENTS # pyright: ignore[reportPrivateUsage] + trusted = set(connector._TRUSTED_SERVICES) # pyright: ignore[reportPrivateUsage] + held = [ + connector._trusted_services_lock, # pyright: ignore[reportPrivateUsage] + connector._service_clients_lock, # pyright: ignore[reportPrivateUsage] + spiraldb_entries._CACHE.lock, # pyright: ignore[reportPrivateUsage] + ] + for lock in held: + assert lock.acquire(blocking=False) + try: + connector._forget_in_child() # pyright: ignore[reportPrivateUsage] + spiraldb_entries._forget_in_child() # pyright: ignore[reportPrivateUsage] + fresh = [ + connector._trusted_services_lock, # pyright: ignore[reportPrivateUsage] + connector._service_clients_lock, # pyright: ignore[reportPrivateUsage] + spiraldb_entries._CACHE.lock, # pyright: ignore[reportPrivateUsage] + ] + assert all(new is not old and not new.locked() for new, old in zip(fresh, held)) + assert spiraldb_entries._CACHE.lock is fresh[2] # pyright: ignore[reportPrivateUsage] + assert connector._TRUSTED_SERVICES == trusted # pyright: ignore[reportPrivateUsage] + assert connector._SERVICE_CLIENTS == {} # pyright: ignore[reportPrivateUsage] + cache = spiraldb_entries._CACHE # pyright: ignore[reportPrivateUsage] + assert not cache.hashes and not cache.values + fake_spiral_sdk.scan_log.clear() + assert entries[0].read().num_rows == 1 + assert [s.key_ranges for s in _entry_scans()] == [1] + finally: + for lock in held: + lock.release() + + +# -------------------------------------------------------------------------------------- +# Delta review of 836fb1f (PR 680). +# -------------------------------------------------------------------------------------- + + +def _other_column(entry: SpiralDBEntry, column: str) -> SpiralDBEntry: + """``entry`` naming another column.""" + return SpiralDBEntry( + entry.table_id, entry.version, entry.key, column, entry.service + ) + + +def test_a_reference_to_a_missing_column_fails_only_itself(stored: dict[str, Any]): + """Delta review D1 of 836fb1f: a reference to a column its version does not have + fails at its own hash, naming the column; good references of the same table + version beside it (the same key, another key) hash as they do alone.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entries = _entries(_table(_source()), "vector") + alone = [e.content_hash() for e in entries[:2]] + misspelled = [_other_column(entries[0], "vectr"), _other_column(entries[1], "nope")] + for bad in misspelled: + spiraldb_entries.clear_entry_cache() + with pytest.raises(ValueError, match=repr(bad.column)): + bad.content_hash() + spiraldb_entries.clear_entry_cache() + fake_spiral_sdk.scan_log.clear() + with SpiralDBEntry.prefetched([entries[0], *misspelled, entries[1]]): + assert [e.content_hash() for e in entries[:2]] == alone + for bad in misspelled: + with pytest.raises(ValueError, match=repr(bad.column)): + bad.content_hash() + assert [s.key_ranges for s in _entry_scans()] == [2] + + +def _input_failing_after_one_row(source: Any, events: list[str]) -> Any: + """A stream over ``source`` that yields its first row, then fails when asked for + the next.""" + + class Input: + def __getattr__(self, name: str) -> Any: + return getattr(source, name) + + def iter_data(self) -> Any: + events.append("yield first row") + yield next(iter(source.iter_data())) + events.append("read next row") + raise RuntimeError("synthetic input iteration failure") + + return Input() + + +@pytest.mark.parametrize("load_only", [False, True]) +def test_a_plain_input_is_hashed_row_by_row_before_the_next_is_read(load_only: bool): + """Delta review D2 of 836fb1f: an input with no column whose hash fetches is not + read ahead: each row is hashed before the next row is asked for, so a failing hash + of the first row is raised and the next row is never read, on the sync run and the + load-only run, as on main. Two rows, two data columns.""" + from orcapod import PipelineJob + from orcapod.databases import InMemoryArrowDatabase + from orcapod.sources import DictSource + + @function_pod(output_keys=("out",)) + def add(n: int, m: int) -> int: + return n + m + + source = DictSource( + [{"id": 1, "n": 1, "m": 3}, {"id": 2, "n": 2, "m": 4}], + tag_columns=["id"], + tag_only_columns=True, + source_id="plain", + ) + job = PipelineJob(name="plain-order", database=InMemoryArrowDatabase()) + with job: + add.pod(source, label="add") + node: Any = job.nodes["add"] + events: list[str] = [] + + def cannot_hash(*args: Any) -> bytes: + events.append("hash first row") + raise ValueError("synthetic row hash failure") + + node.compute_instance_id = cannot_hash + with pytest.raises(ValueError, match="synthetic row hash failure"): + node.execute(_input_failing_after_one_row(source, events), load_only=load_only) + assert events == ["yield first row", "hash first row"] + + +def test_prefetch_refuses_an_untrusted_service_before_signing_in( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """Delta review D3 of 836fb1f: ``SpiralDBEntry.prefetch`` refuses a reference to + a service this process never reached, as ``read`` does, before any client is + made, also when trusted references are beside it; trusted ones alone still + prefetch.""" + from orcapod.errors import SpiralDBUntrustedServiceError + + entries = _entries(_table(_source()), "vector") + others = [_elsewhere(e, "https://elsewhere.invalid") for e in entries[:2]] + made: list[object] = [] + + class Recording(fake_spiral_sdk.FakeClient): + def __init__(self, **kwargs: Any) -> None: + made.append(kwargs.get("api_url")) + super().__init__(**kwargs) + + monkeypatch.setattr(fake_spiral_sdk.fake_module, "Client", Recording) + for batch in (others, [entries[0], *others]): + with pytest.raises(SpiralDBUntrustedServiceError, match=r"client="): + SpiralDBEntry.prefetch(batch) + assert made == [] + fake_spiral_sdk.scan_log.clear() + SpiralDBEntry.prefetch(entries) + assert [s.key_ranges for s in _entry_scans()] == [3] + + +def test_an_async_node_reads_at_most_256_rows_per_scan( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """Delta review D4 of 836fb1f: the bound is per function-node batch, not per batch + a source reads: 257 rows of one version read by the source in one batch take two + scans on the async path, of 256 and 1 keys, and one on the sync path.""" + from orcapod import PipelineJob + from orcapod.databases import InMemoryArrowDatabase + + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 1000) + count = 257 + project = fake_spiral_sdk.ExternalProject(_PROJECT) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + table = project.create_table("default.encoded", key_schema=_key_schema()) + picks = pa.array([i % 3 for i in range(count)]) + rows = ( + _plain_rows() + .take(picks) + .set_column( + 0, + "unit", + pa.array([f"u{i:03}" for i in range(count)], pa.large_string()), + ) + ) + table.write(rows) + table.write_encoded( + "vector", + _encoded_values(0).take(picks), + pa.field("vector", _STORAGE, metadata=_ENCODING), + ) + + @function_pod(output_keys=("size",)) + def size(vector: SpiralDBEntry, rate: float | None) -> int: + return len(vector.key) + int(rate or 0) + + for orchestrator, expected in (("async", [256, 1]), ("sync", [257])): + job = PipelineJob(name=orchestrator, database=InMemoryArrowDatabase()) + with job: + size.pod(_source().select_data_columns(["vector", "rate"]), label="size") + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + spiraldb_entries.clear_entry_cache() + fake_spiral_sdk.scan_log.clear() + summary = _run(job, orchestrator) + assert summary.nodes["size"].failed == 0 + assert sorted(s.key_ranges for s in _entry_scans()) == sorted(expected) + + +def test_a_batch_serves_only_its_own_process_while_open( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit on 836fb1f (spiraldb_entries.py:521 and :757): a batch's outcomes + serve only the process that fetched them, while its block is open. A forked + child (another process id) inside the block, and a task that hashes after the + block closed, do not take a held error; they fetch the entries again, and a + batch nested in the child inherits nothing.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entries = _entries(_table(_source()), "vector")[:2] + alone = [e.content_hash() for e in entries] + real_scan = spiraldb_entries.scan_keys + + def broken(*args: Any, **kwargs: Any) -> Any: + raise ValueError("synthetic transient failure") + + spiraldb_entries.clear_entry_cache() + monkeypatch.setattr(spiraldb_entries, "scan_keys", broken) + with SpiralDBEntry.prefetched(entries): + monkeypatch.setattr(spiraldb_entries, "scan_keys", real_scan) + with pytest.raises(ValueError, match="synthetic transient failure"): + entries[0].content_hash() + parent = os.getpid() + monkeypatch.setattr(spiraldb_entries.os, "getpid", lambda: parent + 1) + spiraldb_entries.clear_entry_cache() + assert [e.content_hash() for e in entries] == alone + spiraldb_entries.clear_entry_cache() + fake_spiral_sdk.scan_log.clear() + with SpiralDBEntry.prefetched(entries): + assert [s.key_ranges for s in _entry_scans()] == [2] + monkeypatch.setattr(spiraldb_entries.os, "getpid", lambda: parent) + + async def outlives() -> list[Any]: + monkeypatch.setattr(spiraldb_entries, "scan_keys", broken) + release = asyncio.Event() + + async def late_hash() -> list[Any]: + await release.wait() + return [e.content_hash() for e in entries] + + spiraldb_entries.clear_entry_cache() + with SpiralDBEntry.prefetched(entries): + task = asyncio.ensure_future(late_hash()) + monkeypatch.setattr(spiraldb_entries, "scan_keys", real_scan) + release.set() + return await task + + assert asyncio.run(outlives()) == alone + + +def test_a_fork_while_a_nested_batch_reads_its_entries_inherits_nothing( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """Final delta review of b4a1c3a (fork during preparation): a nested batch belongs + to the process that started preparing it. A fork while the nested batch consumes + its entries (simulated by a new process id) leaves the child a batch that serves + it none of the outer batch's outcomes: the child hashes the entries again.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entries = _entries(_table(_source()), "vector")[:2] + alone = [e.content_hash() for e in entries] + real_scan = spiraldb_entries.scan_keys + parent = os.getpid() + + def broken(*args: Any, **kwargs: Any) -> Any: + raise ValueError("synthetic transient failure") + + def forking(chosen: list[SpiralDBEntry]) -> Iterator[SpiralDBEntry]: + monkeypatch.setattr(spiraldb_entries.os, "getpid", lambda: parent + 1) + yield from chosen + + spiraldb_entries.clear_entry_cache() + monkeypatch.setattr(spiraldb_entries, "scan_keys", broken) + with SpiralDBEntry.prefetched(entries): + monkeypatch.setattr(spiraldb_entries, "scan_keys", real_scan) + with SpiralDBEntry.prefetched(forking(list(reversed(entries)))): + assert [e.content_hash() for e in entries] == alone + monkeypatch.setattr(spiraldb_entries.os, "getpid", lambda: parent) + with pytest.raises(ValueError, match="synthetic transient failure"): + entries[0].content_hash() + + +class _CountingEvents(_Events): + """``_Events`` that also records the node-end reports, by node label.""" + + def __init__(self) -> None: + super().__init__() + self.node_ends: list[str] = [] + + def on_node_end(self, node: str, *args: Any, **kwargs: Any) -> None: + self.node_ends.append(node) + self.events.append(f"node_end {node} -") + + def ends_last(self, node: str) -> bool: + """Whether ``node`` ended once, after every row event at it.""" + at = [e for e in self.events if e.split(" ")[1] == node] + return self.node_ends.count(node) == 1 and at[-1] == f"node_end {node} -" + + +@pytest.mark.parametrize("failure", ["function", "missing_input"]) +@pytest.mark.parametrize( + "hash_fails", [True, False], ids=["hash_fails", "hash_succeeds"] +) +def test_a_waiting_failed_row_crashes_when_a_held_result_cannot_be_hashed( + stored: dict[str, Any], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + failure: str, + hash_fails: bool, +) -> None: + """A waiting failed row crashes once before the node ends.""" + from orcapod import PipelineJob + from orcapod.core.sources import spiraldb_entries + from orcapod.databases import DeltaTableDatabase + from orcapod.sources import DictSource + + entries = _entries(_table(_source()), "vector") + second_input = ( + _missing_reference(entries[1]) if failure == "missing_input" else entries[1] + ) + function_error = ValueError("synthetic function failure") + + def broken(*args: Any, **kwargs: Any) -> Any: + raise ValueError("synthetic scan failure") + + @function_pod(output_keys="ref_out") + def pick(slot: int, ref_in: SpiralDBEntry) -> SpiralDBEntry: + if slot == 1: + raise function_error + if hash_fails: + monkeypatch.setattr(spiraldb_entries, "scan_keys", broken) + return entries[2] + + rows: Any = [ + {"id": 0, "slot": 0, "ref_in": entries[0]}, + {"id": 1, "slot": 1, "ref_in": second_input}, + ] + job = PipelineJob(name="held", database=DeltaTableDatabase(tmp_path / "db")) + with job: + source = DictSource( + rows, tag_columns=["id"], tag_only_columns=True, source_id="refs" + ) + pick.pod(source, label="pick") + + class CrashEvents(_CountingEvents): + def __init__(self) -> None: + super().__init__() + self.errors: list[Exception] = [] + + def on_data_crash(self, node: str, tag: Any, data: Any, exc: Exception) -> None: + self.__getattr__("on_data_crash")(node, tag, data, exc) + if node == "pick": + self.errors.append(exc) + + events = CrashEvents() + if hash_fails: + with pytest.raises(RuntimeError, match="synthetic scan failure") as raised: + _run_observed(job, "sync", "continue", events) + assert events.errors[0] is raised.value + else: + _run_observed(job, "sync", "continue", events) + + assert [event for event in events.events if event.split()[1] == "pick"] == [ + "data_start pick 0", + "data_start pick 1", + "data_crash pick 0" if hash_fails else "data_end pick 0", + "data_crash pick 1", + "node_end pick -", + ] + if failure == "function": + assert events.errors[-1] is function_error + else: + assert isinstance(events.errors[-1], SpiralDBEntryMissingError) + + +@pytest.mark.parametrize("failure", ["function", "missing_input"]) +def test_a_sync_crash_observer_cannot_discard_prior_held_rows( + stored: dict[str, Any], tmp_path: Path, failure: str +) -> None: + """Under continue, finish the preceding row before reporting either failure.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + from orcapod.sources import DictSource + + entries = _entries(_table(_source()), "vector") + inputs = list(entries) + if failure == "missing_input": + inputs[1] = _missing_reference(entries[1]) + calls: list[int] = [] + + @function_pod(output_keys="ref") + def pick(slot: int, ref_in: SpiralDBEntry) -> SpiralDBEntry: + calls.append(slot) + if slot == 1: + raise ValueError("synthetic function failure") + return ref_in + + class FailsOnCrash(_CountingEvents): + """Raise after recording the row's crash.""" + + def on_data_crash(self, node: str, tag: Any, data: Any, exc: Any) -> None: + self.__getattr__("on_data_crash")(node, tag, data, exc) + if node == "pick": + raise RuntimeError("synthetic crash observer failure") + + rows: Any = [ + {"id": i, "slot": i, "ref_in": entry} for i, entry in enumerate(inputs) + ] + root = tmp_path / "db" + job = PipelineJob(name="held", database=DeltaTableDatabase(root)) + with job: + source = DictSource( + rows, tag_columns=["id"], tag_only_columns=True, source_id="refs" + ) + pick.pod(source, label="pick") + events = FailsOnCrash() + with pytest.raises(RuntimeError, match="synthetic crash observer failure"): + _run_observed(job, "sync", "continue", events) + + assert calls == ([0, 1] if failure == "function" else [0]) + terminal = [ + e for e in events.events if e.startswith(("data_end pick", "data_crash pick")) + ] + assert terminal == ["data_end pick 0", "data_crash pick 1"] + reopened = DeltaTableDatabase(root) + [path] = [ + p + for p in reopened.list_table_paths() + if p[1] == "pick" and p[-1].startswith("pdb") + ] + written = reopened.get_all_records(path) + assert written is not None + assert _values(written, "id") == [0] + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_fail_fast_keeps_a_missing_input_error_when_the_crash_observer_raises( + stored: dict[str, Any], tmp_path: Path, orchestrator: str +) -> None: + """A scalar-output node reports its end and raises the missing input error.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + + @function_pod(output_keys=("size",)) + def size(vector: SpiralDBEntry) -> int: + return len(vector.key) + + class FailingObserver(_CountingEvents): + """Record the crash and node end before raising from their callbacks.""" + + def on_data_crash(self, node: str, tag: Any, data: Any, exc: Any) -> None: + self.__getattr__("on_data_crash")(node, tag, data, exc) + if node == "size": + raise RuntimeError("synthetic crash observer failure") + + def on_node_end(self, node: str, *args: Any, **kwargs: Any) -> None: + super().on_node_end(node, *args, **kwargs) + if node == "size": + raise RuntimeError("synthetic node-end observer failure") + + job = PipelineJob( + name="missing_input", database=DeltaTableDatabase(tmp_path / "db") + ) + with job: + size.pod(_source_with_a_missing_entry(), label="size") + + events = FailingObserver() + with pytest.raises(Exception) as raised: + _run_observed(job, orchestrator, "fail_fast", events) + + chain = _error_chain(raised.value) + assert any(isinstance(error, SpiralDBEntryMissingError) for error in chain), chain + assert all("synthetic crash observer failure" not in str(error) for error in chain) + notes = [note for error in chain for note in getattr(error, "__notes__", [])] + assert any("synthetic crash observer failure" in note for note in notes) + assert any("synthetic node-end observer failure" in note for note in notes) + assert events.terminal("size")["1"] == ["data_crash"] + assert events.ends_last("size") + + +def test_fail_fast_reports_the_first_missing_input_entry_not_a_later_error( + stored: dict[str, Any], tmp_path: Path +): + """CodeRabbit on b271b70 (function_node.py:2806): under ``fail_fast`` a sync run + stops hashing its inputs at the first row whose entry is missing, so that row's + failure is the one reported and raised; a later row whose hash would raise + another error is never hashed. Three rows, the missing one in the middle.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + + @function_pod(output_keys=("size",)) + def size(vector: SpiralDBEntry) -> int: + return len(vector.key) + + source = _source_with_a_missing_entry() + job = PipelineJob(name="first", database=DeltaTableDatabase(tmp_path / "db")) + with job: + size.pod(source, label="size") + node: Any = job.nodes["size"] + real = node.compute_instance_id + hashed: list[int] = [] + + def hash_or_fail_later(tag: Any, data: Any) -> bytes: + hashed.append(tag.as_dict()["id"]) + if tag.as_dict()["id"] == 2: + raise ValueError("synthetic later hash failure") + return real(tag, data) + + node.compute_instance_id = hash_or_fail_later + events = _Events() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + with pytest.raises(BaseException) as raised: + node.execute(source, observer=events, error_policy="fail_fast") + chain = _error_chain(raised.value) + assert any(isinstance(e, SpiralDBEntryMissingError) for e in chain) + assert not any("synthetic later hash failure" in str(e) for e in chain) + assert hashed == [0, 1] + assert events.terminal("size") == {"0": ["data_end"], "1": ["data_crash"]} + + +def test_a_fatal_row_error_during_a_failing_batch_ends_the_node_once( + stored: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit on b271b70 (function_node.py:3100): when a row's database write + fails while a held row's result cannot be hashed (a failing scan), both rows are + reported as crashed, the database error is the one raised, and the node's end is + reported once.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + from orcapod.core.nodes.function_node import FunctionJobNode + from orcapod.errors import OrcapodDatabaseError + + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + job = _picking_job(tmp_path, [entries[0], entries[1], entries[2]], calls) + real = FunctionJobNode._process_data_internal # pyright: ignore[reportPrivateUsage] + + def failing_second(self: Any, tag: Any, data: Any, **kwargs: Any) -> Any: + if tag.as_dict()["id"] == 1: + raise OrcapodDatabaseError("synthetic write failure") + return real(self, tag, data, **kwargs) + + def broken(*args: Any, **kwargs: Any) -> Any: + raise ValueError("synthetic scan failure") + + spiraldb_entries.clear_entry_cache() + monkeypatch.setattr(FunctionJobNode, "_process_data_internal", failing_second) + monkeypatch.setattr(spiraldb_entries, "scan_keys", broken) + events = _CountingEvents() + with pytest.raises(BaseException) as raised: + _run_observed(job, "sync", "continue", events) + chain = _error_chain(raised.value) + assert isinstance(chain[0], OrcapodDatabaseError) + notes = "\n".join(getattr(chain[0], "__notes__", [])) + assert "synthetic scan failure" in notes + assert events.terminal("pick") == {"0": ["data_crash"], "1": ["data_crash"]} + assert events.ends_last("pick") + + +def test_a_sync_batch_is_bounded_by_its_held_rows( + stored: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit on b271b70 (function_node.py:3172): the rows a sync run holds + before their results are hashed are bounded by ``_PREFETCH_ROWS`` counting every + held row, so repeats of one computed input (cache hits that add no record) end + in batches of that size, not all at the end of the input.""" + from orcapod.core.nodes import function_node + from orcapod.core.streams.arrow_table_stream import ArrowTableStream + + monkeypatch.setattr(function_node, "_PREFETCH_ROWS", 2) + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + job = _picking_job(tmp_path, [entries[0], entries[1]], calls) + node = job.nodes["pick"] + repeated = ArrowTableStream( + pa.table({"id": [0, 0, 1, 1, 0], "slot": [0, 0, 1, 1, 0], "count": [0] * 5}), + tag_columns=["id"], + ) + events = _Events() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + _ = node.execute(repeated, observer=events, error_policy="continue") # pyright: ignore[reportArgumentType] + kinds = [event.split(" ")[0] for event in events.events] + assert kinds == [ + "data_start", + "data_start", + "data_end", + "data_end", + "data_start", + "data_start", + "data_end", + "data_end", + "data_start", + "data_end", + ] + assert sorted(calls) == [0, 1] + + +def test_an_async_record_write_failure_ends_a_held_row_in_a_crash( + stored: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit on b271b70 (function_node.py:5380): on the async path, a row whose + end was held for its pipeline record, and whose record write fails, is reported + as crashed, and the database error is the one raised.""" + from orcapod.core.nodes.function_node import FunctionJobNode + from orcapod.errors import OrcapodDatabaseError + + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + job = _picking_job(tmp_path, [entries[0], entries[1], entries[2]], calls) + real = FunctionJobNode._add_pipeline_record # pyright: ignore[reportPrivateUsage] + + def failing_second(self: Any, tag: Any, *args: Any, **kwargs: Any) -> Any: + if tag.as_dict()["id"] == 1: + raise OrcapodDatabaseError("synthetic record failure") + return real(self, tag, *args, **kwargs) + + monkeypatch.setattr(FunctionJobNode, "_add_pipeline_record", failing_second) + events = _Events() + with pytest.raises(BaseException) as raised: + _run_observed(job, "async", "continue", events) + assert any("synthetic record failure" in str(e) for e in _error_chain(raised.value)) + assert events.terminal("pick").get("1") == ["data_crash"] + + +@pytest.mark.parametrize("failure", ["record", "record_validation", "hash"]) +def test_an_async_held_row_crashes_with_the_input_its_start_was_reported_with( + stored: dict[str, Any], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + failure: str, +): + """CodeRabbit on b271b70 (review body, function_node.py:5382): on the async path, + a computed row whose end was held for its result's record, and whose record + write or result hash fails, is reported as crashed with the input its start was + reported with: the function's input, without the data-tags that fall through + it. Two data-tags, two parameters.""" + from orcapod import PipelineJob + from orcapod.core.nodes.function_node import FunctionJobNode + from orcapod.databases import DeltaTableDatabase + from orcapod.errors import InputValidationError, OrcapodDatabaseError + from orcapod.sources import DictSource + + entries = _entries(_table(_source()), "vector") + returned = [entries[0], entries[1], entries[2]] + if failure == "hash": + returned[1] = _missing_reference(entries[0]) + rows: Any = [ + {"id": i, "group": f"g{i % 2}", "batch": i // 2, "slot": i, "count": i} + for i in range(3) + ] + source = DictSource(rows, tag_columns=["id", "group", "batch"]) + + @function_pod(output_keys=("ref", "count")) + def pick(slot: int, count: int) -> tuple[SpiralDBEntry, int]: + return returned[slot], count + + job = PipelineJob(name="seen", database=DeltaTableDatabase(tmp_path / "db")) + with job: + pick.pod(source, label="pick") + error_type = ( + InputValidationError if failure == "record_validation" else OrcapodDatabaseError + ) + if failure != "hash": + real = FunctionJobNode._add_pipeline_record # pyright: ignore[reportPrivateUsage] + + def failing_second(self: Any, tag: Any, *args: Any, **kwargs: Any) -> Any: + if tag.as_dict()["id"] == 1: + raise error_type("synthetic record failure") + return real(self, tag, *args, **kwargs) + + monkeypatch.setattr(FunctionJobNode, "_add_pipeline_record", failing_second) + seen: dict[str, dict[str, Any]] = {} + crashes: list[Exception] = [] + + class Seen(_Events): + def on_data_start(self, node: str, tag: Any, data: Any) -> None: + if node == "pick" and tag.as_dict()["id"] == 1: + seen["start"] = data.as_dict() + + def on_data_crash(self, node: str, tag: Any, data: Any, exc: Any) -> None: + if node == "pick" and tag.as_dict()["id"] == 1: + crashes.append(exc) + seen["crash"] = data.as_dict() + if failure == "record_validation": + raise RuntimeError("synthetic crash observer failure") + + if failure != "hash": + with pytest.raises(BaseException) as raised: + _run_observed(job, "async", "continue", Seen()) + assert any( + isinstance(e, error_type) and "synthetic record failure" in str(e) + for e in _error_chain(raised.value) + ) + else: + summary = _run_observed(job, "async", "continue", Seen()) + assert summary.nodes["pick"].failed == 1 + assert len(crashes) == 1 + if failure == "record_validation": + assert any( + "synthetic crash observer failure" in note + for note in getattr(crashes[0], "__notes__", []) + ) + assert seen["start"] == {"slot": 1, "count": 1} + assert seen["crash"] == seen["start"] + + +def test_a_hash_that_aborts_a_sync_batch_ends_every_row_held_behind_it( + stored: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit on 9905e20 (function_node.py:3149): under ``continue``, when a held + result's hash raises another error than a missing entry, the run stops and every + row started and held behind it is reported as crashed with that error, before + the node's end, reported once. Three held rows.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + job = _picking_job(tmp_path, [entries[0], entries[1], entries[2]], calls) + + def broken(*args: Any, **kwargs: Any) -> Any: + raise ValueError("synthetic scan failure") + + spiraldb_entries.clear_entry_cache() + monkeypatch.setattr(spiraldb_entries, "scan_keys", broken) + events = _CountingEvents() + with pytest.raises(BaseException) as raised: + _run_observed(job, "sync", "continue", events) + assert any("synthetic scan failure" in str(e) for e in _error_chain(raised.value)) + assert sorted(calls) == [0, 1, 2] + assert events.terminal("pick") == { + "0": ["data_crash"], + "1": ["data_crash"], + "2": ["data_crash"], + } + assert events.ends_last("pick") + + +@pytest.mark.parametrize("callback", ["on_data_start", "create_data_logger"]) +def test_a_sync_observer_failure_finishes_earlier_held_rows( + stored: dict[str, Any], tmp_path: Path, callback: str +) -> None: + """An observer failure on the next input leaves earlier results loadable.""" + from orcapod.databases import DeltaTableDatabase + + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + job = _picking_job(tmp_path, entries, calls) + failure = RuntimeError("synthetic observer failure") + + class FailingObserver(_CountingEvents): + def on_data_start(self, node: str, tag: Any, data: Any) -> None: + if ( + callback == "on_data_start" + and node == "pick" + and tag.as_dict()["id"] == 1 + ): + raise failure + self.__getattr__("on_data_start")(node, tag, data) + + def create_data_logger(self, *args: Any) -> None: + if callback == "create_data_logger" and args[0].as_dict()["id"] == 1: + raise failure + + events = FailingObserver() + with pytest.raises(RuntimeError, match="synthetic observer failure") as raised: + _run_observed(job, "sync", "continue", events) + assert raised.value is failure + assert calls == [0] + terminal = {"0": ["data_end"]} + if callback == "create_data_logger": + terminal["1"] = ["data_crash"] + assert events.terminal("pick") == terminal + assert events.ends_last("pick") + + reopened = DeltaTableDatabase(tmp_path / "db") + [path] = [ + p + for p in reopened.list_table_paths() + if p[1] == "pick" and p[-1].startswith("pdb") + ] + written = reopened.get_all_records(path) + assert written is not None + assert _values(written, "id") == [0] + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + job.run(load_only=True) + remaining = job.nodes["pick"].as_table() + assert _values(remaining, "id") == [0] + assert _entries(remaining, "ref") == [entries[0]] + assert calls == [0] + + +@pytest.mark.parametrize("start_fails", [False, True], ids=["normal", "after_callback"]) +def test_a_sync_prefetch_setup_failure_aborts_unreported_held_rows( + stored: dict[str, Any], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + start_fails: bool, +) -> None: + """A prefetch setup failure closes held rows even during observer recovery.""" + from orcapod.core.nodes import function_node + + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + job = _picking_job(tmp_path, entries, calls) + original = RuntimeError("synthetic start failure") + prefetch_error = RuntimeError("synthetic prefetch setup failure") + real_prefetch = function_node.prefetched_rows + + @contextlib.contextmanager + def fail_output_prefetch(rows: Any, *args: Any) -> Iterator[None]: + if rows and "ref" in rows[0]: + raise prefetch_error + with real_prefetch(rows, *args): + yield + + monkeypatch.setattr(function_node, "prefetched_rows", fail_output_prefetch) + + class FailingObserver(_CountingEvents): + def on_data_start(self, node: str, tag: Any, data: Any) -> None: + if start_fails and node == "pick" and tag.as_dict()["id"] == 1: + raise original + self.__getattr__("on_data_start")(node, tag, data) + + events = FailingObserver() + with pytest.raises(RuntimeError, match="synthetic .* failure") as raised: + _run_observed(job, "sync", "continue", events) + assert raised.value is (original if start_fails else prefetch_error) + assert calls == ([0] if start_fails else [0, 1, 2]) + assert events.terminal("pick") == {str(slot): ["data_crash"] for slot in calls} + assert events.ends_last("pick") + if start_fails: + assert any( + "synthetic prefetch setup failure" in note for note in original.__notes__ + ) + + +@pytest.mark.parametrize("end_fails", [False, True], ids=["normal", "with_callback"]) +def test_a_sync_prefetch_teardown_failure_preserves_terminal_reports( + stored: dict[str, Any], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + end_fails: bool, +) -> None: + """End the node once and keep any earlier failure while releasing the batch.""" + from orcapod.core.nodes import function_node + + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + job = _picking_job(tmp_path, entries, calls) + original = RuntimeError("synthetic end failure") + prefetch_error = RuntimeError("synthetic prefetch teardown failure") + real_prefetch = function_node.prefetched_rows + + @contextlib.contextmanager + def fail_output_teardown(rows: Any, *args: Any) -> Iterator[None]: + with real_prefetch(rows, *args): + try: + yield + finally: + if rows and "ref" in rows[0]: + raise prefetch_error + + monkeypatch.setattr(function_node, "prefetched_rows", fail_output_teardown) + + class FailingObserver(_CountingEvents): + def on_data_end(self, node: str, tag: Any, *args: Any, **kwargs: Any) -> None: + self.__getattr__("on_data_end")(node, tag, *args, **kwargs) + if end_fails and node == "pick" and tag.as_dict()["id"] == 0: + raise original + + events = FailingObserver() + with pytest.raises(RuntimeError, match="synthetic .* failure") as raised: + _run_observed(job, "sync", "continue", events) + assert raised.value is (original if end_fails else prefetch_error) + assert calls == [0, 1, 2] + tail_event = "data_crash" if end_fails else "data_end" + assert events.terminal("pick") == { + "0": ["data_end"], + "1": [tail_event], + "2": [tail_event], + } + assert events.ends_last("pick") + + +@pytest.mark.parametrize("callback", ["on_data_end", "on_data_crash"]) +def test_a_sync_observer_failure_ends_the_held_tail( + stored: dict[str, Any], tmp_path: Path, callback: str +) -> None: + """Report each held row once, preserving the observer failure.""" + entries = _entries(_table(_source()), "vector") + if callback == "on_data_crash": + entries[0] = _missing_reference(entries[0]) + calls: list[int] = [] + job = _picking_job(tmp_path, entries, calls) + failure = RuntimeError("synthetic row observer failure") + + class FailingObserver(_CountingEvents): + """Record the callback before raising for the first row.""" + + def __getattr__(self, name: str) -> Any: + record = super().__getattr__(name) + if name != callback: + return record + + def fail_first(node: str, tag: Any, *args: Any, **kwargs: Any) -> None: + record(node, tag, *args, **kwargs) + if node == "pick" and tag.as_dict()["id"] == 0: + raise failure + + return fail_first + + events = FailingObserver() + with pytest.raises(RuntimeError, match="synthetic row observer failure") as raised: + _run_observed(job, "sync", "continue", events) + assert raised.value is failure + assert calls == [0, 1, 2] + assert events.terminal("pick") == { + "0": [callback.removeprefix("on_")], + "1": ["data_crash"], + "2": ["data_crash"], + } + assert events.ends_last("pick") + + +@pytest.mark.parametrize("first_failure", ["record", "missing"]) +def test_a_sync_side_effect_stops_at_its_fatal_record_write( + stored: dict[str, Any], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + first_failure: str, +) -> None: + """Finish each delivery before invoking the next, honoring the failure policy.""" + from orcapod import PipelineJob + from orcapod.core.nodes.function_node import FunctionJobNode + from orcapod.databases import DeltaTableDatabase + from orcapod.errors import OrcapodDatabaseError + from orcapod.sources import DictSource + + entries = _entries(_table(_source()), "vector") + delivered: list[int] = [] + if first_failure == "missing": + entries[0] = _missing_reference(entries[0]) + + @function_pod(output_keys="ref", ctx_arg="ctx") + def deliver(slot: int, ctx: InvocationContext) -> SpiralDBEntry: + delivered.append(slot) + return entries[slot] + + rows: Any = [{"id": i, "slot": i} for i in range(len(entries))] + job = PipelineJob(name="deliver", database=DeltaTableDatabase(tmp_path / "db")) + with job: + deliver.pod( + DictSource(rows, tag_columns=["id"], tag_only_columns=True), label="deliver" + ) + if first_failure == "missing": + summary = _run(job, "sync", "continue") + assert summary.nodes["deliver"].failed == 1 + assert delivered == [0, 1, 2] + else: + + def fail_record(*args: Any, **kwargs: Any) -> None: + raise OrcapodDatabaseError("synthetic record failure") + + monkeypatch.setattr(FunctionJobNode, "_add_pipeline_record", fail_record) + with pytest.raises(OrcapodDatabaseError, match="synthetic record failure"): + _run(job, "sync", "continue") + assert delivered == [0] + + +def test_async_transport_failure_keeps_results_already_recorded( + stored: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A later input can reach the recorder while an earlier input is still waiting.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + from orcapod import PipelineJob + from orcapod.core.function_pod import FunctionPod + from orcapod.databases import DeltaTableDatabase + from orcapod.sources import DictSource + from orcapod.types import PodConfig + + table = _table(_source()) + vector = _entries(table, "vector")[1] + embeddings = _entries(table, "embeddings")[2] + started = asyncio.Event() + recorded = asyncio.Event() + wait_for_cancellation = asyncio.Event() + interrupted: list[int] = [] + + async def pick(slot: int) -> SpiralDBEntry: + if slot == 0: + started.set() + try: + await asyncio.wait_for(wait_for_cancellation.wait(), timeout=10) + except asyncio.CancelledError: + interrupted.append(slot) + raise + if slot == 2: + await asyncio.wait_for(recorded.wait(), timeout=10) + return embeddings + await asyncio.wait_for(started.wait(), timeout=10) + return vector + + class RecordGate(_CountingEvents): + """Release the failing result once row 1's record has been written.""" + + def on_data_end(self, node: str, tag: Any, *args: Any, **kwargs: Any) -> None: + self.__getattr__("on_data_end")(node, tag, *args, **kwargs) + if node == "pick" and tag.as_dict()["id"] == 1: + recorded.set() + + scan_keys = spiraldb_entries.scan_keys + + def fail_embeddings(table: Any, columns: Any, keys: Any) -> Any: + if "embeddings" in columns: + raise ConnectionError("synthetic transport failure") + return scan_keys(table, columns, keys) + + monkeypatch.setattr(spiraldb_entries, "scan_keys", fail_embeddings) + rows: Any = [{"id": i, "slot": i} for i in range(3)] + source = DictSource(rows, tag_columns=["id"], tag_only_columns=True) + root = tmp_path / "db" + job = PipelineJob(name="arrival", database=DeltaTableDatabase(root)) + with job: + FunctionPod.from_fn( + pick, output_keys="ref", pod_config=PodConfig(max_concurrency=3) + )(source, label="pick") + events = RecordGate() + with pytest.raises(Exception) as raised: + _run_observed(job, "async", "continue", events) + assert any( + isinstance(error, ConnectionError) for error in _error_chain(raised.value) + ) + assert interrupted == [0] + assert events.terminal("pick") == {"1": ["data_end"], "2": ["data_crash"]} + reopened = DeltaTableDatabase(root) + [path] = [ + p + for p in reopened.list_table_paths() + if p[1] == "pick" and p[-1].startswith("pdb") + ] + written = reopened.get_all_records(path) + assert written is not None + assert _values(written, "id") == [1] + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + job.run(load_only=True) + remaining = job.nodes["pick"].as_table() + assert _values(remaining, "id") == [1] + assert _entries(remaining, "ref") == [vector] + assert ( + "On the asynchronous path, results reach the recorder in arrival order" + in " ".join(_source_guide().split()) + ) + + +@pytest.mark.parametrize("error_policy", ["continue", "fail_fast"]) +def test_a_sync_node_end_observer_cannot_replace_the_hash_failure( + stored: dict[str, Any], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + error_policy: str, +): + """Preserve the original error in both the abort and fail-fast paths.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entry = _entries(_table(_source()), "vector")[0] + + def broken_scan(*args: Any, **kwargs: Any) -> Any: + raise ValueError("synthetic scan failure") + + if error_policy == "continue": + spiraldb_entries.clear_entry_cache() + monkeypatch.setattr(spiraldb_entries, "scan_keys", broken_scan) + else: + entry = _missing_reference(entry) + + class FailingObserver(_CountingEvents): + """Record callbacks before raising from the observer.""" + + def on_data_crash(self, node: str, *args: Any, **kwargs: Any) -> None: + self.__getattr__("on_data_crash")(node, *args, **kwargs) + if node == "pick" and error_policy == "fail_fast": + raise RuntimeError("synthetic crash observer failure") + + def on_node_end(self, node: str, *args: Any, **kwargs: Any) -> None: + super().on_node_end(node, *args, **kwargs) + if node == "pick": + raise RuntimeError("synthetic node-end observer failure") + + job = _picking_job(tmp_path, [entry], []) + events = FailingObserver() + expected = RuntimeError if error_policy == "continue" else SpiralDBEntryMissingError + with pytest.raises(expected) as raised: + _run_observed(job, "sync", error_policy, events) + if error_policy == "continue": + assert ( + str(raised.value) + == "Failed to process column 'ref': synthetic scan failure" + ) + assert isinstance(raised.value.__cause__, ValueError) + notes = getattr(raised.value, "__notes__", []) + assert any("synthetic node-end observer failure" in note for note in notes) + if error_policy == "fail_fast": + assert any("synthetic crash observer failure" in note for note in notes) + assert events.terminal("pick") == {"0": ["data_crash"]} + assert events.ends_last("pick") + + +@pytest.mark.parametrize("error_policy", ["fail_fast", "continue"]) +def test_an_input_read_error_after_a_missing_entry( + stored: dict[str, Any], tmp_path: Path, error_policy: str +): + """CodeRabbit on 9905e20 (function_node.py:3585): a sync input of references that + fails when read after its second row, whose entry is missing. Under ``fail_fast`` + the missing row's failure is reported and raised, as the row-by-row path stops + there before reading on; under ``continue`` the read error is raised after the + rows read before it are hashed.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + + @function_pod(output_keys=("size",)) + def size(vector: SpiralDBEntry) -> int: + return len(vector.key) + + source = _source_with_a_missing_entry() + job = PipelineJob(name="read", database=DeltaTableDatabase(tmp_path / "db")) + with job: + size.pod(source, label="size") + node: Any = job.nodes["size"] + real_hash = node.compute_instance_id + hashed: list[int] = [] + + def record_hash(tag: Any, data: Any) -> bytes: + hashed.append(tag.as_dict()["id"]) + return real_hash(tag, data) + + node.compute_instance_id = record_hash + + class Input: + def __getattr__(self, name: str) -> Any: + return getattr(source, name) + + def iter_data(self) -> Any: + rows = iter(source.iter_data()) + yield next(rows) + yield next(rows) + raise RuntimeError("synthetic input read failure") + + events = _Events() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + with pytest.raises(BaseException) as raised: + node.execute(Input(), observer=events, error_policy=error_policy) + chain = _error_chain(raised.value) + if error_policy == "fail_fast": + assert any(isinstance(e, SpiralDBEntryMissingError) for e in chain) + assert not any("synthetic input read failure" in str(e) for e in chain) + assert events.terminal("size") == {"0": ["data_end"], "1": ["data_crash"]} + else: + assert hashed == [0, 1] + assert any("synthetic input read failure" in str(e) for e in chain) + + +def test_a_commit_that_fails_in_a_held_batch_ends_every_row_held_behind_it( + stored: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit on 629cf51 (function_node.py:3182): when the commit after a held + row's record fails, that row keeps its end, every row held behind it crashes + with the commit's error before the node's end, reported once, and the commit's + error is the one raised. Three held rows.""" + from orcapod.core.nodes.function_node import FunctionJobNode + from orcapod.errors import OrcapodDatabaseError + + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + job = _picking_job(tmp_path, [entries[0], entries[1], entries[2]], calls) + real = FunctionJobNode._row_processed # pyright: ignore[reportPrivateUsage] + commits: list[int] = [] + + def failing_first(self: Any) -> None: + commits.append(1) + if len(commits) == 1: + raise OrcapodDatabaseError("synthetic commit failure") + real(self) + + monkeypatch.setattr(FunctionJobNode, "_row_processed", failing_first) + events = _CountingEvents() + with pytest.raises(BaseException) as raised: + _run_observed(job, "sync", "continue", events) + chain = _error_chain(raised.value) + assert isinstance(chain[0], OrcapodDatabaseError) + assert "synthetic commit failure" in str(chain[0]) + assert events.terminal("pick") == { + "0": ["data_end"], + "1": ["data_crash"], + "2": ["data_crash"], + } + assert events.ends_last("pick") + + +def test_an_aborted_async_record_stage_ends_every_held_row( + stored: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit on 629cf51 (function_node.py:5498): in ephemeral mode, stored + results whose end events wait for their hash, when hashing one stops the run (a + failing scan), every started row ends once, in a crash, before the node's end. + The first run stores the three results but records none (their references name + a missing entry), so the second run finds them in the result store.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + from orcapod.databases import InMemoryArrowDatabase + from orcapod.types import NodeConfig + + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + job = _picking_job(tmp_path, [_missing_reference(entries[0])] * 3, calls) + assert _run(job, "async").nodes["pick"].failed == 3 + node = job.nodes["pick"] + node.node_config = NodeConfig(is_result_ephemeral=True) + node.set_ephemeral_database(InMemoryArrowDatabase()) + + def broken(*args: Any, **kwargs: Any) -> Any: + raise ValueError("synthetic scan failure") + + spiraldb_entries.clear_entry_cache() + monkeypatch.setattr(spiraldb_entries, "scan_keys", broken) + events = _CountingEvents() + calls.clear() + with pytest.raises(BaseException) as raised: + _run_observed(job, "async", "continue", events) + assert any("synthetic scan failure" in str(e) for e in _error_chain(raised.value)) + started = { + e.split(" ")[2] for e in events.events if e.startswith("data_start pick") + } + # CodeRabbit on 1e627fc (test line 2908): the three rows are started and held + # before the scan fails, so the cleanup ends siblings held behind the failure. + assert started == {"0", "1", "2"} + assert events.terminal("pick") == {row: ["data_crash"] for row in started} + assert events.ends_last("pick") + + +def test_an_observer_failing_on_a_held_crash_keeps_the_run_error( + stored: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """Delta review of 7089f1f (function_node.py:5687): when the async record stage + stops (a failing scan) with three rows held, an observer that raises on row 1's + crash replaces nothing: rows 0 to 2 each get their crash, the node's end is + reported, and the run raises the scan failure, with the observer's failure noted + on it.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + from orcapod.databases import InMemoryArrowDatabase + from orcapod.types import NodeConfig + + entries = _entries(_table(_source()), "vector") + calls: list[int] = [] + job = _picking_job(tmp_path, [_missing_reference(entries[0])] * 3, calls) + assert _run(job, "async").nodes["pick"].failed == 3 + node = job.nodes["pick"] + node.node_config = NodeConfig(is_result_ephemeral=True) + node.set_ephemeral_database(InMemoryArrowDatabase()) + + def broken(*args: Any, **kwargs: Any) -> Any: + raise ValueError("synthetic scan failure") + + class FailsOnRowOneCrash(_CountingEvents): + """Records every event, then raises on row 1's crash.""" + + def __getattr__(self, name: str) -> Any: + record = super().__getattr__(name) + if name != "on_data_crash": + return record + + def crash(node: str, tag: Any, *args: Any, **kwargs: Any) -> None: + record(node, tag, *args, **kwargs) + if tag.as_dict().get("id") == 1: + raise RuntimeError("synthetic cleanup observer failure") + + return crash + + spiraldb_entries.clear_entry_cache() + monkeypatch.setattr(spiraldb_entries, "scan_keys", broken) + events = FailsOnRowOneCrash() + with pytest.raises(BaseException) as raised: + _run_observed(job, "async", "continue", events) + chain = _error_chain(raised.value) + assert any("synthetic scan failure" in str(e) for e in chain) + assert not any("synthetic cleanup observer failure" in str(e) for e in chain) + notes = [note for e in chain for note in getattr(e, "__notes__", [])] + assert any("synthetic cleanup observer failure" in note for note in notes) + assert events.terminal("pick") == {row: ["data_crash"] for row in ("0", "1", "2")} + assert events.ends_last("pick") + + +def test_an_observer_failing_on_the_active_async_crash_keeps_the_hash_error( + stored: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """The active async row's crash observer cannot replace its output hash error.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entry = _entries(_table(_source()), "vector")[0] + job = _picking_job(tmp_path, [entry], []) + + def broken_scan(*args: Any, **kwargs: Any) -> Any: + raise ValueError("synthetic scan failure") + + class FailsOnCrash(_CountingEvents): + """Record the crash before raising from its callback.""" + + def on_data_crash(self, node: str, tag: Any, data: Any, exc: Any) -> None: + super().__getattr__("on_data_crash")(node, tag, data, exc) + raise RuntimeError("synthetic crash observer failure") + + spiraldb_entries.clear_entry_cache() + monkeypatch.setattr(spiraldb_entries, "scan_keys", broken_scan) + events = FailsOnCrash() + with pytest.raises(BaseException) as raised: + _run_observed(job, "async", "continue", events) + chain = _error_chain(raised.value) + assert any("synthetic scan failure" in str(error) for error in chain) + assert not any("synthetic crash observer failure" in str(error) for error in chain) + notes = [note for error in chain for note in getattr(error, "__notes__", [])] + assert any("synthetic crash observer failure" in note for note in notes) + assert events.terminal("pick") == {"0": ["data_crash"]} + assert events.ends_last("pick") + + +def test_an_observer_failing_on_a_sync_abort_keeps_the_hash_error( + stored: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit on 1e627fc (function_node.py:3135): when a held result's hash + raises another error than a missing entry (a failing scan) in a sync run under + ``continue``, an observer that raises on a crash report replaces nothing: rows 0 + to 2 each get their crash, the node's end is reported, and the run raises the + hash error, with the observer's failure noted on it. Once for the failing row's + own report (row 0), once for a row held behind it (row 1).""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entries = _entries(_table(_source()), "vector") + + def broken(*args: Any, **kwargs: Any) -> Any: + raise ValueError("synthetic scan failure") + + for failing_row in (0, 1): + calls: list[int] = [] + job = _picking_job( + tmp_path / str(failing_row), [entries[0], entries[1], entries[2]], calls + ) + + class FailsOnOneCrash(_CountingEvents): + """Records every event, then raises on one row's crash.""" + + def __getattr__(self, name: str) -> Any: + record = super().__getattr__(name) + if name != "on_data_crash": + return record + + def crash(node: str, tag: Any, *args: Any, **kwargs: Any) -> None: + record(node, tag, *args, **kwargs) + if tag.as_dict().get("id") == failing_row: + raise RuntimeError("synthetic abort observer failure") + + return crash + + spiraldb_entries.clear_entry_cache() + monkeypatch.setattr(spiraldb_entries, "scan_keys", broken) + events = FailsOnOneCrash() + with pytest.raises(BaseException) as raised: + _run_observed(job, "sync", "continue", events) + chain = _error_chain(raised.value) + assert any("synthetic scan failure" in str(e) for e in chain) + assert not any("synthetic abort observer failure" in str(e) for e in chain) + notes = [note for e in chain for note in getattr(e, "__notes__", [])] + assert any("synthetic abort observer failure" in note for note in notes) + assert events.terminal("pick") == { + row: ["data_crash"] for row in ("0", "1", "2") + } + assert events.ends_last("pick") + + +def test_a_primary_key_that_cannot_name_a_row_is_refused_beside_an_encoded_column( + tmp_path: Path, +): + """CodeRabbit on 629cf51 (spiraldb_table_source.py:599): a reference names its row + by the primary key, so a source over a table with an encoded column and a binary + primary-key column is refused when built, also with string ``record_id_columns``; + the same table without the encoded column is accepted.""" + project = fake_spiral_sdk.ExternalProject(_PROJECT) + rows = _plain_rows().append_column( + "blob", pa.array([b"a", b"b", b"c"], pa.large_binary()) + ) + key = pa.schema([rows.schema.field("unit"), rows.schema.field("blob")]) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + plain = project.create_table("default.binkey_plain", key_schema=key) + plain.write(rows) + encoded = project.create_table("default.binkey", key_schema=key) + encoded.write(rows) + encoded.write_encoded( + "vector", + _encoded_values(0), + pa.field("vector", _STORAGE, metadata=_ENCODING), + ) + assert _source("binkey_plain", record_id_columns=["unit", "time"]) is not None + for kwargs in ({}, {"record_id_columns": ["unit", "time"]}): + with pytest.raises(ValueError, match=r"'blob' has type large_binary"): + _source("binkey", **kwargs) + + +def test_a_table_without_a_primary_key_is_refused_beside_an_encoded_column( + stored: dict[str, Any], +): + """Delta review of 7089f1f (spiraldb_table_source.py:416): a reference names its + row by the primary key, so a table with an encoded column and an empty primary key + is refused when built, also with explicit ``record_id_columns`` (which used to + give references named ``row_0`` that could not be read). The same key metadata as + ``test_a_table_without_a_key_schema_raises``; the table without the encoded + column still builds with explicit ``record_id_columns``.""" + from unittest.mock import PropertyMock, patch + + from orcapod.databases.spiraldb_connector import SpiralDBTable + + with patch.object( + SpiralDBTable, "key_columns", new_callable=PropertyMock, return_value=[] + ): + assert _source("plain", record_id_columns=["unit", "time"]) is not None + for kwargs in ({}, {"record_id_columns": ["unit", "time"]}): + with pytest.raises(ValueError, match="no primary key"): + _source("encoded", **kwargs) + + +def test_two_reads_missing_one_version_together_share_its_handle( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit on 629cf51 (spiraldb_table_source.py:1199): when two reads open one + version at once, the handle stored first is the one both use, so the version a + reference records and the scan read are one snapshot. The race is simulated: the + other read stores its handle while this one opens.""" + from orcapod.databases import spiraldb_connector as connector + + source = _source() + table: Any = source._handle # pyright: ignore[reportPrivateUsage] + real = connector._open_keyed_table_by_id # pyright: ignore[reportPrivateUsage] + first: list[Any] = [] + + def racing(client: Any, table_id: str, asof: Any) -> Any: + if not first: + first.append(real(client, table_id, asof)) + table._versions[str(asof)] = first[0] # the other read stored first + return real(client, table_id, asof) + + monkeypatch.setattr(connector, "_open_keyed_table_by_id", racing) + version = int(str(table._table.version_id)) # pyright: ignore[reportPrivateUsage] + older = version - 1 + handles = [table._at(older), table._at(older)] # pyright: ignore[reportPrivateUsage] + assert handles[0] is first[0] + assert handles[1] is first[0] diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index 5ebeaf084..da976b243 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -26,7 +26,7 @@ from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path -from typing import Any, cast +from typing import Any, NamedTuple, cast from unittest.mock import patch import pyarrow as pa @@ -84,6 +84,12 @@ "negative NaN below -inf, -0.0 below 0.0, positive NaNs above inf (seen November 26, " "2026, ITL-998); a null meets no comparison", "rows": "rows come in key order; filter before limit", + "vortex": "a column stored in a Vortex encoding (vortex.turboquant), at the top level " + "or as a struct field, reads with its ARROW:extension:name and metadata on its field " + "(seen November 29, 2026, ITL-1789)", + "key-range": "a scan's key range of one full key (both bounds that key, inclusive) " + "reads at most that row; several ranges read their rows range after range " + "(spiral-sdk 0.16.74 KeyedTable.scan docstring, read December 2, 2026)", "list": "the documented listing filters a dataset and pages; a page can be empty " "(documented, not seen)", "table-metadata": "spiral-sdk 0.16.78 (November 26, 2026): get_metadata and " @@ -126,6 +132,8 @@ class ScanRecord: columns: list[str] | None filter: Any limit: int | None + count: bool = False + key_ranges: int = 0 batches_read: int = 0 closed: bool = False @@ -795,6 +803,20 @@ def __repr__(self) -> str: return " & ".join(f"{name} {op} {w.value!r}" for name, w, op in self.terms) +class KeyBound(NamedTuple): + """Stands in for ``spiral.KeyBound``.""" + + values: tuple[_Literal, ...] + inclusive: bool = True + + +class KeyRange(NamedTuple): + """Stands in for ``spiral.KeyRange``.""" + + start: KeyBound | None = None + end: KeyBound | None = None + + def column(name: str) -> _Column: """Stand in for ``spiral.column``.""" return _Column(name) @@ -897,7 +919,7 @@ def to_reader(self) -> FakeReader: log = ( schema_scan_log if self._record.identifier.endswith(f".{SCHEMA_TABLE}") - else (count_log if self._record.columns else scan_log) + else (count_log if self._record.count else scan_log) ) log.append(self._record) return FakeReader(self._rows, self._record, self._batch_rows) @@ -949,9 +971,21 @@ def scan( filter: FakePredicate | None = None, limit: int | None = None, batch_rows: int | None = None, + key_ranges: list[KeyRange] | None = None, ) -> FakeScan: - """Plan a scan (``rows``, ``literal``, ``float-eq``, ``float-order``).""" + """Plan a scan (``rows``, ``literal``, ``float-eq``, ``float-order``, + ``key-range``).""" rows = self._store.read(self.resource_id, self._version) + if key_ranges: + # Several ranges are a union, read range after range (spiral-sdk 0.16.74, + # ``KeyedTable.scan``: "replays ranges in supplied order and retains + # overlaps"). + rows = pa.concat_tables( + [ + rows.filter(pa.array(self._one_key(rows, r), pa.bool_())) + for r in key_ranges + ] + ) for name, wanted, op in filter.terms if filter else (): if rows.schema.field(name).type != wanted.type: raise SpiralError( @@ -990,12 +1024,42 @@ def scan( columns, filter, limit, + count=columns == [self._table["keys"][0]], + key_ranges=len(key_ranges or ()), ) size = ( scan_batch_rows if batch_rows is None else min(batch_rows, scan_batch_rows) ) return FakeScan(rows, record, size) + def _one_key(self, rows: pa.Table, key_range: KeyRange) -> list[bool]: + """Return which rows have the one key both bounds of ``key_range`` name.""" + start, end = key_range + if ( + start is None + or end is None + or start != end + or not start.inclusive + or len(start.values) != len(self._table["keys"]) + ): + raise NotImplementedError("the fake reads the key range of one full key") + keep = [True] * rows.num_rows + for name, wanted in zip(self._table["keys"], start.values): + stored: Any = rows.column(name) + if stored.type != wanted.type: + raise SpiralError( + f"key range: column {name!r} is {stored.type}, got {wanted.type}" + ) + given: Any = pa.array([wanted.value], wanted.type) + if pa.types.is_temporal(wanted.type): + # Both as their counts: a date literal holds a Python date. + width = pa.int32() if pa.types.is_date32(wanted.type) else pa.int64() + stored, given = stored.cast(width), given.cast(width) + values: list[Any] = stored.to_pylist() + (value,) = given.to_pylist() + keep = [k and v == value for k, v in zip(keep, values)] + return keep + def append(self, data: pa.Table) -> FakeKeyedTable: """Upsert rows and return the new snapshot.""" writer = self.writer() @@ -1214,6 +1278,8 @@ def fake_http_get_json(url: str, token: str | None) -> dict[str, Any]: gte=gte, and_=and_, drop_column=drop_column, + KeyBound=KeyBound, + KeyRange=KeyRange, ) @@ -1240,6 +1306,40 @@ def write(self, rows: pa.Table) -> None: """Upsert rows.""" _open(self._store, self._table, None).append(rows) + def write_encoded( + self, name: str, array: pa.Array[Any], field: pa.Field[Any] + ) -> None: + """Add column ``name`` stored in a Vortex encoding to the latest version + (``vortex``): ``field`` is the column's field as SpiralDB reports it, with the + encoding's extension name and metadata on it or on a struct field inside it. + The rows stay in their order; ``array`` holds one value per row.""" + rows = self._store.read( + self._table["id"], max([0, *self._store.versions(self._table["id"])]) + ) + rows = rows.append_column(field.with_name(name), array) + # Columns in the order SpiralDB gives them (``order``), as a write would. + keys = self._table["keys"] + values = [f for f in rows.schema if f.name not in keys] + order = [ + *keys, + *sorted(f.name for f in values if not pa.types.is_struct(f.type)), + *sorted(f.name for f in values if pa.types.is_struct(f.type)), + ] + self._store.write(self._table["id"], rows.select(order)) + + def rewrite_rows( + self, keep: pa.Array[Any], column: str, array: pa.Array[Any] + ) -> None: + """Write a new version: the latest rows where ``keep`` is true, with ``column`` + replaced by ``array`` (one value per kept row, its field unchanged). Rewrites + an encoded entry under its key, or deletes rows, as another program would.""" + rows = self._store.read( + self._table["id"], max([0, *self._store.versions(self._table["id"])]) + ).filter(keep) + index = rows.schema.get_field_index(column) + rows = rows.set_column(index, rows.schema.field(index), array) + self._store.write(self._table["id"], rows) + def record(self, schema: pa.Schema) -> None: """Migrate the dataset, with ``schema`` as what this table was written with.""" migrate( @@ -1281,16 +1381,31 @@ def drop_table(self, identifier: str) -> None: @contextmanager def install(root: Path | str): - """Route Orcapod's SpiralDB calls to the fake, with tables stored under ``root``.""" - with ( - patch.dict(os.environ, {_ROOT_ENV: str(root)}), - patch("orcapod.databases.spiraldb_connector.sp", fake_module), - patch("orcapod.databases.spiraldb_connector.require_sign_in", lambda: None), - patch( - "orcapod.databases.spiraldb_connector._http_get_json", fake_http_get_json - ), - ): - yield + """Route Orcapod's SpiralDB calls to the fake, with tables stored under ``root``. + + The process's SpiralDB entry cache, its trusted service addresses and its clients by + service address start empty and are emptied again at the end, so no test sees + another's entries or store. + """ + from orcapod.core.sources.spiraldb_entries import clear_entry_cache + from orcapod.databases.spiraldb_connector import forget_trusted_services + + clear_entry_cache() + forget_trusted_services() + try: + with ( + patch.dict(os.environ, {_ROOT_ENV: str(root)}), + patch("orcapod.databases.spiraldb_connector.sp", fake_module), + patch("orcapod.databases.spiraldb_connector.require_sign_in", lambda: None), + patch( + "orcapod.databases.spiraldb_connector._http_get_json", + fake_http_get_json, + ), + ): + yield + finally: + clear_entry_cache() + forget_trusted_services() def migrate( diff --git a/tests/test_databases/test_spiraldb_keyed_table_deprecation.py b/tests/test_databases/test_spiraldb_keyed_table_deprecation.py index 48ce773b6..57632409e 100644 --- a/tests/test_databases/test_spiraldb_keyed_table_deprecation.py +++ b/tests/test_databases/test_spiraldb_keyed_table_deprecation.py @@ -36,6 +36,10 @@ class _NativeTable: class _NativeClient: """A native client that answers an open of table ``t`` and nothing else.""" + # The connector reads its service address when built (ITL-1789), as on the real + # native client. + api_url = "https://api.stub.invalid" + def keyed_table( self, project: str, dataset: str, name: str, *, asof: int | None = None ) -> _NativeTable: diff --git a/tests/test_hashing/golden/cases.py b/tests/test_hashing/golden/cases.py index c13f47da3..49dde2066 100644 --- a/tests/test_hashing/golden/cases.py +++ b/tests/test_hashing/golden/cases.py @@ -1003,6 +1003,7 @@ def schema_source_stream_builder() -> dict[str, Any]: for variant, kwargs in variants.items(): result = builder.build(_builder_table(), tag_columns=["subject"], **kwargs) out[f"{variant}.schema_hash"] = result.schema_hash + assert result.table_hash is not None out[f"{variant}.table_hash"] = result.table_hash.to_string() out[f"{variant}.source_id"] = result.source_id out[f"{variant}.system_tag_columns"] = [ @@ -1187,6 +1188,7 @@ def build(kind: str, rows: list[dict[str, Any]], **kw: Any) -> Any: kind_part="arrow_table_v1", **kwargs, ) + assert result.table_hash is not None out[f"builder.{variant}.{order}.table_hash"] = result.table_hash.to_string() return out diff --git a/tests/test_hashing/test_schema_hash_storage_form.py b/tests/test_hashing/test_schema_hash_storage_form.py index efa1fe6c7..50d62cff0 100644 --- a/tests/test_hashing/test_schema_hash_storage_form.py +++ b/tests/test_hashing/test_schema_hash_storage_form.py @@ -94,6 +94,7 @@ def _hasher() -> Any: "orcapod.path": False, "orcapod.polars.dataframe": True, "orcapod.polars.series": True, + "orcapod.spiraldb.entry": True, "orcapod.torch.tensor": True, "orcapod.upath": False, "orcapod.uuid": False, @@ -596,18 +597,26 @@ def _holder_classes(name: str) -> dict[str, Any]: return {"exact class field": exact, "structural class field": structural} +_NOT_IN_A_CLASS = frozenset({"orcapod.spiraldb.entry"}) +"""Types a user class may not hold (ITL-1789: a reference lives in a column of its +own); their class-field forms are refused, as ``test_a_class_field_is_refused_for`` +checks.""" + + def _orcapod_containers(name: str) -> dict[str, pa.DataType]: - """Orcapod's containers of the named type: native containers and user classes.""" + """Orcapod's containers of the named type: native containers and user classes + (for a type a class may hold).""" python_type = _python_type(name) - holders = _holder_classes(name) - exact = holders["exact class field"] types: dict[str, Any] = { "list[T]": list[python_type], "set[T]": set[python_type], "list[list[T]]": list[list[python_type]], - **holders, - "list[exact class]": list[exact], } + if name not in _NOT_IN_A_CLASS: + holders = _holder_classes(name) + types.update(holders) + exact = holders["exact class field"] + types["list[exact class]"] = list[exact] return {label: _arrow_type(python_type) for label, python_type in types.items()} @@ -661,7 +670,9 @@ def test_a_dict_of_the_type_is_refused_at_definition(self, name: str) -> None: def test_containers_of_two_types_differ_in_every_form(label: str) -> None: """A container of one named type never hashes as a container of another.""" per_type = { - name: _schema(_orcapod_containers(name)[label]) for name in _available_names() + name: _schema(_orcapod_containers(name)[label]) + for name in _available_names() + if label in _orcapod_containers(name) } for form in ("live", "metadata", "unregistered"): hashes = { @@ -670,6 +681,20 @@ def test_containers_of_two_types_differ_in_every_form(label: str) -> None: assert len(set(hashes.values())) == len(hashes), form +@pytest.mark.parametrize("name", sorted(_NOT_IN_A_CLASS)) +def test_a_class_field_is_refused_for(name: str) -> None: + """A type a user class may not hold is refused when an exact or a structural + class with a field of it, or of a list of it, is converted (ITL-1789).""" + list_holder = dataclasses.make_dataclass( + f"HoldsList_{_safe(name)}", [("f", list[_python_type(name)])] + ) + list_holder.__module__ = __name__ + holders = [*_holder_classes(name).values(), list_holder] + for holder in holders: + with pytest.raises(NestedTypeNotStorableError, match="inside a field"): + _arrow_type(holder) + + # ── 4. identity paths: sources, slots, saved jobs, sync and async ──────────── KINDS = ("orcapod.file", "orcapod.directory", "orcapod.numpy.ndarray") diff --git a/tests/test_logical_types/test_provisional_hash_warning.py b/tests/test_logical_types/test_provisional_hash_warning.py index dbd639fd1..fe3cf55d2 100644 --- a/tests/test_logical_types/test_provisional_hash_warning.py +++ b/tests/test_logical_types/test_provisional_hash_warning.py @@ -36,6 +36,7 @@ # The test hook that forgets which types have warned; not a public entry point. from orcapod.logical_types.provisional import reset_provisional_warnings +from orcapod.logical_types.spiraldb_entry_type import SpiralDBEntry from orcapod.sources import DictSource REGISTRATION = Path(contexts_package.__file__).parent / "logical_types.json" @@ -53,6 +54,9 @@ def _value(name: str) -> Any: return pd.Series([1, 2], name="a") if name == "orcapod.polars.dataframe": return pl.DataFrame({"a": [1, 2]}) + if name == "orcapod.spiraldb.entry": + # Its hash is its entry's content: an entry the fake SpiralDB holds. + return SpiralDBEntry(*_ENTRY) assert name == "orcapod.polars.series" return pl.Series("a", [1, 2]) @@ -64,10 +68,44 @@ def _value(name: str) -> Any: "orcapod.pandas.series": pd.Series, "orcapod.polars.dataframe": pl.DataFrame, "orcapod.polars.series": pl.Series, + "orcapod.spiraldb.entry": SpiralDBEntry, } NAMES = sorted(PYTHON_TYPES) +_ENTRY: list[Any] = [] +"""The fields of a ``SpiralDBEntry`` naming an entry of the fake SpiralDB +(``_fake_spiral``).""" + + +@pytest.fixture(autouse=True) +def _fake_spiral(tmp_path_factory: pytest.TempPathFactory) -> Iterator[None]: + """A fake SpiralDB holding one entry, which ``_value`` names (ITL-1789).""" + from tests.test_databases import fake_spiral_sdk + + with fake_spiral_sdk.install(tmp_path_factory.mktemp("spiral")): + project = fake_spiral_sdk.ExternalProject("test-project-123456") + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + table = project.create_table( + "default.entries", key_schema=[("k", pa.int64())] + ) + table.write(pa.table({"k": [1], "v": pa.array([b"\x01\x02"], pa.binary())})) + _ENTRY[:] = [ + table.table_id, + table.last_modified_at(), + '{"k":1}', + "v", + "https://api.fake.invalid", + ] + # The test builds no connector, so it trusts the fake's address itself. + from orcapod.databases.spiraldb_connector import trust_service + + trust_service("https://api.fake.invalid") + yield + _ENTRY.clear() + + @pytest.fixture(autouse=True) def _fresh_bookkeeping() -> Iterator[None]: """Every test starts as a new process would: no type has warned yet.""" @@ -127,7 +165,9 @@ def test_the_warning_is_a_public_user_warning() -> None: assert ProvisionalHashWarning.__module__ == "orcapod.errors" -def test_the_six_library_value_types_are_declared_provisional() -> None: +def test_the_library_value_types_and_spiraldb_entries_are_declared_provisional() -> ( + None +): assert sorted(_registration()["provisional"]) == NAMES diff --git a/tests/test_logical_types/test_spiraldb_entry_type.py b/tests/test_logical_types/test_spiraldb_entry_type.py new file mode 100644 index 000000000..68802355a --- /dev/null +++ b/tests/test_logical_types/test_spiraldb_entry_type.py @@ -0,0 +1,428 @@ +"""``orcapod.SpiralDBEntry`` and its logical type ``orcapod.spiraldb.entry`` (ITL-1789). + +The reference itself: its fields, equality, immutability, the logical type's identifier +and storage, the digest of an entry's content (``entry_content_hash``), and sources over +references, which need a given source id. Fetching and hashing entries, and reading +them, are tested with the SpiralDB source +(``tests/test_core/sources/test_spiraldb_table_source_encoded.py``). No test here +reaches SpiralDB: none installs a fake, so a fetch would fail. +""" + +from __future__ import annotations + +import pickle +from dataclasses import dataclass +from typing import Any + +import pyarrow as pa +import pytest + +import orcapod as op +from orcapod import function_pod +from orcapod.errors import InputValidationError +from orcapod.logical_types.identifier import logical_type_identifier +from orcapod.logical_types.spiraldb_entry_type import ( + SPIRALDB_ENTRY_HASH_LABEL, + SPIRALDB_ENTRY_STORAGE, + LogicalSpiralDBEntry, + SpiralDBEntry, + entry_content_hash, +) +from orcapod.sources import ArrowTableSource, DictSource, ListSource + +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") + +_SERVICE = "https://spiral.example.invalid" +"""A synthetic service address.""" + +_FIELDS: dict[str, Any] = { + "table_id": "table_a", + "version": 7, + "key": '{"unit":"u1","time":"2026-01-01T00:00:00Z"}', + "column": "vector", + "service": _SERVICE, +} + + +def _entry(**changes: Any) -> SpiralDBEntry: + fields = {**_FIELDS, **changes} + return SpiralDBEntry( + fields["table_id"], + fields["version"], + fields["key"], + fields["column"], + fields["service"], + ) + + +def _reference_array(*entries: SpiralDBEntry) -> pa.ExtensionArray[Any]: + storage = pa.array( + [LogicalSpiralDBEntry().python_to_storage(e) for e in entries], + SPIRALDB_ENTRY_STORAGE, + ) + return pa.ExtensionArray.from_storage( + LogicalSpiralDBEntry().get_arrow_extension_type(), storage + ) + + +def test_is_exported_at_the_top_level(): + """``orcapod.SpiralDBEntry`` is the class.""" + assert op.SpiralDBEntry is SpiralDBEntry + + +def test_fields_equality_and_hash(): + """Two references with equal fields are equal and hash alike; any field tells + them apart.""" + assert _entry() == _entry() + assert hash(_entry()) == hash(_entry()) + for name, other in ( + ("table_id", "table_b"), + ("version", 8), + ("key", '{"unit":"u2","time":"2026-01-01T00:00:00Z"}'), + ("column", "embeddings"), + ("service", "https://other.example.invalid"), + ): + assert _entry(**{name: other}) != _entry(), name + entry = _entry() + assert ( + entry.table_id, + entry.version, + entry.key, + entry.column, + entry.service, + ) == tuple(_FIELDS.values()) + + +def test_fields_are_read_only_and_it_pickles(): + """No field can be set; a pickled reference comes back equal.""" + entry = _entry() + with pytest.raises(AttributeError): + entry.version = 9 # pyright: ignore[reportAttributeAccessIssue] + with pytest.raises(AttributeError): + entry.service = "x" # pyright: ignore[reportAttributeAccessIssue] + assert pickle.loads(pickle.dumps(entry)) == entry + + +@pytest.mark.parametrize( + ("name", "value"), + [ + ("table_id", 1), + ("version", "7"), + ("version", True), + ("key", None), + ("column", b"v"), + ("service", None), + ], +) +def test_refuses_a_field_of_another_type(name: str, value: Any): + """Each field takes exactly its type (a bool is not a version).""" + with pytest.raises(TypeError, match=name): + _entry(**{name: value}) + + +def test_identifier_and_storage(): + """Extension ``orcapod.spiraldb.entry``, metadata version 1 hashed by the entry's + content (``spiraldb_entry_v1``), over a struct of five non-null fields.""" + extension = LogicalSpiralDBEntry().get_arrow_extension_type() + identifier = logical_type_identifier(LogicalSpiralDBEntry()) + + assert SPIRALDB_ENTRY_HASH_LABEL == "spiraldb_entry_v1" + assert identifier.name == "orcapod.spiraldb.entry" + assert identifier.metadata == b'{"value_hash":"spiraldb_entry_v1","version":1}' + assert extension.storage_type == SPIRALDB_ENTRY_STORAGE + assert [f.name for f in SPIRALDB_ENTRY_STORAGE] == [ + "table_id", + "version", + "key", + "column", + "service", + ] + assert not any(f.nullable for f in SPIRALDB_ENTRY_STORAGE) + + +def test_storage_round_trip(): + """A reference's stored struct gives the same reference back.""" + logical = LogicalSpiralDBEntry() + for entry in (_entry(), _entry(version=8, service="https://b.example.invalid")): + assert logical.storage_to_python(logical.python_to_storage(entry)) == entry + + +_ENCODING = { + b"ARROW:extension:name": b"vortex.turboquant", + b"ARROW:extension:metadata": b"CAkQBBgIICooAzIBQA==", +} + + +def _entry_table( + name: str = "vector", + norm: float = 1.5, + codes: tuple[int, ...] = (1, 2, 3, 4), + metadata: dict[bytes, bytes] | None = None, +) -> pa.Table: + """One synthetic entry: a struct of a norm and codes, with an encoding's metadata.""" + storage = pa.struct( + [ + pa.field("norms", pa.float32()), + pa.field("codes", pa.list_(pa.field("item", pa.uint8(), False), 4)), + ] + ) + value = pa.array([{"norms": norm, "codes": list(codes)}], storage) + field = pa.field( + name, storage, metadata=_ENCODING if metadata is None else metadata + ) + return pa.Table.from_arrays([value], schema=pa.schema([field])) + + +def test_entry_content_hash_is_the_content(): + """The entry's hash is labelled ``spiraldb_entry_v1``; equal content hashes alike + under any column name; a value, a bit (``-0.0`` against ``0.0``) or the encoding's + metadata moves it.""" + base = entry_content_hash(_entry_table()) + + assert base.method == SPIRALDB_ENTRY_HASH_LABEL + assert entry_content_hash(_entry_table()) == base + assert entry_content_hash(_entry_table(name="embeddings")) == base + for changed in ( + _entry_table(norm=2.5), + _entry_table(codes=(1, 2, 3, 5)), + _entry_table(metadata={b"ARROW:extension:name": b"vortex.other"}), + _entry_table(metadata={}), + ): + assert entry_content_hash(changed) != base + assert entry_content_hash(_entry_table(norm=-0.0)) != entry_content_hash( + _entry_table(norm=0.0) + ) + + +@pytest.mark.parametrize("rows", [0, 2]) +def test_entry_content_hash_refuses_other_than_one_row(rows: int): + """An entry is one row and one column.""" + table = _entry_table() + table = pa.concat_tables([table] * rows) if rows else table.slice(0, 0) + with pytest.raises(ValueError, match="one row and one column"): + entry_content_hash(table) + + +def _rows() -> list[dict[str, Any]]: + return [ + {"id": 1, "label": "a", "ref": _entry(), "other": _entry(column="embeddings")}, + { + "id": 2, + "label": "b", + "ref": _entry(key='{"unit":"u2","time":"2026-01-01T00:00:00Z"}'), + "other": _entry( + key='{"unit":"u2","time":"2026-01-01T00:00:00Z"}', column="embeddings" + ), + }, + ] + + +def test_a_dict_source_over_references_needs_a_source_id(): + """A source over references has no default source id: hashing its table would + fetch every entry. The error names the columns, in name order.""" + rows: Any = _rows() + with pytest.raises(ValueError, match=r"\['other', 'ref'\].*source_id"): + DictSource(rows, tag_columns=["id"], tag_only_columns=True) + + +def test_an_arrow_table_source_over_references_needs_a_source_id(): + """The same refusal for an Arrow table source, with the columns in another order.""" + table = pa.table( + { + "ref": _reference_array(_entry(), _entry(version=8)), + "id": pa.array([1, 2], pa.int64()), + "other": _reference_array(_entry(column="x"), _entry(column="y")), + } + ) + with pytest.raises(ValueError, match=r"\['other', 'ref'\].*source_id"): + ArrowTableSource(table, tag_columns=["id"], tag_only_columns=True) + + +def test_a_list_source_over_references_needs_a_source_id(): + """And for a list source.""" + with pytest.raises(ValueError, match=r"\['ref'\].*source_id"): + ListSource("ref", [_entry(), _entry(version=8)]) + + +def test_a_source_over_references_with_a_source_id_builds_and_passes_them_on(): + """Given a source id, the source builds without fetching anything (no SpiralDB is + reachable here), and a function pod outside a job takes and returns the references + unchanged, in a column of the logical type.""" + rows: Any = _rows() + source = DictSource( + rows, tag_columns=["id"], tag_only_columns=True, source_id="refs" + ) + seen: list[SpiralDBEntry] = [] + + @function_pod(output_keys=("same", "column")) + def keep(ref: SpiralDBEntry) -> tuple[SpiralDBEntry, str]: + seen.append(ref) + return ref, ref.column + + table = keep.pod(source.select_data_columns(["ref"])).as_table() + + first, second = rows[0]["ref"], rows[1]["ref"] + assert sorted(seen, key=lambda e: e.key) == [first, second] + assert table.schema.field("same").type.extension_name == "orcapod.spiraldb.entry" + stored: list[Any] = table.column("same").to_pylist() + assert [LogicalSpiralDBEntry().storage_to_python(v) for v in stored] == [ + first, + second, + ] + assert table.column("column").to_pylist() == ["vector", "vector"] + + +@dataclass +class _HoldsAReference: + """A user class with a field of entry references.""" + + ref: SpiralDBEntry + count: int + + +@dataclass +class _HoldsAHolder: + """A user class whose field is a user class holding a reference.""" + + inner: _HoldsAReference + name: str + + +@dataclass +class _HoldsReferences: + """A user class with a list of entry references.""" + + refs: list[SpiralDBEntry] + + +@op.dataclass +class _StructuralHolder: + """A structural class with a field of entry references.""" + + ref: SpiralDBEntry + + +@dataclass +class _Plain: + """A user class of plain fields.""" + + count: int + name: str + + +_REFUSED = r"declares a SpiralDBEntry inside a field.*column of its own" + + +@pytest.mark.parametrize( + ("column", "value"), + [ + ("held", _HoldsAReference(_entry(), 1)), + ("deep", _HoldsAHolder(_HoldsAReference(_entry(version=8), 2), "x")), + ("listed", _HoldsReferences([_entry(), _entry(version=8)])), + ("structural", _StructuralHolder(_entry())), + ], +) +def test_a_reference_inside_a_user_class_is_refused(column: str, value: Any): + """Review B6 of fd64224: a reference inside a user class (a field, a nested class's + field, a list field, a structural class) would hash as its stored fields, not its + entry's content; it is refused where the class is declared, with or without a + source id, beside a plain column and a column of references.""" + rows: Any = [{"id": 1, "plain": 3, "ref": _entry(column="x"), column: value}] + with pytest.raises(ValueError, match=_REFUSED): + DictSource(rows, tag_columns=["id"], tag_only_columns=True, source_id="held") + with pytest.raises(ValueError, match=_REFUSED): + DictSource(rows, tag_columns=["id"], tag_only_columns=True) + + +def test_a_function_declaring_a_reference_inside_a_user_class_is_refused(): + """Review B6 of fd64224: a function pod taking or returning such a class is + refused where it is declared, for an input and for an output.""" + with pytest.raises(ValueError, match=_REFUSED): + + @function_pod(output_keys=("n",)) + def takes(plain: int, held: _HoldsAReference) -> int: + """Takes the class as an input: refused at declaration.""" + return held.count + plain + + with pytest.raises(ValueError, match=_REFUSED): + + @function_pod(output_keys=("n", "held")) + def returns(n: int) -> tuple[int, _HoldsReferences]: + """Returns the class as an output: refused at declaration.""" + return n, _HoldsReferences([]) + + +@pytest.mark.parametrize( + "value", + [{"a": _entry(), "b": _entry(version=8)}, (_entry(), 1)], + ids=["dict", "tuple"], +) +def test_a_reference_in_a_dict_or_tuple_is_refused(value: Any): + """Review B6 of fd64224: a dict value or a tuple field holding a reference is + refused where its type is converted, as any logical type there (a tuple of a + logical type is not supported at all).""" + rows: Any = [{"id": 1, "plain": 3, "held": value}] + refused = "cannot be a dict key or value or a tuple|Unsupported annotation: tuple" + with pytest.raises(ValueError, match=refused): + DictSource(rows, tag_columns=["id"], tag_only_columns=True, source_id="held") + + +def test_an_arrow_struct_holding_references_is_refused(): + """Review B6 of fd64224: an Arrow table whose struct or map column holds references + is refused when its source is built, naming the columns in name order; a list of + references in a column is accepted.""" + refs = _reference_array(_entry(), _entry(version=8)) + struct = pa.StructArray.from_arrays([refs, pa.array([1, 2])], names=["ref", "n"]) + table = pa.table( + { + "id": pa.array([1, 2], pa.int64()), + "z_held": struct, + "a_held": struct, + "plain": pa.array([3, 4], pa.int64()), + } + ) + with pytest.raises(InputValidationError, match=r"\['a_held', 'z_held'\]"): + ArrowTableSource( + table, tag_columns=["id"], tag_only_columns=True, source_id="s" + ) + rows: list[dict[str, Any]] = [ + {"id": 1, "refs": [_entry(), _entry(version=8)], "plain": 3} + ] + listed = DictSource( + rows, + tag_columns=["id"], + tag_only_columns=True, + source_id="listed", + ) + assert listed.as_table().num_rows == 1 + + +def test_a_user_class_without_references_is_unchanged(): + """Review B6 of fd64224: the refusal concerns references only: a user class of + plain fields and a column of references build side by side, and the class's + identity does not move (its golden values are checked by the golden tests).""" + + rows: Any = [{"id": 1, "held": _Plain(1, "a"), "ref": _entry()}] + source = DictSource(rows, tag_columns=["id"], tag_only_columns=True, source_id="p") + assert source.as_table().num_rows == 1 + + +def test_the_type_token_of_the_reference_type_itself_is_its_identifier(): + """CodeRabbit on 4ce0a09 (user_class_identity.py:532): only a class that holds a + reference is refused; the type token of ``SpiralDBEntry`` itself, with no class + around it, is its logical identifier, and a class holding it, also in a list, + is still refused.""" + from orcapod.contexts import get_default_context + from orcapod.logical_types import user_class_identity as uci + from orcapod.logical_types.identifier import logical_type_identifier + from orcapod.semantic_types.nested_storage import NestedTypeNotStorableError + + converter: Any = get_default_context().type_converter + logical = converter.get_logical_type_for_python_type(SpiralDBEntry) + assert logical is not None + assert uci.type_token(SpiralDBEntry, converter) == { + "logical": logical_type_identifier(logical).text + } + for holder in (_HoldsAReference, _HoldsReferences): + with pytest.raises(NestedTypeNotStorableError, match=_REFUSED): + uci.class_record(holder, converter) diff --git a/tests/test_pipeline/test_async_fan_out_does_not_hang.py b/tests/test_pipeline/test_async_fan_out_does_not_hang.py index c4a0ed6df..6f9a44aa4 100644 --- a/tests/test_pipeline/test_async_fan_out_does_not_hang.py +++ b/tests/test_pipeline/test_async_fan_out_does_not_hang.py @@ -266,6 +266,9 @@ async def __anext__(self) -> tuple[TagProtocol, DataProtocol]: async def collect(self) -> list[tuple[TagProtocol, DataProtocol]]: return [row async for row in self] + def take_ready(self, max_items: int) -> list[tuple[TagProtocol, DataProtocol]]: + return self._reader.take_ready(max_items) + class _FailingOutput: """A writable channel whose sends fail: it stands for a failed downstream node. diff --git a/tests/test_pipeline/test_job_batched_commits.py b/tests/test_pipeline/test_job_batched_commits.py index b0bc52642..645bf5cab 100644 --- a/tests/test_pipeline/test_job_batched_commits.py +++ b/tests/test_pipeline/test_job_batched_commits.py @@ -365,9 +365,8 @@ def test_a_failing_observer_does_not_skip_the_failed_nodes_commit( ) -> None: """An observer raising in ``on_node_end`` as a node fails still lets the node commit. - The node's failure under ``fail_fast`` ends it for the observer and then commits - its ephemeral results; the observer's own exception must not skip that commit, as - on the sync path, where it propagates to the handler that commits. + Under ``fail_fast``, the node reports its end, commits its ephemeral results, + and raises its original error with the observer failure attached as a note. """ job = PipelineJob(name="batched", database=DeltaTableDatabase(tmp_path / "store")) with job: @@ -386,13 +385,15 @@ def test_a_failing_observer_does_not_skip_the_failed_nodes_commit( job.set_ephemeral_database(DeltaTableDatabase(tmp_path / "ephemeral")) job.apply_node_config(NodeConfig(is_result_ephemeral=True)) - with pytest.raises(RuntimeError, match="observer failed"): + with pytest.raises(ValueError, match="last row") as raised: job.run( orchestrator=AsyncPipelineOrchestrator(error_policy="fail_fast"), observer=RaisingNodeEnd(), commit_every_rows=100, ) + notes = getattr(raised.value, "__notes__", []) + assert any("observer failed" in note for note in notes) records = delta_rows_named(tmp_path / "store", "double_until_last") assert records == CANCEL_ROWS - 1 assert delta_rows_named(tmp_path / "ephemeral", "double_until_last") >= records diff --git a/tests/test_pipeline/test_observer_order_of_a_chain.py b/tests/test_pipeline/test_observer_order_of_a_chain.py new file mode 100644 index 000000000..bc25ce9c5 --- /dev/null +++ b/tests/test_pipeline/test_observer_order_of_a_chain.py @@ -0,0 +1,462 @@ +"""The observer's ordered events of a two-node function chain equal those of the +release before ITL-1789 (review B4 of PR 680 at fd64224). + +A function node routes its input rows one by one, as before, when no input column's +values fetch when hashed: draining rows ahead (which batches SpiralDB entry fetches) +would change the order in which nodes' events interleave on the async orchestrator. +The expected traces were recorded on ``main`` before ITL-1789 (merge base +``2075e85e2``), for both orchestrators, a passing and a failing second function, the +``continue`` and ``fail_fast`` policies, and a load-only run after. On the async +orchestrator main's trace is fixed only up to the end of the routing stage; the rest +follows the concurrent computing stage. +""" + +from __future__ import annotations + +import warnings +from typing import Any, cast + +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.sources import DictSource + + +@function_pod(output_keys=("x", "y")) +def first(n: int, s: str) -> tuple[int, str]: + """The chain's first function node: always succeeds.""" + return n + 1, s + s + + +@function_pod(output_keys=("a", "b")) +def second(x: int, y: str) -> tuple[int, str]: + """The chain's second function node, in the passing cases.""" + return x + 1, y + y + + +@function_pod(output_keys=("a", "b")) +def failing(x: int, y: str) -> tuple[int, str]: + """The chain's second function node in the failing cases: it raises for the row + whose ``x`` is 2 (row id 1), the one deliberate failure.""" + if x == 2: + raise ValueError("synthetic row failure") + return x + 1, y + y + + +class _Recorder: + """Records node and row events as short strings: event, node, row id, cached.""" + + def __init__(self) -> None: + self.events: list[str] = [] + + def contextualize(self, *args: Any) -> _Recorder: + """Return this recorder: every node's events go to one list, so their + interleaving across nodes is recorded.""" + return self + + def create_data_logger(self, *args: Any) -> None: + """No per-row logger: logs are not part of the trace.""" + return None + + def __getattr__(self, name: str) -> Any: + """Record the node and row events; ignore every other hook (run start and + end, which carry no node or row).""" + if name in {"on_node_start", "on_node_end"}: + return lambda node, *args, **kwargs: self.events.append( + f"{name.removeprefix('on_')} {node}" + ) + if name in {"on_data_start", "on_data_end", "on_data_crash"}: + + def record(node: str, tag: Any, *args: Any, **kwargs: Any) -> None: + parts = [name.removeprefix("on_"), node, str(tag.as_dict().get("id"))] + if kwargs.get("cached") is not None: + parts.append(str(kwargs["cached"])) + self.events.append(" ".join(parts)) + + return record + if name.startswith("on_"): + return lambda *args, **kwargs: None + raise AttributeError(name) + + +def _per_node(events: list[str], kind: str) -> dict[str, list[str]]: + """The events of one kind (``data_start``, ``node_start``...), node by node, in + the order they came.""" + out: dict[str, list[str]] = {} + for event in events: + name, node, *rest = event.split(" ") + if name == kind: + out.setdefault(node, []).append(" ".join(rest)) + return out + + +def _assert_async_follows_main(events: list[str], expected: list[str], policy: str): + """What an async run fixes in its trace equals main's: the nodes' starts, the + first node's routing order of the source's rows (``data_start``), the second + node's routing in the order the first delivered (its ``data_end`` order in this + run), and every row starting before it ends. With ``continue`` every event is + main's; under ``fail_fast`` a node may stop earlier or later, so a routing is a + prefix of what it is compared with, or the reverse. (How events interleave across + nodes varies on main itself, with load; that the rows are routed one by one is + checked on the route taken.)""" + + def agree(got: list[str], want: list[str], what: str) -> None: + if policy == "continue": + assert got == want, what + else: + shorter, longer = sorted((got, want), key=len) + assert longer[: len(shorter)] == shorter, what + + assert _per_node(events, "node_start") == _per_node(expected, "node_start") + starts = _per_node(events, "data_start") + agree(starts.get("first", []), _per_node(expected, "data_start")["first"], "first") + agree( + starts.get("second", []), + _per_node(events, "data_end").get("first", []), + "second", + ) + if policy == "continue": + assert sorted(events) == sorted(expected) + for index, event in enumerate(events): + if event.startswith(("data_end ", "data_crash ")): + _, node, row, *_ = event.split(" ") + assert f"data_start {node} {row}" in events[:index], event + + +def _in_delivered_order(expected: list[str], delivered: list[str]) -> list[str]: + """Return ``expected`` with its rows (by id) placed in the order ``delivered`` + gives them: the i-th row of ``expected`` becomes the i-th of ``delivered`` that + ``expected`` holds, and every other event stays where it is.""" + rows = [event.split(" ")[2] for event in expected if event.startswith("data_start")] + ordered = [row for row in delivered if row in rows] + assert sorted(ordered) == sorted(rows), (delivered, rows) + moved = dict(zip(rows, ordered)) + out: list[str] = [] + for event in expected: + parts = event.split(" ") + if len(parts) > 2: + parts[2] = moved[parts[2]] + out.append(" ".join(parts)) + return out + + +def _job(failing_second: bool) -> PipelineJob: + source = DictSource( + [{"id": i, "group": "g", "n": i, "s": str(i)} for i in (3, 1, 4, 0, 2)], + tag_columns=["id", "group"], + tag_only_columns=True, + source_id="chain-plain", + ) + job = PipelineJob(name="chain", database=InMemoryArrowDatabase()) + with job: + upstream = first.pod(source.select_data_columns(["s", "n"]), label="first") + (failing if failing_second else second).pod(upstream, label="second") + return job + + +_MAIN_TRACES: dict[str, list[str]] = { + "sync/continue/passing/run": [ + "node_start chain-plain", + "node_end chain-plain", + "node_start SelectDataColumns", + "node_end SelectDataColumns", + "node_start first", + "data_start first 3", + "data_end first 3", + "data_start first 1", + "data_end first 1", + "data_start first 4", + "data_end first 4", + "data_start first 0", + "data_end first 0", + "data_start first 2", + "data_end first 2", + "node_end first", + "node_start second", + "data_start second 3", + "data_end second 3", + "data_start second 1", + "data_end second 1", + "data_start second 4", + "data_end second 4", + "data_start second 0", + "data_end second 0", + "data_start second 2", + "data_end second 2", + "node_end second", + ], + "sync/continue/passing/load_only": [], + "sync/continue/failing/run": [ + "node_start chain-plain", + "node_end chain-plain", + "node_start SelectDataColumns", + "node_end SelectDataColumns", + "node_start first", + "data_start first 3", + "data_end first 3", + "data_start first 1", + "data_end first 1", + "data_start first 4", + "data_end first 4", + "data_start first 0", + "data_end first 0", + "data_start first 2", + "data_end first 2", + "node_end first", + "node_start second", + "data_start second 3", + "data_end second 3", + "data_start second 1", + "data_crash second 1", + "data_start second 4", + "data_end second 4", + "data_start second 0", + "data_end second 0", + "data_start second 2", + "data_end second 2", + "node_end second", + ], + "sync/continue/failing/load_only": [ + "node_start second", + "data_start second 3", + "data_end second 3", + "data_start second 4", + "data_end second 4", + "data_start second 0", + "data_end second 0", + "data_start second 2", + "data_end second 2", + "node_end second", + ], + "sync/fail_fast/failing/run": [ + "node_start chain-plain", + "node_end chain-plain", + "node_start SelectDataColumns", + "node_end SelectDataColumns", + "node_start first", + "data_start first 3", + "data_end first 3", + "data_start first 1", + "data_end first 1", + "data_start first 4", + "data_end first 4", + "data_start first 0", + "data_end first 0", + "data_start first 2", + "data_end first 2", + "node_end first", + "node_start second", + "data_start second 3", + "data_end second 3", + "data_start second 1", + "data_crash second 1", + "node_end second", + ], + "async/continue/passing/run": [ + "node_start chain-plain", + "node_end chain-plain", + "node_start SelectDataColumns", + "node_start first", + "node_start second", + "data_start first 3", + "data_start first 1", + "data_start first 4", + "data_start first 0", + "data_start first 2", + "node_end SelectDataColumns", + "data_end first 3", + "data_end first 1", + "data_end first 4", + "data_end first 0", + "data_end first 2", + "data_start second 3", + "data_start second 1", + "data_start second 4", + "data_start second 0", + "data_start second 2", + "node_end first", + "data_end second 3", + "data_end second 1", + "data_end second 4", + "data_end second 0", + "data_end second 2", + "node_end second", + ], + "async/continue/passing/load_only": [], + "async/continue/failing/run": [ + "node_start chain-plain", + "node_end chain-plain", + "node_start SelectDataColumns", + "node_start first", + "node_start second", + "data_start first 3", + "data_start first 1", + "data_start first 4", + "data_start first 0", + "data_start first 2", + "node_end SelectDataColumns", + "data_end first 3", + "data_end first 1", + "data_end first 4", + "data_end first 0", + "data_end first 2", + "data_start second 3", + "data_start second 1", + "data_start second 4", + "data_start second 0", + "data_start second 2", + "node_end first", + "data_end second 3", + "data_crash second 1", + "data_end second 4", + "data_end second 0", + "data_end second 2", + "node_end second", + ], + "async/continue/failing/load_only": [ + "node_start second", + "data_start second 3", + "data_end second 3", + "data_start second 4", + "data_end second 4", + "data_start second 0", + "data_end second 0", + "data_start second 2", + "data_end second 2", + "node_end second", + ], + "async/fail_fast/failing/run": [ + "node_start chain-plain", + "node_end chain-plain", + "node_start SelectDataColumns", + "node_start first", + "node_start second", + "data_start first 3", + "data_start first 1", + "data_start first 4", + "data_start first 0", + "data_start first 2", + "node_end SelectDataColumns", + "data_end first 3", + "data_end first 1", + "data_end first 4", + "data_end first 0", + "data_end first 2", + "data_start second 3", + "data_start second 1", + "data_start second 4", + "data_start second 0", + "data_start second 2", + "node_end first", + "data_end second 3", + "data_crash second 1", + "data_end second 4", + "data_end second 0", + "data_end second 2", + "node_end second", + ], +} +"""Main's ordered events, by orchestrator, policy, second function and run.""" + +_MAIN_ROWS: dict[str, Any] = { + "sync/continue/passing/run": [[[3, 5], [1, 3], [4, 6], [0, 2], [2, 4]], 0], + "sync/continue/passing/load_only": [[[3, 5], [1, 3], [4, 6], [0, 2], [2, 4]], 0], + "sync/continue/failing/run": [[[3, 5], [4, 6], [0, 2], [2, 4]], 1], + "sync/continue/failing/load_only": [[[3, 5], [4, 6], [0, 2], [2, 4]], 0], + "sync/fail_fast/failing/run": ["ValueError", None], + "async/continue/passing/run": [[[3, 5], [1, 3], [4, 6], [0, 2], [2, 4]], 0], + "async/continue/passing/load_only": [[[3, 5], [1, 3], [4, 6], [0, 2], [2, 4]], 0], + "async/continue/failing/run": [[[3, 5], [4, 6], [0, 2], [2, 4]], 1], + "async/continue/failing/load_only": [[[3, 5], [4, 6], [0, 2], [2, 4]], 0], + "async/fail_fast/failing/run": ["ValueError", None], +} +"""Main's rows of the second node (id, a) and failed count, or the error raised.""" + + +@pytest.mark.parametrize("mode", ["sync", "async"]) +@pytest.mark.parametrize( + ("policy", "failing_second"), + [("continue", False), ("continue", True), ("fail_fast", True)], +) +def test_observer_events_of_a_chain_follow_main( + mode: str, policy: str, failing_second: bool, monkeypatch: pytest.MonkeyPatch +): + """Review B4 of fd64224: the full ordered event trace across the source, an + operator and two function nodes equals main's, on both orchestrators, with a + passing and a failing second function under both policies, and so do the rows, + the failed count and a load-only run after. No node of this chain (no column + whose hash fetches) takes its rows as a drained batch: each row is routed as it + arrives, as on main.""" + from orcapod.core.nodes import function_node + + drained: list[int] = [] + real_drain = function_node._with_waiting_rows # pyright: ignore[reportPrivateUsage] + + async def recording_drain(*args: Any, **kwargs: Any) -> Any: + drained.append(1) + return await real_drain(*args, **kwargs) + + monkeypatch.setattr(function_node, "_with_waiting_rows", recording_drain) + job = _job(failing_second) + # The first node's rows in the order it delivered them in the async run. + delivered: list[str] = [] + orchestrator_class = ( + AsyncPipelineOrchestrator if mode == "async" else SyncPipelineOrchestrator + ) + orchestrator = orchestrator_class(error_policy=policy) # pyright: ignore[reportArgumentType] + case = f"{mode}/{policy}/{'failing' if failing_second else 'passing'}" + for load_only in (False, True): + if load_only and policy == "fail_fast": + continue + key = f"{case}/{'load_only' if load_only else 'run'}" + recorder = _Recorder() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + try: + summary = job.run( + orchestrator=orchestrator, + observer=cast(Any, recorder), + load_only=load_only, + ) + except ValueError as error: + # The run stopped at the synthetic failure, reported at its row. + assert _MAIN_ROWS[key] == ["ValueError", None] + assert str(error) == "synthetic row failure" + assert "data_crash second 1" in recorder.events + else: + table = job.nodes["second"].as_table() + rows = [ + list(pair) + for pair in zip( + table.column("id").to_pylist(), table.column("a").to_pylist() + ) + ] + want_rows, want_failed = _MAIN_ROWS[key] + if mode == "async": + # The async orchestrator stores rows as they finish. + rows, want_rows = sorted(rows), sorted(cast(list[Any], want_rows)) + assert [rows, summary.nodes["second"].failed] == [ + want_rows, + want_failed, + ] + expected = _MAIN_TRACES[key] + if mode == "async" and load_only: + # The load-only run reads the second node's input from the first node's + # held rows, kept in the order the async run finished them, which varies + # from run to run on main too. Every event is main's, with the rows in + # the order the first node delivered them in the run before. + expected = _in_delivered_order(expected, delivered) + if mode == "sync" or load_only: + assert recorder.events == expected + continue + delivered = [ + end.split(" ")[0] + for end in _per_node(recorder.events, "data_end").get("first", []) + ] + # On the async orchestrator rows are computed concurrently, so main's own + # trace interleaves differently from run to run (more so under load); what + # it fixes must be main's. + _assert_async_follows_main(recorder.events, expected, policy) + assert drained == []