From 0a5f00112f5054393fa8598b33d1ee153cf84bd0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 22:55:02 -0800 Subject: [PATCH 01/28] feat(spiraldb): present Vortex-encoded columns as entry references (ITL-1789) A SpiralDB table that stores a column in a Vortex encoding (such as vortex.turboquant), at the top level or as a struct field, was refused when the source was built, so none of its columns could be read. SpiralDBTableSource now presents each such column as a column of orcapod.SpiralDBEntry references (logical type orcapod.spiraldb.entry, hashed as the stored reference, provisional): the table id, the pinned version, the row's primary-key values and the column. The scan does not read the encoded columns; every other column reads as from the same table without them. entry.read() and entry.scan() read the one entry through spiral-sdk, opening the table by id at that version. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1789.md | 27 ++ docs/api/types.md | 4 + docs/concepts/arrays.md | 7 +- docs/concepts/sources.md | 63 ++- src/orcapod/__init__.py | 5 + src/orcapod/contexts/logical_types.json | 14 + src/orcapod/core/sources/spiraldb_entries.py | 234 +++++++++ .../core/sources/spiraldb_table_source.py | 83 +++- src/orcapod/databases/spiraldb_connector.py | 90 +++- .../semantic_hashing/builtin_handlers.py | 41 ++ .../logical_types/spiraldb_entry_type.py | 257 ++++++++++ tests/test_contexts/test_data_context_v1.py | 5 +- .../test_spiraldb_table_source_encoded.py | 448 ++++++++++++++++++ tests/test_databases/fake_spiral_sdk.py | 79 ++- .../test_schema_hash_storage_form.py | 1 + .../test_provisional_hash_warning.py | 8 +- .../test_spiraldb_entry_type.py | 175 +++++++ 17 files changed, 1524 insertions(+), 17 deletions(-) create mode 100644 changelog.d/ITL-1789.md create mode 100644 src/orcapod/core/sources/spiraldb_entries.py create mode 100644 src/orcapod/logical_types/spiraldb_entry_type.py create mode 100644 tests/test_core/sources/test_spiraldb_table_source_encoded.py create mode 100644 tests/test_logical_types/test_spiraldb_entry_type.py diff --git a/changelog.d/ITL-1789.md b/changelog.d/ITL-1789.md new file mode 100644 index 000000000..c00aeeffa --- /dev/null +++ b/changelog.d/ITL-1789.md @@ -0,0 +1,27 @@ +### 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 and the column. Its logical type is + `orcapod.spiraldb.entry`, hashed as the stored reference, never as the value it names. + `entry.read()` returns the entry through spiral-sdk as a one-row `pyarrow.Table`, and + `entry.scan()` returns spiral-sdk's scan of that one key and column. Both take an + optional `client`; without one they use spiral-sdk's own sign-in. + +### 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. + +### Known limitations + +- A reference names the version the source read. When a run's check pins a newer table + version, every reference value changes, so function pods that take the column compute + again for every row, also for entries that did not change. +- `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/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 64012062f..7ffad7d80 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -987,7 +987,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. @@ -1025,6 +1026,66 @@ 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 source's `pinned_version`), the row's primary-key values (`key`, the + canonical JSON of the key columns in key order, the form of a record ID) and the column + (`column`). 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()` reads the entry through spiral-sdk: 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. `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 open the table by its id at the + reference's version, so they read the same value whenever they are called. Both take an + optional `client` (a `spiral.Client`); without one they sign in as spiral-sdk does (the + `SPIRAL_*` environment variables, or a saved `spiral login`), and never ask a person to + sign in. A key that the version does not hold raises `LookupError`. +- 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 + +items = SpiralDBTableSource("my-project-123456", "items") # "vector" is encoded + + +@function_pod(output_keys="first_norm") +def first_norm(vector: op.SpiralDBEntry) -> float: + value = vector.read().column("vector")[0].as_py() + return value["block_0"]["norms"] + + +norms = first_norm.pod(items.select_data_columns(["vector"])) +``` + +**A reference holds the version.** A reference is exact: it reads the value of the version +the source read, also after the table has changed. The price: when a run's check +(`check_for_new_data()`) pins a newer version of the table, every reference names the new +version, so every reference value changes, and function pods that take the column compute +again for every row, also for entries that did not change. A source built with `asof=` +never moves its pin. + +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`). + ### `DerivedSource` A `DerivedSource` is a source whose rows come from something Orcapod already has: another 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/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/sources/spiraldb_entries.py b/src/orcapod/core/sources/spiraldb_entries.py new file mode 100644 index 000000000..71316f8fd --- /dev/null +++ b/src/orcapod/core/sources/spiraldb_entries.py @@ -0,0 +1,234 @@ +"""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``). +""" + +from __future__ import annotations + +import datetime +import json +from collections.abc import Iterator, Sequence +from typing import Any, cast + +import pyarrow as pa + +from orcapod.core.sources.stream_builder import row_identifiers +from orcapod.databases.spiraldb_connector import open_table_version, scan_one_key +from orcapod.logical_types.spiraldb_entry_type import ( + SPIRALDB_ENTRY_STORAGE, + LogicalSpiralDBEntry, + SpiralDBEntry, +) + +ENCODING_PREFIX = "vortex." +"""The extension names of the encodings presented as references: Vortex's own.""" + +_EXTENSION_NAME_KEY = b"ARROW:extension:name" + +_FRACTION_DIGITS = {"s": 0, "ms": 3, "us": 6, "ns": 9} + + +def _encodings(field: pa.Field[Any]) -> Iterator[str]: + """Yield the Vortex encoding names on ``field`` and on its children, at any depth.""" + name = (field.metadata or {}).get(_EXTENSION_NAME_KEY) + if name is not None: + text = name.decode("utf-8", errors="backslashreplace") + if text.startswith(ENCODING_PREFIX): + yield text + arrow_type = field.type + if isinstance(arrow_type, pa.DictionaryType): + yield from _encodings(pa.field(field.name, arrow_type.value_type)) + for index in range(arrow_type.num_fields): + yield from _encodings(arrow_type.field(index)) + + +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(set(_encodings(field))) + if names: + found[field.name] = tuple(names) + return found + + +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, +) -> 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. + + 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()), + ], + 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, table: Any) -> list[pa.Array[Any]]: # pyright: ignore[reportExplicitAny] # an SDK table, untyped + """Return ``entry``'s key values as arrays of ``table``'s key column types. + + 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). + """ + key_columns = [str(c) for c in table.key_columns] # pyright: ignore[reportAny] + values = json.loads(entry.key) # pyright: ignore[reportAny] + if not isinstance(values, dict) or list(values) != key_columns: # pyright: ignore[reportUnknownArgumentType] + raise ValueError( + f"SpiralDB entry {entry!r}: the key does not name the table's primary-key " + f"columns {key_columns} in order" + ) + schema: pa.Schema = table.schema() # pyright: ignore[reportAny] + 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 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`` makes one with spiral-sdk's own sign-in. + + 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. + """ + table = open_table_version(client, entry.table_id, entry.version) # pyright: ignore[reportAny] + return scan_one_key(table, entry.column, _key_arrays(entry, table)) # pyright: ignore[reportAny] + + +def read_entry(entry: SpiralDBEntry, client: Any = None) -> pa.Table: # pyright: ignore[reportExplicitAny] # an SDK client, untyped + """Read ``entry`` through spiral-sdk: one row, one column, as SpiralDB stores it. + + Args: + entry: The reference. + client: As for ``scan_entry``. + + Raises: + LookupError: If the table at the entry's version has no row with its key. + ValueError: If the key does not fit the table's primary key. + """ + table: pa.Table = scan_entry(entry, client).to_table() # pyright: ignore[reportAny] + if table.num_rows != 1: + raise LookupError( + f"SpiralDB entry {entry!r}: the table at version {entry.version} holds " + f"{table.num_rows} rows with this key, not one" + ) + return table diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index ca1f243e2..dd113defb 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -51,13 +51,18 @@ from concurrent.futures import ThreadPoolExecutor from threading import Lock from types import TracebackType -from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple +from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple, cast import pyarrow as pa from typing_extensions import override 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, +) 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 @@ -406,6 +411,10 @@ def __init__( 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)) + 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) @@ -437,6 +446,14 @@ def __init__( f"columns {list(self._key_columns)}: {'; '.join(key_problems)}. A 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( @@ -449,9 +466,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(), @@ -460,8 +488,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) @@ -516,6 +551,38 @@ def _check_tags_as_data( f"null. Key columns, which can be copied: {list(self._key_columns)}." ) + def _with_references(self, rows: "pa.Table", asof: int | None) -> "pa.Table": + """Return ``rows`` with a reference column for each encoded column (ITL-1789). + + Each reference names its row's entry: the table id, the version read + (``asof``), the row's primary-key values and the column. It takes the encoded + column's name and position in the table's schema. + + Raises: + RowIdentifierError: If a primary-key value is null. + """ + if not self._encoded: + return rows + if asof is None and rows.num_rows: + raise ValueError( + f"SpiralDB table {self._qualified!r} returned rows without a version, " + "which a reference to its entries needs" + ) + for position, field in enumerate(self._table_schema): + if field.name in self._encoded: + rows = rows.add_column( + position, + field, + reference_column( + rows, + self._primary_key, + table_id=self._table_id, + version=asof or 0, + column=field.name, + ), + ) + return rows + def _with_tag_copies(self, table: "pa.Table") -> "pa.Table": """Return ``table`` with each ``tags_as_data`` copy appended, in mapping order. @@ -928,10 +995,10 @@ def _check_table(self) -> bool: raw_schema = table.arrow_schema(asof=given) 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: @@ -1054,6 +1121,7 @@ def _read_batches( where=None if self._condition.is_empty else self._condition, limit=limit, asof=asof, + columns=self._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)]) @@ -1063,10 +1131,10 @@ def _read_batches( rows = arrow_utils.drop_system_columns(raw) # Metadata too: field metadata is how a column's logical type is # recorded, and the schema hash was computed at construction. - if not rows.schema.equals(self._table_schema, check_metadata=True): + if not rows.schema.equals(self._scanned_schema, check_metadata=True): raise ValueError( f"SpiralDB table {self._qualified!r}: " - f"{_schema_difference(rows.schema, self._table_schema)}. " + f"{_schema_difference(rows.schema, self._scanned_schema)}. " "The table changed after the source was built; build the " "source again to read it as it is now." ) @@ -1083,6 +1151,7 @@ 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, asof) rows = self._with_tag_copies(rows) if not rows.num_rows: continue diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index db3a0b45c..3cf2a39cb 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -24,7 +24,7 @@ import urllib.parse import urllib.request import warnings -from collections.abc import Iterator, Mapping +from collections.abc import Iterator, Mapping, Sequence from contextlib import contextmanager from copy import copy from threading import local @@ -287,6 +287,55 @@ def _new_client(overrides: Mapping[str, str] | None) -> Any: return client_class(api_url=api_url) +def new_client() -> Any: # pyright: ignore[reportExplicitAny] # an SDK client, untyped + """Return a spiral-sdk client with spiral-sdk's own sign-in and service address. + + Raises: + SpiralDBSignInError: If spiral-sdk would have to ask a person to sign in. + ImportError: If spiral-sdk is not installed. + """ + return _new_client(None) + + +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 ``version`` (ITL-1789). + + Args: + client: A ``spiral.Client``; ``None`` makes one (``new_client``). + table_id: SpiralDB's id of the table. + version: The version. + """ + if client is None: + client = new_client() + with _service_call(f"open table {table_id} at version {version}"): + return client.keyed_table_by_id(table_id, asof=version) # 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. + """ + 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 table.scan([column], key_ranges=[sp.KeyRange(bound, bound)]) # pyright: ignore[reportAny] + + class _NoRedirect(urllib.request.HTTPRedirectHandler): """Follows no redirect, so a token is never sent to another address.""" @@ -554,6 +603,7 @@ def scan_batches( where: Condition | None = None, limit: int | None = None, asof: int | None = None, + columns: Sequence[str] | None = None, ) -> Iterator[pa.RecordBatch]: """Yield prepared Arrow batches from this resolved table in key order. @@ -562,6 +612,8 @@ def scan_batches( (``SpiralDBConnector.scan_batches``). limit: Read at most this many matching rows. asof: Read this version. + columns: Read only these columns, in this order; ``None`` for every + column. ``where`` may name a column that is not read. Raises: ValueError: If ``where`` holds anything else, or a range of a column whose @@ -590,8 +642,10 @@ def scan_batches( continue equals = sp.eq(sp.column(column), literal) predicate = equals if predicate is None else sp.and_(predicate, equals) + read = reading if columns is None else reading.project(columns) with connector._service_call("read", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle reader = table.scan( + None if columns is None else list(columns), filter=predicate, # The limit counts rows that match every condition. limit=None if local else limit, @@ -604,7 +658,7 @@ def scan_batches( batch = next(reader, None) if batch is None: return - batch = reading.prepare(batch) + batch = read.prepare(batch) for column, value in local: batch = batch.filter(_equals(batch.column(column), value)) if local and left is not None: @@ -687,9 +741,41 @@ def __init__( else: self.schema = recorded self._paths = schema_paths(recorded) + self._recorded = recorded self._table = table # The batch schema last found to have the snapshot's columns. self._accepted = found + # The reading of each projection of the snapshot's columns (``project``). + self._projections: dict[tuple[str, ...], _Reading] = {} + + def project(self, columns: Sequence[str]) -> _Reading: + """Return how a scan of only ``columns`` (in this order) of the snapshot is read. + + Args: + columns: Columns of the snapshot. + """ + names = tuple(columns) + projected = self._projections.get(names) + if projected is None: + found = pa.schema( + [self.found.field(c) for c in names], + metadata=cast( + "dict[bytes | str, bytes | str] | None", self.found.metadata + ), + ) + recorded = ( + None + if self._recorded is None + else pa.schema( + [self._recorded.field(c) for c in names], + metadata=cast( + "dict[bytes | str, bytes | str] | None", self._recorded.metadata + ), + ) + ) + projected = _Reading(found, recorded, self._table) + self._projections[names] = projected + return projected def prepare(self, batch: pa.RecordBatch) -> pa.RecordBatch: """Return a scanned batch under ``schema``, its non-null columns checked. diff --git a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py index a153ecc11..4d00a1fce 100644 --- a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py +++ b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py @@ -61,6 +61,10 @@ POLARS_SERIES_EXTENSION_NAME, POLARS_SERIES_HASH_LABEL, ) +from orcapod.logical_types.spiraldb_entry_type import ( + SPIRALDB_ENTRY_EXTENSION_NAME, + SpiralDBEntry, +) from orcapod.types import ContentHash, Schema from orcapod.utils.canonical_type_names import canonical_type_name @@ -104,6 +108,43 @@ def handle(self, obj: Any, hasher: "SemanticHasherProtocol") -> Encoded: raise TypeError(f"UUIDHandler: expected uuid.UUID, got {type(obj)!r}") +class SpiralDBEntryHandler: + """Hasher for a bare ``SpiralDBEntry``: the tagged reference, never the value it names. + + ``{"__type__": "spiraldb_entry", "table_id": ..., "version": ..., "key": ..., + "column": ...}`` (ITL-1789). The logical type declares stored for its columns. + """ + + EXTENSION_NAME = SPIRALDB_ENTRY_EXTENSION_NAME + + def handle(self, obj: Any, hasher: "SemanticHasherProtocol") -> Encoded: + """Encode ``obj`` as its four fields under the tag ``spiraldb_entry``. + + Args: + obj: A ``SpiralDBEntry``. + hasher: The semantic hasher (unused). + + Returns: + ``Encoded("spiraldb_entry", {...})``. + + Raises: + TypeError: If ``obj`` is not a ``SpiralDBEntry``. + """ + if isinstance(obj, SpiralDBEntry): + return Encoded( + "spiraldb_entry", + { + "table_id": obj.table_id, + "version": obj.version, + "key": obj.key, + "column": obj.column, + }, + ) + raise TypeError( + f"SpiralDBEntryHandler: expected SpiralDBEntry, got {type(obj)!r}" + ) + + 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..f165f497f --- /dev/null +++ b/src/orcapod/logical_types/spiraldb_entry_type.py @@ -0,0 +1,257 @@ +"""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 and the column. It is stored as +itself (``LogicalSpiralDBEntry``, extension name ``orcapod.spiraldb.entry``), and its +value hash is the hash of the reference, never of the encoded value. + +This module imports no spiral-sdk; ``read`` and ``scan`` load it when called. +""" + +from __future__ import annotations + +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, +) + +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.""" + +_IDENTIFIER_METADATA = version_metadata(1, "stored") +"""Version 1 of the stored layout; the value hash is that of the stored reference.""" + +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), + ] +) +"""The stored layout: the four 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 is exact: it names the + version the source read, so it reads the same value whenever it is read, also + after the table has changed. Its value hash is the hash of the reference, never of + the value it points to. Its fields are read-only; two references are equal when + their four 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. + + Raises: + TypeError: If a field is not of its type (``str``, ``int``, ``str``, ``str``). + """ + + __slots__ = ("_table_id", "_version", "_key", "_column") + + def __init__(self, table_id: str, version: int, key: str, column: str) -> None: + for name, value, kind in ( + ("table_id", table_id, str), + ("version", version, int), + ("key", key, str), + ("column", column, 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 + + @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 + + def _fields(self) -> tuple[str, int, str, str]: + return (self._table_id, self._version, self._key, self._column) + + 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})" + ) + + def __reduce__(self) -> tuple[type[SpiralDBEntry], tuple[str, int, 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 ``version``; the scan's key range is the one + primary key, so it holds at most one row. + + Args: + client: A ``spiral.Client``. ``None`` (default) makes one 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]``). + SpiralDBSignInError: If ``client`` is ``None`` and spiral-sdk would have + to ask a person to sign in. + """ + 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 through spiral-sdk, as SpiralDB stores it. + + 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]``). + LookupError: If the table at ``version`` has no row with this key. + """ + from orcapod.core.sources.spiraldb_entries import read_entry + + return read_entry(self, client) + + +class LogicalSpiralDBEntry(BaseLogicalType): + """Logical type for ``SpiralDBEntry``: extension ``orcapod.spiraldb.entry``. + + Stored as a struct of the reference's four fields (``SPIRALDB_ENTRY_STORAGE``), + with metadata ``{"value_hash":"stored","version":1}``: a reference is hashed as + stored. 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": ...}``. + """ + return { + "table_id": value.table_id, + "version": value.version, + "key": value.key, + "column": value.column, + } + + 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 four 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"], + ) 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..a0b71ae19 --- /dev/null +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -0,0 +1,448 @@ +"""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 datetime +import warnings +from pathlib import Path +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 +from orcapod.logical_types.provisional import reset_provisional_warnings +from orcapod.logical_types.spiraldb_entry_type import ( + LogicalSpiralDBEntry, + SpiralDBEntry, +) +from orcapod.system_constants import constants +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) + + +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]): + """``where`` on a reference column is refused when the source is built.""" + with pytest.raises((TypeError, ValueError)): + _source(where={"vector": "x"}) + + +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: ``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", + ) + + with pytest.raises(LookupError, match="0 rows"): + missing.read() + + +@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").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() + run() + assert calls == [] diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index e022d4207..e72249a46 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -23,7 +23,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 @@ -73,6 +73,11 @@ "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", "list": "the documented listing filters a dataset and pages; a page can be empty " "(documented, not seen)", } @@ -104,6 +109,7 @@ class ScanRecord: columns: list[str] | None filter: Any limit: int | None + count: bool = False batches_read: int = 0 closed: bool = False @@ -540,6 +546,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) @@ -642,7 +662,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) @@ -686,9 +706,13 @@ 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) + for key_range in key_ranges or (): + rows = rows.filter(pa.array(self._one_key(rows, key_range), pa.bool_())) for name, wanted, op in filter.terms if filter else (): if rows.schema.field(name).type != wanted.type: raise SpiralError( @@ -727,12 +751,38 @@ def scan( columns, filter, limit, + count=columns == [self._table["keys"][0]], ) 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}" + ) + if pa.types.is_temporal(wanted.type): + width = pa.int32() if pa.types.is_date32(wanted.type) else pa.int64() + stored = stored.cast(width) + values: list[Any] = stored.to_pylist() + keep = [k and v == wanted.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() @@ -934,6 +984,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, ) @@ -960,6 +1012,27 @@ 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 record(self, schema: pa.Schema) -> None: """Migrate the dataset, with ``schema`` as what this table was written with.""" migrate( diff --git a/tests/test_hashing/test_schema_hash_storage_form.py b/tests/test_hashing/test_schema_hash_storage_form.py index efa1fe6c7..da59607f3 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": False, "orcapod.torch.tensor": True, "orcapod.upath": False, "orcapod.uuid": False, diff --git a/tests/test_logical_types/test_provisional_hash_warning.py b/tests/test_logical_types/test_provisional_hash_warning.py index dbd639fd1..c59db9123 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,8 @@ 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": + return SpiralDBEntry("table_x", 1, '{"k":1}', "v") assert name == "orcapod.polars.series" return pl.Series("a", [1, 2]) @@ -64,6 +67,7 @@ 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) @@ -127,7 +131,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..47d5c4e86 --- /dev/null +++ b/tests/test_logical_types/test_spiraldb_entry_type.py @@ -0,0 +1,175 @@ +"""``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 round trip through a source and a function pod, and its value hash +(the reference's, never the value it names). Reading a reference is tested with the +SpiralDB source (``tests/test_core/sources/test_spiraldb_table_source_encoded.py``). +""" + +from __future__ import annotations + +import pickle +from typing import Any + +import pyarrow as pa +import pytest + +import orcapod as op +from orcapod import function_pod +from orcapod.contexts import get_default_context +from orcapod.logical_types.identifier import logical_type_identifier +from orcapod.logical_types.spiraldb_entry_type import ( + SPIRALDB_ENTRY_STORAGE, + LogicalSpiralDBEntry, + SpiralDBEntry, +) +from orcapod.sources import DictSource + +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") + +_FIELDS: dict[str, Any] = { + "table_id": "table_a", + "version": 7, + "key": '{"unit":"u1","time":"2026-01-01T00:00:00Z"}', + "column": "vector", +} + + +def _entry(**changes: Any) -> SpiralDBEntry: + fields = {**_FIELDS, **changes} + return SpiralDBEntry( + fields["table_id"], fields["version"], fields["key"], fields["column"] + ) + + +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"), + ): + assert _entry(**{name: other}) != _entry(), name + assert (_entry().table_id, _entry().version, _entry().key, _entry().column) == ( + _FIELDS["table_id"], + _FIELDS["version"], + _FIELDS["key"], + _FIELDS["column"], + ) + + +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] + assert pickle.loads(pickle.dumps(entry)) == entry + + +@pytest.mark.parametrize( + ("name", "value"), + [ + ("table_id", 1), + ("version", "7"), + ("version", True), + ("key", None), + ("column", b"v"), + ], +) +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 as stored, over a + struct of four non-null fields.""" + extension = LogicalSpiralDBEntry().get_arrow_extension_type() + identifier = logical_type_identifier(LogicalSpiralDBEntry()) + + assert identifier.name == "orcapod.spiraldb.entry" + assert identifier.metadata == b'{"value_hash":"stored","version":1}' + assert extension.storage_type == SPIRALDB_ENTRY_STORAGE + assert [f.name for f in SPIRALDB_ENTRY_STORAGE] == [ + "table_id", + "version", + "key", + "column", + ] + assert not any(f.nullable for f in SPIRALDB_ENTRY_STORAGE) + + +def test_round_trip_through_a_source_and_a_function_pod(): + """References given to a source, taken by a function pod and returned by it come + back equal, as ``SpiralDBEntry`` objects, in a column of the logical type.""" + first, second = _entry(), _entry(key='{"unit":"u2","time":"2026-01-01T00:00:00Z"}') + rows: Any = [ + {"id": 1, "label": "a", "ref": first}, + {"id": 2, "label": "b", "ref": second}, + ] + source = DictSource(rows, tag_columns=["id"], tag_only_columns=True) + 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() + + 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"] + + +def test_the_value_hash_is_the_references(): + """A bare reference hashes by its four fields: equal references hash alike, and any + field moves the hash.""" + hasher = get_default_context().semantic_hasher + base = hasher.hash_object(_entry()) + + assert hasher.hash_object(_entry()) == base + for name, other in ( + ("table_id", "table_b"), + ("version", 8), + ("key", '{"unit":"u2","time":"2026-01-01T00:00:00Z"}'), + ("column", "embeddings"), + ): + assert hasher.hash_object(_entry(**{name: other})) != base, name + + +def test_a_column_hashes_as_stored(): + """A column of references hashes from its stored struct: rows with equal references + give one table hash, and another reference moves it.""" + extension = LogicalSpiralDBEntry().get_arrow_extension_type() + hasher = get_default_context().arrow_hasher + + def table(*entries: SpiralDBEntry) -> pa.Table: + storage = pa.array( + [LogicalSpiralDBEntry().python_to_storage(e) for e in entries], + SPIRALDB_ENTRY_STORAGE, + ) + return pa.table( + {"ref": pa.ExtensionArray.from_storage(extension, storage)}, + schema=pa.schema([pa.field("ref", extension, nullable=False)]), + ) + + assert hasher.hash_table(table(_entry())) == hasher.hash_table(table(_entry())) + assert hasher.hash_table(table(_entry())) != hasher.hash_table( + table(_entry(version=8)) + ) From 425d7a1d4a6f229e344b31560e8dd0c1b6f2ef61 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 23:23:19 -0800 Subject: [PATCH 02/28] fix(spiraldb): address review of the encoded-column references (ITL-1789) - Refuse a stored logical type that is not a Vortex encoding inside a struct column that also holds an encoded field, before the column is replaced by references (InputValidationError, as in any other column). - SpiralDBTable.scan_batches(columns=...) reads the columns a local (float16) equality filters on, then returns only the requested ones. - The fake SDK compares a date key literal with the stored column as counts, so a reference over a date key finds its entry. Each with a regression test. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/sources/spiraldb_entries.py | 53 +++++++++- .../core/sources/spiraldb_table_source.py | 2 + src/orcapod/databases/spiraldb_connector.py | 12 ++- .../test_spiraldb_table_source_encoded.py | 98 +++++++++++++++++++ tests/test_databases/fake_spiral_sdk.py | 7 +- 5 files changed, 167 insertions(+), 5 deletions(-) diff --git a/src/orcapod/core/sources/spiraldb_entries.py b/src/orcapod/core/sources/spiraldb_entries.py index 71316f8fd..5a7a7db3d 100644 --- a/src/orcapod/core/sources/spiraldb_entries.py +++ b/src/orcapod/core/sources/spiraldb_entries.py @@ -17,7 +17,10 @@ import pyarrow as pa -from orcapod.core.sources.stream_builder import row_identifiers +from orcapod.core.sources.stream_builder import ( + require_live_logical_types, + row_identifiers, +) from orcapod.databases.spiraldb_connector import open_table_version, scan_one_key from orcapod.logical_types.spiraldb_entry_type import ( SPIRALDB_ENTRY_STORAGE, @@ -68,6 +71,54 @@ def encoded_columns(schema: pa.Schema) -> dict[str, tuple[str, ...]]: 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.decode("utf-8", errors="replace").startswith( + ENCODING_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: + InputValidationError: If one of ``columns`` holds a stored logical type other + than a Vortex encoding. + """ + require_live_logical_types( + pa.schema([_without_encodings(schema.field(c)) for c in columns]) + ) + + def reference_field(name: str) -> pa.Field[Any]: """Return the field a reference column has: ``orcapod.spiraldb.entry``, non-null. diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index dd113defb..c33861f22 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -62,6 +62,7 @@ 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 @@ -414,6 +415,7 @@ def __init__( # 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. diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 3cf2a39cb..2fbfe68a7 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -642,10 +642,16 @@ def scan_batches( continue equals = sp.eq(sp.column(column), literal) predicate = equals if predicate is None else sp.and_(predicate, equals) - read = reading if columns is None else reading.project(columns) + # A column filtered here is read too, and left out again after the filter. + scanned = ( + None + if columns is None + else [*columns, *dict.fromkeys(c for c, _ in local if c not in columns)] + ) + read = reading if scanned is None else reading.project(scanned) with connector._service_call("read", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle reader = table.scan( - None if columns is None else list(columns), + scanned, filter=predicate, # The limit counts rows that match every condition. limit=None if local else limit, @@ -661,6 +667,8 @@ def scan_batches( batch = read.prepare(batch) for column, value in local: batch = batch.filter(_equals(batch.column(column), value)) + if columns is not None and scanned != list(columns): + batch = batch.select(list(columns)) if local and left is not None: batch = batch.slice(0, left) left -= batch.num_rows diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index a0b71ae19..ccf2ea306 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -446,3 +446,101 @@ def run() -> PipelineJob: calls.clear() run() assert calls == [] + + +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] diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index e72249a46..ba98137d8 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -776,11 +776,14 @@ def _one_key(self, rows: pa.Table, key_range: KeyRange) -> list[bool]: 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 = stored.cast(width) + stored, given = stored.cast(width), given.cast(width) values: list[Any] = stored.to_pylist() - keep = [k and v == wanted.value for k, v in zip(keep, values)] + (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: From 3bdae578090157ecbe85cac3d8ca7ae5c304e2df Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 07:15:47 -0800 Subject: [PATCH 03/28] feat(spiraldb): hash entry references by content and fetch entries in batches (ITL-1789) A SpiralDBEntry reference is now hashed by the content of the entry it names (label spiraldb_entry_v1), so an unchanged entry keeps its hash when a source's pin moves. Hashing fetches entries in batches: one scan with many key ranges per table version, through a generic prefetch hook that function nodes, row-built tables and the Arrow hasher call before hashing rows one by one. A process cache keeps the hashes and, within a byte budget, the values. - read() returns the cached entry or reads the recorded version; a gone version or key raises SpiralDBEntryMissingError (no fallback: ITL-1872). - In a job, SpiralDBEntryMissingError fails its own input row under the error policy; any other error propagates as before. - A reference records the service address of its source; read() connects there unless a client is given. - An in-memory source over references has no default source id. - ReadableChannel gains take_ready (non-blocking), used to batch the rows already waiting on the async path. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1789.md | 27 +- docs/concepts/sources.md | 49 +- docs/reference/hashing.md | 2 + src/orcapod/channels.py | 32 ++ src/orcapod/core/nodes/function_node.py | 341 +++++++++----- src/orcapod/core/nodes/operator_node.py | 7 + src/orcapod/core/sources/spiraldb_entries.py | 279 +++++++++++- .../core/sources/spiraldb_table_source.py | 3 + src/orcapod/core/sources/stream_builder.py | 46 +- .../core/streams/arrow_table_stream.py | 10 +- .../core/streams/record_batch_input.py | 12 + src/orcapod/databases/spiraldb_connector.py | 99 +++- src/orcapod/errors.py | 17 + src/orcapod/hashing/arrow_hashers.py | 13 +- src/orcapod/hashing/prefetch.py | 207 +++++++++ .../semantic_hashing/builtin_handlers.py | 37 +- .../logical_types/spiraldb_entry_type.py | 158 +++++-- .../protocols/core_protocols/streams.py | 6 + .../protocols/semantic_types_protocols.py | 4 + tests/test_channels/test_channels.py | 99 ++++ .../test_native_async_operators.py | 10 + .../test_record_batch_channels.py | 15 + .../test_spiraldb_table_source_encoded.py | 429 +++++++++++++++++- tests/test_databases/fake_spiral_sdk.py | 64 ++- tests/test_hashing/golden/cases.py | 2 + .../test_schema_hash_storage_form.py | 2 +- .../test_provisional_hash_warning.py | 32 +- .../test_spiraldb_entry_type.py | 217 ++++++--- .../test_async_fan_out_does_not_hang.py | 3 + 29 files changed, 1916 insertions(+), 306 deletions(-) create mode 100644 src/orcapod/hashing/prefetch.py diff --git a/changelog.d/ITL-1789.md b/changelog.d/ITL-1789.md index c00aeeffa..63c0f7148 100644 --- a/changelog.d/ITL-1789.md +++ b/changelog.d/ITL-1789.md @@ -1,11 +1,20 @@ ### 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 and the column. Its logical type is - `orcapod.spiraldb.entry`, hashed as the stored reference, never as the value it names. - `entry.read()` returns the entry through spiral-sdk as a one-row `pyarrow.Table`, and - `entry.scan()` returns spiral-sdk's scan of that one key and column. Both take an - optional `client`; without one they use spiral-sdk's own sign-in. + 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 and a function pod over it does not + compute again after the source's pin moves. `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. +- 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, never one per row. Entries read + are kept in a cache for the process. +- `orcapod.errors.SpiralDBEntryMissingError` (a `LookupError`), raised when the version a + reference names holds no row with its key or is no longer available. In a job it fails + that input row under the node's error policy. ### Fixed @@ -18,9 +27,11 @@ ### Known limitations -- A reference names the version the source read. When a run's check pins a newer table - version, every reference value changes, so function pods that take the column compute - again for every row, also for entries that did not change. +- A source over `SpiralDBEntry` references built from in-memory data (`ArrowTableSource`, + `DictSource`, `ListSource` and the like) has no default source id, since the default + would read every entry: it must be given a `source_id`. +- `read()` never falls back to a newer version when the recorded one is gone: it raises + `SpiralDBEntryMissingError` (ITL-1872). - `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 diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 7ffad7d80..a8b817045 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1040,18 +1040,23 @@ as **references** to its entries, one per row: 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 source's `pinned_version`), the row's primary-key values (`key`, the - canonical JSON of the key columns in key order, the form of a record ID) and the column - (`column`). The entry it names may itself hold a null. + 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()` reads the entry through spiral-sdk: 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. `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 open the table by its id at the - reference's version, so they read the same value whenever they are called. Both take an - optional `client` (a `spiral.Client`); without one they sign in as spiral-sdk does (the +- `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 the reference's version, so it returns the same value + whenever it is called; an entry hashed or read before in the process is not read again. + `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 key that the version does not hold raises `LookupError`. + sign in. When the version no longer holds a row with the key (or is no longer + available), they raise `orcapod.errors.SpiralDBEntryMissingError` (a `LookupError`) + naming the reference; a newer version is never read in its place. - 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. @@ -1074,12 +1079,26 @@ def first_norm(vector: op.SpiralDBEntry) -> float: norms = first_norm.pod(items.select_data_columns(["vector"])) ``` -**A reference holds the version.** A reference is exact: it reads the value of the version -the source read, also after the table has changed. The price: when a run's check -(`check_for_new_data()`) pins a newer version of the table, every reference names the new -version, so every reference value changes, and function pods that take the column compute -again for every row, also for entries that did not change. A source built with `asof=` -never moves its pin. +**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. So when a run's check (`check_for_new_data()`) +pins a newer version of the table, a function pod computes again only for the entries whose +content changed: an entry that is the same in both versions has the same hash, and its +stored result is used. Hashing needs the content, so a job reads the entries it is about to +use first, together: one SpiralDB scan per table version for the rows a node takes at once +(all its input rows on the synchronous path, the rows that have arrived on the asynchronous +one), never one per row. The entries read stay in a cache for the process (their hashes for +as long as the process runs, their values up to 512 MiB). Reading the source, `head()`, the +preview and building the source read no entry. + +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); any other error is raised as for any other input. + +**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) 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. 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 diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index edb21d4c0..c61c604be 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` | @@ -381,6 +382,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 per process in the entry cache (display only: an in-memory key) | `logical_types/spiraldb_entry_type.py:entry_content_hash`, `core/sources/spiraldb_entries.py:_EntryCache.keep`, `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/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/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 3518b8450..88db1b29f 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -54,7 +54,12 @@ stored_data_tags, without_tag_kind_marks, ) -from orcapod.channels import Channel, ReadableChannel, WritableChannel +from orcapod.channels import ( + Channel, + ChannelClosed, + ReadableChannel, + WritableChannel, +) from orcapod.config import OrcapodConfig from orcapod.core.cached_function_pod import CachedFunctionPod from orcapod.core.data_function import PYTHON_FUNCTION, declaration_for @@ -89,11 +94,13 @@ InputValidationError, PipelineJobRequiredError, OrcapodDatabaseError, + SpiralDBEntryMissingError, TypeIdentityError, OrcapodDatabaseWriteError, StoredTableSchemaError, UnstorableColumnError, ) +from orcapod.hashing.prefetch import prefetch_rows from orcapod.contexts.stored import ( StaleTables, keep_rows_of_data_context, @@ -152,6 +159,40 @@ ) +_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).""" + + def _pipeline_record_order( recorded_at: datetime, result_id: bytes ) -> tuple[datetime, bytes]: @@ -2161,12 +2202,19 @@ 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) + pairs = list(input_stream.iter_data()) inputs = [ - (tag, data, self.compute_instance_id(tag, data)) - for tag, data in input_stream.iter_data() + (tag, data, eid) + for (tag, data), eid in zip(pairs, self._instance_ids_of(pairs)) ] - _ = self.get_cached_results(instance_ids=[eid for _, _, eid in inputs]) + _ = 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 @@ -2216,14 +2264,21 @@ async def _async_execute_load_only( columns={"system_tags": True} )[0] ctx_obs.on_node_start(node_label, node_hash, tag_schema=tag_schema) + pairs = [(tag, data) async for tag, data in input_channel] inputs = [ - (tag, data, self.compute_instance_id(tag, data)) - async for tag, data in input_channel + (tag, data, eid) + for (tag, data), eid in zip(pairs, self._instance_ids_of(pairs)) ] - _ = self.get_cached_results(instance_ids=[eid for _, _, eid in inputs]) + _ = 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 @@ -2726,11 +2781,16 @@ 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() + pairs = list(input_stream.iter_data()) + upstream_entries: list[ + tuple[TagProtocol, DataProtocol, bytes | SpiralDBEntryMissingError] + ] = [ + (tag, data, eid) + for (tag, data), eid in zip(pairs, self._instance_ids_of(pairs)) + ] + 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 @@ -2747,6 +2807,21 @@ def execute( for tag, data, instance_id in upstream_entries: ctx_obs.on_data_start(node_label, tag, data) + 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, + ) + ctx_obs.on_data_crash(node_label, tag, data, instance_id) + if error_policy == "fail_fast": + ctx_obs.on_node_end(node_label, node_hash) + raise 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 ): @@ -3196,6 +3271,37 @@ async def _async_process_data_internal( return tag_out, output_data + def _prefetch_inputs(self, rows: Sequence[DataProtocol]) -> None: + """Fetch together what hashing ``rows`` needs (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, before the rows are hashed one by one. Placeholders hold nothing. + """ + prefetch_rows( + [row for row in rows if not isinstance(row, EmptyData)], + self.data_context.type_converter, + self.data_context.semantic_hasher, + ) + + def _instance_ids_of( + self, pairs: Sequence[tuple[TagProtocol, DataProtocol]] + ) -> 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``. + """ + self._prefetch_inputs([data for _, data in pairs]) + ids: list[bytes | SpiralDBEntryMissingError] = [] + for tag, data in pairs: + try: + ids.append(self.compute_instance_id(tag, data)) + except SpiralDBEntryMissingError as exc: + ids.append(exc) + return ids + def compute_instance_id( self, tag: TagProtocol, @@ -4770,114 +4876,131 @@ def lookup_crashed( async def route_inputs() -> None: """Stage 1: send cache hits to output; stamp misses for computation.""" 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) + while True: + # 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. + try: + first = await input_channel.receive() + except ChannelClosed: + break + batch = await _with_waiting_rows(input_channel, first) + self._prefetch_inputs([data for _, data in batch]) + for tag, data in batch: try: - found_tag, found = self._empty_data_cache_hit( - tag, data, instance_id - ) - except Exception as exc: + 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 continue - 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. + # 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 + continue 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) + 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, ) - 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), + 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), + ) ) - ) finally: await compute_channel.writer.close() diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 91e5f7b25..939eb5121 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -183,6 +183,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 index 5a7a7db3d..b366288c8 100644 --- a/src/orcapod/core/sources/spiraldb_entries.py +++ b/src/orcapod/core/sources/spiraldb_entries.py @@ -6,14 +6,23 @@ 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 are fetched +together (``prefetch_entries``: one scan per service, table and version, with one key +range per entry) into a process-wide cache (``_CACHE``), which keeps every entry's +content hash, or that it is missing, and the fetched values up to a byte budget +(``ENTRY_CACHE_BYTES``), so ``read`` after hashing returns the bytes that were hashed +without another fetch. """ from __future__ import annotations import datetime import json -from collections.abc import Iterator, Sequence -from typing import Any, cast +from collections import OrderedDict +from collections.abc import Iterable, Iterator, Sequence +from threading import Lock +from typing import Any, NamedTuple, cast import pyarrow as pa @@ -21,12 +30,20 @@ require_live_logical_types, row_identifiers, ) -from orcapod.databases.spiraldb_connector import open_table_version, scan_one_key +from orcapod.databases.spiraldb_connector import ( + client_for_service, + open_table_version, + scan_keys, + scan_one_key, +) +from orcapod.errors import SpiralDBEntryMissingError from orcapod.logical_types.spiraldb_entry_type import ( SPIRALDB_ENTRY_STORAGE, LogicalSpiralDBEntry, SpiralDBEntry, + entry_content_hash, ) +from orcapod.types import ContentHash ENCODING_PREFIX = "vortex." """The extension names of the encodings presented as references: Vortex's own.""" @@ -153,6 +170,7 @@ def reference_column( table_id: str, version: int, column: str, + service: str, ) -> pa.ExtensionArray[Any]: """Return one reference per row of ``keys`` to its entry of ``column``. @@ -162,6 +180,7 @@ def reference_column( 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. @@ -176,6 +195,7 @@ def reference_column( 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) @@ -214,22 +234,27 @@ def _key_value(value: object, arrow_type: pa.DataType) -> pa.Array[Any]: return pa.array([value], arrow_type) -def _key_arrays(entry: SpiralDBEntry, table: Any) -> list[pa.Array[Any]]: # pyright: ignore[reportExplicitAny] # an SDK table, untyped - """Return ``entry``'s key values as arrays of ``table``'s key column types. +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). """ - key_columns = [str(c) for c in table.key_columns] # pyright: ignore[reportAny] values = json.loads(entry.key) # pyright: ignore[reportAny] - if not isinstance(values, dict) or list(values) != key_columns: # pyright: ignore[reportUnknownArgumentType] + 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 {key_columns} in order" + f"columns {list(key_columns)} in order" ) - schema: pa.Schema = table.schema() # pyright: ignore[reportAny] arrays: list[pa.Array[Any]] = [] for name in key_columns: value: object = values[name] # pyright: ignore[reportUnknownVariableType] @@ -249,37 +274,247 @@ def _key_arrays(entry: SpiralDBEntry, table: Any) -> list[pa.Array[Any]]: # pyr 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`` makes one with spiral-sdk's own sign-in. + 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. """ - table = open_table_version(client, entry.table_id, entry.version) # pyright: ignore[reportAny] - return scan_one_key(table, entry.column, _key_arrays(entry, table)) # pyright: ignore[reportAny] + table = _table_of(entry, client) # pyright: ignore[reportAny] + 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). + +Content hashes, and which entries are missing, are kept for the life of the process +whatever this budget: they are small. +""" + + +class _EntryKey(NamedTuple): + """What names one entry in the cache: every field of its reference.""" + + service: str + table_id: str + version: int + key: str + column: str + + +def _entry_key(entry: SpiralDBEntry) -> _EntryKey: + return _EntryKey( + entry.service, entry.table_id, entry.version, entry.key, entry.column + ) + + +class _EntryCache: + """The process-wide cache of fetched entries (``_CACHE``). + + ``hashes`` holds each fetched entry's content hash, or ``None`` for an entry its + version does not hold; ``values`` the fetched values, least recently used first, + within ``ENTRY_CACHE_BYTES``. A table version never changes, so neither ever goes + stale. + """ + + def __init__(self) -> None: + self.lock = Lock() + self.hashes: dict[_EntryKey, ContentHash | None] = {} + self.values: OrderedDict[_EntryKey, pa.Table] = OrderedDict() + self.value_bytes = 0 + + def keep(self, key: _EntryKey, value: pa.Table | None) -> None: + """Record what was fetched for ``key`` (``None``: no such entry).""" + with self.lock: + if value is None: + self.hashes[key] = None + return + self.hashes[key] = entry_content_hash(value) + size = value.nbytes + if size > ENTRY_CACHE_BYTES or key in self.values: + return + self.values[key] = value + self.value_bytes += size + while self.value_bytes > ENTRY_CACHE_BYTES: + _, dropped = self.values.popitem(last=False) + self.value_bytes -= dropped.nbytes + + def value(self, key: _EntryKey) -> pa.Table | None: + """Return the held value of ``key``, if any, as the most recently used.""" + with self.lock: + value = self.values.get(key) + if value is not None: + self.values.move_to_end(key) + return value + + def clear(self) -> None: + """Forget everything.""" + with self.lock: + self.hashes.clear() + self.values.clear() + self.value_bytes = 0 + + +_CACHE = _EntryCache() + + +def clear_entry_cache() -> None: + """Forget every fetched entry of this process: its hash and its value.""" + _CACHE.clear() + + +def _fetch( + entries: Sequence[SpiralDBEntry], + client: Any, + *, + skip_malformed: bool, # pyright: ignore[reportExplicitAny] # an SDK client, untyped +) -> dict[_EntryKey, pa.Table | None]: + """Fetch ``entries`` with one scan per (service, table, version) and cache them. + + 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. + + Args: + entries: The references, all fetched (the cache is not consulted). + client: A ``spiral.Client`` for every group; ``None`` uses one per service. + skip_malformed: Leave out an entry whose key does not fit its table's primary + key (hashing it raises later) instead of raising. + + Returns: + What was fetched for each entry: its value, or ``None`` when its version holds + no row with its key. + + Raises: + ValueError: If ``skip_malformed`` is false and a key does not fit its table. + """ + groups: dict[tuple[str, str, int], list[SpiralDBEntry]] = {} + for entry in entries: + groups.setdefault((entry.service, entry.table_id, entry.version), []).append( + entry + ) + fetched: dict[_EntryKey, pa.Table | None] = {} + for group in groups.values(): + table = _table_of(group[0], client) # pyright: ignore[reportAny] + 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.key not in keys: + try: + keys[entry.key] = _key_arrays(entry, key_columns, schema) + except ValueError: + if skip_malformed: + continue + raise + wanted.append(entry) + if not wanted: + continue + 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) + value = ( + None + if index is None + else pa.Table.from_arrays( + [rows.column(entry.column).slice(index, 1)], + schema=pa.schema([rows.schema.field(entry.column)]), + ) + ) + _CACHE.keep(_entry_key(entry), value) + fetched[_entry_key(entry)] = value + return fetched + + +def prefetch_entries(entries: Iterable[SpiralDBEntry]) -> None: + """Fetch, together, the entries this process has not fetched yet. + + One scan per (service, table, version), never one per entry. An entry whose key + does not fit its table is left for its own hash to refuse. + + Args: + entries: The references; repeats are fetched once. + """ + with _CACHE.lock: + todo = { + _entry_key(entry): entry + for entry in entries + if _entry_key(entry) not in _CACHE.hashes + } + if todo: + _ = _fetch(list(todo.values()), None, skip_malformed=True) + + +def _missing(entry: SpiralDBEntry) -> SpiralDBEntryMissingError: + return SpiralDBEntryMissingError( + entry, f"the table at version {entry.version} holds no row with this key" + ) + + +def cached_content_hash(entry: SpiralDBEntry) -> ContentHash: + """Return the content hash of ``entry``, fetching it if this process has not. + + Raises: + SpiralDBEntryMissingError: If its version holds no row with its key. + ValueError: If its key does not fit the table's primary key. + """ + key = _entry_key(entry) + with _CACHE.lock: + known = key in _CACHE.hashes + found = _CACHE.hashes.get(key) + if not known: + _ = _fetch([entry], None, skip_malformed=False) + with _CACHE.lock: + found = _CACHE.hashes.get(key) + if found is None: + raise _missing(entry) + return found def read_entry(entry: SpiralDBEntry, client: Any = None) -> pa.Table: # pyright: ignore[reportExplicitAny] # an SDK client, untyped - """Read ``entry`` through spiral-sdk: one row, one column, as SpiralDB stores it. + """Read ``entry``: one row, one column, as SpiralDB stores it at its version. + + The value comes from the process cache when it holds it (the bytes that were + hashed), else from SpiralDB at the entry's version, never another. Args: entry: The reference. - client: As for ``scan_entry``. + client: A ``spiral.Client``; ``None`` uses a client of the entry's service. Raises: - LookupError: If the table at the entry's version has no row with its key. + SpiralDBEntryMissingError: If its version holds no row with its key. ValueError: If the key does not fit the table's primary key. """ - table: pa.Table = scan_entry(entry, client).to_table() # pyright: ignore[reportAny] - if table.num_rows != 1: - raise LookupError( - f"SpiralDB entry {entry!r}: the table at version {entry.version} holds " - f"{table.num_rows} rows with this key, not one" - ) - return table + key = _entry_key(entry) + value = _CACHE.value(key) + with _CACHE.lock: + known_missing = key in _CACHE.hashes and _CACHE.hashes[key] is None + if value is None and not known_missing: + value = _fetch([entry], client, skip_malformed=False)[key] + if value is None: + raise _missing(entry) + return value diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index c33861f22..90e8b678d 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -407,6 +407,8 @@ 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) @@ -581,6 +583,7 @@ def _with_references(self, rows: "pa.Table", asof: int | None) -> "pa.Table": table_id=self._table_id, version=asof or 0, column=field.name, + service=self._service, ), ) return rows diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 74e104683..c961f7136 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -33,6 +33,7 @@ EXTENSION_METADATA_KEY, EXTENSION_NAME_KEY, ) +from orcapod.hashing.prefetch import fetching_columns from orcapod.logical_types.identifier import LogicalTypeIdentifierError from orcapod.system_constants import constants from orcapod.types import ContentHash @@ -539,7 +540,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, ...] @@ -708,20 +710,37 @@ 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 + 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. @@ -732,6 +751,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 02e92d1cd..3a8120a6f 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -21,6 +21,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 prefetch_rows from orcapod.protocols.core_protocols import PodProtocol, StreamProtocol, TagProtocol from orcapod.protocols.hashing_protocols import ( IdentityChains, @@ -517,8 +518,15 @@ def hashes() -> pa.Array[Any]: rows = self.iter_data() if limit is not None: rows = itertools.islice(rows, limit) + datas = [data for _, data in rows] + # What hashing the rows needs is fetched together (ITL-1789). + prefetch_rows( + datas, + self.data_context.type_converter, + self.data_context.semantic_hasher, + ) return pa.array( - [str(data.content_hash()) for _, data in rows], type=pa.large_string() + [str(data.content_hash()) for data in datas], type=pa.large_string() ) def shape(carried: "pa.Table") -> "pa.Table": diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py index 158bfdbe4..c39e7461f 100644 --- a/src/orcapod/core/streams/record_batch_input.py +++ b/src/orcapod/core/streams/record_batch_input.py @@ -285,6 +285,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 2fbfe68a7..b88a053a8 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -27,7 +27,7 @@ from collections.abc import Iterator, Mapping, Sequence from contextlib import contextmanager from copy import copy -from threading import local +from threading import Lock, local from typing import TYPE_CHECKING, Any, cast import pyarrow as pa @@ -297,6 +297,49 @@ def new_client() -> Any: # pyright: ignore[reportExplicitAny] # an SDK client, return _new_client(None) +def client_for_service(service: str) -> Any: # pyright: ignore[reportExplicitAny] # an SDK client, untyped + """Return a spiral-sdk client of the service at ``service``, one per address and process. + + 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: + SpiralDBSignInError: If spiral-sdk would have to ask a person to sign in. + ImportError: If spiral-sdk is not installed. + """ + with _SERVICE_CLIENTS_LOCK: + held = _SERVICE_CLIENTS.get(service) + if held is not None and held[0] == os.getpid(): + return held[1] # pyright: ignore[reportAny] + client = _new_client({"server.url": service}) # pyright: ignore[reportAny] + _SERVICE_CLIENTS[service] = (os.getpid(), client) + return client # pyright: ignore[reportAny] + + +_SERVICE_CLIENTS: dict[str, tuple[int, Any]] = {} # pyright: ignore[reportExplicitAny] +"""The clients ``client_for_service`` made, by address, with the process that made them.""" + +_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 + + 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 ``version`` (ITL-1789). @@ -311,15 +354,8 @@ def open_table_version(client: Any, table_id: str, version: int) -> Any: # pyri return client.keyed_table_by_id(table_id, asof=version) # 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. - """ +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 @@ -333,7 +369,43 @@ def scan_one_key(table: Any, column: str, key: Sequence[pa.Array[Any]]) -> Any: else: literals.append(sp.literal(array[0].as_py(), arrow_type)) bound = sp.KeyBound(tuple(literals), True) - return table.scan([column], key_ranges=[sp.KeyRange(bound, bound)]) # pyright: ignore[reportAny] + 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): @@ -853,6 +925,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 share_client(self) -> SpiralDBConnector: """Return an independently closable connector in the same SDK client scope.""" self._require_open() diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 91a77a590..0b49aad9f 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -749,6 +749,23 @@ class SpiralDBSignInError(RuntimeError): """ +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``). + """ + + def __init__(self, entry: object, reason: str) -> None: + self.entry = entry + super().__init__(f"SpiralDB entry {entry!r}: {reason}") + + 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..b60919f42 100644 --- a/src/orcapod/hashing/arrow_hashers.py +++ b/src/orcapod/hashing/arrow_hashers.py @@ -14,8 +14,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 prefetch_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,6 +141,11 @@ def _process_table_columns(self, table: "pa.Table | pa.RecordBatch") -> "pa.Tabl new_columns: list[pa.Array | pa.ChunkedArray] = [] new_fields: list[pa.Field] = [] + if table.num_rows > 1: + # Values whose hash needs a fetch are fetched together, not one per cell + # (ITL-1789); a one-row table's cell is fetched by its own hash. + prefetch_table(table, self._type_converter, self._semantic_hasher) + 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 @@ -183,6 +189,11 @@ def _process_table_columns(self, table: "pa.Table | pa.RecordBatch") -> "pa.Tabl 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 diff --git a/src/orcapod/hashing/prefetch.py b/src/orcapod/hashing/prefetch.py new file mode 100644 index 000000000..0c1ea652a --- /dev/null +++ b/src/orcapod/hashing/prefetch.py @@ -0,0 +1,207 @@ +"""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``; before rows are hashed one by one, ``prefetch_rows`` +(rows) or ``prefetch_table`` (a table) hands it every value of its columns at once. +Prefetching changes no hash: it only fills the handler's own cache. + +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. A value anywhere else (inside a +struct) is fetched on its own when hashed. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable + +import pyarrow as pa + +from orcapod.logical_types.identifier import ( + arrow_type_identifier, + container_element_identifier, +) + +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 (``prefetch``).""" + + def prefetch(self, values: Sequence[object]) -> None: + """Fetch what hashing ``values`` needs, together, into the handler's cache. + + Args: + values: Python values of the handler's type; a value it does not fetch + for is ignored. + """ + ... + + +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( + 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. + + 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 + logical_type = type_converter.get_logical_type_by_arrow_extension_name( + element.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 + ) + except Exception: + return None + if not isinstance(handler, PrefetchingHandlerProtocol): + return None + return _Prefetching(handler, logical_type, depth) + + +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) + + def prefetch(self) -> None: + for handler, values in self._values.values(): + if values: + handler.prefetch(values) + + +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] + + +def prefetch_table( + table: pa.Table | pa.RecordBatch, + type_converter: ExtensionLookupProtocol, + semantic_hasher: SemanticHasherProtocol, +) -> None: + """Hand every prefetching handler all the values of its columns of ``table``. + + 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). + """ + if table.num_rows == 0: + return + batches = _Batches() + 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) + batches.add( + found.handler, + [found.logical_type.storage_to_python(value) for value in stored], # pyright: ignore[reportAny] + ) + batches.prefetch() + + +def prefetch_rows( + rows: Sequence[DataProtocol], + type_converter: ExtensionLookupProtocol, + semantic_hasher: SemanticHasherProtocol, +) -> None: + """Hand every prefetching handler all the values of its columns in ``rows``. + + 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) + if not payloads: + return + batches = _Batches() + 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 + ), + ) + batches.prefetch() + + +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). + + 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 _prefetching(field.type, type_converter, semantic_hasher) is not None + ) diff --git a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py index 4d00a1fce..548f99728 100644 --- a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py +++ b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py @@ -24,7 +24,7 @@ from __future__ import annotations import logging -from collections.abc import Iterable +from collections.abc import Iterable, Sequence from typing import TYPE_CHECKING, Any from uuid import UUID @@ -63,6 +63,7 @@ ) from orcapod.logical_types.spiraldb_entry_type import ( SPIRALDB_ENTRY_EXTENSION_NAME, + SPIRALDB_ENTRY_HASH_LABEL, SpiralDBEntry, ) from orcapod.types import ContentHash, Schema @@ -109,41 +110,45 @@ def handle(self, obj: Any, hasher: "SemanticHasherProtocol") -> Encoded: class SpiralDBEntryHandler: - """Hasher for a bare ``SpiralDBEntry``: the tagged reference, never the value it names. + """Hasher for a ``SpiralDBEntry``: the content of the entry it names (ITL-1789). - ``{"__type__": "spiraldb_entry", "table_id": ..., "version": ..., "key": ..., - "column": ...}`` (ITL-1789). The logical type declares stored for its columns. + 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. The value is fetched once per process; a node + fetches the entries of many rows together through ``prefetch`` first. """ EXTENSION_NAME = SPIRALDB_ENTRY_EXTENSION_NAME + HASH_LABEL = SPIRALDB_ENTRY_HASH_LABEL - def handle(self, obj: Any, hasher: "SemanticHasherProtocol") -> Encoded: - """Encode ``obj`` as its four fields under the tag ``spiraldb_entry``. + 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: - ``Encoded("spiraldb_entry", {...})``. + 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 Encoded( - "spiraldb_entry", - { - "table_id": obj.table_id, - "version": obj.version, - "key": obj.key, - "column": obj.column, - }, - ) + return obj.content_hash() raise TypeError( f"SpiralDBEntryHandler: expected SpiralDBEntry, got {type(obj)!r}" ) + def prefetch(self, values: Sequence[object]) -> None: + """Fetch the entries of ``values`` together, before they are hashed one by one. + + Args: + values: ``SpiralDBEntry`` references; anything else is left to ``handle``. + """ + SpiralDBEntry.prefetch(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 index f165f497f..a912cab53 100644 --- a/src/orcapod/logical_types/spiraldb_entry_type.py +++ b/src/orcapod/logical_types/spiraldb_entry_type.py @@ -6,15 +6,20 @@ 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 and the column. It is stored as -itself (``LogicalSpiralDBEntry``, extension name ``orcapod.spiraldb.entry``), and its -value hash is the hash of the reference, never of the encoded value. - -This module imports no spiral-sdk; ``read`` and ``scan`` load it when called. +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 typing import TYPE_CHECKING, Any import polars as pl @@ -26,6 +31,8 @@ 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 @@ -34,8 +41,46 @@ SPIRALDB_ENTRY_EXTENSION_NAME = "orcapod.spiraldb.entry" """The Arrow extension name of a SpiralDB entry reference.""" -_IDENTIFIER_METADATA = version_metadata(1, "stored") -"""Version 1 of the stored layout; the value hash is that of the stored 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( [ @@ -43,20 +88,25 @@ 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 four fields of ``SpiralDBEntry``, none of them nullable.""" +"""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 is exact: it names the - version the source read, so it reads the same value whenever it is read, also - after the table has changed. Its value hash is the hash of the reference, never of - the value it points to. Its fields are read-only; two references are equal when - their four fields are. + 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. @@ -70,19 +120,25 @@ class SpiralDBEntry: 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``). + TypeError: If a field is not of its type (``str``, ``int``, ``str``, ``str``, + ``str``). """ - __slots__ = ("_table_id", "_version", "_key", "_column") + __slots__ = ("_table_id", "_version", "_key", "_column", "_service") - def __init__(self, table_id: str, version: int, key: str, column: str) -> None: + 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( @@ -92,6 +148,7 @@ def __init__(self, table_id: str, version: int, key: str, column: str) -> None: self._version: int = version self._key: str = key self._column: str = column + self._service: str = service @property def table_id(self) -> str: @@ -113,8 +170,13 @@ def column(self) -> str: """The top-level column.""" return self._column - def _fields(self) -> tuple[str, int, str, str]: - return (self._table_id, self._version, self._key, 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): @@ -127,10 +189,10 @@ def __hash__(self) -> int: 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})" + f"key={self._key!r}, column={self._column!r}, service={self._service!r})" ) - def __reduce__(self) -> tuple[type[SpiralDBEntry], tuple[str, int, str, str]]: + 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 @@ -140,9 +202,9 @@ def scan(self, client: Any = None) -> Any: # pyright: ignore[reportExplicitAny, primary key, so it holds at most one row. Args: - client: A ``spiral.Client``. ``None`` (default) makes one with spiral-sdk's - own sign-in (``SPIRAL_*`` environment variables, or a saved - ``spiral login``); it never asks a person to sign in. + 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``. @@ -157,7 +219,11 @@ def scan(self, client: Any = None) -> Any: # pyright: ignore[reportExplicitAny, 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 through spiral-sdk, as SpiralDB stores it. + """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. Args: client: As for ``scan``. @@ -169,19 +235,48 @@ def read(self, client: Any = None) -> pa.Table: # pyright: ignore[reportExplici Raises: ImportError: If spiral-sdk is not installed (``orcapod[spiraldb]``). - LookupError: If the table at ``version`` has no row with this key. + SpiralDBEntryMissingError: If the table at ``version`` has no row with this + key, or the version cannot be read any more. """ 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``). + + Fetched once per process (``prefetch`` fetches many entries together). + + Raises: + SpiralDBEntryMissingError: If the table at ``version`` has no row with this + key, or the version cannot be read any more. + """ + 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. + + Args: + entries: The references. + """ + from orcapod.core.sources.spiraldb_entries import prefetch_entries + + prefetch_entries(entries) + class LogicalSpiralDBEntry(BaseLogicalType): """Logical type for ``SpiralDBEntry``: extension ``orcapod.spiraldb.entry``. - Stored as a struct of the reference's four fields (``SPIRALDB_ENTRY_STORAGE``), - with metadata ``{"value_hash":"stored","version":1}``: a reference is hashed as - stored. Provisional (``provisional`` of ``contexts/logical_types.json``). + 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( @@ -228,13 +323,15 @@ def python_to_storage( converter: Ignored. Present for protocol conformance. Returns: - ``{"table_id": ..., "version": ..., "key": ..., "column": ...}``. + ``{"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( @@ -243,7 +340,7 @@ def storage_to_python( """Rebuild a reference from its stored struct value. Args: - storage_value: A mapping with the four fields. + storage_value: A mapping with the five fields. converter: Ignored. Present for protocol conformance. Returns: @@ -254,4 +351,5 @@ def storage_to_python( version=storage_value["version"], key=storage_value["key"], column=storage_value["column"], + service=storage_value["service"], ) diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index bd681e63a..3184ab69c 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -672,6 +672,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 3ab03e28d..f88476633 100644 --- a/src/orcapod/protocols/semantic_types_protocols.py +++ b/src/orcapod/protocols/semantic_types_protocols.py @@ -57,6 +57,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/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 f05abad59..439d0d5ee 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -2518,3 +2518,18 @@ 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) == [] diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index ccf2ea306..fccc4b4c3 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -25,7 +25,11 @@ from orcapod import function_pod from orcapod.core.sources import SpiralDBTableSource -from orcapod.errors import InputValidationError, ProvisionalHashWarning +from orcapod.errors import ( + InputValidationError, + ProvisionalHashWarning, + SpiralDBEntryMissingError, +) from orcapod.logical_types.provisional import reset_provisional_warnings from orcapod.logical_types.spiraldb_entry_type import ( LogicalSpiralDBEntry, @@ -368,7 +372,8 @@ def test_references_are_provisional(stored: dict[str, Any]): 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: ``LookupError``.""" + """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( @@ -376,10 +381,13 @@ def test_read_of_a_missing_key_raises_lookup_error(stored: dict[str, Any]): entry.version, '{"unit":"u1","time":"2026-01-01T12:00:00.123456Z"}', "vector", + entry.service, ) - with pytest.raises(LookupError, match="0 rows"): + 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( @@ -401,7 +409,9 @@ def test_read_refuses_a_key_that_does_not_fit_the_primary_key( fake_spiral_sdk.scan_log.clear() with pytest.raises(ValueError, match="SpiralDB entry"): - SpiralDBEntry(entry.table_id, entry.version, key, "vector").read() + SpiralDBEntry( + entry.table_id, entry.version, key, "vector", entry.service + ).read() assert fake_spiral_sdk.scan_log == [] @@ -544,3 +554,414 @@ def test_a_projected_scan_filters_on_a_column_it_does_not_return(limit: int | No 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 _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() == [] + + _write_row("u9", _TIMES[2]) + _rewrite_vector([True] * 4, _encoded_values(0).take([0, 1, 2, 0])) + fake_spiral_sdk.scan_log.clear() + _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"}'] + + +@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] diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index ba98137d8..18f396b52 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -77,7 +77,8 @@ "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", + "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)", } @@ -110,6 +111,7 @@ class ScanRecord: filter: Any limit: int | None count: bool = False + key_ranges: int = 0 batches_read: int = 0 closed: bool = False @@ -711,8 +713,16 @@ def scan( """Plan a scan (``rows``, ``literal``, ``float-eq``, ``float-order``, ``key-range``).""" rows = self._store.read(self.resource_id, self._version) - for key_range in key_ranges or (): - rows = rows.filter(pa.array(self._one_key(rows, key_range), pa.bool_())) + 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( @@ -752,6 +762,7 @@ def scan( 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) @@ -1036,6 +1047,19 @@ def write_encoded( ] 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( @@ -1077,16 +1101,30 @@ 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 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 clear_service_clients + + clear_entry_cache() + clear_service_clients() + 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() + clear_service_clients() def migrate( diff --git a/tests/test_hashing/golden/cases.py b/tests/test_hashing/golden/cases.py index b5de293bd..5d61ec311 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 da59607f3..b3d3cca2c 100644 --- a/tests/test_hashing/test_schema_hash_storage_form.py +++ b/tests/test_hashing/test_schema_hash_storage_form.py @@ -94,7 +94,7 @@ def _hasher() -> Any: "orcapod.path": False, "orcapod.polars.dataframe": True, "orcapod.polars.series": True, - "orcapod.spiraldb.entry": False, + "orcapod.spiraldb.entry": True, "orcapod.torch.tensor": True, "orcapod.upath": False, "orcapod.uuid": False, diff --git a/tests/test_logical_types/test_provisional_hash_warning.py b/tests/test_logical_types/test_provisional_hash_warning.py index c59db9123..876305d87 100644 --- a/tests/test_logical_types/test_provisional_hash_warning.py +++ b/tests/test_logical_types/test_provisional_hash_warning.py @@ -55,7 +55,8 @@ def _value(name: str) -> Any: if name == "orcapod.polars.dataframe": return pl.DataFrame({"a": [1, 2]}) if name == "orcapod.spiraldb.entry": - return SpiralDBEntry("table_x", 1, '{"k":1}', "v") + # 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]) @@ -72,6 +73,35 @@ def _value(name: str) -> Any: 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", + ] + 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.""" diff --git a/tests/test_logical_types/test_spiraldb_entry_type.py b/tests/test_logical_types/test_spiraldb_entry_type.py index 47d5c4e86..84ff33f4e 100644 --- a/tests/test_logical_types/test_spiraldb_entry_type.py +++ b/tests/test_logical_types/test_spiraldb_entry_type.py @@ -1,9 +1,11 @@ """``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 round trip through a source and a function pod, and its value hash -(the reference's, never the value it names). Reading a reference is tested with the -SpiralDB source (``tests/test_core/sources/test_spiraldb_table_source_encoded.py``). +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 @@ -16,29 +18,48 @@ import orcapod as op from orcapod import function_pod -from orcapod.contexts import get_default_context 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 DictSource +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["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 ) @@ -57,14 +78,17 @@ def test_fields_equality_and_hash(): ("version", 8), ("key", '{"unit":"u2","time":"2026-01-01T00:00:00Z"}'), ("column", "embeddings"), + ("service", "https://other.example.invalid"), ): assert _entry(**{name: other}) != _entry(), name - assert (_entry().table_id, _entry().version, _entry().key, _entry().column) == ( - _FIELDS["table_id"], - _FIELDS["version"], - _FIELDS["key"], - _FIELDS["column"], - ) + 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(): @@ -72,6 +96,8 @@ def test_fields_are_read_only_and_it_pickles(): 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 @@ -83,6 +109,7 @@ def test_fields_are_read_only_and_it_pickles(): ("version", True), ("key", None), ("column", b"v"), + ("service", None), ], ) def test_refuses_a_field_of_another_type(name: str, value: Any): @@ -92,32 +119,137 @@ def test_refuses_a_field_of_another_type(name: str, value: Any): def test_identifier_and_storage(): - """Extension ``orcapod.spiraldb.entry``, metadata version 1 hashed as stored, over a - struct of four non-null fields.""" + """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":"stored","version":1}' + 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_round_trip_through_a_source_and_a_function_pod(): - """References given to a source, taken by a function pod and returned by it come - back equal, as ``SpiralDBEntry`` objects, in a column of the logical type.""" - first, second = _entry(), _entry(key='{"unit":"u2","time":"2026-01-01T00:00:00Z"}') - rows: Any = [ - {"id": 1, "label": "a", "ref": first}, - {"id": 2, "label": "b", "ref": second}, +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" + ), + }, ] - source = DictSource(rows, tag_columns=["id"], tag_only_columns=True) + + +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")) @@ -127,6 +259,7 @@ def keep(ref: SpiralDBEntry) -> tuple[SpiralDBEntry, str]: 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() @@ -135,41 +268,3 @@ def keep(ref: SpiralDBEntry) -> tuple[SpiralDBEntry, str]: second, ] assert table.column("column").to_pylist() == ["vector", "vector"] - - -def test_the_value_hash_is_the_references(): - """A bare reference hashes by its four fields: equal references hash alike, and any - field moves the hash.""" - hasher = get_default_context().semantic_hasher - base = hasher.hash_object(_entry()) - - assert hasher.hash_object(_entry()) == base - for name, other in ( - ("table_id", "table_b"), - ("version", 8), - ("key", '{"unit":"u2","time":"2026-01-01T00:00:00Z"}'), - ("column", "embeddings"), - ): - assert hasher.hash_object(_entry(**{name: other})) != base, name - - -def test_a_column_hashes_as_stored(): - """A column of references hashes from its stored struct: rows with equal references - give one table hash, and another reference moves it.""" - extension = LogicalSpiralDBEntry().get_arrow_extension_type() - hasher = get_default_context().arrow_hasher - - def table(*entries: SpiralDBEntry) -> pa.Table: - storage = pa.array( - [LogicalSpiralDBEntry().python_to_storage(e) for e in entries], - SPIRALDB_ENTRY_STORAGE, - ) - return pa.table( - {"ref": pa.ExtensionArray.from_storage(extension, storage)}, - schema=pa.schema([pa.field("ref", extension, nullable=False)]), - ) - - assert hasher.hash_table(table(_entry())) == hasher.hash_table(table(_entry())) - assert hasher.hash_table(table(_entry())) != hasher.hash_table( - table(_entry(version=8)) - ) 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 79f11ea72..7c613ca37 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 @@ -239,6 +239,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. From 05c050232a3f74b8c14c20cad1876817313f0765 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 08:16:40 -0800 Subject: [PATCH 04/28] docs(api): list SpiralDBEntryMissingError in the errors reference (ITL-1789) Co-Authored-By: Claude Opus 5.5 --- docs/api/errors.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/api/errors.md b/docs/api/errors.md index 860739d66..08d6c63da 100644 --- a/docs/api/errors.md +++ b/docs/api/errors.md @@ -134,6 +134,8 @@ These exceptions and warnings report storage, schema, and connector problems. ::: orcapod.errors.SpiralDBSignInError +::: orcapod.errors.SpiralDBEntryMissingError + ## Feature availability and stability These exceptions and warnings report optional dependencies and features still in development. From 6f629f37c01a2f2d8f5254b9c186c86b25f6972e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 08:28:51 -0800 Subject: [PATCH 05/28] fix(spiraldb): address review of entry hashing and batched fetches (ITL-1789) - Open exactly the reference's version (asof is a cutoff); a gone table or version makes that group's entries missing, other groups still fetch. - References record the version SpiralDB resolved the pin to. - Keep cached entries per sign-in; a read through a given client bypasses the cache; held service clients are scoped to the sign-in. - Bound the held hashes; keep a copied one-row value, not a scan slice. - Use the fetched result directly, so a concurrent clear cannot make an entry look missing. - A projected read scans the primary key for the references it keeps and builds only those. - Refuse a condition on a reference column with ValueError. - Detect references nested in structs, lists and user-class fields when refusing a default source id. - SpiralDBEntryMissingError pickles with its reason and notes; list it in the errors API reference. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1789.md | 12 +- docs/concepts/sources.md | 42 +-- src/orcapod/core/sources/spiraldb_entries.py | 221 ++++++++++----- .../core/sources/spiraldb_table_source.py | 52 +++- src/orcapod/databases/spiraldb_connector.py | 72 ++++- src/orcapod/errors.py | 7 + src/orcapod/hashing/prefetch.py | 92 +++++- .../test_spiraldb_table_source_encoded.py | 268 +++++++++++++++++- .../test_spiraldb_entry_type.py | 39 +++ 9 files changed, 663 insertions(+), 142 deletions(-) diff --git a/changelog.d/ITL-1789.md b/changelog.d/ITL-1789.md index 63c0f7148..039f31477 100644 --- a/changelog.d/ITL-1789.md +++ b/changelog.d/ITL-1789.md @@ -11,10 +11,11 @@ one they connect to the recorded service address with spiral-sdk's own sign-in. - 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, never one per row. Entries read - are kept in a cache for the process. + are 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. - `orcapod.errors.SpiralDBEntryMissingError` (a `LookupError`), raised when the version a - reference names holds no row with its key or is no longer available. In a job it fails - that input row under the node's error policy. + 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. ### Fixed @@ -28,8 +29,9 @@ ### Known limitations - A source over `SpiralDBEntry` references built from in-memory data (`ArrowTableSource`, - `DictSource`, `ListSource` and the like) has no default source id, since the default - would read every entry: it must be given a `source_id`. + `DictSource`, `ListSource` and the like), also references inside a struct, a list or a + user class's field, has no default source id, since the default would read every + entry: it must be given a `source_id`. - `read()` never falls back to a newer version when the recorded one is gone: it raises `SpiralDBEntryMissingError` (ITL-1872). - `orcapod.spiraldb.entry` is provisional: its value hash and stored identity may change diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 7f54e25d9..f96473348 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1070,24 +1070,30 @@ as **references** to its entries, one per row: 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 source's `pinned_version`), 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 + 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 the reference's version, so it returns the same value - whenever it is called; an entry hashed or read before in the process is not read again. - `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. When the version no longer holds a row with the key (or is no longer - available), they raise `orcapod.errors.SpiralDBEntryMissingError` (a `LookupError`) - naming the reference; a newer version is never read in its place. + 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. `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 entries are held per sign-in. +- When the version no longer holds a row with the key, or the table or that version can + no longer be opened, `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 cannot be opened: the scan + is lazy, and for a key the version does not hold it yields no row, which its caller + must handle. - 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. @@ -1118,9 +1124,10 @@ content changed: an entry that is the same in both versions has the same hash, a stored result is used. Hashing needs the content, so a job reads the entries it is about to use first, together: one SpiralDB scan per table version for the rows a node takes at once (all its input rows on the synchronous path, the rows that have arrived on the asynchronous -one), never one per row. The entries read stay in a cache for the process (their hashes for -as long as the process runs, their values up to 512 MiB). Reading the source, `head()`, the -preview and building the source read no entry. +one), never one per row. The entries read stay in a cache for the process, per sign-in +(up to a million hashes and 512 MiB of values, least recently used first; an entry no +longer held is read again at its version). Reading the source, `head()`, the preview and +building the source read no entry. 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 @@ -1128,8 +1135,9 @@ the run); any other error is raised as for any other input. **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) 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. +`ListSource` and the like), also inside a struct, a list or a field of your own class, 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. 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 diff --git a/src/orcapod/core/sources/spiraldb_entries.py b/src/orcapod/core/sources/spiraldb_entries.py index b366288c8..487f5045c 100644 --- a/src/orcapod/core/sources/spiraldb_entries.py +++ b/src/orcapod/core/sources/spiraldb_entries.py @@ -9,10 +9,10 @@ A reference's value hash is the hash of its entry's content. The entries are fetched together (``prefetch_entries``: one scan per service, table and version, with one key -range per entry) into a process-wide cache (``_CACHE``), which keeps every entry's -content hash, or that it is missing, and the fetched values up to a byte budget -(``ENTRY_CACHE_BYTES``), so ``read`` after hashing returns the bytes that were hashed -without another fetch. +range per entry) into a process-wide cache (``_CACHE``), kept per sign-in, which keeps +entries' content hashes, or that they are missing (``ENTRY_CACHE_HASHES``), and the +fetched values 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. """ from __future__ import annotations @@ -31,10 +31,12 @@ row_identifiers, ) from orcapod.databases.spiraldb_connector import ( + TableVersionNotFoundError, client_for_service, open_table_version, scan_keys, scan_one_key, + sign_in_scope, ) from orcapod.errors import SpiralDBEntryMissingError from orcapod.logical_types.spiraldb_entry_type import ( @@ -301,16 +303,23 @@ def scan_entry(entry: SpiralDBEntry, client: Any = None) -> Any: # pyright: ign ENTRY_CACHE_BYTES = 512 * 1024 * 1024 -"""How many bytes of fetched entry values the process keeps for ``read`` (512 MiB). +"""How many bytes of fetched entry values the process keeps for ``read`` (512 MiB).""" -Content hashes, and which entries are missing, are kept for the life of the process -whatever this budget: they are small. +ENTRY_CACHE_HASHES = 1_000_000 +"""How many entries' content hashes (or that they are missing) the process keeps. + +Each holds a reference's fields and a digest: a few hundred bytes. An entry evicted is +fetched again at its exact version when it is next hashed. """ +_NO_ROW = "the table at version {version} holds no row with this key" + class _EntryKey(NamedTuple): - """What names one entry in the cache: every field of its reference.""" + """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 @@ -318,42 +327,69 @@ class _EntryKey(NamedTuple): column: str -def _entry_key(entry: SpiralDBEntry) -> _EntryKey: +def _entry_key(entry: SpiralDBEntry, sign_in: object) -> _EntryKey: return _EntryKey( - entry.service, entry.table_id, entry.version, entry.key, entry.column + sign_in, entry.service, entry.table_id, entry.version, entry.key, entry.column ) +class _Fetched(NamedTuple): + """What a fetch found for one entry: its value, or why there is none.""" + + value: pa.Table | None + missing: str | None + + class _EntryCache: """The process-wide cache of fetched entries (``_CACHE``). - ``hashes`` holds each fetched entry's content hash, or ``None`` for an entry its - version does not hold; ``values`` the fetched values, least recently used first, - within ``ENTRY_CACHE_BYTES``. A table version never changes, so neither ever goes - stale. + 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``; + ``values`` the fetched values, 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: dict[_EntryKey, ContentHash | None] = {} + self.hashes: OrderedDict[_EntryKey, ContentHash | str] = OrderedDict() self.values: OrderedDict[_EntryKey, pa.Table] = OrderedDict() self.value_bytes = 0 - def keep(self, key: _EntryKey, value: pa.Table | None) -> None: - """Record what was fetched for ``key`` (``None``: no such entry).""" + 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: ContentHash | str = ( + entry_content_hash(value) + if value is not None + else cast(str, fetched.missing) + ) with self.lock: - if value is None: - self.hashes[key] = None - return - self.hashes[key] = entry_content_hash(value) + self.hashes[key] = known + self.hashes.move_to_end(key) + while len(self.hashes) > ENTRY_CACHE_HASHES: + _ = self.hashes.popitem(last=False) + if value is None or key in self.values: + return known size = value.nbytes - if size > ENTRY_CACHE_BYTES or key in self.values: - return + if size > ENTRY_CACHE_BYTES: + return known self.values[key] = value self.value_bytes += size while self.value_bytes > ENTRY_CACHE_BYTES: _, dropped = self.values.popitem(last=False) self.value_bytes -= dropped.nbytes + 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 not None: + self.hashes.move_to_end(key) + return found def value(self, key: _EntryKey) -> pa.Table | None: """Return the held value of ``key``, if any, as the most recently used.""" @@ -379,17 +415,30 @@ def clear_entry_cache() -> None: _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 cached 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, + client: Any, # pyright: ignore[reportExplicitAny] # an SDK client, untyped *, - skip_malformed: bool, # pyright: ignore[reportExplicitAny] # an SDK client, untyped -) -> dict[_EntryKey, pa.Table | None]: - """Fetch ``entries`` with one scan per (service, table, version) and cache them. + skip_malformed: bool, +) -> dict[SpiralDBEntry, _Fetched]: + """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. + 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). @@ -398,8 +447,7 @@ def _fetch( key (hashing it raises later) instead of raising. Returns: - What was fetched for each entry: its value, or ``None`` when its version holds - no row with its key. + What was fetched for each entry: its value, or why it is missing. Raises: ValueError: If ``skip_malformed`` is false and a key does not fit its table. @@ -409,9 +457,14 @@ def _fetch( groups.setdefault((entry.service, entry.table_id, entry.version), []).append( entry ) - fetched: dict[_EntryKey, pa.Table | None] = {} + fetched: dict[SpiralDBEntry, _Fetched] = {} for group in groups.values(): - table = _table_of(group[0], client) # pyright: ignore[reportAny] + try: + table = _table_of(group[0], client) # pyright: ignore[reportAny] + except TableVersionNotFoundError as exc: + for entry in group: + fetched[entry] = _Fetched(None, str(exc)) + continue 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]]] = {} @@ -437,16 +490,11 @@ def _fetch( } for entry in wanted: index = row_of.get(entry.key) - value = ( - None + fetched[entry] = ( + _Fetched(None, _NO_ROW.format(version=entry.version)) if index is None - else pa.Table.from_arrays( - [rows.column(entry.column).slice(index, 1)], - schema=pa.schema([rows.schema.field(entry.column)]), - ) + else _Fetched(_one_row(rows, entry.column, index), None) ) - _CACHE.keep(_entry_key(entry), value) - fetched[_entry_key(entry)] = value return fetched @@ -454,67 +502,88 @@ def prefetch_entries(entries: Iterable[SpiralDBEntry]) -> None: """Fetch, together, the entries this process has not fetched yet. One scan per (service, table, version), never one per entry. An entry whose key - does not fit its table is left for its own hash to refuse. + does not fit its table is left for its own hash to refuse. 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. """ - with _CACHE.lock: - todo = { - _entry_key(entry): entry - for entry in entries - if _entry_key(entry) not in _CACHE.hashes - } + sign_in = sign_in_scope() + if sign_in is None: + return + todo = { + entry: key + for entry in entries + if _CACHE.known(key := _entry_key(entry, sign_in)) is None + } if todo: - _ = _fetch(list(todo.values()), None, skip_malformed=True) + for entry, found in _fetch(list(todo), None, skip_malformed=True).items(): + _ = _CACHE.keep(todo[entry], found) -def _missing(entry: SpiralDBEntry) -> SpiralDBEntryMissingError: - return SpiralDBEntryMissingError( - entry, f"the table at version {entry.version} holds no row with this key" - ) +def _missing(entry: SpiralDBEntry, reason: str) -> SpiralDBEntryMissingError: + return SpiralDBEntryMissingError(entry, reason) def cached_content_hash(entry: SpiralDBEntry) -> ContentHash: """Return the content hash of ``entry``, fetching it if this process has not. Raises: - SpiralDBEntryMissingError: If its version holds no row with its key. + SpiralDBEntryMissingError: If its version holds no row with its key, or the + table or that version cannot be opened. ValueError: If its key does not fit the table's primary key. """ - key = _entry_key(entry) - with _CACHE.lock: - known = key in _CACHE.hashes - found = _CACHE.hashes.get(key) - if not known: - _ = _fetch([entry], None, skip_malformed=False) - with _CACHE.lock: - found = _CACHE.hashes.get(key) - if found is None: - raise _missing(entry) - return found + sign_in = sign_in_scope() + 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: + found = _fetch([entry], None, skip_malformed=False)[entry] + known = ( + _CACHE.keep(key, found) + if key is not None + else ( + entry_content_hash(found.value) + if found.value is not None + else cast(str, found.missing) + ) + ) + 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. - The value comes from the process cache when it holds it (the bytes that were - hashed), else from SpiralDB at the entry's version, never another. + 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. With ``client``, it is always read through that client, and + nothing is taken from the cache or kept in it. 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. + SpiralDBEntryMissingError: If its version holds no row with its key, or the + table or that version cannot be opened. ValueError: If the key does not fit the table's primary key. """ - key = _entry_key(entry) - value = _CACHE.value(key) - with _CACHE.lock: - known_missing = key in _CACHE.hashes and _CACHE.hashes[key] is None - if value is None and not known_missing: - value = _fetch([entry], client, skip_malformed=False)[key] - if value is None: - raise _missing(entry) - return value + if client is not None: + found = _fetch([entry], client, skip_malformed=False)[entry] + 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 = _fetch([entry], None, skip_malformed=False)[entry] + if key is not None: + _ = _CACHE.keep(key, found) + if found.value is None: + raise _missing(entry, cast(str, found.missing)) + return found.value diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index f9e009cca..5b81455ef 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -564,19 +564,27 @@ def _check_tags_as_data( f"null. Key columns, which can be copied: {list(self._key_columns)}." ) - def _with_references(self, rows: "pa.Table", asof: int | None) -> "pa.Table": - """Return ``rows`` with a reference column for each encoded column (ITL-1789). + 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. - Each reference names its row's entry: the table id, the version read - (``asof``), the row's primary-key values and the column. It takes the encoded - column's name and position in the table's schema. + 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 self._encoded: + if not columns: return rows - if asof is None and rows.num_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" @@ -585,12 +593,12 @@ def _with_references(self, rows: "pa.Table", asof: int | None) -> "pa.Table": # columns read (a projected read reads only some). position = 0 for field in self._table_schema: - if field.name in self._encoded: + if field.name in columns: reference = reference_column( rows, self._primary_key, table_id=self._table_id, - version=asof or 0, + version=version, column=field.name, service=self._service, ) @@ -764,12 +772,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 @@ -1157,10 +1171,19 @@ def _read_batches( # Keys must be unique across the whole read, not only within a slice. identifiers: set[str] = set() # What the scan returns: the table's columns (or ``table_columns``) without - # the encoded ones, whose references are added after (ITL-1789). + # 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._scanned_schema if f.name in scanned], metadata=cast( @@ -1168,6 +1191,7 @@ def _read_batches( self._scanned_schema.metadata, ), ) + version = table.version_at(asof) if references else None read_columns = ( expected_schema.names if table_columns is not None @@ -1211,7 +1235,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, asof) + 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/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index d99a8c9bb..1ab0c92ee 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -496,7 +496,7 @@ def client_for_service(service: str) -> Any: # pyright: ignore[reportExplicitAn """Return this process's spiral-sdk client of the service at ``service``. The client is the one the connectors of that address and sign-in share - (``_client_for``), held here so that it outlives them. Signed in as spiral-sdk signs + (``_client_for``), held here, for that sign-in only, so that it outlives them. Signed in as spiral-sdk signs in (``SPIRAL_*`` environment variables, or a saved ``spiral login``); it never asks a person to sign in. @@ -507,18 +507,32 @@ def client_for_service(service: str) -> Any: # pyright: ignore[reportExplicitAn SpiralDBSignInError: If spiral-sdk would have to ask a person to sign in. ImportError: If spiral-sdk is not installed. """ + 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. + return _client_for({"server.url": service}).sdk # pyright: ignore[reportAny] with _SERVICE_CLIENTS_LOCK: - held = _SERVICE_CLIENTS.get(service) + held = _SERVICE_CLIENTS.get((service, sign_in)) if held is not None and held[0] == os.getpid() and not held[1].health.failed: return held[1].sdk # pyright: ignore[reportAny] shared = _client_for({"server.url": service}) with _SERVICE_CLIENTS_LOCK: - _SERVICE_CLIENTS[service] = (os.getpid(), shared) + _SERVICE_CLIENTS[(service, sign_in)] = (os.getpid(), shared) return shared.sdk # pyright: ignore[reportAny] -_SERVICE_CLIENTS: dict[str, tuple[int, _SharedClient]] = {} -"""The clients ``client_for_service`` holds, by address, with the process that got them.""" +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[tuple[str, Any], tuple[int, _SharedClient]] = {} # pyright: ignore[reportExplicitAny] +"""The clients ``client_for_service`` holds, by address and sign-in, with the process +that got them: a changed sign-in never reuses one.""" _SERVICE_CLIENTS_LOCK = Lock() @@ -538,18 +552,55 @@ def service_address(client: Any) -> str: # pyright: ignore[reportExplicitAny] 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 ``version`` (ITL-1789). + """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``; ``None`` makes one (``new_client``). + client: A ``spiral.Client``; ``None`` uses ``new_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``. """ if client is None: client = new_client() with _service_call(f"open table {table_id} at version {version}"): - return client.keyed_table_by_id(table_id, asof=version) # pyright: ignore[reportAny] + 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 @@ -853,6 +904,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 diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 0b49aad9f..b885a35c0 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -759,12 +759,19 @@ class SpiralDBEntryMissingError(LookupError): 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/prefetch.py b/src/orcapod/hashing/prefetch.py index 0c1ea652a..da81d31a9 100644 --- a/src/orcapod/hashing/prefetch.py +++ b/src/orcapod/hashing/prefetch.py @@ -14,8 +14,9 @@ from __future__ import annotations -from collections.abc import Sequence -from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable +import json +from collections.abc import Iterator, Sequence +from typing import TYPE_CHECKING, Any, Protocol, cast, runtime_checkable import pyarrow as pa @@ -68,6 +69,26 @@ def __init__( 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, @@ -86,19 +107,61 @@ def _prefetching( while (inner := container_element_identifier(element)) is not None: element = inner depth += 1 - logical_type = type_converter.get_logical_type_by_arrow_extension_name( - element.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 - ) + found = _prefetching_handler(element.name, type_converter, semantic_hasher) except Exception: return None - if not isinstance(handler, PrefetchingHandlerProtocol): + if found is None: return None - return _Prefetching(handler, logical_type, depth) + 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: @@ -193,7 +256,8 @@ def fetching_columns( """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). + 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. @@ -203,5 +267,5 @@ def fetching_columns( return sorted( field.name for field in schema - if _prefetching(field.type, type_converter, semantic_hasher) is not None + if _fetches(field.type, type_converter, semantic_hasher) ) diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index 79e659b52..d9741e829 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -16,6 +16,7 @@ import asyncio import datetime +import os import warnings from pathlib import Path from typing import Any @@ -336,9 +337,15 @@ def test_an_encoded_column_cannot_be_a_tag(stored: dict[str, Any]): def test_a_condition_on_a_reference_column_is_refused(stored: dict[str, Any]): - """``where`` on a reference column is refused when the source is built.""" - with pytest.raises((TypeError, ValueError)): + """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(): @@ -591,6 +598,14 @@ def _rewrite_vector(keep: list[bool], values: pa.Array[Any]) -> None: ) +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 @@ -712,14 +727,26 @@ def both(vector: SpiralDBEntry, embeddings: SpiralDBEntry) -> tuple[float, int]: 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]) - _rewrite_vector([True] * 4, _encoded_values(0).take([0, 1, 2, 0])) + # 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() - _run(job, orchestrator) + 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"]) @@ -968,13 +995,28 @@ def counting(table_id: str, **kwargs: Any) -> Any: @pytest.mark.parametrize( - "selected", [["rate"], ["vector", "rate"], ["label", "embeddings", "vector"]] + ("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] + 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.""" + 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 @@ -984,7 +1026,7 @@ def test_a_projected_read_places_the_references_as_the_whole_read( with warnings.catch_warnings(): warnings.simplefilter("ignore") with job: - _source().select_data_columns(selected, label="sel") + _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() @@ -993,7 +1035,12 @@ def test_a_projected_read_places_the_references_as_the_whole_read( narrowed = read.projected_table(selected, columns=config) assert narrowed is not None - unread = [c for c in ("rate", "label", "vector", "embeddings") if c not in selected] + 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] ) @@ -1002,3 +1049,206 @@ def test_a_projected_read_places_the_references_as_the_whole_read( 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'"] diff --git a/tests/test_logical_types/test_spiraldb_entry_type.py b/tests/test_logical_types/test_spiraldb_entry_type.py index 84ff33f4e..0a8279fc5 100644 --- a/tests/test_logical_types/test_spiraldb_entry_type.py +++ b/tests/test_logical_types/test_spiraldb_entry_type.py @@ -11,6 +11,7 @@ from __future__ import annotations import pickle +from dataclasses import dataclass from typing import Any import pyarrow as pa @@ -268,3 +269,41 @@ def keep(ref: SpiralDBEntry) -> tuple[SpiralDBEntry, str]: 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 + + +def test_a_source_over_references_inside_user_classes_needs_a_source_id(): + """CodeRabbit on PR 680 (prefetch.py:206): a reference inside a column (a user + class's field, also one level further down) fetches when hashed, so such a source + has no default source id either; with one, it builds without fetching.""" + rows: Any = [ + { + "id": 1, + "plain": 3, + "held": _HoldsAReference(_entry(), 1), + "deep": _HoldsAHolder(_HoldsAReference(_entry(version=8), 2), "x"), + } + ] + with pytest.raises(ValueError, match=r"\['deep', 'held'\].*source_id"): + DictSource(rows, tag_columns=["id"], tag_only_columns=True) + source = DictSource( + rows, tag_columns=["id"], tag_only_columns=True, source_id="held" + ) + assert source.as_table().num_rows == 1 + plain: Any = [{"id": 1, "plain": 3}] + assert DictSource(plain, tag_columns=["id"], tag_only_columns=True).source_id From ea10790829fc86552211438e920e4ae30f6c7674 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 09:20:54 -0800 Subject: [PATCH 06/28] fix(spiraldb): keep fetched entries only under the sign-in still current (ITL-1789) - A fetch is kept in the entry cache, and a client held for a service, only when the sign-in is unchanged after the fetch or client was taken. - Each fetched group is kept as soon as it is read, so a later group's error does not lose it; the content hash is computed once per entry. - scan() raises SpiralDBEntryMissingError for a table or version that cannot be opened, as documented. Co-Authored-By: Claude Opus 5.5 --- docs/reference/hashing.md | 2 +- src/orcapod/core/sources/spiraldb_entries.py | 83 +++++++++++++------ src/orcapod/databases/spiraldb_connector.py | 3 + .../test_spiraldb_table_source_encoded.py | 80 ++++++++++++++++++ 4 files changed, 143 insertions(+), 25 deletions(-) diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 58af33634..5024a2619 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -382,7 +382,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 per process in the entry cache (display only: an in-memory key) | `logical_types/spiraldb_entry_type.py:entry_content_hash`, `core/sources/spiraldb_entries.py:_EntryCache.keep`, `core/sources/spiraldb_entries.py:cached_content_hash`, `hashing/semantic_hashing/builtin_handlers.py:SpiralDBEntryHandler.handle` | +| 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 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:_found`, `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/core/sources/spiraldb_entries.py b/src/orcapod/core/sources/spiraldb_entries.py index 487f5045c..58ae728ce 100644 --- a/src/orcapod/core/sources/spiraldb_entries.py +++ b/src/orcapod/core/sources/spiraldb_entries.py @@ -20,7 +20,7 @@ import datetime import json from collections import OrderedDict -from collections.abc import Iterable, Iterator, Sequence +from collections.abc import Callable, Iterable, Iterator, Sequence from threading import Lock from typing import Any, NamedTuple, cast @@ -295,8 +295,13 @@ def scan_entry(entry: SpiralDBEntry, client: Any = None) -> Any: # pyright: ign 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 cannot be + opened. (For a key the version does not hold, the scan yields no row.) """ - table = _table_of(entry, client) # pyright: ignore[reportAny] + 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] @@ -334,10 +339,38 @@ def _entry_key(entry: SpiralDBEntry, sign_in: object) -> _EntryKey: class _Fetched(NamedTuple): - """What a fetch found for one entry: its value, or why there is none.""" + """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 _found(value: pa.Table) -> _Fetched: + return _Fetched(value, None, entry_content_hash(value)) + + +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 class _EntryCache: @@ -360,11 +393,7 @@ 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: ContentHash | str = ( - entry_content_hash(value) - if value is not None - else cast(str, fetched.missing) - ) + known = fetched.known with self.lock: self.hashes[key] = known self.hashes.move_to_end(key) @@ -432,6 +461,7 @@ def _fetch( client: Any, # pyright: ignore[reportExplicitAny] # an SDK client, untyped *, skip_malformed: bool, + publish: Callable[[SpiralDBEntry, _Fetched], object] | None = None, ) -> dict[SpiralDBEntry, _Fetched]: """Fetch ``entries`` with one scan per (service, table, version). @@ -445,6 +475,8 @@ def _fetch( client: A ``spiral.Client`` for every group; ``None`` uses one per service. skip_malformed: Leave out an entry whose key does not fit its table's primary key (hashing it raises later) instead of raising. + publish: 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. Returns: What was fetched for each entry: its value, or why it is missing. @@ -464,6 +496,8 @@ def _fetch( except TableVersionNotFoundError as exc: for entry in group: fetched[entry] = _Fetched(None, str(exc)) + if publish is not None: + _ = publish(entry, fetched[entry]) continue key_columns = [str(c) for c in table.key_columns] # pyright: ignore[reportAny] schema: pa.Schema = table.schema() # pyright: ignore[reportAny] @@ -493,8 +527,10 @@ def _fetch( fetched[entry] = ( _Fetched(None, _NO_ROW.format(version=entry.version)) if index is None - else _Fetched(_one_row(rows, entry.column, index), None) + else _found(_one_row(rows, entry.column, index)) ) + if publish is not None: + _ = publish(entry, fetched[entry]) return fetched @@ -518,8 +554,7 @@ def prefetch_entries(entries: Iterable[SpiralDBEntry]) -> None: if _CACHE.known(key := _entry_key(entry, sign_in)) is None } if todo: - for entry, found in _fetch(list(todo), None, skip_malformed=True).items(): - _ = _CACHE.keep(todo[entry], found) + _ = _fetch(list(todo), None, skip_malformed=True, publish=_publisher(sign_in)) def _missing(entry: SpiralDBEntry, reason: str) -> SpiralDBEntryMissingError: @@ -538,16 +573,13 @@ def cached_content_hash(entry: SpiralDBEntry) -> ContentHash: 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: - found = _fetch([entry], None, skip_malformed=False)[entry] - known = ( - _CACHE.keep(key, found) - if key is not None - else ( - entry_content_hash(found.value) - if found.value is not None - else cast(str, found.missing) - ) - ) + found = _fetch( + [entry], + None, + skip_malformed=False, + publish=None if sign_in is None else _publisher(sign_in), + )[entry] + known = found.known if isinstance(known, str): raise _missing(entry, known) return known @@ -581,9 +613,12 @@ def read_entry(entry: SpiralDBEntry, client: Any = None) -> pa.Table: # pyright known = None if key is None else _CACHE.known(key) if isinstance(known, str): raise _missing(entry, known) - found = _fetch([entry], None, skip_malformed=False)[entry] - if key is not None: - _ = _CACHE.keep(key, found) + found = _fetch( + [entry], + None, + skip_malformed=False, + publish=None if sign_in is None else _publisher(sign_in), + )[entry] if found.value is None: raise _missing(entry, cast(str, found.missing)) return found.value diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 1ab0c92ee..589d5ec12 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -516,6 +516,9 @@ def client_for_service(service: str) -> Any: # pyright: ignore[reportExplicitAn if held is not None and held[0] == os.getpid() and not held[1].health.failed: return held[1].sdk # pyright: ignore[reportAny] shared = _client_for({"server.url": service}) + 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[(service, sign_in)] = (os.getpid(), shared) return shared.sdk # pyright: ignore[reportAny] diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index d9741e829..f2371013a 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -1252,3 +1252,83 @@ def test_a_missing_entry_error_pickles_with_its_notes(stored: dict[str, Any]): 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, which + propagates), the earlier group's entries are not fetched again.""" + 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) + with pytest.raises(ConnectionError): + SpiralDBEntry.prefetch([*first, *later]) + 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() == [] From fd64224278cc55d73d617cdad2f628070dff35b1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 10:50:28 -0800 Subject: [PATCH 07/28] fix(spiraldb): charge held values their overhead; prefetch holds no values (ITL-1789) - Each held value is charged its buffers plus ENTRY_VALUE_OVERHEAD. - A prefetch only fills the cache: it collects no fetched value. - Docs: a scan per version is what reading ahead does, not a bound on every scan; a read asking for row hashes reads entries; changing the sign-in while reads run in other threads is not supported. Co-Authored-By: Claude Opus 5.5 --- docs/concepts/sources.md | 24 +++++++--- src/orcapod/core/sources/spiraldb_entries.py | 36 +++++++++++--- .../test_spiraldb_table_source_encoded.py | 48 +++++++++++++++++++ 3 files changed, 94 insertions(+), 14 deletions(-) diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index f96473348..06cb49994 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1121,13 +1121,23 @@ the entry it names (its value, bit for bit, and its encoding's extension name an parameters), not of the reference's fields. So when a run's check (`check_for_new_data()`) pins a newer version of the table, a function pod computes again only for the entries whose content changed: an entry that is the same in both versions has the same hash, and its -stored result is used. Hashing needs the content, so a job reads the entries it is about to -use first, together: one SpiralDB scan per table version for the rows a node takes at once -(all its input rows on the synchronous path, the rows that have arrived on the asynchronous -one), never one per row. The entries read stay in a cache for the process, per sign-in -(up to a million hashes and 512 MiB of values, least recently used first; an entry no -longer held is read again at its version). Reading the source, `head()`, the preview and -building the source read no entry. +stored result is used. 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 node takes at +once (all its input rows on the synchronous path, the rows that have arrived on the +asynchronous one). The entries read stay in a cache for the process, per sign-in (up to a +million hashes and 512 MiB of values, least recently used first). An entry that is no +longer held when it is hashed or read is read again on its own, at its version; so is +every entry when the process's sign-in cannot be told apart (then nothing is read ahead +or kept). 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. 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 diff --git a/src/orcapod/core/sources/spiraldb_entries.py b/src/orcapod/core/sources/spiraldb_entries.py index 58ae728ce..9338f7004 100644 --- a/src/orcapod/core/sources/spiraldb_entries.py +++ b/src/orcapod/core/sources/spiraldb_entries.py @@ -310,6 +310,10 @@ def scan_entry(entry: SpiralDBEntry, client: Any = None) -> Any: # pyright: ign 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 Arrow buffers (its table, schema and +column objects), 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. @@ -373,6 +377,11 @@ def publish(entry: SpiralDBEntry, found: _Fetched) -> object: return publish +def _charge(value: pa.Table) -> int: + """The bytes a held value is charged: its buffers and ``ENTRY_VALUE_OVERHEAD``.""" + return value.nbytes + ENTRY_VALUE_OVERHEAD + + class _EntryCache: """The process-wide cache of fetched entries (``_CACHE``). @@ -401,14 +410,14 @@ def keep(self, key: _EntryKey, fetched: _Fetched) -> ContentHash | str: _ = self.hashes.popitem(last=False) if value is None or key in self.values: return known - size = value.nbytes + size = _charge(value) if size > ENTRY_CACHE_BYTES: return known self.values[key] = value self.value_bytes += size while self.value_bytes > ENTRY_CACHE_BYTES: _, dropped = self.values.popitem(last=False) - self.value_bytes -= dropped.nbytes + self.value_bytes -= _charge(dropped) return known def known(self, key: _EntryKey) -> ContentHash | str | None: @@ -462,6 +471,7 @@ def _fetch( *, skip_malformed: bool, publish: Callable[[SpiralDBEntry, _Fetched], object] | None = None, + collect: bool = True, ) -> dict[SpiralDBEntry, _Fetched]: """Fetch ``entries`` with one scan per (service, table, version). @@ -477,6 +487,8 @@ def _fetch( key (hashing it raises later) instead of raising. publish: 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. + collect: Whether to return what was found. A caller that only fills the cache + passes ``False``, so no value outlives its group unless the cache holds it. Returns: What was fetched for each entry: its value, or why it is missing. @@ -495,9 +507,11 @@ def _fetch( table = _table_of(group[0], client) # pyright: ignore[reportAny] except TableVersionNotFoundError as exc: for entry in group: - fetched[entry] = _Fetched(None, str(exc)) + missing = _Fetched(None, str(exc)) + if collect: + fetched[entry] = missing if publish is not None: - _ = publish(entry, fetched[entry]) + _ = publish(entry, missing) continue key_columns = [str(c) for c in table.key_columns] # pyright: ignore[reportAny] schema: pa.Schema = table.schema() # pyright: ignore[reportAny] @@ -524,13 +538,15 @@ def _fetch( } for entry in wanted: index = row_of.get(entry.key) - fetched[entry] = ( + found = ( _Fetched(None, _NO_ROW.format(version=entry.version)) if index is None else _found(_one_row(rows, entry.column, index)) ) + if collect: + fetched[entry] = found if publish is not None: - _ = publish(entry, fetched[entry]) + _ = publish(entry, found) return fetched @@ -554,7 +570,13 @@ def prefetch_entries(entries: Iterable[SpiralDBEntry]) -> None: if _CACHE.known(key := _entry_key(entry, sign_in)) is None } if todo: - _ = _fetch(list(todo), None, skip_malformed=True, publish=_publisher(sign_in)) + _ = _fetch( + list(todo), + None, + skip_malformed=True, + publish=_publisher(sign_in), + collect=False, + ) def _missing(entry: SpiralDBEntry, reason: str) -> SpiralDBEntryMissingError: diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index f2371013a..445521fd3 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -1332,3 +1332,51 @@ def second_fails(*args: Any, **kwargs: Any) -> Any: 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 buffers plus + ``ENTRY_VALUE_OVERHEAD``, so a budget of two small values holds two, not all.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entries = _entries(_table(_source()), "vector") + size = entries[0].read().nbytes + spiraldb_entries.clear_entry_cache() + monkeypatch.setattr( + spiraldb_entries, + "ENTRY_CACHE_BYTES", + 2 * (size + spiraldb_entries.ENTRY_VALUE_OVERHEAD), + ) + SpiralDBEntry.prefetch(entries) + cache = spiraldb_entries._CACHE # pyright: ignore[reportPrivateUsage] + assert len(cache.values) == 2 + assert cache.value_bytes == 2 * (size + spiraldb_entries.ENTRY_VALUE_OVERHEAD) + + +def test_a_prefetch_keeps_no_value_the_cache_does_not_hold( + stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch +): + """CodeRabbit (spiraldb_entries.py:533): a prefetch only fills the cache; it does + not hold every fetched value until all groups are read.""" + import orcapod.core.sources.spiraldb_entries as spiraldb_entries + + entries = _entries(_table(_source()), "vector") + real = spiraldb_entries._fetch # pyright: ignore[reportPrivateUsage] + returned: list[int] = [] + + def recording(*args: Any, **kwargs: Any) -> Any: + found = real(*args, **kwargs) + returned.append(len(found)) + return found + + monkeypatch.setattr(spiraldb_entries, "_fetch", recording) + SpiralDBEntry.prefetch(entries) + assert returned == [0] + assert len({e.content_hash() for e in entries}) == 3 From 4ce0a098f4cd9e142e43d8a92ecc4c512542e581 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 12:47:56 -0800 Subject: [PATCH 08/28] fix(spiraldb): address the independent review of entry references (ITL-1789) - A default read, scan or prefetch signs in only to a service address this process reached through a connector or source it built; any other raises SpiralDBUntrustedServiceError before a client is made. One client per address. - Held values are frozen; read() returns the caller's own table. - The async route keeps main's single-row order unless the input has a fetching column; a chain's full observer trace is compared with main's. - A batch keeps its fetched outcomes in a batch-local map, so each entry is scanned once per batch whatever the cache keeps; references a function returns are fetched together before its outputs are hashed. - A SpiralDBEntry inside a user class field or an Arrow struct or map column is refused where it is declared or the source is built. - Budgets charge keys, strings and metadata; a read through a given client computes no digest; a prefetch error propagates as from the row hash. - The documentation sample has a several-item form and runs in a test. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1789.md | 33 +- docs/api/errors.md | 2 + docs/concepts/sources.md | 68 +- docs/reference/hashing.md | 2 +- src/orcapod/core/nodes/function_node.py | 826 ++++++++++++------ src/orcapod/core/sources/spiraldb_entries.py | 412 ++++++--- src/orcapod/core/sources/stream_builder.py | 20 +- .../core/streams/arrow_table_stream.py | 16 +- src/orcapod/databases/spiraldb_connector.py | 112 ++- src/orcapod/errors.py | 27 + src/orcapod/hashing/arrow_hashers.py | 143 +-- src/orcapod/hashing/prefetch.py | 125 ++- .../semantic_hashing/builtin_handlers.py | 15 +- .../logical_types/spiraldb_entry_type.py | 21 + .../logical_types/user_class_identity.py | 33 +- .../test_spiraldb_table_source_encoded.py | 512 ++++++++++- tests/test_databases/fake_spiral_sdk.py | 11 +- .../test_schema_hash_storage_form.py | 36 +- .../test_provisional_hash_warning.py | 4 + .../test_spiraldb_entry_type.py | 126 ++- .../test_observer_order_of_a_chain.py | 365 ++++++++ 21 files changed, 2286 insertions(+), 623 deletions(-) create mode 100644 tests/test_pipeline/test_observer_order_of_a_chain.py diff --git a/changelog.d/ITL-1789.md b/changelog.d/ITL-1789.md index 039f31477..26ea7ba18 100644 --- a/changelog.d/ITL-1789.md +++ b/changelog.d/ITL-1789.md @@ -8,15 +8,29 @@ compute again after the source's pin moves. `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. + 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. 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, never one per row. Entries read - are 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. + per table version for the rows the node takes at once, 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. 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 @@ -29,9 +43,14 @@ ### Known limitations - A source over `SpiralDBEntry` references built from in-memory data (`ArrowTableSource`, - `DictSource`, `ListSource` and the like), also references inside a struct, a list or a - user class's field, has no default source id, since the default would read every - entry: it must be given a `source_id`. + `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). - `orcapod.spiraldb.entry` is provisional: its value hash and stored identity may change diff --git a/docs/api/errors.md b/docs/api/errors.md index 08d6c63da..3a72293d0 100644 --- a/docs/api/errors.md +++ b/docs/api/errors.md @@ -136,6 +136,8 @@ These exceptions and warnings report storage, schema, and connector problems. ::: 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/concepts/sources.md b/docs/concepts/sources.md index 06cb49994..8acd4bacb 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1082,12 +1082,21 @@ as **references** to its entries, one per row: 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. `entry.scan()` returns spiral-sdk's + 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 entries are held per sign-in. + 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: build a source of that service first, or pass a client + of it (`entry.read(client=...)`). - When the version no longer holds a row with the key, or the table or that version can no longer be opened, `entry.read()` raises `orcapod.errors.SpiralDBEntryMissingError` (a `LookupError`) naming the reference; a newer version is never read in its place. @@ -1104,18 +1113,26 @@ import orcapod as op from orcapod import function_pod from orcapod.sources import SpiralDBTableSource -items = SpiralDBTableSource("my-project-123456", "items") # "vector" is encoded +# "vector" and "embeddings" are encoded; "rate" is a plain column. +items = SpiralDBTableSource("my-project-123456", "items") -@function_pod(output_keys="first_norm") -def first_norm(vector: op.SpiralDBEntry) -> float: - value = vector.read().column("vector")[0].as_py() - return value["block_0"]["norms"] +@function_pod(output_keys=("first_norm", "count")) +def summarize( + vector: op.SpiralDBEntry, embeddings: op.SpiralDBEntry, rate: float | None +) -> tuple[float, int]: + norm = vector.read().column("vector")[0].as_py()["block_0"]["norms"] + count = embeddings.read().column("embeddings")[0].as_py()["count"] + return norm * (rate or 1.0), count -norms = first_norm.pod(items.select_data_columns(["vector"])) +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. So when a run's check (`check_for_new_data()`) @@ -1124,11 +1141,17 @@ content changed: an entry that is the same in both versions has the same hash, a stored result is used. 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 node takes at once (all its input rows on the synchronous path, the rows that have arrived on the -asynchronous one). The entries read stay in a cache for the process, per sign-in (up to a -million hashes and 512 MiB of values, least recently used first). An entry that is no -longer held when it is hashed or read is read again on its own, at its version; so is -every entry when the process's sign-in cannot be told apart (then nothing is read ahead -or kept). Building the source, a plain read (`as_table()`, `iter_data()`), `head()` and +asynchronous one), and hashes those rows from what that scan read. 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 (up to 256 on the synchronous path, the results that have arrived on the +asynchronous one). 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. @@ -1141,13 +1164,24 @@ 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); any other error is raised as for any other input. +the run); so does a returned reference whose entry cannot be read. Any other error (a +failed scan, a refused service address) is raised as for any other input, at the first +row whose hash needs that entry, with the column named. **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 struct, a list or a field of your own class, 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. +`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 diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 5024a2619..2a906e052 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -382,7 +382,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 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:_found`, `core/sources/spiraldb_entries.py:cached_content_hash`, `hashing/semantic_hashing/builtin_handlers.py:SpiralDBEntryHandler.handle` | +| 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/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 88db1b29f..59652ed12 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -18,6 +18,7 @@ import asyncio import contextlib +import functools import dataclasses import logging import sys @@ -54,12 +55,7 @@ stored_data_tags, without_tag_kind_marks, ) -from orcapod.channels import ( - Channel, - ChannelClosed, - ReadableChannel, - WritableChannel, -) +from orcapod.channels import Channel, ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig from orcapod.core.cached_function_pod import CachedFunctionPod from orcapod.core.data_function import PYTHON_FUNCTION, declaration_for @@ -100,7 +96,7 @@ StoredTableSchemaError, UnstorableColumnError, ) -from orcapod.hashing.prefetch import prefetch_rows +from orcapod.hashing.prefetch import prefetched_columns, prefetched_rows from orcapod.contexts.stored import ( StaleTables, keep_rows_of_data_context, @@ -193,6 +189,27 @@ async def _with_waiting_rows( 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]: @@ -1564,6 +1581,9 @@ def __init__( self._commit_every_rows: int | None = None 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 (``_record_after_batch``; ITL-1789). + self._deferred_records: list[_DeferredRecord] | None = None self.attach_databases( pipeline_database=pipeline_database, @@ -2804,84 +2824,97 @@ 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 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, - ) - ctx_obs.on_data_crash(node_label, tag, data, instance_id) - if error_policy == "fail_fast": - ctx_obs.on_node_end(node_label, node_hash) - raise instance_id - failed_rows += 1 - continue + 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, + ) + ctx_obs.on_data_crash(node_label, tag, data, instance_id) + if error_policy == "fail_fast": + ctx_obs.on_node_end(node_label, node_hash) + raise 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 - 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) + 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, + self._commit_or_end_node( + self._row_processed, ctx_obs, node_label, node_hash ) - 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)) - 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 @@ -3006,6 +3039,186 @@ 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`` computed rows + are held, whose results' references are then fetched together, one scan per + table version. The rows keep their input order. A row that fails under + ``fail_fast`` first finishes the rows held before it. + + Returns: + How many rows failed. + """ + failed = 0 + held: list[_HeldRow] = [] + + 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, + ) + 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 exc + + def stop( + tag: TagProtocol, + data: DataProtocol, + exc: OrcapodDatabaseError | TypeIdentityError, + ) -> None: + """Report a row whose database read or write failed, or whose stored + result cannot be decoded: the run stops whatever the policy.""" + if isinstance(exc, OrcapodDatabaseError): + 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) + + 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() + with prefetched_rows( + [record.output_data for record in pending], + self.data_context.type_converter, + self.data_context.semantic_hasher, + ): + for row in rows: + if row.record is not None: + deferred = pending[row.record] + try: + deferred.record( + output_data_hash=deferred.output_data.content_hash() + ) + except (OrcapodDatabaseError, TypeIdentityError) as exc: + stop(row.tag, row.data, exc) + raise + except Exception as exc: + crash(row.tag, row.data, exc) + failed += 1 + continue + if not row.cached: + ctx_obs.on_data_end( + node_label, row.tag, row.data, row.result, cached=False + ) + 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._commit_or_end_node( + self._row_processed, ctx_obs, node_label, node_hash + ) + + self._deferred_records = [] + try: + for tag, data, instance_id in upstream_entries: + ctx_obs.on_data_start(node_label, tag, data) + if isinstance(instance_id, SpiralDBEntryMissingError): + # No input hash: a failed row (see ``execute``). + if error_policy == "fail_fast": + finish() + crash(tag, data, instance_id) + failed += 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) + held.append( + _HeldRow(tag, data, instance_id, tag_out, result, None, True) + ) + 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: + stop(tag, data, exc) + raise + except Exception as exc: + if error_policy == "fail_fast": + finish() + crash(tag, data, exc) + failed += 1 + continue + record = before if len(self._deferred_records) > before else None + held.append( + _HeldRow(tag, data, instance_id, tag_out, result, record, False) + ) + if len(self._deferred_records) >= _PREFETCH_ROWS: + finish() + finish() + 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 + (``_record_after_batch``). + + 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, @@ -3082,15 +3295,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( @@ -3105,14 +3321,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( @@ -3271,19 +3490,35 @@ async def _async_process_data_internal( return tag_out, output_data - def _prefetch_inputs(self, rows: Sequence[DataProtocol]) -> None: - """Fetch together what hashing ``rows`` needs (ITL-1789). + 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, before the rows are hashed one by one. Placeholders hold nothing. + version, and the rows hashed one by one inside the block use what was fetched. + Placeholders hold nothing. """ - prefetch_rows( + 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 _instance_ids_of( self, pairs: Sequence[tuple[TagProtocol, DataProtocol]] ) -> list[bytes | SpiralDBEntryMissingError]: @@ -3291,15 +3526,16 @@ def _instance_ids_of( 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``. + as that row's failure. Any other error raises, as from ``compute_instance_id``, + at the first row it concerns. """ - self._prefetch_inputs([data for _, data in pairs]) ids: list[bytes | SpiralDBEntryMissingError] = [] - for tag, data in pairs: - try: - ids.append(self.compute_instance_id(tag, data)) - except SpiralDBEntryMissingError as exc: - ids.append(exc) + 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) return ids def compute_instance_id( @@ -4873,194 +5109,222 @@ def lookup_crashed( failed_rows[0] += 1 return True + async def route_one(tag: TagProtocol, data: DataProtocol) -> None: + """Send one input row: a cache hit to output, a miss to compute.""" + try: + 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: + 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 + 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) + 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)) + 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: - while True: + # 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. - try: - first = await input_channel.receive() - except ChannelClosed: - break - batch = await _with_waiting_rows(input_channel, first) - self._prefetch_inputs([data for _, data in batch]) - for tag, data in batch: - try: - 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 - continue - # 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 - continue - 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), - ) - ) + 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) - ) - result_computed = bool( - output_data.get_meta_value( - execution_pod.RESULT_COMPUTED_FLAG, False - ) + 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 ) - 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. - exc.add_context( - node_label=node_label, tag=original_tag.as_dict() - ) - raise + ) + try: + output_hash = output_data.content_hash() + except Exception as exc: + # A result that cannot be hashed (it returns a reference to + # a missing entry): a failed row under the row failure + # policy, as on the sync path (ITL-1789). 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 - ), + if not lookup_crashed(original_tag, input_data, exc): + raise + return + 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, ) - # Update in-memory cache so iter_data() sees the result. - clean_tag = output_tag.drop_meta_columns( - _TAG_NODE_INPUT_REF, ignore_missing=True + except OrcapodDatabaseError as exc: + # This runs outside the pod's per-row handler: name the + # node and row here. + exc.add_context( + node_label=node_label, tag=original_tag.as_dict() ) - self._cached_output_datas[instance_id] = ( - clean_tag, - output_data, + 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 + ) + 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. + outputs_fetch = self._outputs_fetch() + 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'. diff --git a/src/orcapod/core/sources/spiraldb_entries.py b/src/orcapod/core/sources/spiraldb_entries.py index 9338f7004..5c1f86451 100644 --- a/src/orcapod/core/sources/spiraldb_entries.py +++ b/src/orcapod/core/sources/spiraldb_entries.py @@ -7,12 +7,15 @@ ``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 are fetched -together (``prefetch_entries``: one scan per service, table and version, with one key -range per entry) into a process-wide cache (``_CACHE``), kept per sign-in, which keeps -entries' content hashes, or that they are missing (``ENTRY_CACHE_HASHES``), and the -fetched values 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 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 @@ -21,6 +24,8 @@ import json 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 @@ -311,16 +316,24 @@ def scan_entry(entry: SpiralDBEntry, client: Any = None) -> Any: # pyright: ign """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 Arrow buffers (its table, schema and -column objects), so that many small values do not exceed the budget unseen.""" +"""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. -Each holds a reference's fields and a digest: a few hundred bytes. An entry evicted is -fetched again at its exact version when it is next hashed. +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" @@ -342,6 +355,15 @@ def _entry_key(entry: SpiralDBEntry, sign_in: object) -> _EntryKey: ) +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.""" @@ -360,10 +382,6 @@ def known(self) -> ContentHash | str: ) -def _found(value: pa.Table) -> _Fetched: - return _Fetched(value, None, entry_content_hash(value)) - - 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 @@ -377,9 +395,34 @@ def publish(entry: SpiralDBEntry, found: _Fetched) -> object: return publish -def _charge(value: pa.Table) -> int: - """The bytes a held value is charged: its buffers and ``ENTRY_VALUE_OVERHEAD``.""" - return value.nbytes + ENTRY_VALUE_OVERHEAD +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: @@ -387,15 +430,19 @@ class _EntryCache: 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``; - ``values`` the fetched values, least recently used first, within - ``ENTRY_CACHE_BYTES``. A table version never changes, so neither goes stale. + 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, ContentHash | str] = OrderedDict() - self.values: OrderedDict[_EntryKey, pa.Table] = OrderedDict() + 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: @@ -403,21 +450,34 @@ def keep(self, key: _EntryKey, fetched: _Fetched) -> ContentHash | str: 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: - self.hashes[key] = known - self.hashes.move_to_end(key) - while len(self.hashes) > ENTRY_CACHE_HASHES: - _ = self.hashes.popitem(last=False) - if value is None or key in self.values: + 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(value) + size = _charge(frozen, key) if size > ENTRY_CACHE_BYTES: return known - self.values[key] = value + 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 -= _charge(dropped) + _, (_, dropped) = self.values.popitem(last=False) + self.value_bytes -= dropped return known def known(self, key: _EntryKey) -> ContentHash | str | None: @@ -425,22 +485,26 @@ def known(self, key: _EntryKey) -> ContentHash | str | None: ``None`` when nothing is held.""" with self.lock: found = self.hashes.get(key) - if found is not None: - self.hashes.move_to_end(key) - return found + if found is None: + return None + self.hashes.move_to_end(key) + return found[0] def value(self, key: _EntryKey) -> pa.Table | None: - """Return the held value of ``key``, if any, as the most recently used.""" + """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: - value = self.values.get(key) - if value is not None: - self.values.move_to_end(key) - return value + 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 @@ -456,7 +520,7 @@ def clear_entry_cache() -> None: 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 cached entry never holds the whole scan's 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( @@ -468,11 +532,11 @@ def _one_row(rows: pa.Table, column: str, index: int) -> pa.Table: def _fetch( entries: Sequence[SpiralDBEntry], client: Any, # pyright: ignore[reportExplicitAny] # an SDK client, untyped + found: Callable[[SpiralDBEntry, _Fetched], object], *, - skip_malformed: bool, - publish: Callable[[SpiralDBEntry, _Fetched], object] | None = None, - collect: bool = True, -) -> dict[SpiralDBEntry, _Fetched]: + 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, @@ -482,81 +546,93 @@ def _fetch( Args: entries: The references, all fetched (the cache is not consulted). - client: A ``spiral.Client`` for every group; ``None`` uses one per service. - skip_malformed: Leave out an entry whose key does not fit its table's primary - key (hashing it raises later) instead of raising. - publish: Called with each entry and what was found, as soon as its group is + 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. - collect: Whether to return what was found. A caller that only fills the cache - passes ``False``, so no value outlives its group unless the cache holds it. - - Returns: - What was fetched for each entry: its value, or why it is missing. + 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 group's client, table or scan + failed); the other entries are still fetched. ``None`` raises the first. Raises: - ValueError: If ``skip_malformed`` is false and a key does not fit its table. + Exception: Without ``failed``, what fetching raised: ``ValueError`` if a key + does not fit its table, ``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 ) - fetched: dict[SpiralDBEntry, _Fetched] = {} for group in groups.values(): try: - table = _table_of(group[0], client) # pyright: ignore[reportAny] - except TableVersionNotFoundError as exc: + _fetch_group(group, client, found, digest=digest, failed=failed) + except Exception as exc: + if failed is None: + raise for entry in group: - missing = _Fetched(None, str(exc)) - if collect: - fetched[entry] = missing - if publish is not None: - _ = publish(entry, missing) - continue - 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] = [] + _ = 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: - if entry.key not in keys: - try: - keys[entry.key] = _key_arrays(entry, key_columns, schema) - except ValueError: - if skip_malformed: - continue + _ = 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.key not in keys: + try: + keys[entry.key] = _key_arrays(entry, key_columns, schema) + except ValueError as exc: + if failed is None: raise - wanted.append(entry) - if not wanted: + _ = 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 - 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) - found = ( - _Fetched(None, _NO_ROW.format(version=entry.version)) - if index is None - else _found(_one_row(rows, entry.column, index)) - ) - if collect: - fetched[entry] = found - if publish is not None: - _ = publish(entry, found) - return fetched + value = _one_row(rows, entry.column, index) + _ = found( + entry, _Fetched(value, None, entry_content_hash(value) if digest else None) + ) def prefetch_entries(entries: Iterable[SpiralDBEntry]) -> None: - """Fetch, together, the entries this process has not fetched yet. + """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 is left for its own hash to refuse. Nothing is fetched when - the current sign-in cannot be told apart (``sign_in_scope``): nothing could be - kept for it. + 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. @@ -564,44 +640,120 @@ def prefetch_entries(entries: Iterable[SpiralDBEntry]) -> None: sign_in = sign_in_scope() if sign_in is None: return - todo = { - entry: key - for entry in entries - if _CACHE.known(key := _entry_key(entry, sign_in)) is None - } + todo = [ + entry + for entry in dict.fromkeys(entries) + if _CACHE.known(_entry_key(entry, sign_in)) is None + ] if todo: - _ = _fetch( - list(todo), - None, - skip_malformed=True, - publish=_publisher(sign_in), - collect=False, - ) + _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.""" + +_BATCH: ContextVar[dict[SpiralDBEntry, _Outcome] | None] = ContextVar( + "orcapod_spiraldb_entry_batch", default=None +) +"""The outcomes fetched for the batch being hashed (``prefetched_entries``).""" + + +@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. 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. + Values are kept in the process cache (``read``) as ``prefetch_entries`` keeps them. + + Args: + entries: The references; repeats are fetched once. + """ + outer = _BATCH.get() + batch: dict[SpiralDBEntry, _Outcome] = {} if outer is None else dict(outer) + sign_in = sign_in_scope() + 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[entry] = exc + + _fetch(todo, None, found, failed=failed) + token = _BATCH.set(batch) + try: + yield + finally: + _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. + Raises: SpiralDBEntryMissingError: If its version holds no row with its key, or the table or that version cannot be opened. + SpiralDBUntrustedServiceError: If its service is not one this process reached. ValueError: If its key does not fit the table's primary key. """ - sign_in = sign_in_scope() - key = None if sign_in is None else _entry_key(entry, sign_in) - known = None if key is None else _CACHE.known(key) + batch = _BATCH.get() + known: _Outcome | None = None if batch is None else batch.get(entry) if known is None: - found = _fetch( - [entry], - None, - skip_malformed=False, - publish=None if sign_in is None else _publisher(sign_in), - )[entry] - known = found.known + sign_in = sign_in_scope() + 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 known if isinstance(known, str): raise _missing(entry, known) return known @@ -612,8 +764,9 @@ def read_entry(entry: SpiralDBEntry, client: Any = None) -> pa.Table: # pyright 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. With ``client``, it is always read through that client, and - nothing is taken from the cache or kept in it. + 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. @@ -622,10 +775,12 @@ def read_entry(entry: SpiralDBEntry, client: Any = None) -> pa.Table: # pyright Raises: SpiralDBEntryMissingError: If its version holds no row with its key, or the table or that version cannot be opened. + 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. """ if client is not None: - found = _fetch([entry], client, skip_malformed=False)[entry] + 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) @@ -635,12 +790,13 @@ def read_entry(entry: SpiralDBEntry, client: Any = None) -> pa.Table: # pyright known = None if key is None else _CACHE.known(key) if isinstance(known, str): raise _missing(entry, known) - found = _fetch( - [entry], + found = _one( + entry, None, - skip_malformed=False, + digest=sign_in is not None, publish=None if sign_in is None else _publisher(sign_in), - )[entry] + ) 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/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 5fb31aee5..105fc0240 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -34,7 +34,7 @@ EXTENSION_METADATA_KEY, EXTENSION_NAME_KEY, ) -from orcapod.hashing.prefetch import fetching_columns +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 @@ -983,6 +983,24 @@ def build( self._data_context.type_converter, self._data_context.semantic_hasher, ) + 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: diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 10edb5381..4cae02e97 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -22,7 +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 prefetch_rows +from orcapod.hashing.prefetch import prefetched_rows from orcapod.protocols.core_protocols import PodProtocol, StreamProtocol, TagProtocol from orcapod.protocols.hashing_protocols import ( IdentityChains, @@ -633,15 +633,17 @@ def hashes() -> pa.Array[Any]: if limit is not None: rows = itertools.islice(rows, limit) datas = [data for _, data in rows] - # What hashing the rows needs is fetched together (ITL-1789). - prefetch_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() - ) + ): + 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/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 589d5ec12..35e51c793 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -52,6 +52,7 @@ from orcapod.databases.spiraldb_store_tables import StoreTables from orcapod.errors import ( NullInNonNullableColumnError, + SpiralDBUntrustedServiceError, SpiralDBWriteNotSupportedError, TableSchemaError, UnrecordedTableSchemaWarning, @@ -492,35 +493,121 @@ def new_client() -> Any: # pyright: ignore[reportExplicitAny] # an SDK client, return _client_for(None).sdk # pyright: ignore[reportAny] +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``. - 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. Signed in as spiral-sdk signs - in (``SPIRAL_*`` environment variables, or a saved ``spiral login``); it never asks - a person to sign in. + 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. return _client_for({"server.url": service}).sdk # pyright: ignore[reportAny] with _SERVICE_CLIENTS_LOCK: - held = _SERVICE_CLIENTS.get((service, sign_in)) - if held is not None and held[0] == os.getpid() and not held[1].health.failed: - return held[1].sdk # pyright: ignore[reportAny] + 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": service}) 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[(service, sign_in)] = (os.getpid(), shared) + _SERVICE_CLIENTS[address] = (sign_in, os.getpid(), shared) return shared.sdk # pyright: ignore[reportAny] @@ -533,9 +620,10 @@ def sign_in_scope() -> object | None: return _sign_in_key() # pyright: ignore[reportAny] -_SERVICE_CLIENTS: dict[tuple[str, Any], tuple[int, _SharedClient]] = {} # pyright: ignore[reportExplicitAny] -"""The clients ``client_for_service`` holds, by address and sign-in, with the process -that got them: a changed sign-in never reuses one.""" +_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() @@ -1167,6 +1255,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() diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index b885a35c0..4cd4b4d2d 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -749,6 +749,33 @@ 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: + 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. diff --git a/src/orcapod/hashing/arrow_hashers.py b/src/orcapod/hashing/arrow_hashers.py index b60919f42..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 @@ -16,7 +17,7 @@ ) from orcapod.errors import MissingOptionalDependencyError, SpiralDBEntryMissingError from orcapod.logical_types.identifier import LogicalTypeIdentifierError -from orcapod.hashing.prefetch import prefetch_table +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 @@ -141,74 +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] = [] - if table.num_rows > 1: - # Values whose hash needs a fetch are fetched together, not one per cell - # (ITL-1789); a one-row table's cell is fetched by its own hash. - prefetch_table(table, self._type_converter, self._semantic_hasher) - - 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 - 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 index da81d31a9..b573b760e 100644 --- a/src/orcapod/hashing/prefetch.py +++ b/src/orcapod/hashing/prefetch.py @@ -3,19 +3,21 @@ 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``; before rows are hashed one by one, ``prefetch_rows`` -(rows) or ``prefetch_table`` (a table) hands it every value of its columns at once. -Prefetching changes no hash: it only fills the handler's own cache. +``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. A value anywhere else (inside a -struct) is fetched on its own when hashed. +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 @@ -43,14 +45,18 @@ def get_logical_type_by_arrow_extension_name( @runtime_checkable class PrefetchingHandlerProtocol(Protocol): - """A value handler that can fetch many values' inputs together (``prefetch``).""" + """A value handler that can fetch many values' inputs together (``prefetched``).""" - def prefetch(self, values: Sequence[object]) -> None: - """Fetch what hashing ``values`` needs, together, into the handler's cache. + 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. """ ... @@ -175,10 +181,13 @@ def __init__(self) -> None: def add(self, handler: PrefetchingHandlerProtocol, values: list[object]) -> None: self._values.setdefault(id(handler), (handler, []))[1].extend(values) - def prefetch(self) -> None: - for handler, values in self._values.values(): - if values: - handler.prefetch(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]: @@ -188,39 +197,43 @@ def _flatten(values: list[Any], depth: int) -> list[Any]: return [value for value in values if value is not None] # pyright: ignore[reportAny] -def prefetch_table( +@contextmanager +def prefetched_table( table: pa.Table | pa.RecordBatch, type_converter: ExtensionLookupProtocol, semantic_hasher: SemanticHasherProtocol, -) -> None: - """Hand every prefetching handler all the values of its columns of ``table``. +) -> 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). """ - if table.num_rows == 0: - return batches = _Batches() - 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) - batches.add( - found.handler, - [found.logical_type.storage_to_python(value) for value in stored], # pyright: ignore[reportAny] - ) - batches.prefetch() - - -def prefetch_rows( + 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) + batches.add( + found.handler, + [found.logical_type.storage_to_python(value) for value in stored], # pyright: ignore[reportAny] + ) + with batches.prefetched(): + yield + + +@contextmanager +def prefetched_rows( rows: Sequence[DataProtocol], type_converter: ExtensionLookupProtocol, semantic_hasher: SemanticHasherProtocol, -) -> None: - """Hand every prefetching handler all the values of its columns in ``rows``. +) -> 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). @@ -232,20 +245,42 @@ def prefetch_rows( semantic_hasher: The data context's semantic hasher (its handler registry). """ payloads = list(rows) - if not payloads: - return batches = _Batches() - 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 - ), - ) - batches.prefetch() + 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( diff --git a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py index 548f99728..4126fa2f5 100644 --- a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py +++ b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py @@ -25,6 +25,7 @@ import logging from collections.abc import Iterable, Sequence +from contextlib import AbstractContextManager from typing import TYPE_CHECKING, Any from uuid import UUID @@ -115,7 +116,7 @@ class SpiralDBEntryHandler: 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. The value is fetched once per process; a node - fetches the entries of many rows together through ``prefetch`` first. + fetches the entries of many rows together through ``prefetched`` first. """ EXTENSION_NAME = SPIRALDB_ENTRY_EXTENSION_NAME @@ -141,13 +142,19 @@ def handle(self, obj: Any, hasher: "SemanticHasherProtocol") -> ContentHash: f"SpiralDBEntryHandler: expected SpiralDBEntry, got {type(obj)!r}" ) - def prefetch(self, values: Sequence[object]) -> None: - """Fetch the entries of ``values`` together, before they are hashed one by one. + 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. """ - SpiralDBEntry.prefetch(v for v in values if isinstance(v, SpiralDBEntry)) + return SpiralDBEntry.prefetched( + v for v in values if isinstance(v, SpiralDBEntry) + ) class BytesHandler: diff --git a/src/orcapod/logical_types/spiraldb_entry_type.py b/src/orcapod/logical_types/spiraldb_entry_type.py index a912cab53..073a12061 100644 --- a/src/orcapod/logical_types/spiraldb_entry_type.py +++ b/src/orcapod/logical_types/spiraldb_entry_type.py @@ -20,6 +20,7 @@ from __future__ import annotations from collections.abc import Iterable +from contextlib import AbstractContextManager from typing import TYPE_CHECKING, Any import polars as pl @@ -270,6 +271,26 @@ def prefetch(entries: Iterable[SpiralDBEntry]) -> None: 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``. diff --git a/src/orcapod/logical_types/user_class_identity.py b/src/orcapod/logical_types/user_class_identity.py index c18a9a0b8..b42624157 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,35 @@ 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. + """ + 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: + return + holder = path[-1].__qualname__ if path else "a user class" + 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/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index 445521fd3..cb7f9f921 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -15,6 +15,7 @@ from __future__ import annotations import asyncio +import contextlib import datetime import os import warnings @@ -35,8 +36,10 @@ 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" @@ -1309,8 +1312,9 @@ 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, which - propagates), the earlier group's entries are not fetched again.""" + 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") @@ -1326,8 +1330,8 @@ def second_fails(*args: Any, **kwargs: Any) -> Any: return real(*args, **kwargs) monkeypatch.setattr(spiraldb_entries, "scan_keys", second_fails) - with pytest.raises(ConnectionError): - SpiralDBEntry.prefetch([*first, *later]) + 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 @@ -1342,41 +1346,497 @@ def second_fails(*args: Any, **kwargs: Any) -> Any: 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 buffers plus - ``ENTRY_VALUE_OVERHEAD``, so a budget of two small values holds two, not all.""" + """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") - size = entries[0].read().nbytes + 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", - 2 * (size + spiraldb_entries.ENTRY_VALUE_OVERHEAD), - ) + 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 == 2 * (size + spiraldb_entries.ENTRY_VALUE_OVERHEAD) + 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) == set(entries) + assert all(isinstance(v, ContentHash) for v in batch.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)) + + +@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_a_prefetch_keeps_no_value_the_cache_does_not_hold( +def test_an_address_is_trusted_in_any_spelling_and_one_client_is_held_per_address( stored: dict[str, Any], monkeypatch: pytest.MonkeyPatch ): - """CodeRabbit (spiraldb_entries.py:533): a prefetch only fills the cache; it does - not hold every fetched value until all groups are read.""" + """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"] + + +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") - real = spiraldb_entries._fetch # pyright: ignore[reportPrivateUsage] - returned: list[int] = [] + 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) - def recording(*args: Any, **kwargs: Any) -> Any: - found = real(*args, **kwargs) - returned.append(len(found)) - return found + @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 - monkeypatch.setattr(spiraldb_entries, "_fetch", recording) - SpiralDBEntry.prefetch(entries) - assert returned == [0] - assert len({e.content_hash() for e in entries}) == 3 + 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 table.column("count").to_pylist() == [3, 5, 1, 4, 0, 2] + 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 (its result cannot be hashed into the record): the other rows are recorded + in order under ``continue``; ``fail_fast`` raises the missing-entry error after + the rows before it are recorded.""" + 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) + ) + 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 _documented_sample() -> str: + """The SpiralDB reference sample of ``docs/concepts/sources.md``.""" + page = Path(__file__).parents[3] / "docs" / "concepts" / "sources.md" + blocks = page.read_text().split("```python\n")[1:] + sample = next(b.split("```")[0] for b in blocks if "op.SpiralDBEntry" in b) + return sample + + +@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 + + sample = _documented_sample() + assert 'SpiralDBTableSource("my-project-123456", "items")' in sample + namespace: dict[str, Any] = {} + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + exec( # noqa: S102 # the documentation's own sample, against the fake + sample.replace('"my-project-123456", "items"', f'"{_PROJECT}", "encoded"'), + namespace, + ) + table = namespace["summaries"].as_table() + assert sorted(table.column("count").to_pylist()) == [10, 20, 30] + + 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 diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index a7fef3d79..9ae0b875d 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -1352,14 +1352,15 @@ def drop_table(self, identifier: str) -> None: def install(root: Path | str): """Route Orcapod's SpiralDB calls to the fake, with tables stored under ``root``. - The process's SpiralDB entry cache and its clients by service address start empty - and are emptied again at the end, so no test sees another's entries or store. + 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 clear_service_clients + from orcapod.databases.spiraldb_connector import forget_trusted_services clear_entry_cache() - clear_service_clients() + forget_trusted_services() try: with ( patch.dict(os.environ, {_ROOT_ENV: str(root)}), @@ -1373,7 +1374,7 @@ def install(root: Path | str): yield finally: clear_entry_cache() - clear_service_clients() + forget_trusted_services() def migrate( diff --git a/tests/test_hashing/test_schema_hash_storage_form.py b/tests/test_hashing/test_schema_hash_storage_form.py index b3d3cca2c..50d62cff0 100644 --- a/tests/test_hashing/test_schema_hash_storage_form.py +++ b/tests/test_hashing/test_schema_hash_storage_form.py @@ -597,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()} @@ -662,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 = { @@ -671,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 876305d87..fe3cf55d2 100644 --- a/tests/test_logical_types/test_provisional_hash_warning.py +++ b/tests/test_logical_types/test_provisional_hash_warning.py @@ -98,6 +98,10 @@ def _fake_spiral(tmp_path_factory: pytest.TempPathFactory) -> Iterator[None]: "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() diff --git a/tests/test_logical_types/test_spiraldb_entry_type.py b/tests/test_logical_types/test_spiraldb_entry_type.py index 0a8279fc5..7ade82763 100644 --- a/tests/test_logical_types/test_spiraldb_entry_type.py +++ b/tests/test_logical_types/test_spiraldb_entry_type.py @@ -19,6 +19,7 @@ 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, @@ -287,23 +288,118 @@ class _HoldsAHolder: name: str -def test_a_source_over_references_inside_user_classes_needs_a_source_id(): - """CodeRabbit on PR 680 (prefetch.py:206): a reference inside a column (a user - class's field, also one level further down) fetches when hashed, so such a source - has no default source id either; with one, it builds without fetching.""" - rows: Any = [ +@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: + return held.count + plain + + with pytest.raises(ValueError, match=_REFUSED): + + @function_pod(output_keys=("n", "held")) + def returns(n: int) -> tuple[int, _HoldsReferences]: + 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": 1, - "plain": 3, - "held": _HoldsAReference(_entry(), 1), - "deep": _HoldsAHolder(_HoldsAReference(_entry(version=8), 2), "x"), + "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} ] - with pytest.raises(ValueError, match=r"\['deep', 'held'\].*source_id"): - DictSource(rows, tag_columns=["id"], tag_only_columns=True) - source = DictSource( - rows, tag_columns=["id"], tag_only_columns=True, source_id="held" + 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 - plain: Any = [{"id": 1, "plain": 3}] - assert DictSource(plain, tag_columns=["id"], tag_only_columns=True).source_id 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..c4f781860 --- /dev/null +++ b/tests/test_pipeline/test_observer_order_of_a_chain.py @@ -0,0 +1,365 @@ +"""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]: + return n + 1, s + s + + +@function_pod(output_keys=("a", "b")) +def second(x: int, y: str) -> tuple[int, str]: + return x + 1, y + y + + +@function_pod(output_keys=("a", "b")) +def failing(x: int, y: str) -> tuple[int, str]: + 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 self + + def create_data_logger(self, *args: Any) -> None: + return None + + def __getattr__(self, name: str) -> Any: + 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) + + +_ASYNC_FIXED = 21 +"""How many first events of an async run every run on main gave in one order: the +nodes' starts, the routing of every input row and the operator's end, interleaved.""" + + +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 +): + """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.""" + job = _job(failing_second) + 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: + assert _MAIN_ROWS[key] == ["ValueError", None] + else: + table = job.nodes["second"].as_table() + rows = [ + list(pair) + for pair in zip( + table.column("id").to_pylist(), table.column("a").to_pylist() + ) + ] + assert [rows, summary.nodes["second"].failed] == _MAIN_ROWS[key] + expected = _MAIN_TRACES[key] + if mode == "sync" or load_only: + assert recorder.events == expected + continue + # On the async orchestrator the computing stage runs rows concurrently, so + # main's trace varies after the routing stage (over 24 runs on main, every + # variant shares its first _ASYNC_FIXED events): those must be main's, and a + # run that finishes has main's events. + assert recorder.events[:_ASYNC_FIXED] == expected[:_ASYNC_FIXED] + if policy == "continue": + assert sorted(recorder.events) == sorted(expected) From f559ef791926da6dce875bb2850a218f9f462c97 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 13:21:10 -0800 Subject: [PATCH 09/28] test(spiraldb): make the async order checks hold under parallel CI (ITL-1789) - The async observer check compares what main fixes: the source's and the operator's events with the first node's routing of its rows (event loop only), each node's routing order, every row starting before it ends, and the event set; rows are compared without order. It still fails when a node waits for its upstream to end before routing. - The stub native client of the keyed-table deprecation tests carries the service address the connector now reads when built. - Returned references are compared without the async row order. Co-Authored-By: Claude Opus 5.5 --- .../test_spiraldb_table_source_encoded.py | 2 +- .../test_spiraldb_keyed_table_deprecation.py | 4 ++ .../test_observer_order_of_a_chain.py | 68 ++++++++++++++++--- 3 files changed, 62 insertions(+), 12 deletions(-) diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index cb7f9f921..66d471b5f 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -1642,7 +1642,7 @@ def pick(pick: int, slot: int, count: int) -> tuple[SpiralDBEntry, int]: with warnings.catch_warnings(): warnings.simplefilter("ignore") table = job.nodes["pick"].as_table() - assert table.column("count").to_pylist() == [3, 5, 1, 4, 0, 2] + 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() == [] 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_pipeline/test_observer_order_of_a_chain.py b/tests/test_pipeline/test_observer_order_of_a_chain.py index c4f781860..96ee448c5 100644 --- a/tests/test_pipeline/test_observer_order_of_a_chain.py +++ b/tests/test_pipeline/test_observer_order_of_a_chain.py @@ -72,9 +72,51 @@ def record(node: str, tag: Any, *args: Any, **kwargs: Any) -> None: raise AttributeError(name) -_ASYNC_FIXED = 21 -"""How many first events of an async run every run on main gave in one order: the -nodes' starts, the routing of every input row and the operator's end, interleaved.""" +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 _streaming_stage(events: list[str]) -> list[str]: + """The events of the source and the operator, and the first function node's + routing of its rows: the part of an async run in the event loop alone (no row is + computed in it), so main gives it in one order. A node that waits for its + upstream to end before routing a row moves the operator's end before them.""" + return [ + event + for event in events + if event.split(" ")[1] in {"chain-plain", "SelectDataColumns"} + or event.startswith("data_start first ") + ] + + +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 streaming stage in + order, the nodes' starts, each node's routing order of its input rows + (``data_start``), 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 its + routing is a prefix of main's or the reverse.""" + assert _streaming_stage(events) == _streaming_stage(expected) + assert _per_node(events, "node_start") == _per_node(expected, "node_start") + got, want = _per_node(events, "data_start"), _per_node(expected, "data_start") + if policy == "continue": + assert got == want + assert sorted(events) == sorted(expected) + else: + for node in got.keys() | want.keys(): + a, b = got.get(node, []), want.get(node, []) + shorter, longer = sorted((a, b), key=len) + assert longer[: len(shorter)] == shorter, node + 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 _job(failing_second: bool) -> PipelineJob: @@ -351,15 +393,19 @@ def test_observer_events_of_a_chain_follow_main( table.column("id").to_pylist(), table.column("a").to_pylist() ) ] - assert [rows, summary.nodes["second"].failed] == _MAIN_ROWS[key] + 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 == "sync" or load_only: assert recorder.events == expected continue - # On the async orchestrator the computing stage runs rows concurrently, so - # main's trace varies after the routing stage (over 24 runs on main, every - # variant shares its first _ASYNC_FIXED events): those must be main's, and a - # run that finishes has main's events. - assert recorder.events[:_ASYNC_FIXED] == expected[:_ASYNC_FIXED] - if policy == "continue": - assert sorted(recorder.events) == sorted(expected) + # 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) From 513d036092ef9735528953d55d6056e8621a985c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 13:48:30 -0800 Subject: [PATCH 10/28] fix(spiraldb): address CodeRabbit's review of 4ce0a09 (ITL-1789) - Sync rows whose results fetch: a repeated input never reuses a result before its hash succeeds; a fatal error records the rows held before it; under fail_fast each row is finished before the next one runs. - A row is reported as ended only after its result is hashed and recorded, on the async path too (computed rows and ephemeral persistent hits). - Only a missing entry fails a row when a result is hashed; any other error stops the run, on both paths. - A batch keeps an entry found before its group failed, holds errors without tracebacks and raises a fresh copy, and serves only the sign-in it was fetched under. - Prefetch only value-hashed columns, and leave a column whose values do not convert to the column loop, which names it. - The type token of SpiralDBEntry itself is its identifier; only an enclosing user class is refused. - The chain test checks the fail_fast error and its crash event. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1789.md | 8 +- docs/concepts/sources.md | 16 +- src/orcapod/core/nodes/function_node.py | 118 ++++-- src/orcapod/core/sources/spiraldb_entries.py | 69 +++- src/orcapod/hashing/prefetch.py | 30 +- .../logical_types/user_class_identity.py | 8 +- .../test_spiraldb_table_source_encoded.py | 388 +++++++++++++++++- .../test_spiraldb_entry_type.py | 21 + .../test_observer_order_of_a_chain.py | 5 +- 9 files changed, 600 insertions(+), 63 deletions(-) diff --git a/changelog.d/ITL-1789.md b/changelog.d/ITL-1789.md index 26ea7ba18..2c6f49bcf 100644 --- a/changelog.d/ITL-1789.md +++ b/changelog.d/ITL-1789.md @@ -14,9 +14,11 @@ - 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, 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. 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. + before its results are recorded (one row at a time under `fail_fast`). 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. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 8acd4bacb..a6ba863dd 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1144,9 +1144,11 @@ once (all its input rows on the synchronous path, the rows that have arrived on asynchronous one), and hashes those rows from what that scan read. 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 (up to 256 on the synchronous path, the results that have arrived on the -asynchronous one). 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 +once (up to 256 on the synchronous path under `continue`, one at a time under +`fail_fast`, so the first failure stops the run before a later row is computed; the +results that have arrived on the asynchronous one). Such 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 @@ -1157,7 +1159,8 @@ the preview read no entry; a read that asks for row hashes entries. Entries are kept per sign-in as Orcapod sees it when a read starts and ends: the -environment and the saved login. Changing the sign-in while reads run in other threads of +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. 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. @@ -1165,8 +1168,9 @@ 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) is raised as for any other input, at the first -row whose hash needs that entry, with the column named. +failed scan, a refused service address) 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, after the rows before it are recorded. **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`, diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 59652ed12..663b366fc 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3060,8 +3060,12 @@ def _execute_fetching_outputs( 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`` computed rows are held, whose results' references are then fetched together, one scan per - table version. The rows keep their input order. A row that fails under - ``fail_fast`` first finishes the rows held before it. + table version. The rows keep their input order. Under ``fail_fast`` each row + is finished before the next one runs, so the first failure stops the run + before any later row is computed. 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. @@ -3083,18 +3087,20 @@ def crash(tag: TagProtocol, data: DataProtocol, exc: Exception) -> None: ctx_obs.on_node_end(node_label, node_hash) raise exc - def stop( - tag: TagProtocol, - data: DataProtocol, - exc: OrcapodDatabaseError | TypeIdentityError, - ) -> None: - """Report a row whose database read or write failed, or whose stored - result cannot be decoded: the run stops whatever the policy.""" + def stop(tag: TagProtocol, data: DataProtocol, exc: Exception) -> None: + """Report a row whose database read or write failed, whose stored result + cannot be decoded, or whose result's hash raised another error than a + missing entry: the run stops whatever the policy.""" + kept = ( + exc + if isinstance(exc, (OrcapodDatabaseError, TypeIdentityError)) + else None + ) if isinstance(exc, OrcapodDatabaseError): exc.add_context(node_label=node_label, tag=tag.as_dict()) - with keep_database_error(exc, "Observer on_data_crash"): + with keep_database_error(kept, "Observer on_data_crash"): ctx_obs.on_data_crash(node_label, tag, data, exc) - with keep_database_error(exc, "Observer on_node_end"): + with keep_database_error(kept, "Observer on_node_end"): ctx_obs.on_node_end(node_label, node_hash) def finish() -> None: @@ -3105,6 +3111,8 @@ def finish() -> None: self._deferred_records = [] rows = list(held) held.clear() + # The instances whose held result names a missing entry, with the error. + missing: dict[bytes, SpiralDBEntryMissingError] = {} with prefetched_rows( [record.output_data for record in pending], self.data_context.type_converter, @@ -3117,17 +3125,25 @@ def finish() -> None: deferred.record( output_data_hash=deferred.output_data.content_hash() ) - except (OrcapodDatabaseError, TypeIdentityError) as exc: - stop(row.tag, row.data, exc) - raise - except Exception as exc: + except SpiralDBEntryMissingError as exc: + # Not reused: a repeat of this input fails with it. + missing[row.instance_id] = exc + _ = self._cached_output_datas.pop(row.instance_id, None) + self._cached_output_table = None + self._cached_content_hash_column = None crash(row.tag, row.data, exc) failed += 1 continue - if not row.cached: - ctx_obs.on_data_end( - node_label, row.tag, row.data, row.result, cached=False - ) + except Exception as exc: + stop(row.tag, row.data, exc) + raise + elif row.instance_id in missing: + crash(row.tag, row.data, missing[row.instance_id]) + 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)) @@ -3151,10 +3167,12 @@ def finish() -> None: 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) + # Ends in ``finish``: its result may be a held one not yet hashed. held.append( _HeldRow(tag, data, instance_id, tag_out, result, None, True) ) + if error_policy == "fail_fast": + finish() continue pkt_logger = ctx_obs.create_data_logger(tag, data) before = len(self._deferred_records) @@ -3167,6 +3185,10 @@ def finish() -> None: 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. + with keep_database_error(exc, "Finishing the rows held before it"): + finish() stop(tag, data, exc) raise except Exception as exc: @@ -3179,7 +3201,10 @@ def finish() -> None: held.append( _HeldRow(tag, data, instance_id, tag_out, result, record, False) ) - if len(self._deferred_records) >= _PREFETCH_ROWS: + if ( + error_policy == "fail_fast" + or len(self._deferred_records) >= _PREFETCH_ROWS + ): finish() finish() finally: @@ -5081,6 +5106,14 @@ 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() + held_ends: dict[ + bytes, tuple[TagProtocol, DataProtocol, DataProtocol, bool] + ] = {} def lookup_crashed( tag: TagProtocol, data: DataProtocol, exc: Exception @@ -5201,9 +5234,12 @@ async def route_one(tag: TagProtocol, data: DataProtocol) -> 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 - ) + if outputs_fetch: + held_ends[correlation_key] = (tag, data, found, False) + else: + 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)) return @@ -5251,16 +5287,27 @@ async def record_one( execution_pod.RESULT_COMPUTED_FLAG, False ) ) + held_end = held_ends.pop(cast(bytes, correlation_key), None) try: output_hash = output_data.content_hash() except Exception as exc: - # A result that cannot be hashed (it returns a reference to - # a missing entry): a failed row under the row failure - # policy, as on the sync path (ITL-1789). + # 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 not lookup_crashed(original_tag, input_data, exc): - raise - return + if isinstance( + exc, + ( + SpiralDBEntryMissingError, + OrcapodDatabaseError, + TypeIdentityError, + ), + ): + if not lookup_crashed(original_tag, input_data, exc): + raise + return + ctx_obs.on_data_crash(node_label, original_tag, input_data, exc) + raise try: self._add_pipeline_record( original_tag, @@ -5281,6 +5328,10 @@ async def record_one( ) 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] + ) # 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. @@ -5310,7 +5361,6 @@ async def record_and_forward() -> None: # 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. - outputs_fetch = self._outputs_fetch() async for output_tag, output_data in result_channel.reader: if not outputs_fetch: await record_one(output_tag, output_data) @@ -5363,6 +5413,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). diff --git a/src/orcapod/core/sources/spiraldb_entries.py b/src/orcapod/core/sources/spiraldb_entries.py index 5c1f86451..69211ca3b 100644 --- a/src/orcapod/core/sources/spiraldb_entries.py +++ b/src/orcapod/core/sources/spiraldb_entries.py @@ -20,6 +20,7 @@ from __future__ import annotations +import copy import datetime import json from collections import OrderedDict @@ -653,12 +654,50 @@ def prefetch_entries(entries: Iterable[SpiralDBEntry]) -> None: """What a batch knows of one entry: its content hash, the reason it is missing, or the error fetching it raised.""" -_BATCH: ContextVar[dict[SpiralDBEntry, _Outcome] | None] = ContextVar( + +class _Batch(NamedTuple): + """The outcomes fetched for a batch, and the sign-in they were fetched under.""" + + sign_in: object + outcomes: dict[SpiralDBEntry, _Outcome] + + +_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. @@ -667,16 +706,21 @@ def prefetched_entries(entries: Iterable[SpiralDBEntry]) -> Iterator[None]: 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. 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. + 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: after a change of sign-in inside + the block 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. """ outer = _BATCH.get() - batch: dict[SpiralDBEntry, _Outcome] = {} if outer is None else dict(outer) sign_in = sign_in_scope() + batch: dict[SpiralDBEntry, _Outcome] = ( + dict(outer.outcomes) if outer is not None and outer.sign_in == sign_in else {} + ) todo: list[SpiralDBEntry] = [] for entry in dict.fromkeys(entries): if entry in batch: @@ -695,10 +739,10 @@ def found(entry: SpiralDBEntry, fetched: _Fetched) -> None: _ = publish(entry, fetched) def failed(entry: SpiralDBEntry, exc: Exception) -> None: - batch[entry] = exc + _ = batch.setdefault(entry, _detached(exc)) _fetch(todo, None, found, failed=failed) - token = _BATCH.set(batch) + token = _BATCH.set(_Batch(sign_in, batch)) try: yield finally: @@ -731,7 +775,8 @@ def found(fetched_entry: SpiralDBEntry, fetched: _Fetched) -> None: 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. + 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 @@ -740,9 +785,13 @@ def cached_content_hash(entry: SpiralDBEntry) -> ContentHash: ValueError: If its key does not fit the table's primary key. """ batch = _BATCH.get() - known: _Outcome | None = None if batch is None else batch.get(entry) + sign_in = sign_in_scope() + known: _Outcome | None = ( + batch.outcomes.get(entry) + if batch is not None and batch.sign_in == sign_in + else None + ) if known is None: - sign_in = sign_in_scope() 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: @@ -753,7 +802,7 @@ def cached_content_hash(entry: SpiralDBEntry) -> ContentHash: publish=None if sign_in is None else _publisher(sign_in), ).known if isinstance(known, Exception): - raise known + raise _fresh(known) if isinstance(known, str): raise _missing(entry, known) return known diff --git a/src/orcapod/hashing/prefetch.py b/src/orcapod/hashing/prefetch.py index b573b760e..e88b976ff 100644 --- a/src/orcapod/hashing/prefetch.py +++ b/src/orcapod/hashing/prefetch.py @@ -25,6 +25,7 @@ from orcapod.logical_types.identifier import ( arrow_type_identifier, container_element_identifier, + declared_value_hash, ) if TYPE_CHECKING: @@ -102,8 +103,11 @@ def _prefetching( ) -> _Prefetching | None: """Return how a column of ``arrow_type`` is prefetched, or ``None`` if it is not. - Anything this cannot resolve is not prefetched: hashing the column then resolves it - and raises what it raises. + 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 @@ -114,9 +118,16 @@ def _prefetching( 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 found is None: + if declaration in (None, "stored"): return None return _Prefetching(found[0], found[1], depth) @@ -218,10 +229,15 @@ def prefetched_table( if found is None: continue stored = _flatten(table.column(index).to_pylist(), found.depth) - batches.add( - found.handler, - [found.logical_type.storage_to_python(value) for value in stored], # pyright: ignore[reportAny] - ) + 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 diff --git a/src/orcapod/logical_types/user_class_identity.py b/src/orcapod/logical_types/user_class_identity.py index b42624157..5e7845ff0 100644 --- a/src/orcapod/logical_types/user_class_identity.py +++ b/src/orcapod/logical_types/user_class_identity.py @@ -522,16 +522,18 @@ def _require_held_in_user_class(extension_name: str, path: tuple[type, ...]) -> own type, or inside ``list[...]`` there. Raises: - NestedTypeNotStorableError: If ``extension_name`` is the reference type's. + 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: + 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__ if path else "a user class" + 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 " diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index 66d471b5f..40d1f915d 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -1380,8 +1380,8 @@ def test_a_batch_keeps_outcomes_not_values(stored: dict[str, Any]): with SpiralDBEntry.prefetched(entries): batch = spiraldb_entries._BATCH.get() # pyright: ignore[reportPrivateUsage] assert batch is not None - assert set(batch) == set(entries) - assert all(isinstance(v, ContentHash) for v in batch.values()) + 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 @@ -1840,3 +1840,387 @@ def test_the_documented_sample_runs( summary = _run(job, orchestrator) assert summary.nodes["summarize"].failed == 0 assert sum(s.key_ranges for s in _entry_scans()) == 3 + + +# -------------------------------------------------------------------------------------- +# 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_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")["1"] == ["data_crash"] + assert all( + kinds == ["data_end"] + for row, kinds in events.terminal("pick").items() + if row != "1" + ) + + +@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): when hashing one entry of a + group fails after another of the group was found, the found one keeps its hash + inside the batch, as hashing it alone gives; the failing ones raise.""" + 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] + for entry in entries[1:]: + with pytest.raises(ValueError, match="synthetic digest failure"): + entry.content_hash() + + +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"] diff --git a/tests/test_logical_types/test_spiraldb_entry_type.py b/tests/test_logical_types/test_spiraldb_entry_type.py index 7ade82763..fab01f89e 100644 --- a/tests/test_logical_types/test_spiraldb_entry_type.py +++ b/tests/test_logical_types/test_spiraldb_entry_type.py @@ -403,3 +403,24 @@ def test_a_user_class_without_references_is_unchanged(): 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_observer_order_of_a_chain.py b/tests/test_pipeline/test_observer_order_of_a_chain.py index 96ee448c5..06ccfc390 100644 --- a/tests/test_pipeline/test_observer_order_of_a_chain.py +++ b/tests/test_pipeline/test_observer_order_of_a_chain.py @@ -383,8 +383,11 @@ def test_observer_events_of_a_chain_follow_main( observer=cast(Any, recorder), load_only=load_only, ) - except ValueError: + 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 = [ From 836fb1f8d5dee236170849328b1915201c3c090b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 13:54:02 -0800 Subject: [PATCH 11/28] fix(spiraldb): reset reference state in a forked child (ITL-1789) - A forked child gets new locks for the trusted service addresses and the clients held for references, holds none of the parent's clients, and starts with an empty entry cache under a new lock; the trusted addresses are kept. - Document that a kept entry is not authorized again, and add the docstrings CodeRabbit asked for. Co-Authored-By: Claude Opus 5.5 --- docs/concepts/sources.md | 4 +- src/orcapod/core/sources/spiraldb_entries.py | 12 +++++ src/orcapod/databases/spiraldb_connector.py | 27 ++++++++---- src/orcapod/errors.py | 5 +++ .../test_spiraldb_table_source_encoded.py | 44 +++++++++++++++++++ .../test_spiraldb_entry_type.py | 2 + .../test_observer_order_of_a_chain.py | 9 ++++ 7 files changed, 93 insertions(+), 10 deletions(-) diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index a6ba863dd..628127a5d 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1160,7 +1160,9 @@ 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. Changing the sign-in while reads run in other threads of +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. diff --git a/src/orcapod/core/sources/spiraldb_entries.py b/src/orcapod/core/sources/spiraldb_entries.py index 69211ca3b..d674f5b43 100644 --- a/src/orcapod/core/sources/spiraldb_entries.py +++ b/src/orcapod/core/sources/spiraldb_entries.py @@ -23,6 +23,7 @@ import copy import datetime import json +import os from collections import OrderedDict from collections.abc import Callable, Iterable, Iterator, Sequence from contextlib import contextmanager @@ -513,6 +514,17 @@ def clear(self) -> None: _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() diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 35e51c793..4f999c153 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -414,11 +414,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"): @@ -527,7 +536,7 @@ def normalize_service_address(address: str) -> str: SpiralDB source it built: the only addresses a reference's own address may sign in to (``client_for_service``).""" -_TRUSTED_SERVICES_LOCK = Lock() +_trusted_services_lock = Lock() def trust_service(address: str) -> None: @@ -537,13 +546,13 @@ def trust_service(address: str) -> None: Args: address: The service's address (its API URL). """ - with _TRUSTED_SERVICES_LOCK: + 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: + with _trusted_services_lock: _TRUSTED_SERVICES.clear() clear_service_clients() @@ -562,7 +571,7 @@ def require_trusted_service(address: str) -> None: SpiralDBUntrustedServiceError: If this process reached no service at ``address`` through a connector or source it built. """ - with _TRUSTED_SERVICES_LOCK: + with _trusted_services_lock: trusted = normalize_service_address(address) in _TRUSTED_SERVICES if not trusted: raise SpiralDBUntrustedServiceError(address) @@ -593,7 +602,7 @@ def client_for_service(service: str) -> Any: # pyright: ignore[reportExplicitAn if sign_in is None: # Whose sign-in it is cannot be told: nothing is held for a later call. return _client_for({"server.url": service}).sdk # pyright: ignore[reportAny] - with _SERVICE_CLIENTS_LOCK: + with _service_clients_lock: held = _SERVICE_CLIENTS.get(address) if ( held is not None @@ -606,7 +615,7 @@ def client_for_service(service: str) -> Any: # pyright: ignore[reportExplicitAn 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: + with _service_clients_lock: _SERVICE_CLIENTS[address] = (sign_in, os.getpid(), shared) return shared.sdk # pyright: ignore[reportAny] @@ -625,12 +634,12 @@ def sign_in_scope() -> object | None: the sign-in and the process that got it. A changed sign-in never reuses one; it replaces it.""" -_SERVICE_CLIENTS_LOCK = Lock() +_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: + with _service_clients_lock: _SERVICE_CLIENTS.clear() diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 4cd4b4d2d..1acf00fd4 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -763,6 +763,11 @@ class SpiralDBUntrustedServiceError(PermissionError): """ 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 " diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index 40d1f915d..31ccbe784 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -2224,3 +2224,47 @@ def test_a_reference_column_declared_stored_is_not_prefetched(): 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() diff --git a/tests/test_logical_types/test_spiraldb_entry_type.py b/tests/test_logical_types/test_spiraldb_entry_type.py index fab01f89e..68802355a 100644 --- a/tests/test_logical_types/test_spiraldb_entry_type.py +++ b/tests/test_logical_types/test_spiraldb_entry_type.py @@ -341,12 +341,14 @@ def test_a_function_declaring_a_reference_inside_a_user_class_is_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([]) diff --git a/tests/test_pipeline/test_observer_order_of_a_chain.py b/tests/test_pipeline/test_observer_order_of_a_chain.py index 06ccfc390..25987e1c5 100644 --- a/tests/test_pipeline/test_observer_order_of_a_chain.py +++ b/tests/test_pipeline/test_observer_order_of_a_chain.py @@ -26,16 +26,20 @@ @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 @@ -48,12 +52,17 @@ 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}" From b4a1c3a92f947fe3239bf8f27c8e98bb4bedff5b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 14:42:35 -0800 Subject: [PATCH 12/28] fix(spiraldb): address the delta review and CodeRabbit's review of 836fb1f (ITL-1789) - A reference to a column the table version lacks fails only its own row: each reference's column is checked before the shared scan. - A per-entry digest or extraction error fails only that entry. - The sync execute path and both load-only paths buffer their input only when it has a column whose entries are fetched; otherwise rows are hashed one by one as before. - SpiralDBEntry.prefetch refuses an untrusted address before any client is made. - A prefetched batch serves only its own process and only while its block is open. - Docs and changelog: the scan bound is per function-node batch (at most 256 rows on the async path); async fail_fast reads the results that have arrived together; a forked child keeps its parent's trusted addresses. - Tests for each finding; the chain order test compares the second node's routing with the first node's delivery. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1789.md | 10 +- docs/concepts/sources.md | 23 +- src/orcapod/core/nodes/function_node.py | 77 ++++-- src/orcapod/core/sources/spiraldb_entries.py | 95 +++++-- .../logical_types/spiraldb_entry_type.py | 6 + .../test_spiraldb_table_source_encoded.py | 240 +++++++++++++++++- .../test_observer_order_of_a_chain.py | 66 +++-- 7 files changed, 425 insertions(+), 92 deletions(-) diff --git a/changelog.d/ITL-1789.md b/changelog.d/ITL-1789.md index 2c6f49bcf..ea1505b38 100644 --- a/changelog.d/ITL-1789.md +++ b/changelog.d/ITL-1789.md @@ -10,11 +10,15 @@ 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. The table `read()` returns is the caller's own. + 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, never one per row, and hashes + per table version for the rows the node takes at once (at most 256 on the asynchronous + path), 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 (one row at a time under `fail_fast`). A reference that + before its results are recorded (on the synchronous path one row at a time under + `fail_fast`; 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 diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 628127a5d..11f9543f9 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1095,8 +1095,10 @@ as **references** to its entries, one per row: 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: build a source of that service first, or pass a client - of it (`entry.read(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. - When the version no longer holds a row with the key, or the table or that version can no longer be opened, `entry.read()` raises `orcapod.errors.SpiralDBEntryMissingError` (a `LookupError`) naming the reference; a newer version is never read in its place. @@ -1139,14 +1141,18 @@ parameters), not of the reference's fields. So when a run's check (`check_for_ne pins a newer version of the table, a function pod computes again only for the entries whose content changed: an entry that is the same in both versions has the same hash, and its stored result is used. 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 node takes at -once (all its input rows on the synchronous path, the rows that have arrived on the -asynchronous one), and hashes those rows from what that scan read. The references a +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; on the asynchronous one, 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 (up to 256 on the synchronous path under `continue`, one at a time under -`fail_fast`, so the first failure stops the run before a later row is computed; the -results that have arrived on the asynchronous one). Such a row is reported as ended only +`fail_fast`, so the first failure stops the run before a later row is computed; on the +asynchronous path the results that have arrived, at most 256, under either policy, so +under `fail_fast` the results computed beside a failing one are read with it before the +run stops). Such 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 @@ -1170,7 +1176,8 @@ 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) stops the run, whatever the policy: for an input, +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, after the rows before it are recorded. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 663b366fc..73446d7e9 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -25,7 +25,7 @@ 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 @@ -2222,11 +2222,7 @@ 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) - pairs = list(input_stream.iter_data()) - inputs = [ - (tag, data, eid) - for (tag, data), eid in zip(pairs, self._instance_ids_of(pairs)) - ] + inputs = self._input_entries(input_stream.iter_data()) _ = self.get_cached_results( instance_ids=[eid for _, _, eid in inputs if isinstance(eid, bytes)] ) @@ -2284,11 +2280,7 @@ async def _async_execute_load_only( columns={"system_tags": True} )[0] ctx_obs.on_node_start(node_label, node_hash, tag_schema=tag_schema) - pairs = [(tag, data) async for tag, data in input_channel] - inputs = [ - (tag, data, eid) - for (tag, data), eid in zip(pairs, self._instance_ids_of(pairs)) - ] + inputs = await self._input_entries_of_channel(input_channel) _ = self.get_cached_results( instance_ids=[eid for _, _, eid in inputs if isinstance(eid, bytes)] ) @@ -2801,13 +2793,7 @@ def execute( output: list[tuple[TagProtocol, DataProtocol]] = [] try: # Collect upstream entries and resolve their instance ids. - pairs = list(input_stream.iter_data()) - upstream_entries: list[ - tuple[TagProtocol, DataProtocol, bytes | SpiralDBEntryMissingError] - ] = [ - (tag, data, eid) - for (tag, data), eid in zip(pairs, self._instance_ids_of(pairs)) - ] + upstream_entries = self._input_entries(input_stream.iter_data()) instance_ids = [ eid for _, _, eid in upstream_entries if isinstance(eid, bytes) ] @@ -3544,6 +3530,61 @@ def _inputs_fetch(self, row: DataProtocol) -> bool: ) ) + def _input_entries( + self, rows: Iterable[tuple[TagProtocol, DataProtocol]] + ) -> 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 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). + """ + 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), *rows] + entries += [ + (pair_tag, pair_data, eid) + for (pair_tag, pair_data), eid in zip( + pairs, self._instance_ids_of(pairs), strict=True + ) + ] + 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]] ) -> list[bytes | SpiralDBEntryMissingError]: diff --git a/src/orcapod/core/sources/spiraldb_entries.py b/src/orcapod/core/sources/spiraldb_entries.py index d674f5b43..b657483b6 100644 --- a/src/orcapod/core/sources/spiraldb_entries.py +++ b/src/orcapod/core/sources/spiraldb_entries.py @@ -41,6 +41,7 @@ TableVersionNotFoundError, client_for_service, open_table_version, + require_trusted_service, scan_keys, scan_one_key, sign_in_scope, @@ -338,6 +339,11 @@ def scan_entry(entry: SpiralDBEntry, client: Any = None) -> Any: # pyright: ign _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 @@ -565,12 +571,14 @@ def _fetch( 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 group's client, table or scan - failed); the other entries are still fetched. ``None`` raises the first. + 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, ``SpiralDBUntrustedServiceError`` or + 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]] = {} @@ -608,6 +616,15 @@ def _fetch_group( 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) @@ -632,10 +649,18 @@ def _fetch_group( if index is None: _ = found(entry, _Fetched(None, _NO_ROW.format(version=entry.version))) continue - value = _one_row(rows, entry.column, index) - _ = found( - entry, _Fetched(value, None, entry_content_hash(value) if digest else None) - ) + 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: @@ -649,7 +674,14 @@ def prefetch_entries(entries: Iterable[SpiralDBEntry]) -> None: 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 @@ -668,10 +700,29 @@ def prefetch_entries(entries: Iterable[SpiralDBEntry]) -> None: class _Batch(NamedTuple): - """The outcomes fetched for a batch, and the sign-in they were fetched under.""" + """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( @@ -721,18 +772,17 @@ def prefetched_entries(entries: Iterable[SpiralDBEntry]) -> Iterator[None]: 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: after a change of sign-in inside - the block an entry is hashed as outside it, and a nested batch inherits nothing. + 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. """ - outer = _BATCH.get() sign_in = sign_in_scope() - batch: dict[SpiralDBEntry, _Outcome] = ( - dict(outer.outcomes) if outer is not None and outer.sign_in == sign_in else {} - ) + batch: dict[SpiralDBEntry, _Outcome] = dict(_batch_outcomes(sign_in)) todo: list[SpiralDBEntry] = [] for entry in dict.fromkeys(entries): if entry in batch: @@ -754,10 +804,12 @@ def failed(entry: SpiralDBEntry, exc: Exception) -> None: _ = batch.setdefault(entry, _detached(exc)) _fetch(todo, None, found, failed=failed) - token = _BATCH.set(_Batch(sign_in, batch)) + is_open = [True] + token = _BATCH.set(_Batch(sign_in, batch, os.getpid(), is_open)) try: yield finally: + is_open[0] = False _BATCH.reset(token) @@ -794,15 +846,11 @@ def cached_content_hash(entry: SpiralDBEntry) -> ContentHash: SpiralDBEntryMissingError: If its version holds no row with its key, or the table or that version cannot be opened. SpiralDBUntrustedServiceError: If its service is not one this process reached. - ValueError: If its key does not fit the table's primary key. + ValueError: If its key does not fit the table's primary key, or the table + has no column of its name. """ - batch = _BATCH.get() sign_in = sign_in_scope() - known: _Outcome | None = ( - batch.outcomes.get(entry) - if batch is not None and batch.sign_in == sign_in - else None - ) + 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) @@ -838,7 +886,8 @@ def read_entry(entry: SpiralDBEntry, client: Any = None) -> pa.Table: # pyright table or that version cannot be opened. 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. + 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) diff --git a/src/orcapod/logical_types/spiraldb_entry_type.py b/src/orcapod/logical_types/spiraldb_entry_type.py index 073a12061..ef052ef40 100644 --- a/src/orcapod/logical_types/spiraldb_entry_type.py +++ b/src/orcapod/logical_types/spiraldb_entry_type.py @@ -263,9 +263,15 @@ def prefetch(entries: Iterable[SpiralDBEntry]) -> None: 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 diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index 31ccbe784..b655fec6a 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -2057,12 +2057,11 @@ def test_a_stored_result_naming_a_missing_entry_has_one_terminal_event( 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")["1"] == ["data_crash"] - assert all( - kinds == ["data_end"] - for row, kinds in events.terminal("pick").items() - if row != "1" - ) + assert events.terminal("pick") == { + "0": ["data_end"], + "1": ["data_crash"], + "2": ["data_end"], + } @pytest.mark.parametrize("orchestrator", ["sync", "async"]) @@ -2094,9 +2093,10 @@ def broken(*args: Any, **kwargs: Any) -> Any: 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): when hashing one entry of a - group fails after another of the group was found, the found one keeps its hash - inside the batch, as hashing it alone gives; the failing ones raise.""" + """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") @@ -2115,9 +2115,9 @@ def second_fails(value: pa.Table) -> Any: with SpiralDBEntry.prefetched(entries): monkeypatch.setattr(spiraldb_entries, "entry_content_hash", real) assert entries[0].content_hash() == alone[0] - for entry in entries[1:]: - with pytest.raises(ValueError, match="synthetic digest failure"): - entry.content_hash() + 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( @@ -2268,3 +2268,219 @@ def test_a_forked_child_keeps_trust_but_no_client_cache_or_held_lock( 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 diff --git a/tests/test_pipeline/test_observer_order_of_a_chain.py b/tests/test_pipeline/test_observer_order_of_a_chain.py index 25987e1c5..3c6b5e330 100644 --- a/tests/test_pipeline/test_observer_order_of_a_chain.py +++ b/tests/test_pipeline/test_observer_order_of_a_chain.py @@ -92,36 +92,33 @@ def _per_node(events: list[str], kind: str) -> dict[str, list[str]]: return out -def _streaming_stage(events: list[str]) -> list[str]: - """The events of the source and the operator, and the first function node's - routing of its rows: the part of an async run in the event loop alone (no row is - computed in it), so main gives it in one order. A node that waits for its - upstream to end before routing a row moves the operator's end before them.""" - return [ - event - for event in events - if event.split(" ")[1] in {"chain-plain", "SelectDataColumns"} - or event.startswith("data_start first ") - ] - - 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 streaming stage in - order, the nodes' starts, each node's routing order of its input rows - (``data_start``), 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 its - routing is a prefix of main's or the reverse.""" - assert _streaming_stage(events) == _streaming_stage(expected) + """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") - got, want = _per_node(events, "data_start"), _per_node(expected, "data_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 got == want assert sorted(events) == sorted(expected) - else: - for node in got.keys() | want.keys(): - a, b = got.get(node, []), want.get(node, []) - shorter, longer = sorted((a, b), key=len) - assert longer[: len(shorter)] == shorter, node for index, event in enumerate(events): if event.startswith(("data_end ", "data_crash ")): _, node, row, *_ = event.split(" ") @@ -367,12 +364,24 @@ def _job(failing_second: bool) -> PipelineJob: [("continue", False), ("continue", True), ("fail_fast", True)], ) def test_observer_events_of_a_chain_follow_main( - mode: str, policy: str, failing_second: bool + 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.""" + 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) orchestrator_class = ( AsyncPipelineOrchestrator if mode == "async" else SyncPipelineOrchestrator @@ -421,3 +430,4 @@ def test_observer_events_of_a_chain_follow_main( # 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 == [] From c92e1c6bbb6c1a5df10931ceb3df5200ee65b49c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 15:16:33 -0800 Subject: [PATCH 13/28] fix(spiraldb): bind a nested batch to its first process; scope the async cap (ITL-1789) - prefetched_entries takes the process id before it copies the outer batch's outcomes, so a fork while it reads its entries leaves the child a batch that serves it nothing. - Docs and changelog: the 256-row cap applies when an asynchronous run executes; a load-only run takes its whole input, one scan per version. - Test: test_a_fork_while_a_nested_batch_reads_its_entries_inherits_nothing. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1789.md | 4 +-- docs/concepts/sources.md | 7 ++-- src/orcapod/core/sources/spiraldb_entries.py | 5 ++- .../test_spiraldb_table_source_encoded.py | 33 +++++++++++++++++++ 4 files changed, 43 insertions(+), 6 deletions(-) diff --git a/changelog.d/ITL-1789.md b/changelog.d/ITL-1789.md index ea1505b38..0d89c05b2 100644 --- a/changelog.d/ITL-1789.md +++ b/changelog.d/ITL-1789.md @@ -13,8 +13,8 @@ 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 on the asynchronous - path), never one per row, and hashes + 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`; the asynchronous path reads the results that have arrived together, up to diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 11f9543f9..698479782 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1142,9 +1142,10 @@ pins a newer version of the table, a function pod computes again only for the en content changed: an entry that is the same in both versions has the same hash, and its stored result is used. 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; on the asynchronous one, 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 +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 diff --git a/src/orcapod/core/sources/spiraldb_entries.py b/src/orcapod/core/sources/spiraldb_entries.py index b657483b6..f1311818e 100644 --- a/src/orcapod/core/sources/spiraldb_entries.py +++ b/src/orcapod/core/sources/spiraldb_entries.py @@ -781,6 +781,9 @@ def prefetched_entries(entries: Iterable[SpiralDBEntry]) -> Iterator[None]: 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] = [] @@ -805,7 +808,7 @@ def failed(entry: SpiralDBEntry, exc: Exception) -> None: _fetch(todo, None, found, failed=failed) is_open = [True] - token = _BATCH.set(_Batch(sign_in, batch, os.getpid(), is_open)) + token = _BATCH.set(_Batch(sign_in, batch, pid, is_open)) try: yield finally: diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index b655fec6a..589068507 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -20,6 +20,7 @@ import os import warnings from pathlib import Path +from collections.abc import Iterator from typing import Any import pyarrow as pa @@ -2484,3 +2485,35 @@ async def late_hash() -> list[Any]: 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() From 9905e20a855cb0ec598e666be068a547a3c131e6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 17:36:50 -0800 Subject: [PATCH 14/28] fix(spiraldb): address CodeRabbit's review of b271b70 (ITL-1789) - Under fail_fast a sync run stops hashing its inputs at the first missing entry, so that row's failure is the one reported. - The sync fetching-outputs path reports the node's end once. - A sync batch is bounded by its held rows, cache hits and repeats included. - An async row whose end was held crashes when its record write fails, and a held row crashes with the input its start was reported with. - Comments name finish in _execute_fetching_outputs. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 91 ++++++-- .../test_spiraldb_table_source_encoded.py | 217 ++++++++++++++++++ 2 files changed, 284 insertions(+), 24 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 5bd720a59..ba68dcda9 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -1592,7 +1592,8 @@ def __init__( 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 (``_record_after_batch``; ITL-1789). + # 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( @@ -2803,7 +2804,9 @@ def execute( output: list[tuple[TagProtocol, DataProtocol]] = [] try: # Collect upstream entries and resolve their instance ids. - upstream_entries = self._input_entries(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) ] @@ -3054,8 +3057,8 @@ def _execute_fetching_outputs( 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`` computed rows - are held, whose results' references are then fetched together, one scan per + 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, so the first failure stops the run before any later row is computed. A repeated input whose first occurrence is @@ -3068,6 +3071,18 @@ def _execute_fetching_outputs( """ failed = 0 held: list[_HeldRow] = [] + # The node's end is reported once, by whichever failure ends the run first. + node_ended = False + + def end_node(kept: OrcapodDatabaseError | TypeIdentityError | None) -> None: + """Report the node's end, unless it was already reported; an observer + error cannot replace ``kept``, the database error on its way out.""" + nonlocal node_ended + if node_ended: + return + node_ended = True + with keep_database_error(kept, "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 @@ -3080,7 +3095,7 @@ def crash(tag: TagProtocol, data: DataProtocol, exc: Exception) -> None: ) ctx_obs.on_data_crash(node_label, tag, data, exc) if error_policy == "fail_fast": - ctx_obs.on_node_end(node_label, node_hash) + end_node(None) raise exc def stop(tag: TagProtocol, data: DataProtocol, exc: Exception) -> None: @@ -3096,13 +3111,12 @@ def stop(tag: TagProtocol, data: DataProtocol, exc: Exception) -> None: exc.add_context(node_label=node_label, tag=tag.as_dict()) with keep_database_error(kept, "Observer on_data_crash"): ctx_obs.on_data_crash(node_label, tag, data, exc) - with keep_database_error(kept, "Observer on_node_end"): - ctx_obs.on_node_end(node_label, node_hash) + end_node(kept) def finish() -> None: """Fetch the held results' references together, then record, end and emit the held rows in order.""" - nonlocal failed + nonlocal failed, node_ended pending = self._deferred_records or [] self._deferred_records = [] rows = list(held) @@ -3144,9 +3158,13 @@ def finish() -> None: if row.result is not None: output.append((row.tag_out, row.result)) if not row.cached: - self._commit_or_end_node( - self._row_processed, ctx_obs, node_label, node_hash - ) + try: + self._commit_or_end_node( + self._row_processed, ctx_obs, node_label, node_hash + ) + except BaseException: + node_ended = True # reported by ``_commit_or_end_node`` + raise self._deferred_records = [] try: @@ -3167,7 +3185,7 @@ def finish() -> None: held.append( _HeldRow(tag, data, instance_id, tag_out, result, None, True) ) - if error_policy == "fail_fast": + if error_policy == "fail_fast" or len(held) >= _PREFETCH_ROWS: finish() continue pkt_logger = ctx_obs.create_data_logger(tag, data) @@ -3197,10 +3215,7 @@ def finish() -> None: held.append( _HeldRow(tag, data, instance_id, tag_out, result, record, False) ) - if ( - error_policy == "fail_fast" - or len(self._deferred_records) >= _PREFETCH_ROWS - ): + if error_policy == "fail_fast" or len(held) >= _PREFETCH_ROWS: finish() finish() finally: @@ -3213,8 +3228,9 @@ def _record_result( 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 - (``_record_after_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). @@ -3541,7 +3557,10 @@ def _inputs_fetch(self, row: DataProtocol) -> bool: ) def _input_entries( - self, rows: Iterable[tuple[TagProtocol, DataProtocol]] + 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. @@ -3550,6 +3569,9 @@ def _input_entries( 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. """ entries: list[ tuple[TagProtocol, DataProtocol, bytes | SpiralDBEntryMissingError] @@ -3561,10 +3583,11 @@ def _input_entries( fetching = self._inputs_fetch(data) if fetching: pairs = [(tag, data), *rows] + 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, self._instance_ids_of(pairs), strict=True + pairs[: len(ids)], ids, strict=True ) ] return entries @@ -3596,14 +3619,18 @@ async def _input_entries_of_channel( return entries def _instance_ids_of( - self, pairs: Sequence[tuple[TagProtocol, DataProtocol]] + 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. + 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]): @@ -3612,6 +3639,8 @@ def _instance_ids_of( 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( @@ -5339,6 +5368,13 @@ async def record_one( ) ) 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: @@ -5354,10 +5390,10 @@ async def record_one( TypeIdentityError, ), ): - if not lookup_crashed(original_tag, input_data, exc): + if not lookup_crashed(seen_tag, seen_input, exc): raise return - ctx_obs.on_data_crash(node_label, original_tag, input_data, exc) + ctx_obs.on_data_crash(node_label, seen_tag, seen_input, exc) raise try: self._add_pipeline_record( @@ -5377,6 +5413,13 @@ async def record_one( exc.add_context( node_label=node_label, tag=original_tag.as_dict() ) + 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_database_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: diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index 589068507..c6ebcf53b 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -2517,3 +2517,220 @@ def forking(chosen: list[SpiralDBEntry]) -> Iterator[SpiralDBEntry]: 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) + + +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.node_ends.count("pick") == 1 + + +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", "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 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") + if failure == "record": + 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) + seen: dict[str, list[str]] = {} + + 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"] = sorted(data.keys()) + + def on_data_crash(self, node: str, tag: Any, data: Any, exc: Any) -> None: + if node == "pick" and tag.as_dict()["id"] == 1: + seen["crash"] = sorted(data.keys()) + + with contextlib.suppress(BaseException): + _run_observed(job, "async", "continue", Seen()) + assert seen["start"] == ["count", "slot"] + assert seen["crash"] == seen["start"] From 614552d31ac59b9465fc4e32ec7f60e75434a03f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 18:41:46 -0800 Subject: [PATCH 15/28] fix(spiraldb): address CodeRabbit's review of 9905e20 (ITL-1789) - When a held result's hash stops a sync run, every row held behind it is reported as crashed before the node's end. - Under fail_fast, an input read error after a row whose entry is missing does not replace that row's failure; under continue it is raised after the rows read before it are hashed. - Tests compare the held row's input values and each variant's outcome. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 34 +++++-- .../test_spiraldb_table_source_encoded.py | 97 +++++++++++++++++-- 2 files changed, 119 insertions(+), 12 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index ba68dcda9..29c1c0cad 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3098,10 +3098,17 @@ def crash(tag: TagProtocol, data: DataProtocol, exc: Exception) -> None: end_node(None) raise exc - def stop(tag: TagProtocol, data: DataProtocol, exc: Exception) -> None: + def stop( + tag: TagProtocol, + data: DataProtocol, + exc: Exception, + aborted: Sequence[_HeldRow] = (), + ) -> None: """Report a row whose database read or write failed, whose stored result cannot be decoded, or whose result's hash raised another error than a - missing entry: the run stops whatever the policy.""" + missing entry: the run stops whatever the policy. The ``aborted`` rows, + started and held behind it, are reported as crashed with the same error + before the node's end, so every started row has a terminal event.""" kept = ( exc if isinstance(exc, (OrcapodDatabaseError, TypeIdentityError)) @@ -3111,6 +3118,9 @@ def stop(tag: TagProtocol, data: DataProtocol, exc: Exception) -> None: exc.add_context(node_label=node_label, tag=tag.as_dict()) with keep_database_error(kept, "Observer on_data_crash"): ctx_obs.on_data_crash(node_label, tag, data, exc) + for row in aborted: + with keep_database_error(kept, "Observer on_data_crash"): + ctx_obs.on_data_crash(node_label, row.tag, row.data, exc) end_node(kept) def finish() -> None: @@ -3128,7 +3138,7 @@ def finish() -> None: self.data_context.type_converter, self.data_context.semantic_hasher, ): - for row in rows: + for index, row in enumerate(rows): if row.record is not None: deferred = pending[row.record] try: @@ -3145,7 +3155,7 @@ def finish() -> None: failed += 1 continue except Exception as exc: - stop(row.tag, row.data, exc) + stop(row.tag, row.data, exc, rows[index + 1 :]) raise elif row.instance_id in missing: crash(row.tag, row.data, missing[row.instance_id]) @@ -3571,7 +3581,9 @@ def _input_entries( 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. + 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] @@ -3582,7 +3594,12 @@ def _input_entries( if fetching is None and not isinstance(data, EmptyData): fetching = self._inputs_fetch(data) if fetching: - pairs = [(tag, data), *rows] + 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) @@ -3590,6 +3607,11 @@ def _input_entries( 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 diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index c6ebcf53b..bfe217d6f 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -2719,18 +2719,103 @@ def failing_second(self: Any, tag: Any, *args: Any, **kwargs: Any) -> Any: return real(self, tag, *args, **kwargs) monkeypatch.setattr(FunctionJobNode, "_add_pipeline_record", failing_second) - seen: dict[str, list[str]] = {} + seen: dict[str, dict[str, Any]] = {} 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"] = sorted(data.keys()) + 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: - seen["crash"] = sorted(data.keys()) + seen["crash"] = data.as_dict() - with contextlib.suppress(BaseException): - _run_observed(job, "async", "continue", Seen()) - assert seen["start"] == ["count", "slot"] + if failure == "record": + with pytest.raises(BaseException) as raised: + _run_observed(job, "async", "continue", Seen()) + assert any( + isinstance(e, OrcapodDatabaseError) 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 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.node_ends.count("pick") == 1 + + +@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"] + + 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 any("synthetic input read failure" in str(e) for e in chain) From 7089f1fd0e1c774346d679b4f03aa5fb8c111aad Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 20:52:54 -0800 Subject: [PATCH 16/28] fix(spiraldb): address CodeRabbit review of 629cf51 (ITL-1789) - docs: a missing table, version or key raises SpiralDBEntryMissingError; a failure to reach the service or sign in is raised as itself - sync held batch: a failing commit crashes every row held behind it before the single node end; a fatal row's crash precedes the node end - async: rows whose end waits for their record crash before the node end when the task group fails - refuse an encoded column beside a primary-key column that cannot form a reference key - SpiralDBTable._at keeps the first handle stored under concurrent misses - remove new_client; open_table_version takes a client - tests compare a second run's results and order events on one timeline Deferred: ITL-1885, ITL-1886. Co-Authored-By: Claude Opus 5.5 --- docs/concepts/sources.md | 9 +- src/orcapod/core/nodes/function_node.py | 75 +++++++-- src/orcapod/core/sources/spiraldb_entries.py | 8 +- .../core/sources/spiraldb_table_source.py | 16 ++ src/orcapod/databases/spiraldb_connector.py | 19 +-- .../test_spiraldb_table_source_encoded.py | 151 +++++++++++++++++- 6 files changed, 239 insertions(+), 39 deletions(-) diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index e9ffa725e..d045e640d 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1121,12 +1121,13 @@ as **references** to its entries, one per row: 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. -- When the version no longer holds a row with the key, or the table or that version can - no longer be opened, `entry.read()` raises `orcapod.errors.SpiralDBEntryMissingError` +- 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 cannot be opened: the scan + `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. + 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. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index aa5ce38bd..943150519 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3078,6 +3078,9 @@ def _execute_fetching_outputs( held: list[_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 def end_node(kept: OrcapodDatabaseError | TypeIdentityError | None) -> None: """Report the node's end, unless it was already reported; an observer @@ -3123,15 +3126,40 @@ def stop( exc.add_context(node_label=node_label, tag=tag.as_dict()) with keep_database_error(kept, "Observer on_data_crash"): ctx_obs.on_data_crash(node_label, tag, data, exc) + abort(aborted, exc, kept) + + def abort( + aborted: Sequence[_HeldRow], + exc: Exception, + kept: OrcapodDatabaseError | TypeIdentityError | None, + ) -> None: + """End the run for the observer: each started row held behind the failure + crashes with ``exc``, the fatal row (if one waits) with its own error, then + the node ends, once.""" + nonlocal fatal for row in aborted: with keep_database_error(kept, "Observer on_data_crash"): ctx_obs.on_data_crash(node_label, row.tag, row.data, exc) + if fatal is not None: + fatal_tag, fatal_data, fatal_exc = fatal + fatal = None + fatal_kept = ( + fatal_exc + if isinstance(fatal_exc, (OrcapodDatabaseError, TypeIdentityError)) + else None + ) + if isinstance(fatal_exc, OrcapodDatabaseError): + fatal_exc.add_context( + node_label=node_label, tag=fatal_tag.as_dict() + ) + with keep_database_error(fatal_kept, "Observer on_data_crash"): + ctx_obs.on_data_crash(node_label, fatal_tag, fatal_data, fatal_exc) end_node(kept) def finish() -> None: """Fetch the held results' references together, then record, end and emit the held rows in order.""" - nonlocal failed, node_ended + nonlocal failed pending = self._deferred_records or [] self._deferred_records = [] rows = list(held) @@ -3174,11 +3202,10 @@ def finish() -> None: output.append((row.tag_out, row.result)) if not row.cached: try: - self._commit_or_end_node( - self._row_processed, ctx_obs, node_label, node_hash - ) - except BaseException: - node_ended = True # reported by ``_commit_or_end_node`` + self._row_processed() + except OrcapodDatabaseError as exc: + # As ``_commit_or_end_node``, after the rows held behind it. + abort(rows[index + 1 :], exc, exc) raise self._deferred_records = [] @@ -3215,10 +3242,14 @@ def finish() -> None: ) except (OrcapodDatabaseError, TypeIdentityError) as exc: # The rows held before it are recorded first; this error is the - # one the run raises. + # one the run raises. When finishing them ends the run, this row's + # crash is reported there, before the node's end. + fatal = (tag, data, exc) with keep_database_error(exc, "Finishing the rows held before it"): finish() - stop(tag, data, exc) + if fatal is not None: + fatal = None + stop(tag, data, exc) raise except Exception as exc: if error_policy == "fail_fast": @@ -3580,8 +3611,9 @@ def _input_entries( """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 and the - rows' entries fetched together (``_instance_ids_of``); otherwise each row's + 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 @@ -5153,6 +5185,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} @@ -5218,9 +5255,6 @@ async def async_execute( # reported only once its result is hashed and recorded: the end # events held meanwhile, by correlation key. outputs_fetch = self._outputs_fetch() - held_ends: dict[ - bytes, tuple[TagProtocol, DataProtocol, DataProtocol, bool] - ] = {} def lookup_crashed( tag: TagProtocol, data: DataProtocol, exc: Exception @@ -5643,6 +5677,21 @@ 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 + ) + for held_tag, held_input, _, _ in list(held_ends.values()): + with keep_database_error( + database_error_of(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( diff --git a/src/orcapod/core/sources/spiraldb_entries.py b/src/orcapod/core/sources/spiraldb_entries.py index f1311818e..7555c8c77 100644 --- a/src/orcapod/core/sources/spiraldb_entries.py +++ b/src/orcapod/core/sources/spiraldb_entries.py @@ -303,8 +303,8 @@ def scan_entry(entry: SpiralDBEntry, client: Any = None) -> Any: # pyright: ign 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 cannot be - opened. (For a key the version does not hold, the scan yields no row.) + 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] @@ -847,7 +847,7 @@ def cached_content_hash(entry: SpiralDBEntry) -> ContentHash: Raises: SpiralDBEntryMissingError: If its version holds no row with its key, or the - table or that version cannot be opened. + 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. @@ -886,7 +886,7 @@ def read_entry(entry: SpiralDBEntry, client: Any = None) -> pa.Table: # pyright Raises: SpiralDBEntryMissingError: If its version holds no row with its key, or the - table or that version cannot be opened. + 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 diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index a595c35f9..f66804abb 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -459,6 +459,22 @@ 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 every primary-key column must form a key value. + 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 ): diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 1154918da..62b41890d 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -507,17 +507,6 @@ 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 new_client() -> Any: # pyright: ignore[reportExplicitAny] # an SDK client, untyped - """Return this process's spiral-sdk client of spiral-sdk's own sign-in and service - address, shared as the connectors share it (``_client_for``). - - Raises: - SpiralDBSignInError: If spiral-sdk would have to ask a person to sign in. - ImportError: If spiral-sdk is not installed. - """ - return _client_for(None).sdk # pyright: ignore[reportAny] - - def normalize_service_address(address: str) -> str: """Return the form of a service address that two spellings of one address share. @@ -690,7 +679,7 @@ def open_table_version(client: Any, table_id: str, version: int) -> Any: # pyri snapshot opened must have ``version`` itself, or the version is not there. Args: - client: A ``spiral.Client``; ``None`` uses ``new_client``. + client: A ``spiral.Client``. table_id: SpiralDB's id of the table. version: The version. @@ -698,8 +687,6 @@ def open_table_version(client: Any, table_id: str, version: int) -> Any: # pyri TableVersionNotFoundError: If the table does not exist, or holds no snapshot of exactly ``version``. """ - if client is None: - client = new_client() with _service_call(f"open table {table_id} at version {version}"): try: _ignore_keyed_table_deprecation() @@ -1107,7 +1094,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( diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index bfe217d6f..cbfa24bcb 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -465,8 +465,15 @@ def run() -> PipelineJob: assert sorted(same, key=lambda e: e.key) == sorted(calls, key=lambda e: e.key) calls.clear() - run() + 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] + assert sorted(_entries(again, "same"), key=lambda e: e.key) == sorted( + same, key=lambda e: e.key + ) def test_another_stored_type_beside_an_encoding_in_a_struct_is_refused(): @@ -2528,6 +2535,12 @@ def __init__(self) -> None: 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} -" def test_fail_fast_reports_the_first_missing_input_entry_not_a_later_error( @@ -2606,7 +2619,7 @@ def broken(*args: Any, **kwargs: Any) -> Any: 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.node_ends.count("pick") == 1 + assert events.ends_last("pick") def test_a_sync_batch_is_bounded_by_its_held_rows( @@ -2772,7 +2785,7 @@ def broken(*args: Any, **kwargs: Any) -> Any: "1": ["data_crash"], "2": ["data_crash"], } - assert events.node_ends.count("pick") == 1 + assert events.ends_last("pick") @pytest.mark.parametrize("error_policy", ["fail_fast", "continue"]) @@ -2819,3 +2832,135 @@ def iter_data(self) -> Any: assert events.terminal("size") == {"0": ["data_end"], "1": ["data_crash"]} else: 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") + } + assert started + assert events.terminal("pick") == {row: ["data_crash"] for row in started} + 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_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] From 1e627fc85531602660d09b81e59d0a0fd46dd772 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 21:39:10 -0800 Subject: [PATCH 17/28] fix(spiraldb): address the delta review of 7089f1f (ITL-1789) - An observer that raises while a failed async run reports a held row's crash no longer replaces the run's error or skips the remaining held rows and the node's end: each crash report is isolated, its failure logged and noted on the run's error (keep_run_error). - A source over a table with an encoded column and no primary key is refused when built, also with explicit record_id_columns. - The public SpiralDBEntry.scan, read and content_hash docstrings state which failures raise SpiralDBEntryMissingError, that a transport or sign-in failure propagates as itself, and that a scan of an absent key is empty. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 9 ++- .../core/sources/spiraldb_table_source.py | 12 ++- .../logical_types/spiraldb_entry_type.py | 33 +++++++-- src/orcapod/utils/database_errors.py | 42 +++++++++++ .../test_spiraldb_table_source_encoded.py | 74 +++++++++++++++++++ 5 files changed, 158 insertions(+), 12 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 943150519..c08d914a2 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -112,6 +112,7 @@ commit_best_effort, database_write_path, keep_database_error, + keep_run_error, database_error_of, ) from orcapod.protocols.core_protocols import ( @@ -5684,10 +5685,12 @@ def create_data_logger(self, tag: Any, data: Any) -> Any: 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_database_error( - database_error_of(run_error), "Observer on_data_crash" - ): + with keep_run_error(run_error, "Observer on_data_crash"): ctx_obs.on_data_crash( node_label, held_tag, held_input, cause ) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index f66804abb..95af659ec 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -460,7 +460,17 @@ def __init__( "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 every primary-key column must form a key value. + # 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}" diff --git a/src/orcapod/logical_types/spiraldb_entry_type.py b/src/orcapod/logical_types/spiraldb_entry_type.py index ef052ef40..4731a0424 100644 --- a/src/orcapod/logical_types/spiraldb_entry_type.py +++ b/src/orcapod/logical_types/spiraldb_entry_type.py @@ -199,8 +199,11 @@ def __reduce__(self) -> tuple[type[SpiralDBEntry], tuple[str, int, str, str, str 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 ``version``; the scan's key range is the one - primary key, so it holds at most one row. + 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`` @@ -212,8 +215,13 @@ def scan(self, client: Any = None) -> Any: # pyright: ignore[reportExplicitAny, 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 @@ -224,7 +232,8 @@ def read(self, client: Any = None) -> pa.Table: # pyright: ignore[reportExplici 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. + 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``. @@ -236,8 +245,12 @@ def read(self, client: Any = None) -> pa.Table: # pyright: ignore[reportExplici Raises: ImportError: If spiral-sdk is not installed (``orcapod[spiraldb]``). - SpiralDBEntryMissingError: If the table at ``version`` has no row with this - key, or the version cannot be read any more. + 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 @@ -246,11 +259,15 @@ def read(self, client: Any = None) -> pa.Table: # pyright: ignore[reportExplici def content_hash(self) -> ContentHash: """Return the hash of the entry's content (``entry_content_hash``). - Fetched once per process (``prefetch`` fetches many entries together). + Fetched once per process (``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 at ``version`` has no row with this - key, or the version cannot be read any more. + 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 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_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index cbfa24bcb..196eaf968 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -2909,6 +2909,58 @@ def broken(*args: Any, **kwargs: Any) -> Any: 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_a_primary_key_that_cannot_name_a_row_is_refused_beside_an_encoded_column( tmp_path: Path, ): @@ -2938,6 +2990,28 @@ def test_a_primary_key_that_cannot_name_a_row_is_refused_beside_an_encoded_colum _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 ): From bcd4f10da9d18d536d3b27dc816dbccbdca8da35 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 23:15:47 -0800 Subject: [PATCH 18/28] fix(spiraldb): address CodeRabbit review of 1e627fc (ITL-1789) - A sync run that stops on a held result's hash reports each crash with keep_run_error, so an observer that raises neither interrupts the remaining reports nor replaces the run's error; a waiting fatal row keeps precedence. - A reference's client is made for the normalized address the trust check matched, not the reference's spelling. - The content-hash docstrings say a retained outcome is reused for the current sign-in, and a miss fetches again. - Two tests are tightened: replayed norms compared with their references, and the async cleanup test asserts the three held rows. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 40 ++++---- src/orcapod/databases/spiraldb_connector.py | 7 +- .../semantic_hashing/builtin_handlers.py | 6 +- .../logical_types/spiraldb_entry_type.py | 9 +- .../test_spiraldb_table_source_encoded.py | 96 ++++++++++++++++++- 5 files changed, 124 insertions(+), 34 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index c08d914a2..d79f3c461 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3118,44 +3118,40 @@ def stop( missing entry: the run stops whatever the policy. The ``aborted`` rows, started and held behind it, are reported as crashed with the same error before the node's end, so every started row has a terminal event.""" - kept = ( - exc - if isinstance(exc, (OrcapodDatabaseError, TypeIdentityError)) - else None - ) if isinstance(exc, OrcapodDatabaseError): exc.add_context(node_label=node_label, tag=tag.as_dict()) - with keep_database_error(kept, "Observer on_data_crash"): + # Each report is isolated, as in the async cleanup: an observer that + # raises is noted on the error the run raises, and the remaining reports + # and the node's end still run. + with keep_run_error(run_error_for(exc), "Observer on_data_crash"): ctx_obs.on_data_crash(node_label, tag, data, exc) - abort(aborted, exc, kept) + abort(aborted, exc) - def abort( - aborted: Sequence[_HeldRow], - exc: Exception, - kept: OrcapodDatabaseError | TypeIdentityError | None, - ) -> None: + 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``.""" + return fatal[2] if fatal 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 fatal row (if one waits) with its own error, then - the node ends, once.""" + the node ends, once. An observer that raises cannot interrupt the reports + or replace the error the run raises.""" nonlocal fatal + run_error = run_error_for(exc) for row in aborted: - with keep_database_error(kept, "Observer on_data_crash"): + with keep_run_error(run_error, "Observer on_data_crash"): ctx_obs.on_data_crash(node_label, row.tag, row.data, exc) if fatal is not None: fatal_tag, fatal_data, fatal_exc = fatal fatal = None - fatal_kept = ( - fatal_exc - if isinstance(fatal_exc, (OrcapodDatabaseError, TypeIdentityError)) - else None - ) if isinstance(fatal_exc, OrcapodDatabaseError): fatal_exc.add_context( node_label=node_label, tag=fatal_tag.as_dict() ) - with keep_database_error(fatal_kept, "Observer on_data_crash"): + with keep_run_error(run_error, "Observer on_data_crash"): ctx_obs.on_data_crash(node_label, fatal_tag, fatal_data, fatal_exc) - end_node(kept) + end_node(database_error_of(run_error)) def finish() -> None: """Fetch the held results' references together, then record, end and @@ -3206,7 +3202,7 @@ def finish() -> None: self._row_processed() except OrcapodDatabaseError as exc: # As ``_commit_or_end_node``, after the rows held behind it. - abort(rows[index + 1 :], exc, exc) + abort(rows[index + 1 :], exc) raise self._deferred_records = [] diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 62b41890d..1c6c24c85 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -605,8 +605,9 @@ def client_for_service(service: str) -> Any: # pyright: ignore[reportExplicitAn 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. - return _client_for({"server.url": service}).sdk # pyright: ignore[reportAny] + # 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 ( @@ -616,7 +617,7 @@ def client_for_service(service: str) -> Any: # pyright: ignore[reportExplicitAn and not held[2].health.failed ): return held[2].sdk # pyright: ignore[reportAny] - shared = _client_for({"server.url": service}) + 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] diff --git a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py index 4126fa2f5..73e24b031 100644 --- a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py +++ b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py @@ -115,8 +115,10 @@ class SpiralDBEntryHandler: 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. The value is fetched once per process; a node - fetches the entries of many rows together through ``prefetched`` first. + 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 diff --git a/src/orcapod/logical_types/spiraldb_entry_type.py b/src/orcapod/logical_types/spiraldb_entry_type.py index 4731a0424..678389129 100644 --- a/src/orcapod/logical_types/spiraldb_entry_type.py +++ b/src/orcapod/logical_types/spiraldb_entry_type.py @@ -259,9 +259,12 @@ def read(self, client: Any = None) -> pa.Table: # pyright: ignore[reportExplici def content_hash(self) -> ContentHash: """Return the hash of the entry's content (``entry_content_hash``). - Fetched once per process (``prefetch`` fetches many entries together). A - failure to reach the service, or to sign in, is not a missing entry: it - propagates as itself. + 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 diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index 196eaf968..c3edb069e 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -471,9 +471,16 @@ def run() -> PipelineJob: warnings.simplefilter("ignore") again = second.nodes["norm"].as_table() assert sorted(again.column("norm").to_pylist()) == [0.125, 1.5, 2.25] - assert sorted(_entries(again, "same"), key=lambda e: e.key) == sorted( - same, key=lambda e: e.key - ) + + # 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(): @@ -1519,6 +1526,32 @@ def test_an_address_is_trusted_in_any_spelling_and_one_client_is_held_per_addres 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.""" @@ -2904,7 +2937,9 @@ def broken(*args: Any, **kwargs: Any) -> Any: started = { e.split(" ")[2] for e in events.events if e.startswith("data_start pick") } - assert started + # 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") @@ -2961,6 +2996,59 @@ def crash(node: str, tag: Any, *args: Any, **kwargs: Any) -> None: 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, ): From 74be83fcea169cb8f1e115a13f7e187713b23a90 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 23:43:23 -0800 Subject: [PATCH 19/28] test(pipeline): compare an async load-only trace in the order the run delivered (ITL-1789) 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 (also on main). The expected trace now places its rows in that order; every other event is compared exactly. Co-Authored-By: Claude Opus 5.5 --- .../test_observer_order_of_a_chain.py | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/test_pipeline/test_observer_order_of_a_chain.py b/tests/test_pipeline/test_observer_order_of_a_chain.py index 3c6b5e330..bc25ce9c5 100644 --- a/tests/test_pipeline/test_observer_order_of_a_chain.py +++ b/tests/test_pipeline/test_observer_order_of_a_chain.py @@ -125,6 +125,23 @@ def agree(got: list[str], want: list[str], what: str) -> None: 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)], @@ -383,6 +400,8 @@ async def recording_drain(*args: Any, **kwargs: Any) -> Any: 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 ) @@ -423,9 +442,19 @@ async def recording_drain(*args: Any, **kwargs: Any) -> Any: 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. From d8da4e15479fdbf564794a4cec597c20246fda3a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 02:27:04 -0800 Subject: [PATCH 20/28] fix(pipeline): preserve async result hash errors during crash reporting --- src/orcapod/core/nodes/function_node.py | 3 +- .../test_spiraldb_table_source_encoded.py | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index d79f3c461..67cac96f2 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -5451,7 +5451,8 @@ async def record_one( if not lookup_crashed(seen_tag, seen_input, exc): raise return - ctx_obs.on_data_crash(node_label, seen_tag, seen_input, exc) + 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( diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index c3edb069e..e98d328ad 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -2996,6 +2996,39 @@ def crash(node: str, tag: Any, *args: Any, **kwargs: Any) -> None: 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 ): From a3d48aa35cd43e31b95c67bb2303f96ae8c678a0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 06:58:28 -0800 Subject: [PATCH 21/28] fix(pipeline): validate held outputs before exposing cached results --- changelog.d/ITL-1789.md | 5 +- docs/concepts/sources.md | 8 +- src/orcapod/core/nodes/function_node.py | 68 ++++---- .../test_spiraldb_table_source_encoded.py | 146 +++++++++++++++++- 4 files changed, 188 insertions(+), 39 deletions(-) diff --git a/changelog.d/ITL-1789.md b/changelog.d/ITL-1789.md index 0d89c05b2..f741f5fd4 100644 --- a/changelog.d/ITL-1789.md +++ b/changelog.d/ITL-1789.md @@ -4,8 +4,9 @@ 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 and a function pod over it does not - compute again after the source's pin moves. `entry.read()` returns the entry as a + 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 diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 1b124ac11..635f1ac71 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1160,10 +1160,10 @@ This sample needs a SpiralDB service. The test suite runs it against a fake Spir **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. So when a run's check (`check_for_new_data()`) -pins a newer version of the table, a function pod computes again only for the entries whose -content changed: an entry that is the same in both versions has the same hash, and its -stored result is used. Hashing needs the content, so a job first reads the entries it is +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`. 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 diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 67cac96f2..013d1cdb9 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3077,20 +3077,20 @@ def _execute_fetching_outputs( """ failed = 0 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 - def end_node(kept: OrcapodDatabaseError | TypeIdentityError | None) -> None: - """Report the node's end, unless it was already reported; an observer - error cannot replace ``kept``, the database error on its way out.""" + 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_database_error(kept, "Observer on_node_end"): + 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: @@ -3104,7 +3104,7 @@ def crash(tag: TagProtocol, data: DataProtocol, exc: Exception) -> None: ) ctx_obs.on_data_crash(node_label, tag, data, exc) if error_policy == "fail_fast": - end_node(None) + end_node(exc) raise exc def stop( @@ -3151,7 +3151,7 @@ def abort(aborted: Sequence[_HeldRow], exc: Exception) -> None: ) with keep_run_error(run_error, "Observer on_data_crash"): ctx_obs.on_data_crash(node_label, fatal_tag, fatal_data, fatal_exc) - end_node(database_error_of(run_error)) + end_node(run_error) def finish() -> None: """Fetch the held results' references together, then record, end and @@ -3161,6 +3161,7 @@ def finish() -> None: 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] = {} with prefetched_rows( @@ -3178,15 +3179,15 @@ def finish() -> None: except SpiralDBEntryMissingError as exc: # Not reused: a repeat of this input fails with it. missing[row.instance_id] = exc - _ = self._cached_output_datas.pop(row.instance_id, None) - self._cached_output_table = None - self._cached_content_hash_column = None crash(row.tag, row.data, exc) failed += 1 continue except Exception as exc: stop(row.tag, row.data, exc, rows[index + 1 :]) raise + self._cache_output_data( + row.instance_id, row.tag_out, row.result + ) elif row.instance_id in missing: crash(row.tag, row.data, missing[row.instance_id]) failed += 1 @@ -3216,11 +3217,16 @@ def finish() -> None: crash(tag, data, instance_id) failed += 1 continue - if instance_id in self._cached_output_datas and not isinstance( - self._cached_output_datas[instance_id][1], EmptyData + 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 = self._cached_output_datas[instance_id] - # Ends in ``finish``: its result may be a held one not yet hashed. + tag_out, result = cached_result held.append( _HeldRow(tag, data, instance_id, tag_out, result, None, True) ) @@ -3255,9 +3261,10 @@ def finish() -> None: failed += 1 continue record = before if len(self._deferred_records) > before else None - held.append( - _HeldRow(tag, data, instance_id, tag_out, result, record, False) - ) + row = _HeldRow(tag, data, instance_id, tag_out, result, record, False) + held.append(row) + if record is not None: + pending_results[instance_id] = row if error_policy == "fail_fast" or len(held) >= _PREFETCH_ROWS: finish() finish() @@ -3311,7 +3318,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: @@ -3348,6 +3356,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: @@ -3423,13 +3432,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]]: @@ -5466,16 +5481,15 @@ async def record_one( output_data_hash=output_hash, run_id=run_id, ) - except OrcapodDatabaseError as exc: - # This runs outside the pod's per-row handler: name the - # node and row here. - exc.add_context( - node_label=node_label, tag=original_tag.as_dict() - ) + except Exception as exc: + if isinstance(exc, OrcapodDatabaseError): + exc.add_context( + node_label=node_label, tag=original_tag.as_dict() + ) 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_database_error(exc, "Observer on_data_crash"): + with keep_run_error(exc, "Observer on_data_crash"): ctx_obs.on_data_crash( node_label, seen_tag, seen_input, exc ) diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index e98d328ad..f73115a31 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -1727,6 +1727,11 @@ def pick(slot: int, count: int) -> tuple[SpiralDBEntry, int]: 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() + assert sorted(table.column("id").to_pylist()) == [0, 1] return summary = _run(job, orchestrator, error_policy) assert summary.nodes["pick"].failed == 1 @@ -1882,6 +1887,29 @@ def test_the_documented_sample_runs( 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() + before = {name: _entries(original, name) for name in ("vector", "embeddings")} + _rewrite_column([True, True, True], "rate", pa.array([1.0, 1.5, 2.5])) + assert items.check_for_new_data() + updated = items.as_table() + for name, entries in before.items(): + assert [entry.content_hash() for entry in entries] == [ + entry.content_hash() for entry in _entries(updated, name) + ] + 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: 3.375, 30: 0.3125} + # -------------------------------------------------------------------------------------- # CodeRabbit on 4ce0a09 (PR 680). @@ -2003,6 +2031,51 @@ def test_a_repeated_input_does_not_reuse_a_result_that_failed_its_hash( 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 ): @@ -2721,7 +2794,7 @@ def failing_second(self: Any, tag: Any, *args: Any, **kwargs: Any) -> Any: assert events.terminal("pick").get("1") == ["data_crash"] -@pytest.mark.parametrize("failure", ["record", "hash"]) +@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, @@ -2736,7 +2809,7 @@ def test_an_async_held_row_crashes_with_the_input_its_start_was_reported_with( from orcapod import PipelineJob from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.databases import DeltaTableDatabase - from orcapod.errors import OrcapodDatabaseError + from orcapod.errors import InputValidationError, OrcapodDatabaseError from orcapod.sources import DictSource entries = _entries(_table(_source()), "vector") @@ -2756,16 +2829,20 @@ def pick(slot: int, count: int) -> tuple[SpiralDBEntry, int]: job = PipelineJob(name="seen", database=DeltaTableDatabase(tmp_path / "db")) with job: pick.pod(source, label="pick") - if failure == "record": + 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 OrcapodDatabaseError("synthetic record failure") + 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: @@ -2774,18 +2851,27 @@ def on_data_start(self, node: str, tag: Any, data: Any) -> None: 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 == "record": + if failure != "hash": with pytest.raises(BaseException) as raised: _run_observed(job, "async", "continue", Seen()) assert any( - isinstance(e, OrcapodDatabaseError) and "synthetic record failure" in str(e) + 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"] @@ -2821,6 +2907,54 @@ def broken(*args: Any, **kwargs: Any) -> Any: assert events.ends_last("pick") +@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 FailsOnEnd(_CountingEvents): + """Record the node's end before raising from its observer.""" + + 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 = FailsOnEnd() + 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) + assert any( + "synthetic node-end observer failure" in note + for note in getattr(raised.value, "__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 From 705e1c7058dfe2d013086e45947a14d8b904cf51 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 07:22:59 -0800 Subject: [PATCH 22/28] fix(pipeline): preserve fail-fast errors when crash observers raise --- changelog.d/ITL-1789.md | 2 ++ src/orcapod/core/nodes/function_node.py | 4 ++- .../test_spiraldb_table_source_encoded.py | 28 +++++++++++++------ 3 files changed, 25 insertions(+), 9 deletions(-) diff --git a/changelog.d/ITL-1789.md b/changelog.d/ITL-1789.md index f741f5fd4..7b64226c8 100644 --- a/changelog.d/ITL-1789.md +++ b/changelog.d/ITL-1789.md @@ -60,6 +60,8 @@ (`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 diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 013d1cdb9..8b430d291 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3102,10 +3102,12 @@ def crash(tag: TagProtocol, data: DataProtocol, exc: Exception) -> None: exc, exc_info=True, ) - ctx_obs.on_data_crash(node_label, tag, data, exc) 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 stop( tag: TagProtocol, diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index f73115a31..0294aa896 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -1891,13 +1891,20 @@ def test_the_documented_sample_runs( 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, 1.5, 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 _entries(updated, name) + entry.content_hash() for entry in refreshed_entries ] refreshed = _run(job, orchestrator).nodes["summarize"] result = job.nodes["summarize"].as_table() @@ -2928,8 +2935,13 @@ def broken_scan(*args: Any, **kwargs: Any) -> Any: else: entry = _missing_reference(entry) - class FailsOnEnd(_CountingEvents): - """Record the node's end before raising from its observer.""" + 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) @@ -2937,7 +2949,7 @@ def on_node_end(self, node: str, *args: Any, **kwargs: Any) -> None: raise RuntimeError("synthetic node-end observer failure") job = _picking_job(tmp_path, [entry], []) - events = FailsOnEnd() + events = FailingObserver() expected = RuntimeError if error_policy == "continue" else SpiralDBEntryMissingError with pytest.raises(expected) as raised: _run_observed(job, "sync", error_policy, events) @@ -2947,10 +2959,10 @@ def on_node_end(self, node: str, *args: Any, **kwargs: Any) -> None: == "Failed to process column 'ref': synthetic scan failure" ) assert isinstance(raised.value.__cause__, ValueError) - assert any( - "synthetic node-end observer failure" in note - for note in getattr(raised.value, "__notes__", []) - ) + 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") From 8b70f7f9c8e8493c4f1de006e872c707912a2d00 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 09:56:00 -0800 Subject: [PATCH 23/28] fix(pipeline): preserve fail-fast missing input errors --- src/orcapod/core/nodes/function_node.py | 15 +++++- .../test_spiraldb_table_source_encoded.py | 46 +++++++++++++++++++ 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 8b430d291..6fc5109ae 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -2853,10 +2853,15 @@ def execute( node_label, instance_id, ) - ctx_obs.on_data_crash(node_label, tag, data, instance_id) if error_policy == "fail_fast": - ctx_obs.on_node_end(node_label, node_hash) + 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 @@ -5291,6 +5296,12 @@ 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 diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index 0294aa896..269fb7fde 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -2656,6 +2656,52 @@ def ends_last(self, node: str) -> bool: return self.node_ends.count(node) == 1 and at[-1] == f"node_end {node} -" +@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" and orchestrator == "sync": + 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) + if orchestrator == "sync": + 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 ): From 0730bedcd85d2df21dfb27aadeec728b7bdbd5ec Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 10:55:14 -0800 Subject: [PATCH 24/28] test(pipeline): check async fail-fast storage guarantees --- .../test_spiraldb_table_source_encoded.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index 269fb7fde..930f10664 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -1695,9 +1695,9 @@ 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 (its result cannot be hashed into the record): the other rows are recorded - in order under ``continue``; ``fail_fast`` raises the missing-entry error after - the rows before it are recorded.""" + 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 @@ -1731,7 +1731,16 @@ def pick(slot: int, count: int) -> tuple[SpiralDBEntry, int]: warnings.simplefilter("ignore") job.run(load_only=True) table = job.nodes["pick"].as_table() - assert sorted(table.column("id").to_pylist()) == [0, 1] + 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 From edb0f48e118a940c8d9948b12285c5cf50196608 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 12:50:00 -0800 Subject: [PATCH 25/28] fix(spiraldb): preserve reference schema and recording guarantees --- changelog.d/ITL-1789.md | 5 +- docs/concepts/sources.md | 37 +- src/orcapod/core/nodes/function_node.py | 46 +-- src/orcapod/core/sources/spiraldb_entries.py | 32 +- src/orcapod/databases/spiraldb_connector.py | 9 + .../databases/spiraldb_schema_table.py | 24 +- .../test_spiraldb_table_source_encoded.py | 324 +++++++++++++++++- .../test_pipeline/test_job_batched_commits.py | 9 +- 8 files changed, 406 insertions(+), 80 deletions(-) diff --git a/changelog.d/ITL-1789.md b/changelog.d/ITL-1789.md index 7b64226c8..d327bb150 100644 --- a/changelog.d/ITL-1789.md +++ b/changelog.d/ITL-1789.md @@ -18,7 +18,8 @@ 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`; the asynchronous path reads the results that have arrived together, up to + `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 @@ -46,6 +47,8 @@ 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. + If a table has a schema record whose Vortex encoding metadata disagrees with the + service, Orcapod raises `TableSchemaError`. ### Known limitations diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index e662b5fc6..4aeda1693 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1132,7 +1132,9 @@ as **references** to its entries, one per row: 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. + 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. @@ -1150,7 +1152,8 @@ import orcapod as op from orcapod import function_pod from orcapod.sources import SpiralDBTableSource -# "vector" and "embeddings" are encoded; "rate" is a plain column. +# "vector" and "embeddings" are encoded and this sample requires non-null cells. +# "rate" is a nullable plain column. items = SpiralDBTableSource("my-project-123456", "items") @@ -1158,9 +1161,14 @@ items = SpiralDBTableSource("my-project-123456", "items") def summarize( vector: op.SpiralDBEntry, embeddings: op.SpiralDBEntry, rate: float | None ) -> tuple[float, int]: - norm = vector.read().column("vector")[0].as_py()["block_0"]["norms"] - count = embeddings.read().column("embeddings")[0].as_py()["count"] - return norm * (rate or 1.0), count + 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") + norm = vector_value["block_0"]["norms"] + return norm * (1.0 if rate is None else rate), embedding_value["count"] summaries = summarize.pod(items.select_data_columns(["vector", "embeddings", "rate"])) @@ -1175,7 +1183,10 @@ the entry it names (its value, bit for bit, and its encoding's extension name an 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`. Hashing needs the content, so a job first reads the entries it is +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 @@ -1184,11 +1195,11 @@ 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 (up to 256 on the synchronous path under `continue`, one at a time under -`fail_fast`, so the first failure stops the run before a later row is computed; on the -asynchronous path the results that have arrived, at most 256, under either policy, so -under `fail_fast` the results computed beside a failing one are read with it before the -run stops). Such a row is reported as ended only +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 @@ -1215,7 +1226,9 @@ the run); so does a returned reference whose entry cannot be read. Any other err 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, after the rows before it are recorded. +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`, diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 9e67e4702..92f2170f1 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -117,7 +117,6 @@ database_write_path, keep_database_error, keep_run_error, - database_error_of, ) from orcapod.protocols.core_protocols import ( FunctionPodProtocol, @@ -3097,8 +3096,8 @@ def _execute_fetching_outputs( 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, so the first failure stops the run - before any later row is computed. A repeated input whose first occurrence is + 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. @@ -3107,6 +3106,7 @@ def _execute_fetching_outputs( 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. @@ -3203,6 +3203,7 @@ def finish() -> None: 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: @@ -3212,22 +3213,26 @@ def finish() -> None: except SpiralDBEntryMissingError as exc: # Not reused: a repeat of this input fails with it. missing[row.instance_id] = exc - crash(row.tag, row.data, exc) - failed += 1 - continue + row_error = exc except Exception as exc: stop(row.tag, row.data, exc, rows[index + 1 :]) raise - self._cache_output_data( - row.instance_id, row.tag_out, row.result + else: + self._cache_output_data( + row.instance_id, row.tag_out, row.result + ) + try: + 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 ) - elif row.instance_id in missing: - crash(row.tag, row.data, missing[row.instance_id]) - failed += 1 - continue - ctx_obs.on_data_end( - node_label, row.tag, row.data, row.result, cached=row.cached - ) + except Exception as exc: + # The current row was already reported to the observer. + abort(rows[index + 1 :], exc) + raise emitted_entry_ids.append(row.instance_id) if row.result is not None: output.append((row.tag_out, row.result)) @@ -3263,7 +3268,7 @@ def finish() -> None: held.append( _HeldRow(tag, data, instance_id, tag_out, result, None, True) ) - if error_policy == "fail_fast" or len(held) >= _PREFETCH_ROWS: + if finish_each_row or len(held) >= _PREFETCH_ROWS: finish() continue pkt_logger = ctx_obs.create_data_logger(tag, data) @@ -3298,7 +3303,7 @@ def finish() -> None: held.append(row) if record is not None: pending_results[instance_id] = row - if error_policy == "fail_fast" or len(held) >= _PREFETCH_ROWS: + if finish_each_row or len(held) >= _PREFETCH_ROWS: finish() finish() finally: @@ -5746,13 +5751,10 @@ def create_data_logger(self, tag: Any, data: Any) -> Any: ) 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/sources/spiraldb_entries.py b/src/orcapod/core/sources/spiraldb_entries.py index 7555c8c77..b567c3e45 100644 --- a/src/orcapod/core/sources/spiraldb_entries.py +++ b/src/orcapod/core/sources/spiraldb_entries.py @@ -46,6 +46,10 @@ scan_one_key, sign_in_scope, ) +from orcapod.databases.spiraldb_schema_table import ( + VORTEX_EXTENSION_PREFIX, + vortex_encodings, +) from orcapod.errors import SpiralDBEntryMissingError from orcapod.logical_types.spiraldb_entry_type import ( SPIRALDB_ENTRY_STORAGE, @@ -55,28 +59,11 @@ ) from orcapod.types import ContentHash -ENCODING_PREFIX = "vortex." -"""The extension names of the encodings presented as references: Vortex's own.""" - _EXTENSION_NAME_KEY = b"ARROW:extension:name" _FRACTION_DIGITS = {"s": 0, "ms": 3, "us": 6, "ns": 9} -def _encodings(field: pa.Field[Any]) -> Iterator[str]: - """Yield the Vortex encoding names on ``field`` and on its children, at any depth.""" - name = (field.metadata or {}).get(_EXTENSION_NAME_KEY) - if name is not None: - text = name.decode("utf-8", errors="backslashreplace") - if text.startswith(ENCODING_PREFIX): - yield text - arrow_type = field.type - if isinstance(arrow_type, pa.DictionaryType): - yield from _encodings(pa.field(field.name, arrow_type.value_type)) - for index in range(arrow_type.num_fields): - yield from _encodings(arrow_type.field(index)) - - def encoded_columns(schema: pa.Schema) -> dict[str, tuple[str, ...]]: """Return the top-level columns that hold a Vortex encoding, with their encodings. @@ -92,7 +79,12 @@ def encoded_columns(schema: pa.Schema) -> dict[str, tuple[str, ...]]: """ found: dict[str, tuple[str, ...]] = {} for field in schema: - names = sorted(set(_encodings(field))) + names = sorted( + { + name.decode("utf-8", errors="backslashreplace") + for _, name, _ in vortex_encodings(field) + } + ) if names: found[field.name] = tuple(names) return found @@ -103,9 +95,7 @@ def _without_encodings(field: pa.Field[Any]) -> pa.Field[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.decode("utf-8", errors="replace").startswith( - ENCODING_PREFIX - ): + 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): diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 1c6c24c85..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 @@ -1579,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/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index 930f10664..5fe197d4d 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -33,6 +33,7 @@ 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, @@ -154,6 +155,54 @@ def _source(name: str = "encoded", **kwargs: Any) -> SpiralDBTableSource: 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_schema_table import ( + FROM_SERVICE, + SchemaRow, + SchemaTable, + ) + from orcapod.errors import TableSchemaError + + external = fake_spiral_sdk.ExternalProject(_PROJECT).table("default.encoded") + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + table = fake_spiral_sdk.FakeClient().keyed_table_by_id(external.table_id) + reported = table.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( + str(table.resource_id), + "encoded", + tuple(table.key_columns), + recorded.serialize().to_pybytes(), + FROM_SERVICE, + int(str(table.version_id)), + ) + + 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 pytest.raises(TableSchemaError, match=rf"Vortex encoding metadata.*{column}"): + _source() + + def _table(source: SpiralDBTableSource, **kwargs: Any) -> pa.Table: """Return ``source.as_table`` with warnings silenced.""" with warnings.catch_warnings(): @@ -1462,6 +1511,7 @@ def __init__(self, **kwargs: Any) -> None: 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"]) @@ -1852,12 +1902,23 @@ def unbatched(entries: Any) -> Any: ) -def _documented_sample() -> str: - """The SpiralDB reference sample of ``docs/concepts/sources.md``.""" +def _source_guide() -> str: + """Read the published source guide from the checkout.""" page = Path(__file__).parents[3] / "docs" / "concepts" / "sources.md" - blocks = page.read_text().split("```python\n")[1:] + 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) - return sample + 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("orchestrator", ["sync", "async"]) @@ -1870,17 +1931,18 @@ def test_the_documented_sample_runs( from orcapod import PipelineJob from orcapod.databases import DeltaTableDatabase - sample = _documented_sample() - assert 'SpiralDBTableSource("my-project-123456", "items")' in sample - namespace: dict[str, Any] = {} + _rewrite_column([True, True, True], "rate", pa.array([0.0, None, 2.5])) with warnings.catch_warnings(): warnings.simplefilter("ignore") - exec( # noqa: S102 # the documentation's own sample, against the fake - sample.replace('"my-project-123456", "items"', f'"{_PROJECT}", "encoded"'), - namespace, - ) + namespace = _run_documented_sample() table = namespace["summaries"].as_table() - assert sorted(table.column("count").to_pylist()) == [10, 20, 30] + 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: @@ -1902,7 +1964,7 @@ def test_the_documented_sample_runs( 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, 1.5, 2.5])) + _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 @@ -1924,7 +1986,66 @@ def test_the_documented_sample_runs( result.column("first_norm").to_pylist(), strict=True, ) - ) == {10: 1.5, 20: 3.375, 30: 0.3125} + ) == {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() + ) # -------------------------------------------------------------------------------------- @@ -2687,7 +2808,7 @@ def on_data_crash(self, node: str, tag: Any, data: Any, exc: Any) -> None: def on_node_end(self, node: str, *args: Any, **kwargs: Any) -> None: super().on_node_end(node, *args, **kwargs) - if node == "size" and orchestrator == "sync": + if node == "size": raise RuntimeError("synthetic node-end observer failure") job = PipelineJob( @@ -2705,8 +2826,7 @@ def on_node_end(self, node: str, *args: Any, **kwargs: Any) -> None: 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) - if orchestrator == "sync": - assert any("synthetic node-end 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") @@ -2969,6 +3089,167 @@ def broken(*args: Any, **kwargs: Any) -> Any: 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) + job = PipelineJob(name="arrival", database=DeltaTableDatabase(tmp_path / "db")) + 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"]} + 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], @@ -3043,6 +3324,14 @@ def size(vector: SpiralDBEntry) -> int: 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: @@ -3065,6 +3354,7 @@ def iter_data(self) -> Any: 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) 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 From 722387d3cd19c878bc88dc25c5d4ee56cffd225f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 14:44:19 -0800 Subject: [PATCH 26/28] fix(spiraldb): address encoded source review findings --- changelog.d/ITL-1789.md | 5 +- docs/concepts/sources.md | 14 +- src/orcapod/core/nodes/function_node.py | 7 +- src/orcapod/core/sources/spiraldb_entries.py | 13 +- .../test_spiraldb_table_source_encoded.py | 137 +++++++++++++++++- 5 files changed, 159 insertions(+), 17 deletions(-) diff --git a/changelog.d/ITL-1789.md b/changelog.d/ITL-1789.md index d327bb150..9ad749f69 100644 --- a/changelog.d/ITL-1789.md +++ b/changelog.d/ITL-1789.md @@ -47,8 +47,9 @@ 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. - If a table has a schema record whose Vortex encoding metadata disagrees with the - service, Orcapod raises `TableSchemaError`. + 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. ### Known limitations diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 4aeda1693..e977f25ac 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1152,7 +1152,7 @@ import orcapod as op from orcapod import function_pod from orcapod.sources import SpiralDBTableSource -# "vector" and "embeddings" are encoded and this sample requires non-null cells. +# 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") @@ -1167,8 +1167,16 @@ def summarize( raise ValueError("vector must be non-null") if embedding_value is None: raise ValueError("embeddings must be non-null") - norm = vector_value["block_0"]["norms"] - return norm * (1.0 if rate is None else rate), embedding_value["count"] + 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"])) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 92f2170f1..80f7c3695 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3250,8 +3250,7 @@ def finish() -> None: ctx_obs.on_data_start(node_label, tag, data) if isinstance(instance_id, SpiralDBEntryMissingError): # No input hash: a failed row (see ``execute``). - if error_policy == "fail_fast": - finish() + finish() crash(tag, data, instance_id) failed += 1 continue @@ -3293,8 +3292,8 @@ def finish() -> None: stop(tag, data, exc) raise except Exception as exc: - if error_policy == "fail_fast": - finish() + # An observer can raise while reporting the failed row. + finish() crash(tag, data, exc) failed += 1 continue diff --git a/src/orcapod/core/sources/spiraldb_entries.py b/src/orcapod/core/sources/spiraldb_entries.py index b567c3e45..8fab4cd68 100644 --- a/src/orcapod/core/sources/spiraldb_entries.py +++ b/src/orcapod/core/sources/spiraldb_entries.py @@ -50,7 +50,7 @@ VORTEX_EXTENSION_PREFIX, vortex_encodings, ) -from orcapod.errors import SpiralDBEntryMissingError +from orcapod.errors import SpiralDBEntryMissingError, TableSchemaError from orcapod.logical_types.spiraldb_entry_type import ( SPIRALDB_ENTRY_STORAGE, LogicalSpiralDBEntry, @@ -128,11 +128,20 @@ def require_only_encodings(schema: pa.Schema, columns: Sequence[str]) -> None: 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(schema.field(c)) for c in columns]) + pa.schema([_without_encodings(field) for field in fields]) ) diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index 5fe197d4d..2fd52f705 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -161,6 +161,7 @@ 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, @@ -168,11 +169,11 @@ def test_a_schema_record_cannot_hide_or_change_an_encoding( ) from orcapod.errors import TableSchemaError - external = fake_spiral_sdk.ExternalProject(_PROJECT).table("default.encoded") with warnings.catch_warnings(): warnings.simplefilter("ignore") - table = fake_spiral_sdk.FakeClient().keyed_table_by_id(external.table_id) - reported = table.schema() + 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} @@ -187,20 +188,47 @@ def test_a_schema_record_cannot_hide_or_change_an_encoding( changed = field.with_type(pa.struct([changed, field.type.field("count")])) recorded = reported.set(reported.get_field_index(column), changed) row = SchemaRow( - str(table.resource_id), + table.table_id, "encoded", tuple(table.key_columns), recorded.serialize().to_pybytes(), FROM_SERVICE, - int(str(table.version_id)), + 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: @@ -1921,6 +1949,33 @@ def _run_documented_sample() -> dict[str, Any]: 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 @@ -2786,6 +2841,66 @@ def ends_last(self, node: str) -> bool: return self.node_ends.count(node) == 1 and at[-1] == f"node_end {node} -" +@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 @@ -3225,7 +3340,8 @@ def fail_embeddings(table: Any, columns: Any, keys: Any) -> Any: 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) - job = PipelineJob(name="arrival", database=DeltaTableDatabase(tmp_path / "db")) + 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) @@ -3238,6 +3354,15 @@ def fail_embeddings(table: Any, columns: Any, keys: Any) -> Any: ) 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) From f606a239acb37fc2826f1ee7b29f927270b90de9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 16:43:27 -0800 Subject: [PATCH 27/28] fix(pipeline): report failed rows when finishing a batch aborts --- src/orcapod/core/nodes/function_node.py | 44 +++++++---- .../test_spiraldb_table_source_encoded.py | 76 +++++++++++++++++++ 2 files changed, 107 insertions(+), 13 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 80f7c3695..3c268b2d5 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3114,6 +3114,7 @@ def _execute_fetching_outputs( # 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 def end_node(run_error: Exception) -> None: """Report the failed node's end once, preserving its error.""" @@ -3167,23 +3168,27 @@ def run_error_for(exc: Exception) -> Exception: 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 fatal row (if one waits) with its own error, then + 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 + 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) - if fatal is not None: - fatal_tag, fatal_data, fatal_exc = fatal + waiting = fatal if fatal is not None else waiting_failure + if waiting is not None: + failed_tag, failed_data, failed_exc = waiting fatal = None - if isinstance(fatal_exc, OrcapodDatabaseError): - fatal_exc.add_context( - node_label=node_label, tag=fatal_tag.as_dict() + waiting_failure = None + if isinstance(failed_exc, OrcapodDatabaseError): + 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, fatal_tag, fatal_data, fatal_exc) + ctx_obs.on_data_crash( + node_label, failed_tag, failed_data, failed_exc + ) end_node(run_error) def finish() -> None: @@ -3244,14 +3249,29 @@ def finish() -> None: abort(rows[index + 1 :], exc) raise + 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() + except Exception as finish_error: + if not node_ended: + abort((), finish_error) + raise + 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) if isinstance(instance_id, SpiralDBEntryMissingError): # No input hash: a failed row (see ``execute``). - finish() - crash(tag, data, instance_id) + finish_before_crash(tag, data, instance_id) failed += 1 continue pending_result = pending_results.get(instance_id) @@ -3292,9 +3312,7 @@ def finish() -> None: stop(tag, data, exc) raise except Exception as exc: - # An observer can raise while reporting the failed row. - finish() - crash(tag, data, exc) + finish_before_crash(tag, data, exc) failed += 1 continue record = before if len(self._deferred_records) > before else None diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index 2fd52f705..a4cea20ca 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -2841,6 +2841,82 @@ def ends_last(self, node: str) -> bool: 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 From 0b592d884c7178b461e6589749dfc6a20e25f53d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 17:43:58 -0800 Subject: [PATCH 28/28] fix(pipeline): finish held sync results after observer errors --- changelog.d/ITL-1789.md | 3 + src/orcapod/core/nodes/function_node.py | 121 +++++++------- .../test_spiraldb_table_source_encoded.py | 148 ++++++++++++++++++ 3 files changed, 216 insertions(+), 56 deletions(-) diff --git a/changelog.d/ITL-1789.md b/changelog.d/ITL-1789.md index 9ad749f69..89a4cf6a6 100644 --- a/changelog.d/ITL-1789.md +++ b/changelog.d/ITL-1789.md @@ -50,6 +50,9 @@ 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 diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 3c268b2d5..d1f2cc857 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3115,6 +3115,8 @@ def _execute_fetching_outputs( # 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.""" @@ -3141,30 +3143,12 @@ def crash(tag: TagProtocol, data: DataProtocol, exc: Exception) -> None: raise exc ctx_obs.on_data_crash(node_label, tag, data, exc) - def stop( - tag: TagProtocol, - data: DataProtocol, - exc: Exception, - aborted: Sequence[_HeldRow] = (), - ) -> None: - """Report a row whose database read or write failed, whose stored result - cannot be decoded, or whose result's hash raised another error than a - missing entry: the run stops whatever the policy. The ``aborted`` rows, - started and held behind it, are reported as crashed with the same error - before the node's end, so every started row has a terminal event.""" - if isinstance(exc, OrcapodDatabaseError): - exc.add_context(node_label=node_label, tag=tag.as_dict()) - # Each report is isolated, as in the async cleanup: an observer that - # raises is noted on the error the run raises, and the remaining reports - # and the node's end still run. - with keep_run_error(run_error_for(exc), "Observer on_data_crash"): - ctx_obs.on_data_crash(node_label, tag, data, exc) - abort(aborted, 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``.""" - return fatal[2] if fatal is not None 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 @@ -3182,9 +3166,10 @@ def abort(aborted: Sequence[_HeldRow], exc: Exception) -> None: fatal = None waiting_failure = None if isinstance(failed_exc, OrcapodDatabaseError): - failed_exc.add_context( - node_label=node_label, tag=failed_tag.as_dict() - ) + 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 @@ -3202,11 +3187,16 @@ def finish() -> None: pending_results.clear() # The instances whose held result names a missing entry, with the error. missing: dict[bytes, SpiralDBEntryMissingError] = {} - with prefetched_rows( - [record.output_data for record in pending], - self.data_context.type_converter, - self.data_context.semantic_hasher, - ): + 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: @@ -3216,38 +3206,43 @@ def finish() -> None: output_data_hash=deferred.output_data.content_hash() ) except SpiralDBEntryMissingError as exc: - # Not reused: a repeat of this input fails with it. + # A repeat of this input fails with the same error. missing[row.instance_id] = exc row_error = exc - except Exception as exc: - stop(row.tag, row.data, exc, rows[index + 1 :]) + 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 ) - try: - 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 - ) - except Exception as exc: - # The current row was already reported to the observer. - abort(rows[index + 1 :], exc) - raise + # 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: - try: - self._row_processed() - except OrcapodDatabaseError as exc: - # As ``_commit_or_end_node``, after the rows held behind it. - abort(rows[index + 1 :], exc) - raise + 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 @@ -3257,10 +3252,6 @@ def finish_before_crash( waiting_failure = (tag, data, exc) try: finish() - except Exception as finish_error: - if not node_ended: - abort((), finish_error) - raise finally: waiting_failure = None crash(tag, data, exc) @@ -3269,8 +3260,10 @@ def finish_before_crash( 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 @@ -3287,6 +3280,7 @@ def finish_before_crash( 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 @@ -3304,25 +3298,40 @@ def finish_before_crash( # 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: - fatal = None - stop(tag, data, exc) + 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 diff --git a/tests/test_core/sources/test_spiraldb_table_source_encoded.py b/tests/test_core/sources/test_spiraldb_table_source_encoded.py index a4cea20ca..239a7e77c 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_encoded.py +++ b/tests/test_core/sources/test_spiraldb_table_source_encoded.py @@ -3280,6 +3280,154 @@ def broken(*args: Any, **kwargs: Any) -> Any: 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