diff --git a/changelog.d/ITL-1871.md b/changelog.d/ITL-1871.md new file mode 100644 index 000000000..67e807a45 --- /dev/null +++ b/changelog.d/ITL-1871.md @@ -0,0 +1,7 @@ +### Fixed + +- Connector-backed jobs reject table paths that exceed the configured depth during database attachment, with the node, path, and limit in the error. +- Every run checks, before it takes a writer lease or writes anything, the table paths of each cached source's cache on a connector database (SQLite, PostgreSQL or SpiralDB) and of the result databases of function pods built outside the job; the error names the cached source or stream. A function pod's own `result_database` or `pod_cache_database` is checked when the job attaches its databases, and again by every full run, so a function job node built on its own is refused, naming the node, before its function is called. +- A polling source that declares its Arrow schema gives its declared zero-row table before its first poll, so a caching operator over it refuses an unsupported column when its cache is attached, without polling. +- Writable SpiralDB jobs reject known unsupported column types, including duration and fixed-size binary, before writing rows. Reads reject decimal values outside their declared precision at every supported width, including inside nested columns. +- A job checks storage paths and schemas against proposed source bindings before changing its bindings or node attachments. Identity hashes computed during the check stay in temporary caches. A refused bind can be retried with the same databases after correcting the source. diff --git a/docs/dev/design_issues/ITL-1162-CA3.md b/docs/dev/design_issues/ITL-1162-CA3.md index 73e1c1ee6..fcbdbca28 100644 --- a/docs/dev/design_issues/ITL-1162-CA3.md +++ b/docs/dev/design_issues/ITL-1162-CA3.md @@ -35,6 +35,14 @@ ruling, November 16, 2026). `PostgreSQLConnector` also states which table names (`UnstorableTableNameError`). The connectors' silent TEXT fallback in `CREATE TABLE` now raises. +When the pipeline or result database changes and a pipeline database is available, +`PipelineJob.bind()` checks storage paths and schemas on the candidate databases using +the proposed source bindings. The check uses temporary identity and schema memos. +A storage refusal preserves the original bindings and attachments. A source-only bind +can succeed without validating that the replacement can be stored (ITL-1871). Run +preflight checks the depth of an automatic source cache path even when the source has +yet to poll and its column types are unknown. + **Open (the real fix, a later release):** store list and struct columns (for example as JSON text read back as the same Arrow type) and timestamps on SQLite, and rename SpiralDB's reserved column names on write and recover them on read, and restore a timestamp's time diff --git a/src/orcapod/contexts/stored.py b/src/orcapod/contexts/stored.py index 3369233a3..cf8cd1531 100644 --- a/src/orcapod/contexts/stored.py +++ b/src/orcapod/contexts/stored.py @@ -30,7 +30,7 @@ import logging import warnings -from collections.abc import Collection +from collections.abc import Callable, Collection from dataclasses import dataclass, field from typing import Any, NamedTuple, Protocol, cast @@ -611,3 +611,37 @@ def require_storable(database: object, schema: pa.Schema) -> None: check = getattr(database, "require_storable", None) if callable(check): _ = check(schema) + + +def require_storable_record_path( + database: object, record_path: Callable[[], tuple[str, ...]] +) -> None: + """Check a table path on a database that declares a path limit. + + A database states its limit with ``require_storable_path`` (a connector database, + whatever its backend); any other database accepts every path. ``record_path`` is + called only when the database declares a limit. + + Args: + database: The database the table would be written to. + record_path: Gives the table's path, relative to the database's base path. + + Raises: + ValueError: If the full path is deeper than the database's limit. + """ + check = getattr(database, "require_storable_path", None) + if callable(check): + _ = check(record_path()) + + +def require_storable_path( + database: object, record_path: Callable[[], tuple[str, ...]], *, node_label: str +) -> None: + """Check a node's table path on databases that declare a path limit. + + As ``require_storable_record_path``, with the refusal naming the node. + """ + try: + require_storable_record_path(database, record_path) + except ValueError as exc: + raise ValueError(f"Node {node_label!r}: {exc}") from exc diff --git a/src/orcapod/core/base.py b/src/orcapod/core/base.py index 1ca4a6955..218716c1d 100644 --- a/src/orcapod/core/base.py +++ b/src/orcapod/core/base.py @@ -14,9 +14,13 @@ logger = logging.getLogger(__name__) -_live_content_hashes: ContextVar[ - dict[int, tuple[object, dict[str, ContentHash]]] | None -] = ContextVar("live_content_hashes", default=None) +_HashMemo = dict[int, tuple[object, dict[str, ContentHash]]] +_live_content_hashes: ContextVar[_HashMemo | None] = ContextVar( + "live_content_hashes", default=None +) +_isolated_pipeline_hashes: ContextVar[_HashMemo | None] = ContextVar( + "isolated_pipeline_hashes", default=None +) _pipeline_hash_probe: ContextVar[object] = ContextVar( "pipeline_hash_probe", default=None ) @@ -33,6 +37,9 @@ def __init__(self, element: PipelineElementBase) -> None: @contextmanager def live_content_hashes() -> Iterator[None]: """Compute content hashes in a temporary cache for a live binding read.""" + if isolating_identity_hashes(): + yield + return token = _live_content_hashes.set({}) try: yield @@ -40,6 +47,23 @@ def live_content_hashes() -> Iterator[None]: _live_content_hashes.reset(token) +@contextmanager +def isolated_identity_hashes() -> Iterator[None]: + """Keep all legacy hash memo entries local to a candidate binding check.""" + content = _live_content_hashes.set({}) + pipeline = _isolated_pipeline_hashes.set({}) + try: + yield + finally: + _isolated_pipeline_hashes.reset(pipeline) + _live_content_hashes.reset(content) + + +def isolating_identity_hashes() -> bool: + """Whether a candidate binding check is using isolated legacy hash memos.""" + return _isolated_pipeline_hashes.get() is not None + + # Base classes for Orcapod core components, providing common functionality. @@ -212,7 +236,10 @@ def content_hash(self, hasher=None) -> ContentHash: cache_key = hasher.hasher_id cache = self._content_hash_cache live_cache = _live_content_hashes.get() - if live_cache is not None and self._content_hash_depends_on_bindings: + if live_cache is not None and ( + self._content_hash_depends_on_bindings + or (isolating_identity_hashes() and cache_key not in cache) + ): # Keep each object alive for the read so its id stays unique. cache = live_cache.setdefault(id(self), (self, {}))[1] @@ -322,7 +349,15 @@ def pipeline_hash(self, hasher=None) -> ContentHash: if hasher is None: hasher = self.data_context.semantic_hasher cache_key = hasher.hasher_id - cached = self._pipeline_hash_cache.get(cache_key) + scoped = _isolated_pipeline_hashes.get() + + def cache_for(element: PipelineElementBase) -> dict[str, ContentHash]: + if scoped is not None: + return scoped.setdefault(id(element), (element, {}))[1] + return element._pipeline_hash_cache + + cache = cache_for(self) + cached = cache.get(cache_key) if cached is not None: return cached if _pipeline_hash_probe.get() is hasher: @@ -355,10 +390,10 @@ def pipeline_resolver(obj: Any) -> ContentHash: pending.append((upstream, upstream.pipeline_identity_structure())) active.add(identity) else: - element._pipeline_hash_cache[cache_key] = digest + cache_for(element)[cache_key] = digest active.remove(id(element)) pending.pop() - return self._pipeline_hash_cache[cache_key] + return cache[cache_key] def _invalidate_pipeline_hash_cache(self) -> None: """Invalidate the cached pipeline hash. diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 74f9ac24a..bed3f05ec 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -26,6 +26,7 @@ StaleTables, data_context_field, require_storable, + require_storable_record_path, ) from orcapod.core.result_cache import ( ResultCache, @@ -95,6 +96,9 @@ def __init__( def require_storable_results(self) -> None: """Refuse a result database that cannot store this pod's result table (ITL-1162). + Each result database the pod writes (its own, its function's + ``function_pod(result_database=)``, a wrapped pod's ``pod_cache_database``) + is checked for the depth of the table's path (ITL-1871) and for its columns. The result table holds the input data hash, the function's variation and execution columns (``__pf_var_*``, ``__pf_exec_*``), its output columns, the ``__pod_ts`` timestamp and ``__data_context``, typed from their declared @@ -103,11 +107,18 @@ def require_storable_results(self) -> None: refuses here, before the function runs; any other database accepts. Raises: + ValueError: If a result table's path is deeper than its database allows. UnstorableColumnError: If the result database cannot store a column. """ import pyarrow as pa pf = self._function_pod.data_function + require_storable_record_path( + self._cache.result_database, lambda: self.record_path + ) + if isinstance(pf, CachedDataFunction): + require_storable_record_path(pf.result_database, lambda: pf.record_path) + python_schema = { **{ f"{constants.PF_VARIATION_PREFIX}{name}": hint diff --git a/src/orcapod/core/identity_chains.py b/src/orcapod/core/identity_chains.py index a4de22b00..c3a7310f4 100644 --- a/src/orcapod/core/identity_chains.py +++ b/src/orcapod/core/identity_chains.py @@ -38,6 +38,19 @@ NODE_HASH_LABEL = "node_hash_v1" _reading_chains: ContextVar[bool] = ContextVar("reading_identity_chains", default=False) +_scoped_chains: ContextVar[dict[tuple[int, str, bool, bool], IdentityChains] | None] = ( + ContextVar("scoped_identity_chains", default=None) +) + + +@contextmanager +def isolated_identity_chains() -> Iterator[None]: + """Compute candidate identities without reading or changing the live chain cache.""" + token = _scoped_chains.set({}) + try: + yield + finally: + _scoped_chains.reset(token) @contextmanager @@ -142,6 +155,8 @@ def __init__( def depend_on(self, element: IdentityChainsMixin) -> None: """Record a dependency for the node whose chains are being evaluated.""" + if _scoped_chains.get() is not None: + return consumer = self._consumer if consumer is not None and consumer is not element: element._identity_dependents[id(consumer)] = consumer @@ -422,6 +437,8 @@ def _identity_hash( preimage: tuple[object, ...] | None = None, ) -> ContentHash: """Reuse hashes across chain reads and unchanged name inputs.""" + if _scoped_chains.get() is not None: + return _hash(label, key_parts if preimage is None else preimage) if label in (SOURCE_CHAIN_HASH_LABEL, CONTENT_HASH_LABEL): if self._identity_source_hashes is None: self._identity_source_hashes = {} @@ -491,10 +508,17 @@ def _identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains: A full memo can satisfy a name-only walk. A name-only memo cannot satisfy a walk that includes sources. """ - if self._identity_cache is None: - self._identity_cache = {} hasher_id = walk.hasher.hasher_id guarded = reading_identity_chains() + scoped = _scoped_chains.get() + if scoped is not None: + scoped_key = (id(self), hasher_id, walk.include_sources, guarded) + if scoped_key not in scoped: + scoped[scoped_key] = self._compute_identity_chains(walk) + return scoped[scoped_key] + + if self._identity_cache is None: + self._identity_cache = {} full_key = (hasher_id, True, guarded) if not walk.include_sources and full_key in self._identity_cache: return self._identity_cache[full_key] diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 33bb2ef69..731743bca 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -33,6 +33,7 @@ import pyarrow as pa from orcapod import contexts +from orcapod.core.base import isolating_identity_hashes from orcapod.core.result_cache import read_stored_result_table from orcapod.core.output_bindings import ( OutputBindings, @@ -64,7 +65,9 @@ ZERO_ROW_INPUT_COLUMNS, StreamBase, check_head_size, + schema_requires_io, short_stream_repr, + typed_arrow_schemas, ) from orcapod.core.streams.view import ( BLUEPRINT_NOTE, @@ -104,6 +107,7 @@ report_rows_of_other_data_contexts, report_unexpected_row_count, require_storable, + require_storable_path, ) from orcapod.utils.database_errors import ( commit_best_effort, @@ -716,14 +720,16 @@ def node_identity_path(self) -> tuple[str, ...]: f"instance:{self.content_hash().to_hex()}", ) return self._stored_pipeline_path - if self._node_identity_path_cache is not None: + isolated = isolating_identity_hashes() + if not isolated and self._node_identity_path_cache is not None: return self._node_identity_path_cache pf = self._function_pod # Hashes inside a path are bare hex digests: a label never enters a name. path = pf.uri + (f"schema:{self.pipeline_hash().to_hex()}",) if self._table_scope != "pipeline_hash": return path + (f"instance:{self.content_hash().to_hex()}",) - self._node_identity_path_cache = path + if not isolated: + self._node_identity_path_cache = path return path @property @@ -1001,6 +1007,9 @@ def require_storable_results(self, result_database: ArrowDatabaseProtocol) -> No persistent result database or an ephemeral one). Raises: + ValueError: If a result table's path (in ``result_database`` or a + function's own result database) is deeper than its database allows, + naming this node. UnstorableColumnError: If the database cannot store a column, naming this node. """ @@ -1013,6 +1022,9 @@ def require_storable_results(self, result_database: ArrowDatabaseProtocol) -> No except UnstorableColumnError as exc: exc.add_context(node_label=self.label) raise + except ValueError as exc: + # A result table's path deeper than its database allows (ITL-1871). + raise ValueError(f"Node {self.label!r}: {exc}") from exc @abstractmethod def set_ephemeral_database(self, database: "ArrowDatabaseProtocol | None") -> None: @@ -1740,6 +1752,11 @@ def require_storable_tables( """ if self._function_pod is None: return + require_storable_path( + pipeline_database, + lambda: self._versioned_pipeline_path, + node_label=self.label, + ) # A table must state its data-tags (ITL-1019): a database that cannot # is refused first, with the two ways out, as ``attach_databases`` refuses it. require_database_keeps_marker( @@ -1748,8 +1765,15 @@ def require_storable_tables( if result_database is None: result_database = pipeline_database.at("_result") self.require_storable_results(result_database) + from orcapod.databases.spiraldb_write_scope import writable_connectors + try: require_storable(pipeline_database, _pipeline_meta_schema()) + if writable_connectors((pipeline_database,)) and not schema_requires_io( + self._input_stream, ColumnConfig() + ): + tags, _ = typed_arrow_schemas(self._input_stream) + require_storable(pipeline_database, tags) except UnstorableColumnError as exc: exc.add_context(node_label=self.label) raise @@ -1796,6 +1820,16 @@ def attach_databases( self.require_storable_tables(pipeline_database, result_database) if ephemeral_database is not None: self.require_storable_results(ephemeral_database) + self._attach_databases(pipeline_database, result_database) + if ephemeral_database is not None: + self.set_ephemeral_database(ephemeral_database) + + def _attach_databases( + self, + pipeline_database: ArrowDatabaseProtocol | None, + result_database: ArrowDatabaseProtocol | None, + ) -> None: + """Install the validated pipeline and result databases.""" # Another database has its own tables of other generations to account for. self._stale_tables_checked = False self._current_tables_checked = False @@ -1812,11 +1846,6 @@ def attach_databases( result_database = pipeline_database.at("_result") if self._function_pod is not None: - # A table must state its data-tags: refuse a database that - # cannot, before anything is written (ITL-1019). - require_database_keeps_marker( - pipeline_database, fall_through_tags(self._function_pod) - ) # Normal path: wrap in CachedFunctionPod for compute + cache. # A fall-through pod's results are its plain pod's (ITL-1023). self._cached_function_pod = CachedFunctionPod( @@ -1845,9 +1874,6 @@ def attach_databases( self._invalidate_content_hash_cache() self._invalidate_pipeline_hash_cache() - if ephemeral_database is not None: - self.set_ephemeral_database(ephemeral_database) - # ------------------------------------------------------------------ # from_descriptor — read-only stub for loaded jobs # ------------------------------------------------------------------ diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 2e181370b..7f3de3ace 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -29,6 +29,7 @@ import pyarrow.compute as pc from orcapod import contexts +from orcapod.core.base import isolating_identity_hashes from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.core.data_tags import ( mark_data_tags, @@ -87,6 +88,7 @@ data_context_field, find_stale_tables, require_storable, + require_storable_path, keep_rows_of_data_context, require_same_data_context, describe_database_table, @@ -596,13 +598,15 @@ def node_identity_path(self) -> tuple[str, ...]: """ if self._operator is None: return self._stored_pipeline_path - if self._node_identity_path_cache is not None: + isolated = isolating_identity_hashes() + if not isolated and self._node_identity_path_cache is not None: return self._node_identity_path_cache # Hashes inside a path are bare hex digests: a label never enters a name. path = self.node_uri + (f"schema:{self.pipeline_hash().to_hex()}",) if self._table_scope != "pipeline_hash": return path + (f"instance:{self.content_hash().to_hex()}",) - self._node_identity_path_cache = path + if not isolated: + self._node_identity_path_cache = path return path @property @@ -1058,8 +1062,8 @@ def require_storable_tables( With caching on, checks the cache's own columns (``__node_content_hash``, ``__data_context``, and the entry id and insertion time every row is stored - with, ``_stored_only_fields``); the operator's output columns are checked - when they are written. Nothing is computed and nothing changes. + with, ``_stored_only_fields``). For writable SpiralDB, it also checks the + output columns whose Arrow types are known without reading rows. Args: pipeline_database: The database for the cache. @@ -1071,6 +1075,12 @@ def require_storable_tables( """ if cache_mode == CacheMode.OFF: return + require_database_keeps_marker(pipeline_database, stream_data_tags(self)) + require_storable_path( + pipeline_database, lambda: self._stored_table_path, node_label=self.label + ) + from orcapod.databases.spiraldb_write_scope import writable_connectors + try: require_storable( pipeline_database, @@ -1082,6 +1092,10 @@ def require_storable_tables( ] ), ) + if writable_connectors((pipeline_database,)): + output = self._typed_zero_row_table() + if output is not None: + require_storable(pipeline_database, output.schema) except UnstorableColumnError as exc: exc.add_context(node_label=self.label) raise @@ -1110,14 +1124,13 @@ def attach_databases( from orcapod.pipeline.restrictions import refuse_restricted_operator_cache refuse_restricted_operator_cache(self, cache_mode) - if cache_mode != CacheMode.OFF: - # A stored table states its data-tags; refuse a database that - # cannot, before anything runs or is written (ITL-1019). - require_database_keeps_marker(pipeline_database, stream_data_tags(self)) - - # A database that cannot store the cache refuses it now, before anything - # runs or changes (ITL-1162). self.require_storable_tables(pipeline_database, cache_mode) + self._attach_databases(pipeline_database, cache_mode) + + def _attach_databases( + self, pipeline_database: ArrowDatabaseProtocol, cache_mode: CacheMode + ) -> None: + """Install a database and cache mode that have passed attachment checks.""" self._skipped_rows_reported = False self._stale_tables_checked = False self._row_count_checked = False diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 559623394..d01e8223d 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -25,6 +25,7 @@ Sequence, ) from concurrent.futures import ThreadPoolExecutor +from contextvars import ContextVar from datetime import datetime from typing import TYPE_CHECKING, Any @@ -36,11 +37,16 @@ ) from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.config import OrcapodConfig -from orcapod.core.base import ContentIdentifiableBase, TraceableBase +from orcapod.core.base import ( + ContentIdentifiableBase, + TraceableBase, + isolated_identity_hashes, +) from orcapod.core.datagrams import Data, Tag from orcapod.core.identity_chains import ( IdentityChainsMixin, graph_hash, + isolated_identity_chains, track_binding_dependency, ) from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied @@ -49,6 +55,7 @@ from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, CompleteStreamFeed, + isolated_schema_predictions, keys_of_rows, reads_as_its_class, system_tags_as_rows_give, @@ -789,7 +796,12 @@ def _identity_leaf( """Use the declared slot name and follow the binding to a concrete source.""" if not walk.include_sources: return self.name, None - bound = self._bound_stream() + return self._binding_identity_leaf(walk, self._bound_stream()) + + def _binding_identity_leaf( + self, walk: IdentityWalkProtocol, bound: StreamProtocol | None + ) -> tuple[str, ContentHash | None]: + """Resolve the source identity of a slot with the given binding.""" if bound is None: return self.name, None if isinstance(bound, RootSource): @@ -803,13 +815,17 @@ def _bound_stream(self) -> "StreamProtocol | None": """The concrete stream bound to this slot; a declaration has none.""" return None + def _schema_binding(self) -> _SourceBinding: + """Return the binding used for schema and Python identity reads.""" + return self._bound_stream(), None + def content_hash(self, hasher=None) -> ContentHash: """Return the identity of the declared schema with the slot's live binding.""" return IdentityChainsMixin.content_hash(self, hasher) def _object_hash(self) -> ContentHash: """Preserve the Python key identity shared by a bound slot and its stream.""" - bound = self._bound_stream() + bound, _ = self._schema_binding() if isinstance(bound, ContentIdentifiableBase): return bound._object_hash() return ContentIdentifiableBase.content_hash(self) @@ -1759,6 +1775,36 @@ def from_stream( _built_by_compile: bool = False +_SourceBinding = tuple["StreamProtocol | None", "_DeclaredForm | None"] +_prospective_bindings: ContextVar[Mapping[int, _SourceBinding] | None] = ContextVar( + "_prospective_bindings", default=None +) + + +@contextlib.contextmanager +def prospective_source_bindings( + bindings: Sequence[ + tuple[SourceJobNode, StreamProtocol | None, _DeclaredForm | None] + ], +) -> Iterator[None]: + """Expose validated candidate bindings to storage checks in the current context.""" + if not bindings: + yield + return + token = _prospective_bindings.set( + {id(slot): (source, form) for slot, source, form in bindings} + ) + try: + with ( + isolated_schema_predictions(), + isolated_identity_chains(), + isolated_identity_hashes(), + ): + yield + finally: + _prospective_bindings.reset(token) + + class SourceJobNode(ProvenanceMethods, SourceNodeBase): """Execution-ready source node wrapping an optional concrete stream. @@ -1966,6 +2012,13 @@ def _bound_stream(self) -> StreamProtocol | None: require_live_source_bindings((self,)) return self._bound_source + def _schema_binding(self) -> _SourceBinding: + """Use the candidate for schema checks during storage validation.""" + bindings = _prospective_bindings.get() + if bindings is not None and (binding := bindings.get(id(self))) is not None: + return binding + return self._bound_stream(), self._declared_form + def _bind(self, value: StreamProtocol | None) -> None: """Check and install a binding once its independence from slots is checked. @@ -2120,13 +2173,14 @@ def _declared_stream( def _identity_leaf( self, walk: IdentityWalkProtocol ) -> tuple[str, ContentHash | None]: - """Read the slot's polling digest when it matches the binding's hasher.""" + """Resolve the proposed or live source identity for this slot.""" + if not walk.include_sources: + return self.name, None + bindings = _prospective_bindings.get() + if bindings is not None and (binding := bindings.get(id(self))) is not None: + return self._binding_identity_leaf(walk, binding[0]) bound = self._bound_source - if ( - type(self) is SourceJobNode - and walk.include_sources - and isinstance(bound, RootSource) - ): + if type(self) is SourceJobNode and isinstance(bound, RootSource): cached = self._memoized_polling_content_hash( bound, bound.data_context.semantic_hasher ) @@ -2147,7 +2201,7 @@ def _memoized_polling_content_hash( def identity_structure(self) -> Any: """Use the bound source's equality preimage, or the declaration's if unbound.""" track_binding_dependency(self) - source = self._bound_stream() + source, _ = self._schema_binding() if source is not None: return source.identity_structure() return super().identity_structure() @@ -2430,13 +2484,13 @@ def _typed_zero_row_table(self) -> "pa.Table | None": table (ITL-1112, ITL-912). ``None`` when unbound or when the source cannot type its rows without rows. See ``typed_zero_row_table``. """ - source = self._bound_stream() + source, form = self._schema_binding() if source is None: return self._declared_zero_row_table() table = typed_zero_row_table(source) - if table is None or self._declared_form is None: + if table is None or form is None: return table - return self._declared_form.apply(table) + return form.apply(table) def _display_name(self) -> str: """The name a preview header shows: the bound source's assigned label, else the @@ -2450,7 +2504,7 @@ def _display_name(self) -> str: def _schema_requires_io(self, config: ColumnConfig) -> bool: """Whether reading the schema with ``config`` would poll: as for the bound source.""" - source = self._bound_stream() + source, _ = self._schema_binding() return source is not None and schema_requires_io(source, config) def head( @@ -2550,8 +2604,8 @@ def output_schema( Returns: Tuple of ``(tag_schema, data_schema)``. """ - source = self._bound_stream() - if source is None or self._declared_form is not None: + source, form = self._schema_binding() + if source is None or form is not None: # Unbound, or bound to a narrower source given as the declared schema. return super().output_schema(columns=columns, all_info=all_info) return source.output_schema(columns=columns, all_info=all_info) diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 773dd7807..10c6dd75a 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -49,6 +49,7 @@ from orcapod.contexts.stored import ( data_context_field, require_storable, + require_storable_record_path, keep_rows_of_data_context, require_same_data_context, account_for_stale_tables, @@ -427,6 +428,10 @@ def _compute_arrow_schemas(self) -> "tuple[pa.Schema, pa.Schema]": # Cache path — scoped to source's content hash # ------------------------------------------------------------------------- + def _automatic_unversioned_cache_path(self, node_component: str) -> tuple[str, ...]: + """Give the automatic path shape for a known or pending content hash.""" + return self._cache_path_prefix + ("source", node_component) + @property def _unversioned_cache_path(self) -> tuple[str, ...]: """The cache path without its layout component. @@ -435,9 +440,8 @@ def _unversioned_cache_path(self) -> tuple[str, ...]: """ if self._explicit_cache_path is not None: return self._explicit_cache_path - return self._cache_path_prefix + ( - "source", - f"node:{self._source.content_hash().to_hex()}", + return self._automatic_unversioned_cache_path( + f"node:{self._source.content_hash().to_hex()}" ) @property @@ -449,6 +453,53 @@ def cache_path(self) -> tuple[str, ...]: """ return self._unversioned_cache_path + (SOURCE_DB_SCHEMA_VERSION,) + def require_storable_cache(self) -> None: + """Refuse a cache database that cannot store this source's cache table. + + Called by a run before it takes a lease or writes anything + (``node_run.preflight_run_writes``). The cache table's path is checked on every + database that declares a path limit (a connector database, whatever its + backend; ITL-1871); a writable SpiralDB cache is also checked against the + source's Arrow types when they are known without reading rows. Nothing is read + or written. + + Raises: + ValueError: If the cache table's path is deeper than the database allows, + naming this source. + UnstorableColumnError: If the database cannot store a column, naming this + source. + """ + from orcapod.databases.spiraldb_write_scope import writable_connectors + + database = self._cache_database + # As every read of this source does first: a rebound wrapped source sets its + # earlier cache path aside. + _ = self._refresh_source_bindings() + schema_needs_io = schema_requires_io(self._source, ColumnConfig()) + if self._explicit_cache_path is None and schema_needs_io: + # An unpolled source may have to fetch rows to compute its hash. + # The hash is one path component regardless of its value. + path = self._automatic_unversioned_cache_path("node:") + ( + SOURCE_DB_SCHEMA_VERSION, + ) + else: + path = self._cache_path_unless_set_aside() + if path is None: + # The run serves the live rows and writes no cache table. + return + try: + require_storable_record_path(database, lambda: path) + except ValueError as exc: + raise ValueError(f"Cached source {self.label!r}: {exc}") from exc + if schema_needs_io or not writable_connectors((database,)): + return + try: + for schema in typed_arrow_schemas(self._source): + require_storable(database, schema) + except UnstorableColumnError as exc: + exc.add_context(node_label=self.label) + raise + def _account_for_stale_tables(self) -> None: """Report, once per source object, cache tables of another layout. @@ -911,10 +962,19 @@ def check_for_new_data(self) -> bool: self._update_modified_time() return True + def _cache_path_unless_set_aside(self) -> tuple[str, ...] | None: + """The cache path a read or write uses now, or ``None`` when an earlier binding + of the wrapped source owns it: the live rows are then used and no cache table + is read or written. Read by ``_cache_path_for_io`` and by the run's preflight + (``require_storable_cache``), so both decide alike. + """ + path = self.cache_path + return None if path in self._previous_cache_paths else path + def _cache_path_for_io(self) -> tuple[str, ...] | None: """Use live rows when a fixed path would mix two bindings in storage.""" - path = self.cache_path - if path in self._previous_cache_paths: + path = self._cache_path_unless_set_aside() + if path is None: return None if self._source_bindings: self._active_cache_path = path diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 9b2aefbd7..946797973 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -593,15 +593,28 @@ def _generated_record_id_column(self) -> str | None: return self._batches[0].generated_record_id_column if self._batches else None def _typed_zero_row_table(self) -> pa.Table | None: - """The zero-row table of the rows polled so far; ``None`` before a poll. + """The zero-row table of the rows polled so far, or, before the first poll, of + the declared schema; ``None`` before a poll with no schema declared. - See ``typed_zero_row_table``. Never polls. Before the first poll the source - knows only the Python schema ``impl.schema()`` declares, which cannot say an - Arrow type such as ``int8`` (a known limitation, ITL-912). + See ``typed_zero_row_table``. Never polls and reads no row. Before the first + poll a source that declared its schema (``impl.schema()``) builds the zero-row + table a poll would give, from its declared Arrow schema (ITL-1852): every + batch is built under that schema, so the types are the rows'. """ batches = list(self._batches) # snapshot, as in ``_get_combined_stream`` if not batches: - return None + if self._declared_arrow is None: + return None + declared = self._declared_arrow + built = SourceStreamBuilder(self.data_context).build( + declared.empty_table(), + tag_columns=self._tag_columns, + source_name=self._source_name, + kind_part=self.kind_part(), + record_id_columns=self._record_id_columns, + input_schema=declared, + ) + return typed_zero_row_table(built.stream) # Each batch with no rows, combined as the batches themselves are (the same # schema check and promotion), so the cost does not grow with the rows polled. result: ArrowTableStream | None = None diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 5ceafe7b2..bd75f2db1 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -169,6 +169,22 @@ def short_stream_repr(stream: object) -> str: ) """The zero-row tables derived during one outermost ``typed_zero_row_table`` call.""" +_SCOPED_OUTPUT_SCHEMAS: ContextVar[ + dict[int, tuple[object, dict[ColumnConfig, tuple[Schema, Schema]]]] | None +] = ContextVar("_SCOPED_OUTPUT_SCHEMAS", default=None) + + +@contextmanager +def isolated_schema_predictions() -> Iterator[None]: + """Read and memoize candidate schemas without using or changing live predictions.""" + zero_rows = _ZERO_ROW_MEMO.set({}) + schemas = _SCOPED_OUTPUT_SCHEMAS.set({}) + try: + yield + finally: + _SCOPED_OUTPUT_SCHEMAS.reset(schemas) + _ZERO_ROW_MEMO.reset(zero_rows) + @contextmanager def shared_zero_row_memo() -> Iterator[None]: @@ -1567,9 +1583,13 @@ def _memoized_output_schema( hash(config) except TypeError: return predict() - if self._output_schema_memo is None: - self._output_schema_memo = {} - memo = self._output_schema_memo + scoped = _SCOPED_OUTPUT_SCHEMAS.get() + if scoped is None: + if self._output_schema_memo is None: + self._output_schema_memo = {} + memo = self._output_schema_memo + else: + _, memo = scoped.setdefault(id(self), (self, {})) if config not in memo: memo[config] = predict() return memo[config] diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index b29b0c4cf..360447ad0 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -396,13 +396,17 @@ def _validate_record_path(self, record_path: tuple[str, ...]) -> None: raise ValueError("record_path cannot be empty") if self._spiral_connector is not None: refuse_other_format_path(record_path) - if len(self._path_prefix) + len(record_path) > self.max_hierarchy_depth: + self._validate_path_components(record_path) + self.require_storable_path(record_path) + + def require_storable_path(self, record_path: tuple[str, ...]) -> None: + """Refuse a record path whose full depth exceeds this database's limit.""" + full_path = self.base_path + record_path + if len(full_path) > self.max_hierarchy_depth: raise ValueError( - f"record_path depth {len(record_path)} exceeds maximum " - f"{self.max_hierarchy_depth - len(self._path_prefix)} " - f"(base_path uses {len(self._path_prefix)} components)" + f"record_path depth {len(full_path)} exceeds maximum " + f"{self.max_hierarchy_depth} for {'/'.join(full_path)!r}" ) - self._validate_path_components(record_path) @staticmethod def _validate_path_components(path: tuple[str, ...]) -> None: diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index 1e78cc312..6cc19e0b0 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -278,6 +278,11 @@ def require_storable(self) -> Callable[[pa.Schema], None]: """ return getattr(self._db, "require_storable") # noqa: B009 # AttributeError when absent, by design + @property + def require_storable_path(self) -> Callable[[tuple[str, ...]], None]: + """Delegate the optional record-path check to the wrapped database.""" + return getattr(self._db, "require_storable_path") # noqa: B009 # AttributeError when absent, by design + # ── Structural delegation ───────────────────────────────────────────────── @property diff --git a/src/orcapod/databases/spiral_database_codec.py b/src/orcapod/databases/spiral_database_codec.py index 92926c51e..16d36d53d 100644 --- a/src/orcapod/databases/spiral_database_codec.py +++ b/src/orcapod/databases/spiral_database_codec.py @@ -796,12 +796,13 @@ def _decode(array: Any, field: pa.Field[Any], physical: pa.Field[Any]) -> Any: restored = array.cast(stored) if t.is_time(logical): restored = restored.view(logical) # the same integers - elif restored.type != logical: - # A decimal32 or decimal64. A coefficient over the precision is refused - # before the cast: pyarrow's narrowing cast lets some through, wrapped. + elif t.is_decimal(logical): + # Validate even when the stored width already matches. Arrow's narrowing + # cast can also wrap a coefficient that exceeds the declared precision. try: restored.validate(full=True) - restored = restored.cast(logical) + if restored.type != logical: + restored = restored.cast(logical) except pa.ArrowInvalid as exc: raise StoredRowsError(f"not a {logical} value: {exc}") from exc if not field.nullable and restored.null_count: diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 12d289a7d..330e712c5 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -19,7 +19,7 @@ from orcapod.core.nodes import JobNode from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode -from orcapod.core.nodes.source_node import SourceJobNode +from orcapod.core.nodes.source_node import SourceJobNode, prospective_source_bindings from orcapod.core.nodes.staleness import RunHoldingNode from orcapod.core.sources.base import RootSource from orcapod.core.sources.derived_source import DerivedSource @@ -722,8 +722,9 @@ def bind( bindings and database as they were. When *database* or *result_database* is provided and differs from the - current one, ``_distribute_databases()`` is called (once a database is set) - so that all job nodes receive live DB references immediately. + current one, storage paths and schemas are checked with the proposed source + bindings. Once the checks pass, all job nodes receive live database references + immediately. Args: sources: Mapping of ``SourceNode.name`` → concrete source. @@ -775,10 +776,6 @@ def bind( f"Known slot names: {sorted(source_names)}" ) - # A database that cannot store a node's tables is refused before anything - # changes too (ITL-1162), and so is a caching operator over a restricted - # source, one this bind binds or one already bound (ITL-1218): a bind of a - # database alone would otherwise set it and fail while distributing it. # The slots this bind changes are the job's own, matched by object: a source # being bound may itself be a slot of another job with the same name. to_bind = sources or {} @@ -794,8 +791,13 @@ def bind( if isinstance(result_database, _Unchanged) else result_database ) + database_views = None if database_changed and new_database is not None: - self._require_storable_tables(new_database, new_result_database) + database_views = self._database_views(new_database, new_result_database) + # A replacement can change content-scoped paths and reveal Arrow types. + # Check the candidate graph before committing any bindings. + with prospective_source_bindings(prepared): + self._require_storable_tables(*database_views) # Every source is validated before anything changes: a refused source leaves # the job as it was, its database included (ITL-1112). @@ -811,8 +813,8 @@ def bind( if execution_context is not None: self._execution_context = execution_context - if database_changed and self._database is not None: - self._distribute_databases() + if database_views is not None: + self._attach_database_views(*database_views) def _replace_source_binding( self, slot: SourceJobNode, source: cp.StreamProtocol | None @@ -900,8 +902,8 @@ def _database_views( def _require_storable_tables( self, - database: "ArrowDatabaseProtocol", - result_database: "ArrowDatabaseProtocol | None", + pipeline_db: "ArrowDatabaseProtocol", + result_db: "ArrowDatabaseProtocol", ) -> None: """Refuse databases that cannot store a table of one of the job's nodes. @@ -909,14 +911,13 @@ def _require_storable_tables( changes (ITL-1162). Args: - database: The job database to check. - result_database: The separate function-result database to check, if any. + pipeline_db: The scoped database for pipeline records. + result_db: The scoped database for function results. Raises: UnstorableColumnError: For the first node whose table a database cannot store, naming the node. """ - pipeline_db, result_db = self._database_views(database, result_database) for node in (self._persistent_node_map or {}).values(): if isinstance(node, FunctionJobNode): # Checked against the candidate databases only, never the job's @@ -932,8 +933,7 @@ def _require_storable_tables( def _distribute_databases(self) -> None: """Wire live DB references to all FunctionJobNode and OperatorJobNode objects. - Called by ``compile()`` when a database is already set, and by ``bind()`` - when *database* is changed. + Called when compiling or restoring a job with a database already set. Raises: RuntimeError: If ``_database`` is not set. @@ -948,30 +948,33 @@ def _distribute_databases(self) -> None: # leaves every node as it was (ITL-1162), and so is a caching operator over # a restricted source (ITL-1218). refuse_restricted_operator_caches((self._persistent_node_map or {}).values()) - self._require_storable_tables(self._database, self._result_database) pipeline_db, result_db = self._database_views( self._database, self._result_database ) + self._require_storable_tables(pipeline_db, result_db) + self._attach_database_views(pipeline_db, result_db) + def _attach_database_views( + self, pipeline_db: "ArrowDatabaseProtocol", result_db: "ArrowDatabaseProtocol" + ) -> None: + """Install the validated views on the job's nodes.""" nodes = (self._persistent_node_map or {}).values() for node in nodes: if isinstance(node, FunctionJobNode): if self._unresolved_result_database is not None: # Left without a database (see ``load``), never given ``_result``. continue - node.attach_databases( + node._attach_databases( # pyright: ignore[reportPrivateUsage] # checked for all nodes before attaching any pipeline_database=pipeline_db, result_database=result_db, ) elif isinstance(node, OperatorJobNode): - node.attach_databases( + node._attach_databases( # pyright: ignore[reportPrivateUsage] # checked for all nodes before attaching any pipeline_database=pipeline_db, cache_mode=node.cache_mode, ) elif isinstance(node, SideEffectJobNode): - node.attach_databases( - pipeline_database=pipeline_db, - ) + node._attach_database(pipeline_db) # pyright: ignore[reportPrivateUsage] # checked for all nodes before attaching any self._node_database_views = (pipeline_db, result_db) # ------------------------------------------------------------------ diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index bb2c4361e..79aa21f36 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -210,6 +210,15 @@ def _pod_result_databases(node: Any) -> list[Any]: (``set_ephemeral_database``, through the pod that writes it). Not the job's result database (``_databases``); not committed at the end of a run, only leased. """ + return [getattr(owner, "result_database", None) for owner in _result_owners(node)] + + +def _result_owners(node: Any) -> list[Any]: + """The pods and data functions under ``node`` that may own a result database. + + Each has ``result_database`` (``None`` when it writes none) and, when it has one, + the ``record_path`` of its result table. See ``_pod_result_databases``. + """ found: list[Any] = [] pods: list[Any] = [ getattr(node, "_function_pod", None), @@ -221,16 +230,35 @@ def _pod_result_databases(node: Any) -> list[Any]: if pod is None or id(pod) in visited: continue visited.add(id(pod)) - found.append(getattr(pod, "result_database", None)) + found.append(pod) pods.append(getattr(pod, "_function_pod", None)) # a wrapping pod's inner pod function = getattr(pod, "data_function", None) while function is not None and id(function) not in visited: visited.add(id(function)) - found.append(getattr(function, "result_database", None)) + found.append(function) function = getattr(function, "_data_function", None) # a wrapper's inner return found +def _require_storable_result_paths(stream: Any) -> None: + """Refuse a function pod stream or function job node whose result table paths are + deeper than their databases allow (ITL-1871). + + Every result database the stream's or node's own pods write (``_result_owners``) + is checked; the caller names the stream or node. Nothing is read or written. + + Raises: + ValueError: If a result table's path is deeper than its database allows. + """ + from orcapod.contexts.stored import require_storable_record_path + + for owner in _result_owners(stream): + database = getattr(owner, "result_database", None) + if database is None: + continue + require_storable_record_path(database, lambda: owner.record_path) # noqa: B023 # called at once + + def _job_name(node: Any) -> str: """The name of the job ``node`` belongs to: its pipeline database's location.""" database = getattr(node, "_pipeline_database", None) @@ -291,26 +319,30 @@ def run_sources(streams: Iterable[Any]) -> list[Any]: return found -def _source_side_databases(streams: Iterable[Any], *, load_only: bool) -> list[Any]: - """The databases written by what feeds ``streams`` from outside the job's nodes, - through bound sources, wrapped sources and streams. - - The cache of every ``CachedSource`` (written when it is checked, and a run checks - every source it finds, ``check_sources``), and the result databases of every - function pod stream a run reads (a stream built outside the job and bound to a - slot computes, and writes its pod's caches, when the run reads it; - ``_pod_result_databases``). Behind an ``ArrowTableStream`` no pod is read: the - table holds its rows, whatever its ``upstreams`` name (ITL-1121), so only the - caches of the sources there are collected. A load-only run reads no function pod - stream (``refuse_unloadable_inputs`` refuses one), so it leases none of their - databases: the refusal is the error it gives, never a busy lease. Each stream is - visited at most twice, behind a table and not (linear in the size of the graph). +def _source_side_streams( + streams: Iterable[Any], *, load_only: bool +) -> list[tuple[Any, bool]]: + """What feeds ``streams`` from outside the job's nodes, through bound sources, + wrapped sources and streams, each with whether a run reads its pods. + + A run checks every source it finds (``check_sources``), so the cache of every + ``CachedSource`` met is written. A function pod stream a run reads (a stream + built outside the job and bound to a slot, or passed into a step) computes, and + writes its pod's caches, when the run reads it. Behind an ``ArrowTableStream`` no + pod is read: the table holds its rows, whatever its ``upstreams`` name (ITL-1121). + A load-only run reads no function pod stream (``refuse_unloadable_inputs`` refuses + one). A job node's own pods are not counted here (``write_scope_databases``). Each + stream is visited at most twice, behind a table and not (linear in the size of the + graph). + + Returns: + Each stream met (job nodes' bound sources in place of the nodes) and whether + a run reads its pods, in the order met. """ from orcapod.core.nodes.source_node import SourceJobNode - from orcapod.core.sources.cached_source import CachedSource from orcapod.core.streams.arrow_table_stream import ArrowTableStream - found: list[Any] = [] + found: list[tuple[Any, bool]] = [] visited: set[tuple[int, bool]] = set() pending: deque[tuple[Any, bool]] = deque((stream, False) for stream in streams) while pending: @@ -322,11 +354,8 @@ def _source_side_databases(streams: Iterable[Any], *, load_only: bool) -> list[A if stream.bound_source is not None: pending.append((stream.bound_source, behind_table)) continue - if isinstance(stream, CachedSource): - found.append(stream._cache_database) # pyright: ignore[reportPrivateUsage] # the database a run must hold the lease of - if not load_only and not behind_table and not _is_job_node(stream): - # A job node's pods: ``write_scope_databases``. - found.extend(db for db in _pod_result_databases(stream) if db is not None) + reads_pods = not load_only and not behind_table and not _is_job_node(stream) + found.append((stream, reads_pods)) behind = behind_table or isinstance(stream, ArrowTableStream) inputs = getattr(stream, "live_source_inputs", None) pending.extend((each, behind) for each in inputs or ()) @@ -334,6 +363,65 @@ def _source_side_databases(streams: Iterable[Any], *, load_only: bool) -> list[A return found +def _source_side_databases(streams: Iterable[Any], *, load_only: bool) -> list[Any]: + """The databases written by what feeds ``streams`` from outside the job's nodes + (``_source_side_streams``): the cache of every ``CachedSource`` and the result + databases of every function pod stream a run reads (``_pod_result_databases``). + """ + from orcapod.core.sources.cached_source import CachedSource + + found: list[Any] = [] + for stream, reads_pods in _source_side_streams(streams, load_only=load_only): + if isinstance(stream, CachedSource): + found.append(stream._cache_database) # pyright: ignore[reportPrivateUsage] # the database a run must hold the lease of + if reads_pods: + found.extend(db for db in _pod_result_databases(stream) if db is not None) + return found + + +def preflight_run_writes(streams: Sequence[Any], *, load_only: bool) -> None: + """Refuse a run that would write a table its database cannot store, before it takes + a lease, checks a source or writes anything (ITL-1871). + + Whatever the backends, and whether or not a writable SpiralDB connector exists: + every cache table of a ``CachedSource`` the run checks + (``CachedSource.require_storable_cache``) and every result table of a function pod + stream outside the job the run reads (``_require_storable_result_paths``), found by + the walk the writer leases use (``_source_side_streams``), and, for a full run, the + result tables of every job node's own pods (``function_pod(result_database=)``, + ``pod_cache_database``, an ephemeral result database): a job checks them when it + attaches its databases (``require_storable_tables``), a job node built on its own + only here. Nothing is read or written. + + Args: + streams: The nodes of the run, or the node whose ``run()`` it is. + load_only: Whether the run is load-only. + + Raises: + ValueError: If a table's path is deeper than its database allows, naming the + cached source, stream or node. + UnstorableColumnError: If a writable SpiralDB cache cannot store a column. + """ + from orcapod.core.sources.cached_source import CachedSource + + if not load_only: + # A job node's pods are also checked when a job attaches its databases, but a + # job node built on its own (no pipeline, no ephemeral database) never is. + for node in _job_nodes_under(streams): + try: + _require_storable_result_paths(node) + except ValueError as exc: + raise ValueError(f"Node {node.label!r}: {exc}") from exc + for stream, reads_pods in _source_side_streams(streams, load_only=load_only): + if isinstance(stream, CachedSource): + stream.require_storable_cache() + if reads_pods: + try: + _require_storable_result_paths(stream) + except ValueError as exc: + raise ValueError(f"Stream {stream.label!r}: {exc}") from exc + + def _job_nodes_under(targets: Iterable[Any]) -> list[Any]: """Every job node among ``targets`` and the job nodes they depend on, once each. @@ -404,7 +492,8 @@ def database_write_scope( whose source check would read an input that computes or delivers is refused first (``refuse_unloadable_source_checks``). When no writable SpiralDB connector exists in the process, no run can write one: nothing is walked - and the scope holds nothing. + for leases and the scope holds nothing. Either way, the run's preflight first + refuses a table its database cannot store (``preflight_run_writes``). Args: streams: The nodes of the run, or the node whose ``run()`` it is. @@ -417,7 +506,9 @@ def database_write_scope( The context manager that holds the leases. Raises: - ValueError: As ``refuse_unloadable_source_checks``, for a load-only run. + ValueError: As ``refuse_unloadable_source_checks``, for a load-only run; as + ``preflight_run_writes``. + UnstorableColumnError: As ``preflight_run_writes``. """ from orcapod.databases.spiraldb_writable_registry import any_writable_connector @@ -425,6 +516,8 @@ def database_write_scope( # Before any lease is taken or source checked: a load-only run never reads an # input that computes or delivers, also through a source's live inputs. refuse_unloadable_source_checks(streams) + # The run's preflight, whatever the backends (ITL-1871), before a lease is taken. + preflight_run_writes(streams, load_only=load_only) if not any_writable_connector(): return contextlib.nullcontext() from orcapod.databases.spiraldb_write_scope import database_writes diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 46d70d5f3..d31b8e5fb 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -54,6 +54,7 @@ find_stale_tables, require_same_data_context, require_storable, + require_storable_path, with_data_context, ) from orcapod.invocation import ( @@ -1180,6 +1181,13 @@ def _refuse_log_of_another_data_context(self) -> None: # DB attachment # ------------------------------------------------------------------ + def _invocation_log_path(self) -> tuple[str, ...]: + """Return the storage path of this node's invocation log.""" + return self.node_uri + ( + f"schema:{self.pipeline_hash().to_hex()}", + TRACKING_DB_SCHEMA_VERSION, + ) + def require_storable_tables(self, pipeline_database: ArrowDatabaseProtocol) -> None: """Refuse a database that cannot store this node's invocation log (ITL-1162). @@ -1192,6 +1200,9 @@ def require_storable_tables(self, pipeline_database: ArrowDatabaseProtocol) -> N UnstorableColumnError: If the database cannot store a column, naming this node. """ + require_storable_path( + pipeline_database, self._invocation_log_path, node_label=self.label + ) try: require_storable(pipeline_database, _stored_invocation_log_schema()) except UnstorableColumnError as exc: @@ -1216,16 +1227,16 @@ def attach_databases( # A database that cannot store the invocation log refuses it now, # before anything is delivered or changes (ITL-1162). self.require_storable_tables(pipeline_database) + self._attach_database(pipeline_database) + + def _attach_database(self, pipeline_database: ArrowDatabaseProtocol | None) -> None: + """Install the validated invocation log database.""" self._pipeline_database = pipeline_database self._unlisted_store_reported = False self._current_log_checked = False - if pipeline_database is not None: - self._table_path = self.node_uri + ( - f"schema:{self.pipeline_hash().to_hex()}", - TRACKING_DB_SCHEMA_VERSION, - ) - else: - self._table_path = None + self._table_path = ( + self._invocation_log_path() if pipeline_database is not None else None + ) # ------------------------------------------------------------------ # Sync execution diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index aa02a2d07..571284d22 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -13,6 +13,7 @@ import datetime as dt import json from collections.abc import Iterator +from decimal import Decimal from pathlib import Path from typing import Any, cast @@ -401,6 +402,57 @@ def test_a_column_the_codec_cannot_keep_is_named_by_require_storable() -> None: db.require_storable(rows(["r0"]).schema) +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize( + "logical", + [ + pa.decimal32(9, 2), + pa.decimal64(18, 2), + pa.decimal128(38, 2), + pa.decimal256(76, 2), + ], +) +@pytest.mark.parametrize("sign", [-1, 1]) +@pytest.mark.parametrize("nested", [False, True], ids=["column", "list-item"]) +def test_stored_decimal_precision_edges(logical: Any, sign: int, nested: bool) -> None: + db = ConnectorArrowDatabase(writable_connector()) + boundary = 10**logical.precision + value = Decimal(f"{sign * (boundary - 1)}e-2") + expected = [[value]] if nested else [value] + logical_column = pa.array( + expected, + type=pa.large_list(logical) if nested else logical, + ) + db.add_records( + RESULT, + rows(["edge"]).append_column("amount", logical_column), + record_id_column="__record_id", + flush=True, + ) + read = db.get_all_records(RESULT, record_id_column="__record_id") + assert read is not None and read["amount"].to_pylist() == expected + + table = _table(identity.spiral_table_name(RESULT)) + physical = table.schema().field("amount").type + stored = physical.value_type if nested else physical + raw = (sign * boundary).to_bytes(stored.byte_width, "little", signed=True) + from_buffers: Any = pa.Array.from_buffers + bad = from_buffers(stored, 1, [None, pa.py_buffer(raw)]) + if nested: + bad = pa.ListArray.from_arrays(pa.array([0, 1], pa.int32()), bad, type=physical) + table.append( + pa.table( + { + "__record_id": pa.array([b"edge"], pa.large_binary()), + "amount": bad, + } + ) + ) + with pytest.raises(OrcapodDatabaseReadError, match="column 'amount'") as raised: + _ = db.get_all_records(RESULT, record_id_column="__record_id") + assert isinstance(raised.value.__cause__, codec.StoredRowsError) + + def _make_table(name: str, metadata: dict[str, bytes], *, with_rows: bool) -> None: key = pa.schema([pa.field("__record_id", pa.large_binary(), nullable=False)]) table = _client().project("p").create_keyed_table("d", name, key) diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 77cd3f4a4..35f77ed60 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -15,7 +15,7 @@ import weakref from collections.abc import Callable, Iterator from pathlib import Path -from typing import Any +from typing import Any, Never, cast from typing_extensions import override @@ -23,13 +23,18 @@ import pytest from orcapod import PipelineJob, function_pod +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.core.nodes.operator_node import OperatorJobNode +from orcapod.core.nodes.source_node import SourceJobNode, SourceNode from orcapod.core.operators import SelectDataColumns -from orcapod.core.sources.cached_source import CachedSource +from orcapod.core.sources.cached_source import CachedSource, SOURCE_RECORDED_AT_COL +from orcapod.core.streams.base import typed_zero_row_table from orcapod.databases import ( ConnectorArrowDatabase, DeltaTableDatabase, InMemoryArrowDatabase, SpiralDBConnector, + SQLiteConnector, ) from orcapod.contexts import get_default_context from orcapod.databases import ( @@ -41,14 +46,19 @@ from orcapod.databases.extension_aware_database import ExtensionAwareDatabase from orcapod.databases.spiraldb_write_scope import database_writes, take_lease from orcapod.databases.store_table_names import is_spiral_lease_table_name -from orcapod.errors import SpiralDBLeaseRequiredError +from orcapod.errors import ( + SpiralDBLeaseRequiredError, + UnboundSourceError, + UnstorableColumnError, +) from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline import node_run +from orcapod.pipeline.execution_context import ExecutionContext from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.side_effects import SideEffectPod, sink_pod from orcapod.sources import ArrowTableSource from orcapod.protocols.core_protocols import StreamProtocol -from orcapod.types import CacheMode, ColumnConfig +from orcapod.types import CacheMode, ColumnConfig, ContentHash from tests.test_databases import fake_spiral_sdk as fake pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") @@ -221,6 +231,68 @@ def _run(job: PipelineJob, entry: str, **kwargs: Any) -> Any: # ------------------------------------------------------------ every table kind +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "run_async"]) +def test_overdeep_pipeline_path_is_refused_before_writes(entry: str) -> None: + database = _database().at("a", "b", "c", "d", "e") + with pytest.raises(ValueError, match=r"combine.*depth \d+ exceeds maximum 10"): + _run(_job(database, result_database=_database("results")), entry) + assert _database_tables() == [] and _lease_tables() == [] + assert calls == [] + + +def test_sqlite_job_checks_the_pipeline_path_at_compile_time() -> None: + database = ConnectorArrowDatabase(SQLiteConnector()).at("a", "b", "c", "d", "e") + with pytest.raises(ValueError, match=r"combine.*depth \d+ exceeds maximum 10"): + with PipelineJob( + name=JOB, database=database, result_database=InMemoryArrowDatabase() + ): + combine.pod(_other_source(), label="combine") + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "run_async"]) +@pytest.mark.parametrize("storage", ["source cache", "pipeline tag", "operator cache"]) +@pytest.mark.parametrize( + ("name", "values"), + [ + ("elapsed", pa.array([1, 2, 3], type=pa.duration("us"))), + ("digest", pa.array([b"ab", b"cd", b"ef"], type=pa.binary(2))), + ], +) +def test_unsupported_job_column_is_refused_before_writes( + entry: str, storage: str, name: str, values: pa.Array[Any] +) -> None: + database = _database() + tags = ["unit", "trial"] + if storage == "pipeline tag": + tags.append(name) + with pytest.raises(UnstorableColumnError, match=name): + with PipelineJob(name=JOB, database=database) as job: + combine.pod(_cached(database, _rows()), label="first") + source = ArrowTableSource( + _rows().append_column(name, values), + tag_columns=tags, + tag_only_columns=True, + source_id="other_trials", + ) + if storage == "source cache": + combine.pod( + CachedSource(source, cache_database=database), label="second" + ) + elif storage == "pipeline tag": + combine.pod(source, label="second") + else: + SelectDataColumns(["x", name])(source, label="second") + if storage == "operator cache": + job.nodes["second"].attach_databases( + pipeline_database=database.at(JOB), cache_mode=CacheMode.LOG + ) + _run(job, entry) + assert _database_tables() == [] and _lease_tables() == [] + assert calls == [] + + @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ENTRIES) @pytest.mark.parametrize("order", ["as given", "reversed"]) @@ -609,7 +681,8 @@ def failing(client: Any, lease: Any) -> None: def test_a_database_write_outside_a_run_is_refused_before_anything() -> None: spiral_db = _database() with pytest.raises( - SpiralDBLeaseRequiredError, match="through the connectors of a job run" + SpiralDBLeaseRequiredError, + match=r"through the connectors of a job run \(job\.run\(\)", ): _ = _cached(spiral_db, _rows()).as_table() spiral_db.add_records( @@ -1509,3 +1582,857 @@ def test_a_cached_source_behind_a_held_table_is_still_leased() -> None: databases = node_run.write_scope_databases([node], load_only=False) leased = spiraldb_write_scope.writable_connectors(databases) assert any(c is connector for c in leased) + + +# ------------------------------------- review of 4715effe3: one preflight (ITL-1871) + +# An entry and its keyword arguments: every way a run starts, load-only included. +PREFLIGHT_ENTRIES = [ + ("sync", {}), + ("run_async", {}), + ("second node", {}), + ("sync", {"load_only": True}), + ("run_async", {"load_only": True}), +] + + +def _start(job: PipelineJob, entry: str, **kwargs: Any) -> Any: + """Start a run of ``job`` by ``entry``: ``job.run``, ``run_async``, or the run of + the node labelled ``second`` (``"second node"``), with ``kwargs`` (``load_only``).""" + if entry == "second node": + return job.nodes["second"].run(**kwargs) + return _run(job, entry, **kwargs) + + +def _other_rows() -> pa.Table: + """A second table of two tags and two data columns, a source of its own.""" + rows = _rows() + return rows.set_column( + 2, rows.schema.field("x"), pa.array([10, 20, 30], pa.int64()) + ) + + +def _other_source() -> ArrowTableSource: + return ArrowTableSource( + _other_rows(), + tag_columns=["unit", "trial"], + tag_only_columns=True, + source_id="other_trials", + record_id_columns=["unit", "trial"], + ) + + +class _SQLiteForCachePathTests(SQLiteConnector): + """Allow cache construction so the test reaches the path check before any write.""" + + @override + def unstorable_column_reason( + self, name: str, arrow_type: pa.DataType, *, primary_key: bool + ) -> str | None: + if name == SOURCE_RECORDED_AT_COL: + return None + return super().unstorable_column_reason( + name, arrow_type, primary_key=primary_key + ) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize(("entry", "kwargs"), PREFLIGHT_ENTRIES) +def test_an_overdeep_sql_cache_path_is_refused_before_any_lease_or_write( + entry: str, kwargs: dict[str, Any] +) -> None: + """A cached source whose cache is on a SQL connector database too deep for its + path is refused by the run's preflight, naming the cached source, before any + lease is taken or any table written, in a job that also writes a writable + SpiralDB database.""" + database = _database() + deep = ConnectorArrowDatabase(_SQLiteForCachePathTests()).at(*"abcdefgh") + with PipelineJob(name=JOB, database=database) as job: + combine.pod(_cached(database, _rows()), label="first") + combine.pod( + CachedSource(_other_source(), label="deep cache", cache_database=deep), + label="second", + ) + with pytest.raises(ValueError, match=r"'deep cache'.*depth 11 exceeds maximum 10"): + _start(job, entry, **kwargs) + assert _database_tables() == [] and _lease_tables() == [] + assert deep.list_table_paths() == [] + assert calls == [] + + +@pytest.mark.parametrize(("entry", "kwargs"), PREFLIGHT_ENTRIES) +def test_an_overdeep_sql_cache_path_is_refused_without_a_writable_database( + tmp_path: Path, entry: str, kwargs: dict[str, Any] +) -> None: + """The same refusal on a job with no SpiralDB database at all: the preflight does + not depend on a writable SpiralDB connector existing.""" + calls.clear() + database = DeltaTableDatabase(tmp_path / "delta") + deep = ConnectorArrowDatabase(_SQLiteForCachePathTests()).at(*"abcdefgh") + with PipelineJob(name=JOB, database=database) as job: + combine.pod(_cached(database, _rows()), label="first") + combine.pod( + CachedSource(_other_source(), label="deep cache", cache_database=deep), + label="second", + ) + with pytest.raises(ValueError, match=r"'deep cache'.*depth 11 exceeds maximum 10"): + _start(job, entry, **kwargs) + assert database.list_table_paths() == [] + assert deep.list_table_paths() == [] + assert calls == [] + + +def _second_pod(cache: str, database: Any) -> Any: + """A second function over the first's outputs, caching in ``database``.""" + + def second(total: int, ratio: float) -> tuple[float, float]: + return total + ratio, total - ratio + + return function_pod(output_keys=("sum", "difference"), **{cache: database})(second) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("cache", ["result_database", "pod_cache_database"]) +@pytest.mark.parametrize("backend", ["writable SpiralDB", "SQLite"]) +def test_an_overdeep_function_result_path_is_refused_before_any_write( + cache: str, backend: str +) -> None: + """A function's own result database (``result_database`` or ``pod_cache_database``) + too deep for the result table's path (six components under a base of five) is + refused with the job's own result database, naming the node, before anything is + computed or written.""" + database = _database() + if backend == "SQLite": + own: Any = ConnectorArrowDatabase(SQLiteConnector()) + else: + own = _database("own") + pod = _second_pod(cache, own.at(*"abcde")) + with pytest.raises(ValueError, match=r"'second'.*depth 11 exceeds maximum 10"): + with PipelineJob(name=JOB, database=database) as job: + first = combine.pod(_cached(database, _rows()), label="first") + pod.pod(first, label="second") + _ = job.run() + assert _database_tables() == [] and _lease_tables() == [] + assert own.list_table_paths() == [] + assert calls == [] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "run_async", "select node"]) +@pytest.mark.parametrize("cache", ["result_database", "pod_cache_database"]) +@pytest.mark.parametrize( + "selected", + [("sum", "difference"), ("difference", "sum")], + ids=["given", "reversed"], +) +def test_an_overdeep_result_path_of_a_pod_built_outside_the_job_is_refused( + entry: str, cache: str, selected: tuple[str, str] +) -> None: + """A function pod stream built outside the job and passed in caches in a database + too deep for its result table: the run's preflight refuses it, naming the stream, + before any lease is taken or anything computed or written, whichever order its + two selected data columns are named in.""" + database = _database() + own = _database("own") + outside = _second_pod(cache, own.at(*"abcde")).pod( + combine.pod(_other_source(), label="outside first"), label="outside second" + ) + with PipelineJob(name=JOB, database=database) as job: + combine.pod(_cached(database, _rows()), label="first") + SelectDataColumns(list(selected))(outside, label="select") + with pytest.raises( + ValueError, match=r"Stream 'outside second'.*depth 11 exceeds maximum 10" + ): + if entry == "select node": + _ = job.nodes["select"].run() + else: + _run(job, entry) + assert _database_tables() == [] and _database_tables("own") == [] + assert _lease_tables() == [] and _lease_tables("own") == [] + assert calls == [] + + +class _DeclaredPolling: + """A polling implementation declaring an Arrow schema, fetching one batch.""" + + def __init__(self, table: pa.Table) -> None: + self._table = table + + def identity(self) -> Any: + return ("declared-polling", 1) + + def to_config(self) -> dict[str, Any] | None: + return None + + @classmethod + def from_config(cls, config: dict[str, Any]) -> "_DeclaredPolling": + raise NotImplementedError + + def schema(self) -> pa.Schema | None: + return self._table.schema + + async def poll(self, cursor: Any = None) -> bool: + return cursor is None + + async def fetch(self, cursor: Any = None) -> Any: + from orcapod.types import Cursor + + return Cursor.now(1), self._table + + async def close(self) -> None: + return None + + +class _NeverPolled(_DeclaredPolling): + """A source that can declare its schema but must never be polled.""" + + def __init__(self, table: pa.Table, *, declare_schema: bool = True) -> None: + super().__init__(table) + self._declare_schema: bool = declare_schema + + @override + def schema(self) -> pa.Schema | None: + return super().schema() if self._declare_schema else None + + @override + async def poll(self, cursor: object = None) -> Never: + raise AssertionError("polled") + + @override + async def fetch(self, cursor: object = None) -> Never: + raise AssertionError("fetched") + + +@pytest.mark.parametrize("load_only", [False, True]) +def test_an_unpolled_source_cache_with_no_declared_schema_checks_path_depth( + load_only: bool, +) -> None: + from orcapod.sources import PollingSource + + deep = ConnectorArrowDatabase(_SQLiteForCachePathTests()).at(*"abcdefgh") + source = PollingSource( + _NeverPolled(_other_rows(), declare_schema=False), + tag_columns=["unit", "trial"], + record_id_columns=["unit", "trial"], + ) + cached = CachedSource(source, label="deep cache", cache_database=deep) + + with pytest.raises(ValueError, match=r"'deep cache'.*depth 11 exceeds maximum 10"): + node_run.preflight_run_writes([cached], load_only=load_only) + assert deep.list_table_paths() == [] + + +# Two arrangements of a polling source of two tags and three data columns: the table's +# column order, the tag order and the order of the two selected data columns. +POLLING_ARRANGEMENTS = { + "given": (False, ["unit", "trial"], ["x", "payload"]), + "reordered": (True, ["trial", "unit"], ["payload", "x"]), +} + + +def _arranged(table: pa.Table, reverse: bool) -> pa.Table: + """``table`` with its columns in reverse order when ``reverse``.""" + return table.select(list(reversed(table.column_names))) if reverse else table + + +@pytest.mark.parametrize("kind", ["function", "operator"]) +def test_bind_checks_the_replacement_content_scoped_path( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """The candidate path policy sees the replacement source's instance hash.""" + original = ArrowTableSource( + _rows(), tag_columns=["unit", "trial"], tag_only_columns=True, source_id="old" + ) + replacement = ArrowTableSource( + _rows(2), tag_columns=["unit", "trial"], tag_only_columns=True, source_id="new" + ) + old_database = InMemoryArrowDatabase() + database = InMemoryArrowDatabase().at("replacement") + with PipelineJob(name=JOB, database=old_database) as job: + if kind == "function": + combine.pod(original, label="checked") + else: + SelectDataColumns(["x", "y"])(original, label="checked") + + slot = next(node for node in job.nodes.values() if isinstance(node, SourceJobNode)) + node = job.nodes["checked"] + assert isinstance(node, (FunctionJobNode, OperatorJobNode)) + if isinstance(node, OperatorJobNode): + node.attach_databases(old_database.at(JOB), cache_mode=CacheMode.LOG) + monkeypatch.setattr(node, "_table_scope", "content_hash") + monkeypatch.setattr(node, "_node_identity_path_cache", None) + old_path = node.node_identity_path + old_attachment = node._pipeline_database # pyright: ignore[reportPrivateUsage] + old_generation = slot.binding_generation + old_modified = slot.last_modified + paths: list[tuple[str, ...]] = [] + refuse_new_path = True + + def check_path(db: InMemoryArrowDatabase, record_path: tuple[str, ...]) -> None: + identity_path = record_path[:-1] + if not any(part.startswith("instance:") for part in identity_path): + return + assert db.base_path == ("replacement", JOB) + paths.append(identity_path) + if refuse_new_path and identity_path != old_path: + raise ValueError("replacement path refused") + + monkeypatch.setattr( + InMemoryArrowDatabase, "require_storable_path", check_path, raising=False + ) + with pytest.raises(ValueError, match=r"Node 'checked': replacement path refused"): + job.bind({slot.name: replacement}, database) + + assert job.database is old_database + assert job.sources[slot.name] is original + assert slot.bound_source is original + assert slot.binding_generation == old_generation + assert slot.last_modified == old_modified + assert node.node_identity_path == old_path + assert node._pipeline_database is old_attachment # pyright: ignore[reportPrivateUsage] + + refuse_new_path = False + job.bind({slot.name: replacement}, database) + assert job.database is database + assert job.sources[slot.name] is replacement + assert slot.bound_source is replacement + assert slot.binding_generation == old_generation + 1 + new_path = node.node_identity_path + assert new_path != old_path + assert paths == [new_path, new_path] + attachment = node._pipeline_database # pyright: ignore[reportPrivateUsage] + assert attachment is not None + assert attachment.base_path == ("replacement", JOB) + + job.bind({slot.name: original}) + assert job.sources[slot.name] is original + assert paths == [new_path, new_path] + + +def _hash_source(n: int) -> ArrowTableSource: + """Make a distinct source with the same declared schema.""" + return ArrowTableSource( + _rows(n), + tag_columns=["unit", "trial"], + tag_only_columns=True, + source_id=f"input-{n}", + ) + + +def _job_for_binding_hashes( + source: ArrowTableSource, monkeypatch: pytest.MonkeyPatch +) -> tuple[PipelineJob, SourceJobNode, OperatorJobNode]: + """Build a slot feeding a content-scoped operator and a downstream function.""" + database = InMemoryArrowDatabase() + with PipelineJob(name=JOB, database=database) as job: + declaration = SourceNode( + "input", *source.output_schema(), arrow_schemas=source.arrow_schemas + ) + selected = SelectDataColumns(["x", "y"])(declaration, label="selected") + combine.pod(selected, label="out") + + slot = next(node for node in job.nodes.values() if isinstance(node, SourceJobNode)) + job.bind({slot.name: source}) + operator = job.nodes["selected"] + assert isinstance(operator, OperatorJobNode) + operator.attach_databases(database.at(JOB), cache_mode=CacheMode.LOG) + monkeypatch.setattr(operator, "_table_scope", "content_hash") + monkeypatch.setattr(operator, "_node_identity_path_cache", None) + return job, slot, operator + + +def _binding_hashes(job: PipelineJob, slot: SourceJobNode) -> tuple[object, ...]: + """Read the public hashes and identity chains across the job.""" + return tuple( + ( + node.pipeline_hash(), + node.content_hash(), + node.name_chain(), + node.source_chain(), + node.node_hash(), + hash(node), + ) + for node in (slot, job.nodes["selected"], job.nodes["out"]) + ) + + +@pytest.mark.parametrize("prime", [False, True], ids=["cold", "warm"]) +def test_bind_hashes_match_fresh_jobs( + monkeypatch: pytest.MonkeyPatch, prime: bool +) -> None: + """Check candidate identity and compare live hashes after refusal and acceptance.""" + original, replacement = _hash_source(3), _hash_source(2) + fresh_a, slot_a, operator_a = _job_for_binding_hashes(_hash_source(3), monkeypatch) + fresh_b, slot_b, operator_b = _job_for_binding_hashes(_hash_source(2), monkeypatch) + expected_a = _binding_hashes(fresh_a, slot_a) + expected_b = _binding_hashes(fresh_b, slot_b) + job, slot, operator = _job_for_binding_hashes(original, monkeypatch) + if prime: + assert _binding_hashes(job, slot) == expected_a + + refuse = True + candidate_reads: list[tuple[object, ...]] = [] + candidate_paths: list[tuple[str, ...]] = [] + + def check_path(_db: InMemoryArrowDatabase, path: tuple[str, ...]) -> None: + if any(part.startswith("instance:") for part in path): + candidate_paths.append(path[:-1]) + assert slot == slot_b + candidate_reads.append(_binding_hashes(job, slot)) + if refuse: + raise ValueError("candidate refused") + + monkeypatch.setattr( + InMemoryArrowDatabase, "require_storable_path", check_path, raising=False + ) + database = InMemoryArrowDatabase() + with pytest.raises(ValueError, match="candidate refused"): + job.bind({slot.name: replacement}, database) + assert slot.bound_source is original + assert _binding_hashes(job, slot) == expected_a + assert operator.node_identity_path == operator_a.node_identity_path + + refuse = False + job.bind({slot.name: replacement}, database) + assert slot.bound_source is replacement + assert _binding_hashes(job, slot) == expected_b + assert operator.node_identity_path == operator_b.node_identity_path + assert candidate_paths == [operator_b.node_identity_path] * 2 + assert candidate_reads == [expected_b] * 2 + + job.bind({slot.name: original}) + assert _binding_hashes(job, slot) == expected_a + + +def test_refused_candidate_does_not_fill_unbound_python_hash( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A structural path check leaves an unbound slot's Python hash intact.""" + original, replacement = _hash_source(3), _hash_source(2) + _, fresh_slot, _ = _job_for_binding_hashes(original, monkeypatch) + fresh_slot.bound_source = None + expected = hash(fresh_slot) + job, slot, operator = _job_for_binding_hashes(original, monkeypatch) + slot.bound_source = None + monkeypatch.setattr(operator, "_table_scope", "pipeline_hash") + slot_memo: dict[str, ContentHash] = {} + replacement_memo: dict[str, ContentHash] = {} + pipeline_memo: dict[str, ContentHash] = {} + monkeypatch.setattr(slot, "_content_hash_cache", slot_memo) + monkeypatch.setattr(replacement, "_content_hash_cache", replacement_memo) + monkeypatch.setattr(operator, "_pipeline_hash_cache", pipeline_memo) + + def check_path(_db: InMemoryArrowDatabase, _path: tuple[str, ...]) -> None: + # The earlier source consistency check can hash the replacement. Make + # its live memo cold again to detect writes made by the storage check. + replacement_memo.clear() + _ = hash(slot) + _ = operator.node_identity_path + raise ValueError("candidate refused") + + monkeypatch.setattr( + InMemoryArrowDatabase, "require_storable_path", check_path, raising=False + ) + with pytest.raises(ValueError, match="candidate refused"): + job.bind({slot.name: replacement}, InMemoryArrowDatabase()) + assert slot.bound_source is None + assert slot_memo == replacement_memo == pipeline_memo == {} + assert operator._node_identity_path_cache is None # pyright: ignore[reportPrivateUsage] + with pytest.raises(UnboundSourceError): + _ = slot.content_hash() + assert hash(slot) == expected + + +class _StreamProxy: + """Expose the stream protocol through a wrapper with no base-class ancestry.""" + + def __init__(self, source: ArrowTableSource) -> None: + self._source = source + + def __getattr__(self, name: str) -> Any: + return getattr(self._source, name) + + +@pytest.mark.parametrize("wrap_replacement", [False, True], ids=["concrete", "proxy"]) +def test_refused_candidate_preserves_protocol_binding_python_hash( + monkeypatch: pytest.MonkeyPatch, wrap_replacement: bool +) -> None: + """Refusing a replacement preserves the Python hash of a protocol-backed slot.""" + original, replacement = _hash_source(3), _hash_source(2) + # The proxy forwards the protocol dynamically via __getattr__. + wrapped = cast(StreamProtocol, cast(object, _StreamProxy(original))) + candidate = ( + cast(StreamProtocol, cast(object, _StreamProxy(replacement))) + if wrap_replacement + else replacement + ) + job, slot, _ = _job_for_binding_hashes(original, monkeypatch) + job.bind({slot.name: wrapped}) + fresh, fresh_slot, _ = _job_for_binding_hashes(original, monkeypatch) + fresh.bind({fresh_slot.name: wrapped}) + expected = hash(fresh_slot) + candidate_job, candidate_slot, _ = _job_for_binding_hashes(replacement, monkeypatch) + candidate_job.bind({candidate_slot.name: candidate}) + expected_candidate = hash(candidate_slot) + slot_memo: dict[str, ContentHash] = {} + monkeypatch.setattr(slot, "_content_hash_cache", slot_memo) + + def check_path(_db: InMemoryArrowDatabase, path: tuple[str, ...]) -> None: + if any(part.startswith("instance:") for part in path): + assert slot == candidate_slot + assert hash(slot) == expected_candidate + raise ValueError("candidate refused") + + monkeypatch.setattr( + InMemoryArrowDatabase, "require_storable_path", check_path, raising=False + ) + with pytest.raises(ValueError, match="candidate refused"): + job.bind({slot.name: candidate}, InMemoryArrowDatabase()) + assert slot.bound_source is wrapped + assert slot_memo == {} + assert hash(slot) == expected + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "run_async"]) +@pytest.mark.parametrize("order", [("first", "second"), ("second", "first")]) +def test_refused_bind_preserves_bindings_and_corrected_retry_attaches_databases( + entry: str, order: tuple[str, str], monkeypatch: pytest.MonkeyPatch +) -> None: + """A storage refusal at the second operator leaves both slots and attachments intact.""" + + def source(source_id: str, table: pa.Table) -> ArrowTableSource: + tags = ["unit", "trial"] + if order[0] == "second": + table = _arranged(table, True) + tags.reverse() + return ArrowTableSource( + table, + tag_columns=tags, + tag_only_columns=True, + source_id=source_id, + ) + + table = _rows() + originals = {name: source(name, table) for name in order} + marked_field = table.schema.field("x").with_metadata({b"output": b"duration"}) + unsupported = source( + "unsupported", + table.set_column(table.schema.get_field_index("x"), marked_field, table["x"]), + ) + corrected: dict[str, StreamProtocol] = { + name: source(f"{name}-corrected", table) for name in order + } + old_database = InMemoryArrowDatabase() + old_result_database = InMemoryArrowDatabase() + old_context = ExecutionContext() + database = _database() + result_database = InMemoryArrowDatabase() + context = ExecutionContext() + with PipelineJob( + name=JOB, + database=old_database, + result_database=old_result_database, + execution_context=old_context, + ) as job: + for name, original in originals.items(): + SelectDataColumns(["x", "y"])(original, label=f"select-{name}") + combine.pod(originals["first"], label="combined") + + slots = { + node.name: node + for node in job.nodes.values() + if isinstance(node, SourceJobNode) + } + assert set(slots) == set(order) + operators = { + node.label.removeprefix("select-"): node + for node in job.nodes.values() + if isinstance(node, OperatorJobNode) + } + checked_order = tuple(operators) + assert set(checked_order) == set(order) + old_attachment = old_database.at(JOB) + old_state = { + name: ( + slot.binding_generation, + slot.last_modified, + operators[name].content_hash(), + ) + for name, slot in slots.items() + } + checked: list[str] = [] + for name, node in operators.items(): + node.attach_databases(old_attachment, cache_mode=CacheMode.LOG) + monkeypatch.setattr(originals[name], "_typed_zero_row_table", lambda: None) + + # Arrow metadata changes the synthetic output without changing slot fit. + def predict_output( + slot: SourceJobNode = slots[name], + normal: Callable[[], pa.Table | None] = node._typed_zero_row_table, # pyright: ignore[reportPrivateUsage] + ) -> pa.Table | None: + zero_rows = typed_zero_row_table(slot) + if zero_rows is None: + return None + checked.append(slot.name) + if zero_rows.schema.field("x").metadata == {b"output": b"duration"}: + return pa.schema( + [pa.field("x", pa.large_list(pa.duration("us")))] + ).empty_table() + return normal() + + monkeypatch.setattr(node, "_typed_zero_row_table", predict_output) + + refused = checked_order[-1] + proposed = dict(corrected) + proposed[refused] = unsupported + with pytest.raises(UnstorableColumnError, match=f"select-{refused}.*'x'"): + job.bind(proposed, database, context, result_database=result_database) + + assert tuple(checked) == checked_order + assert job.database is old_database + assert job.result_database is old_result_database + assert job.execution_context is old_context + for name, slot in slots.items(): + node = operators[name] + assert job.sources[name] is originals[name] + assert slot.bound_source is originals[name] + assert (slot.binding_generation, slot.last_modified, node.content_hash()) == ( + old_state[name] + ) + assert node._pipeline_database is old_attachment # pyright: ignore[reportPrivateUsage] + + job.bind(corrected, database, context, result_database=result_database) + assert job.database is database + assert job.result_database is result_database + assert job.execution_context is context + for name, slot in slots.items(): + assert job.sources[name] is corrected[name] + assert slot.bound_source is corrected[name] + assert slot.binding_generation == old_state[name][0] + 1 + attachment = operators[name]._pipeline_database # pyright: ignore[reportPrivateUsage] + assert isinstance(attachment, ConnectorArrowDatabase) + assert attachment.base_path == (JOB,) + _run(job, entry) + assert _database_tables() + assert result_database.list_table_paths() + assert old_database.list_table_paths() == [] + assert old_result_database.list_table_paths() == [] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("arrangement", sorted(POLLING_ARRANGEMENTS)) +def test_a_polling_sources_declared_unstorable_column_is_refused_at_attachment( + arrangement: str, +) -> None: + """A polling source declaring ``large_list`` feeds a logging + operator on a writable SpiralDB database: its declared schema types the + operator's output before any poll, so attaching the cache refuses the column, + and nothing is polled, leased or written, in either arrangement of its tags and + data columns.""" + reverse, tags, selected = POLLING_ARRANGEMENTS[arrangement] + from orcapod.sources import PollingSource + + payload = pa.array([[1], [2, 3], []], type=pa.large_list(pa.duration("us"))) + table = _arranged( + _rows().append_column( + pa.field("payload", payload.type, nullable=False), payload + ), + reverse, + ) + database = _database() + + source = PollingSource( + _NeverPolled(table), tag_columns=tags, record_id_columns=tags + ) + with PipelineJob(name=JOB, database=database) as job: + combine.pod(_cached(database, _rows()), label="first") + SelectDataColumns(selected)(source, label="second") + + with pytest.raises(UnstorableColumnError, match="payload"): + job.nodes["second"].attach_databases( + pipeline_database=database.at(JOB), cache_mode=CacheMode.LOG + ) + assert _database_tables() == [] and _lease_tables() == [] + assert calls == [] + + +@pytest.mark.parametrize("arrangement", sorted(POLLING_ARRANGEMENTS)) +def test_a_polling_sources_zero_row_table_before_a_poll_is_its_declared_one( + arrangement: str, +) -> None: + """Before its first poll a polling source with a declared Arrow schema gives the + zero-row table its first poll gives (types, nullability, every column group), + and the same public ``arrow_schema()`` (column by column; column order is + presentation), without polling, in either arrangement of its tags and data + columns.""" + from orcapod.core.streams.base import typed_zero_row_table + from orcapod.sources import PollingSource + + reverse, tags, _ = POLLING_ARRANGEMENTS[arrangement] + payload = pa.array([[1], [2, 3], []], type=pa.large_list(pa.int32())) + table = _arranged( + _rows().append_column( + pa.field("payload", payload.type, nullable=False), payload + ), + reverse, + ) + + class _CountedPolling(_DeclaredPolling): + fetched = 0 + + async def fetch(self, cursor: Any = None) -> Any: + _CountedPolling.fetched += 1 + return await super().fetch(cursor) + + def build() -> PollingSource[int]: + return PollingSource( + _CountedPolling(table), tag_columns=tags, record_id_columns=tags + ) + + unpolled = build() + before = typed_zero_row_table(unpolled) + declared = unpolled.arrow_schema() + assert _CountedPolling.fetched == 0 + polled = build() + _ = polled.as_table() + after = typed_zero_row_table(polled) + assert before is not None and after is not None + assert before.schema == after.schema + fetched = polled.arrow_schema() + assert {f.name: f for f in declared} == {f.name: f for f in fetched} + assert set(declared.names) >= {*tags, "x", "y", "payload"} + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("cache", ["result_database", "pod_cache_database"]) +@pytest.mark.parametrize("backend", ["writable SpiralDB", "SQLite"]) +def test_an_overdeep_result_path_of_a_standalone_function_node_is_refused( + cache: str, backend: str +) -> None: + """A function job node built on its own (no pipeline, no ephemeral database), + whose function caches in a database too deep for its result table, is refused by + its run's preflight, naming the node and the depth, before any lease is taken, + the function called or any table written (its input's cache included).""" + from orcapod.core.nodes.function_node import FunctionJobNode + + if backend == "SQLite": + root_database: Any = ConnectorArrowDatabase(SQLiteConnector()) + cache_database = InMemoryArrowDatabase() + else: + root_database = _database("own") + cache_database = root_database + node = FunctionJobNode( + function_pod=_second_pod(cache, root_database.at(*"abcde")).pod, + input_stream=combine.pod(_cached(cache_database, _rows())), + label="standalone", + ) + with pytest.raises( + ValueError, match=r"Node 'standalone'.*depth 11 exceeds maximum 10" + ): + _ = node.run() + assert root_database.list_table_paths() == [] + assert cache_database.list_table_paths() == [] + assert _database_tables("own") == [] and _lease_tables("own") == [] + assert calls == [] + + +# ------------------- review of 16ca64e4a: the preflight and a set-aside cache path + + +def _origin_job(rows: pa.Table, tags: list[str]) -> PipelineJob: + """A job whose ``combine`` node reads a rebindable slot ``trials`` over ``rows``, + run once, so its node's stored results can be wrapped in a cached source.""" + from orcapod import Pipeline, SourceNode + + source = ArrowTableSource( + rows, tag_columns=tags, tag_only_columns=True, source_id="trials" + ) + with Pipeline(name="origin") as pipeline: + combine.pod(SourceNode.from_stream(source, name="trials"), label="combine") + job = PipelineJob.from_pipeline( + pipeline, database=InMemoryArrowDatabase(), sources={"trials": source} + ) + _ = job.run() + return job + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "run_async"]) +@pytest.mark.parametrize("unstorable", ["overdeep SQLite path", "SpiralDB column"]) +def test_a_cache_path_set_aside_by_a_rebind_is_not_checked_by_the_preflight( + entry: str, unstorable: str +) -> None: + """A cached source over another job's stored results, with a fixed cache path its + database cannot store (a path too deep for a SQLite database; a duration tag on a + writable SpiralDB database). Its cache path is used once (a direct read, which + fails at the write), then the + origin's slot is rebound, which sets that path aside: the source serves the live + rows and writes no cache table. A run over it completes as it did before the + preflight existed, and nothing is written to the set-aside path; without the + rebind the same run is refused, and a direct read fails at its write as it + always did.""" + rows = _rows().append_column( + pa.field("elapsed", pa.duration("us"), nullable=False), + pa.array([1, 2, 3], type=pa.duration("us")), + ) + tags = ["unit", "elapsed", "trial"] + origin = _origin_job(rows, tags) + + def build() -> tuple[CachedSource, Any, PipelineJob]: + from orcapod import Pipeline, SourceNode + + if unstorable == "overdeep SQLite path": + cache: Any = ConnectorArrowDatabase(_SQLiteForCachePathTests()).at( + *"abcdefghi" + ) + else: + cache = _database("cache") + cached = CachedSource( + origin.nodes["combine"].as_source(), + cache_database=cache, + cache_path=("stored",), + label="cached results", + ) + with Pipeline(name="reader") as pipeline: + slot = SourceNode.from_stream(cached, name="stored") + SelectDataColumns(["ratio", "total"])(slot, label="selected") + job = PipelineJob.from_pipeline( + pipeline, database=InMemoryArrowDatabase(), sources={"stored": cached} + ) + return cached, cache, job + + error = ( + ValueError if unstorable == "overdeep SQLite path" else UnstorableColumnError + ) + # Without a rebind the run would write the cache table: refused before writes. + _, cache, job = build() + with pytest.raises(error, match="cached results|elapsed"): + _ = _run(job, entry) + assert cache.list_table_paths() == [] + + # A direct read uses the cache path, and fails at its write as before. + cached, cache, job = build() + with pytest.raises(error, match="exceeds maximum|elapsed"): + _ = cached.as_table() + other = rows.set_column( + rows.column_names.index("x"), + rows.schema.field("x"), + pa.array([10, 20, 30], pa.int64()), + ) + origin.bind( + sources={ + "trials": ArrowTableSource( + other, tag_columns=tags, tag_only_columns=True, source_id="trials" + ) + } + ) + _ = origin.run() + _ = _run(job, entry) + # The live rows: every result stored for the origin node, both bindings. + stored = origin.nodes["combine"].as_source().as_table()["total"].to_pylist() + totals = job.nodes["selected"].as_table()["total"].to_pylist() + assert sorted(totals) == sorted(stored) and len(totals) == 6 + assert cache.list_table_paths() == [] + if unstorable == "SpiralDB column": + assert _database_tables("cache") == [] diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index 511e283a0..f66b9beac 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -468,7 +468,9 @@ def test_describing_a_poller_that_has_not_polled_reads_nothing() -> None: """L7: ``arrow_schema()`` of a poller that has not polled never fetches. It answers from the declared schema, the same every time, with each data column's - source info, and ``arrow_types_declared`` stays false (Codex on PR #485). + source info (Codex on PR #485). The declared schema types the rows a poll gives + (every batch is held to it), so ``arrow_types_declared`` is true and the types + are those of the polled rows (ITL-1852). """ from orcapod.core.sources import PollingSource from orcapod.types import Schema @@ -507,7 +509,11 @@ def schema(self) -> Any: "_source_a", "_source_b", ] - assert not poller.arrow_types_declared + assert poller.arrow_types_declared + assert fetches == [] + _ = poller.as_table() + assert fetches == [1] + assert poller.arrow_schema().equals(first) def test_an_operator_stream_declares_its_tags_in_its_rows_order() -> None: