diff --git a/changelog.d/ITL-1125.md b/changelog.d/ITL-1125.md new file mode 100644 index 000000000..d39fe3a30 --- /dev/null +++ b/changelog.d/ITL-1125.md @@ -0,0 +1,21 @@ +### Breaking changes and migration + +- Assigning `upstreams` on a live operator or function node compares the current + and replacement inputs when every input has a declared schema available without + reading rows, polling, or computing a new pipeline hash. The setter requires the + same input count and the same multiset of tag and data schemas, including declared + system-tag names and types. It compares types and nullability by column name, + ignores input order and data meta columns, and leaves read-only blueprints and + inputs with unavailable schemas to the existing setter behavior. If any schema + read raises an exception, the setter treats the declaration as unavailable. + A source's system-tag declaration is unavailable if reading it would compute + its schema hash. An Arrow-backed stream's Python declaration is available once + its schema has been read with system tags. Assignment leaves Arrow conversion + to ordinary schema reads. Self-references are diagnosed when a job node runs. + Function nodes still require exactly one input. Build a new pipeline to change + known input schemas. + +### Known limitations + +- An Arrow width change is detected only if it changes `output_schema()`, for + example through a changed system-tag name. The setter uses declared schema types. diff --git a/docs/dev/design_issues/ITL-1111-GW1.md b/docs/dev/design_issues/ITL-1111-GW1.md index 7746e42a2..9e70bc6ec 100644 --- a/docs/dev/design_issues/ITL-1111-GW1.md +++ b/docs/dev/design_issues/ITL-1111-GW1.md @@ -25,12 +25,9 @@ a polling source's answer changes once it has polled. The debug logs take `%s` a a stream or logging at debug level is bounded too. Call-count tests over 20 stages: `tests/test_pipeline/test_graph_walk_cost.py`. -Left as they are: assigning `SourceJobNode.bound_source` directly, or setting a node's -`upstreams`, clears no memo of the nodes downstream of it, which keep their schema (their -pipeline hashes are equally stale today; a strict xfail test records the `upstreams` case, and a -`bound_source` of another column type is refused, ITL-1112). The risk is bounded: -nothing in `src` calls the `upstreams` setter (the loaders build a node with `__new__` and set -`_input_streams` before any schema is asked; only tests call it), and after ITL-1112 a bind -cannot change a slot's schema. Cascading the clear (a registry of dependents, or a setter that -refuses an upstream of another schema) is for the developer to decide. And each join keeps both inputs' system-tag columns, so their number doubles per +Assigning `SourceJobNode.bound_source` directly or setting a node's `upstreams` clears no memo +of downstream nodes. A bind preserves the slot's schema (ITL-1112), and the `upstreams` +setter refuses a change to the multiset of input schemas when every schema is available +without reading rows (ITL-1125). Each join keeps both inputs' +system-tag columns, so their number doubles per stage (2 ** (stages + 1)), which is the width of the output, not a walk. diff --git a/docs/dev/design_issues/ITL-1125-USC1.md b/docs/dev/design_issues/ITL-1125-USC1.md new file mode 100644 index 000000000..70f9d5092 --- /dev/null +++ b/docs/dev/design_issues/ITL-1125-USC1.md @@ -0,0 +1,26 @@ +## `src/orcapod/core/nodes/` + +### USC1 — Rewiring a node could leave downstream schemas and pipeline hashes stale +**Status:** resolved +**Severity:** high +**Issue:** ITL-1125 + +Assigning an upstream with a different schema could change the rewired node's output +schema while downstream nodes kept their previous schema predictions and pipeline hashes. +A stale pipeline hash still names the table for the old schema. + +**Fix:** When every input's `output_schema()` is available without reading or hashing +rows, running a zero-row derivation, polling, or computing a pipeline hash, the live +setters compare the old and new input counts and multisets of declared schema pairs. +They compare tag fields, including system tags, and data fields by name, type and +nullability. Data meta fields and input order do not enter the comparison. The setters +read existing schema predictions and keep any new predictions local to the check. +A source whose system-tag schema hash has not been computed is unavailable to the +comparison. Assigning an upstream leaves that computation to an explicit schema read. +Arrow-backed streams provide a Python declaration after a schema read with system +tags. The comparison does not run Arrow conversion. A node's own output declaration +describes its prior wiring, so a self-reference is left to the run's cycle diagnostic. +A refusal preserves the wiring. Unavailable declarations and read-only +blueprints retain the previous setter behavior, including function nodes' one-input +requirement. An exception during a schema read makes the declaration unavailable +to the setter. Arrow widths that produce identical declarations are outside this check. diff --git a/src/orcapod/core/base.py b/src/orcapod/core/base.py index 836f25276..9bb48e973 100644 --- a/src/orcapod/core/base.py +++ b/src/orcapod/core/base.py @@ -7,6 +7,7 @@ import orcapod.contexts as contexts from orcapod.config import DEFAULT_CONFIG, OrcapodConfig +from orcapod.core.schema_read import require_schema_work_allowed from orcapod.types import ContentHash logger = logging.getLogger(__name__) @@ -269,6 +270,9 @@ def pipeline_hash(self, hasher=None) -> ContentHash: hasher = self.data_context.semantic_hasher cache_key = hasher.hasher_id if cache_key not in self._pipeline_hash_cache: + # Predictions can need a pipeline hash for system-tag names. A cold + # hash may compute content hashes while building a symmetric input set. + require_schema_work_allowed() from orcapod.protocols.hashing_protocols import PipelineElementProtocol def pipeline_resolver(obj: Any) -> ContentHash: diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 953359409..7f2d91c36 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -34,6 +34,8 @@ from orcapod import contexts from orcapod.core.nodes.provenance_methods import ProvenanceMethods +from orcapod.core.nodes.upstream_schema import require_same_upstream_schemas +from orcapod.core.schema_read import require_schema_work_allowed from orcapod.core.function_pod import ( fall_through_tags, function_input, @@ -561,7 +563,14 @@ def upstreams(self) -> tuple[StreamProtocol, ...]: @upstreams.setter def upstreams(self, value: tuple[StreamProtocol, ...]) -> None: - if len(value) != 1: + """Replace the node's input, preserving its schema when both are known. + + Raises: + ValueError: If there is not exactly one input or the known schemas differ. + """ + if self._function_pod is not None and self._input_stream is not None: + require_same_upstream_schemas(self, value, fixed_arity=True) + elif len(value) != 1: raise ValueError("FunctionPod can only have one upstream") self._input_stream = value[0] self._forget_output_schema() @@ -599,6 +608,7 @@ def output_schema( restored to a Python type (an unregistered logical type). """ if self._function_pod is None: + require_schema_work_allowed() from orcapod.pipeline.serialization import ( deserialize_output_schema, SavedSchemaVersionError, diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 6ef01fb4b..0d047e148 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -30,6 +30,8 @@ from orcapod import contexts from orcapod.core.nodes.provenance_methods import ProvenanceMethods +from orcapod.core.nodes.upstream_schema import require_same_upstream_schemas +from orcapod.core.schema_read import require_schema_work_allowed from orcapod.core.data_tags import ( mark_data_tags, data_tag_names, @@ -363,15 +365,19 @@ def cache_mode(self) -> CacheMode: @upstreams.setter def upstreams(self, value: tuple[StreamProtocol, ...]) -> None: - """Replace the node's inputs. + """Replace the node's inputs, preserving schemas known without reading rows. Raises: - ValueError: If the node caches (``LOG`` or ``REPLAY``) and a source - feeding ``value`` is restricted (ITL-1218); nothing changes. + ValueError: If all input schemas are available for a live operator and + the input count or schema multiset changes, or if the node caches + (``LOG`` or ``REPLAY``) and a source feeding ``value`` is restricted + (ITL-1218). """ from orcapod.pipeline.restrictions import refuse_restricted_operator_cache refuse_restricted_operator_cache(self, self.cache_mode, streams=value) + if self._operator is not None: + require_same_upstream_schemas(self, value) self._input_streams = value self._forget_output_schema() @@ -474,6 +480,7 @@ def output_schema( restored to a Python type (an unregistered logical type). """ if self._operator is None: + require_schema_work_allowed() from orcapod.pipeline.serialization import ( deserialize_output_schema, SavedSchemaVersionError, diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index a0d27f6c0..f65d7e946 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -27,6 +27,7 @@ from orcapod.core.base import TraceableBase from orcapod.core.datagrams import Data, Tag from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied +from orcapod.core.schema_read import require_schema_work_allowed from orcapod.core.sources.base import table_is_rows from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( @@ -681,6 +682,7 @@ def _resolve(self) -> bool: texts = self._saved_arrow_texts if texts is None: return True + require_schema_work_allowed() # Local import: orcapod.pipeline imports the node modules. from orcapod.pipeline.serialization import ( arrow_schema_from_texts, @@ -879,6 +881,7 @@ def _schema_hash_str(self) -> str: Returns: Hex string schema hash. """ + require_schema_work_allowed() if not self._resolve(): # The saved type text stands in until the class is registered (ITL-1138). return self.data_context.semantic_hasher.hash_object( diff --git a/src/orcapod/core/nodes/upstream_schema.py b/src/orcapod/core/nodes/upstream_schema.py new file mode 100644 index 000000000..79b9239b0 --- /dev/null +++ b/src/orcapod/core/nodes/upstream_schema.py @@ -0,0 +1,85 @@ +"""Schema validation for node upstream setters.""" + +from orcapod.core.schema_read import declared_schema_only +from orcapod.core.streams.base import StreamBase, temporary_output_schema_memos +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.system_constants import constants +from orcapod.types import ColumnConfig, Schema + +_SCHEMA_COLUMNS = ColumnConfig(system_tags=True) +_SchemaPair = tuple[Schema, Schema] + + +def _available_schema( + node: StreamBase, stream: StreamProtocol | None +) -> _SchemaPair | None: + """Read the tag and data declarations, omitting data-only meta fields.""" + # The node's current output describes its old wiring. It cannot declare its + # own prospective input schema. The run diagnoses cycles. + if stream is None or stream is node: + return None + with declared_schema_only(), temporary_output_schema_memos(): + try: + tag, data = stream.output_schema(columns=_SCHEMA_COLUMNS) + except Exception: + # An unreadable declaration must fall back to the original setter behavior. + return None + meta = [ + name + for name in data + if name.startswith(constants.META_PREFIX) and name not in tag + ] + return tag, data.drop(*meta) if meta else data + + +def _describe(schemas: tuple[_SchemaPair | None, ...]) -> tuple[_SchemaPair | str, ...]: + """Describe schemas for a setter error without consulting the input streams.""" + return tuple( + schema if schema is not None else "" + for schema in schemas + ) + + +def require_same_upstream_schemas( + node: StreamBase, + replacements: tuple[StreamProtocol, ...], + *, + fixed_arity: bool = False, +) -> None: + """Require a wired node to keep its input count and multiset of known schemas. + + Args: + node: The wired node. + replacements: The proposed upstreams. + fixed_arity: Whether the node already requires a fixed input count even + when some schemas are unavailable. + + Raises: + ValueError: If all schemas are available and their counts or schema pairs + differ, or if the node has fixed arity and the count changes. + """ + current = tuple(_available_schema(node, stream) for stream in node.upstreams) + proposed = tuple(_available_schema(node, stream) for stream in replacements) + available = all(schema is not None for schema in (*current, *proposed)) + if len(current) != len(proposed) and (available or fixed_arity): + raise ValueError( + f"Cannot rewire node {node.label!r} with a different upstream count: " + + f"current schemas {_describe(current)!r}, " + + f"replacement schemas {_describe(proposed)!r}" + ) + + if not available: + return + remaining = [schema for schema in proposed if schema is not None] + for old in current: + assert old is not None + for index, new in enumerate(remaining): + if old == new: + _ = remaining.pop(index) + break + else: + raise ValueError( + f"Cannot rewire node {node.label!r} with a different schema multiset " + + "(tags including system-tag columns, and data): " + + f"current schemas {current!r}, replacement schemas {proposed!r}" + ) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 3c1534d7c..26a45fb77 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -41,6 +41,7 @@ warn_provisional_operator, ) from orcapod.utils.provisional import note_provisional_use, provisional_class_name +from orcapod.core.schema_read import require_schema_work_allowed from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, @@ -1580,6 +1581,7 @@ def __init__( def built(self) -> StreamProtocol: """The stream, built from the rows on the first call (``main``'s row path).""" if self._stream is None: + require_schema_work_allowed() self._stream = StaticOutputOperatorPod._materialize_upstream( self._rows, self._node ) diff --git a/src/orcapod/core/schema_read.py b/src/orcapod/core/schema_read.py new file mode 100644 index 000000000..6be0835ea --- /dev/null +++ b/src/orcapod/core/schema_read.py @@ -0,0 +1,32 @@ +"""Prevent new computation while inspecting declared output schemas.""" + +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar + +_declared_only = ContextVar("declared_schema_only", default=False) + + +class SchemaWorkRequired(Exception): + """The requested schema needs work beyond reading its declaration.""" + + +@contextmanager +def declared_schema_only() -> Iterator[None]: + """Read declared schemas and cached dependencies without producing new results.""" + token = _declared_only.set(True) + try: + yield + finally: + _declared_only.reset(token) + + +def require_schema_work_allowed() -> None: + """Raise when a declared-schema read tries to perform additional work.""" + if is_declared_schema_only(): + raise SchemaWorkRequired + + +def is_declared_schema_only() -> bool: + """Whether the caller can use existing Python schemas only.""" + return _declared_only.get() diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index a2cee2919..701ac904f 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -14,6 +14,7 @@ ) from typing_extensions import override +from orcapod.core.schema_read import require_schema_work_allowed from orcapod.core.sources.base import RootSource from orcapod.core.sources.provisional import warn_provisional_source from orcapod.core.sources.reload import same_rows @@ -469,6 +470,7 @@ def _columns_stream(self, tags_as_data: Mapping[str, str]) -> ArrowTableStream: if self._cached_stream is not None: return self._cached_stream if self._zero_row_stream is None: + require_schema_work_allowed() self._zero_row_stream = self._derive_from( self._empty_origin_table(), tags_as_data ) diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 107a42328..34a4164c6 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -22,6 +22,7 @@ import pyarrow as pa from typing_extensions import override +from orcapod.core.schema_read import require_schema_work_allowed from orcapod.core.sources.base import RootSource from orcapod.core.sources.source_ids import hash_source_name from orcapod.logical_types.canonical_form import declaration_form_schema @@ -399,6 +400,7 @@ def _declared_schema_hash(self) -> str | None: Hex schema-hash string, or ``None`` if ``impl.schema()`` returned ``None`` (schema not yet known). """ + require_schema_work_allowed() declared = self._declared_arrow_pair() if declared is None: return None @@ -765,6 +767,7 @@ def _sync_poll_and_commit(self) -> bool: Safe to call concurrently with ``async_iter_data``. """ + require_schema_work_allowed() with self._state_lock: cursor_snapshot = self._cursor diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index df49eaff6..738f7fa6e 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -10,6 +10,7 @@ from orcapod.hashing.orcapod_table import OrcapodTable from orcapod import contexts from orcapod.core.datagrams import Data, Tag +from orcapod.core.schema_read import SchemaWorkRequired, is_declared_schema_only from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, StreamBase, @@ -216,6 +217,9 @@ def __init__( self._system_tag_schema = system_tag_schema self._all_tag_schema = all_tag_schema self._data_schema = data_schema + self._python_schemas: dict[ + bool, tuple[contexts.DataContext, tuple[Schema, Schema]] + ] = {} self._cached_elements: list[tuple[TagProtocol, Data]] | None = None self._update_modified_time() # set modified time to now @@ -325,18 +329,33 @@ def output_schema( Returns the types of the tag and data columns in the stream. This is useful for accessing the types of the columns in the stream. """ - # normalize column config - columns_config = ColumnConfig.handle_config(columns, all_info=all_info) - # TODO: consider using MappingProxyType to avoid copying the dicts - converter = self.data_context.type_converter - if columns_config.system_tags: - tag_schema = self._all_tag_schema - else: - tag_schema = self._tag_schema - return ( - converter.arrow_schema_to_python_schema(tag_schema), + include_system_tags = ColumnConfig.handle_config( + columns, all_info=all_info + ).system_tags + context = self.data_context + if is_declared_schema_only(): + cached = self._python_schemas.get(include_system_tags) + if cached is not None and cached[0] is context: + return cached[1] + raise SchemaWorkRequired + + converter = context.type_converter + schemas = ( + converter.arrow_schema_to_python_schema( + self._all_tag_schema if include_system_tags else self._tag_schema + ), converter.arrow_schema_to_python_schema(self._data_schema), ) + # Retain the declaration for inspection without another Arrow conversion. + self._python_schemas[include_system_tags] = (context, schemas) + if include_system_tags: + self._python_schemas[False] = ( + context, + (schemas[0].select(*self._tag_schema.names), schemas[1]), + ) + elif not self._system_tag_schema: + self._python_schemas[True] = (context, schemas) + return schemas def as_table( self, diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 78d6ae944..65f57ba22 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -25,6 +25,7 @@ import pyarrow as pa from orcapod.core.base import TraceableBase +from orcapod.core.schema_read import require_schema_work_allowed from orcapod.core.data_tags import data_tag_names from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel from orcapod.core.streams.view import ( @@ -154,6 +155,21 @@ def short_stream_repr(stream: object) -> str: ) """The zero-row tables derived during one outermost ``typed_zero_row_table`` call.""" +_OutputSchemaMemo = dict[ColumnConfig, tuple[Schema, Schema]] +_TEMPORARY_SCHEMA_MEMOS: ContextVar[ + dict[int, tuple[object, _OutputSchemaMemo]] | None +] = ContextVar("_TEMPORARY_SCHEMA_MEMOS", default=None) + + +@contextmanager +def temporary_output_schema_memos() -> Iterator[None]: + """Keep newly predicted output schemas local to this inspection.""" + token = _TEMPORARY_SCHEMA_MEMOS.set({}) + try: + yield + finally: + _TEMPORARY_SCHEMA_MEMOS.reset(token) + @contextmanager def shared_zero_row_memo() -> Iterator[None]: @@ -201,6 +217,7 @@ def typed_zero_row_table(stream: object) -> pa.Table | None: a function pod's stream or node (ITL-985), an unbound input slot, a source that reads, polls or derives its rows later, a pod stream not yet computed. """ + require_schema_work_allowed() memo = _ZERO_ROW_MEMO.get() if memo is None: # The outermost call: a memo for this derivation only, so an upstream that @@ -1438,7 +1455,7 @@ def output_schema( # Predicted output schemas by normalized column config; see # ``_memoized_output_schema``. Set on first use, so a subclass that asks for its # schema before ``StreamBase.__init__`` runs still works. - _output_schema_memo: dict[ColumnConfig, tuple[Schema, Schema]] | None = None + _output_schema_memo: _OutputSchemaMemo | None = None def _memoized_output_schema( self, @@ -1474,9 +1491,17 @@ 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 + temporary = _TEMPORARY_SCHEMA_MEMOS.get() + if temporary is None: + if self._output_schema_memo is None: + self._output_schema_memo = {} + memo = self._output_schema_memo + else: + persistent = self._output_schema_memo + if persistent is not None and config in persistent: + return persistent[config] + # Keep the stream alive for this read and key it without hashing it. + memo = temporary.setdefault(id(self), (self, {}))[1] if config not in memo: memo[config] = predict() return memo[config] diff --git a/tests/test_core/operators/test_index_pick_arrow_types.py b/tests/test_core/operators/test_index_pick_arrow_types.py index c939d6001..aba85f44c 100644 --- a/tests/test_core/operators/test_index_pick_arrow_types.py +++ b/tests/test_core/operators/test_index_pick_arrow_types.py @@ -650,18 +650,16 @@ async def test_reused_pick_on_logical_mapping(logical_first: bool) -> None: ( "op", "old_value", - "old_type", "current_value", - "current_type", + "data_type", "expected", "expected_type", ), [ - (Index("c", 0), [3], list[int], [Path("/a")], list[Path], Path("/a"), Path), + (Index("c", 0), [Path("/old")], [Path("/a")], list[Path], Path("/a"), Path), ( Pick("c", "k"), - {"k": 3}, - dict[str, int], + {"k": "old"}, {"k": "a"}, dict[str, str], "a", @@ -674,18 +672,17 @@ async def test_reused_pick_on_logical_mapping(logical_first: bool) -> None: async def test_rewired_projection_uses_current_input( op: UnaryOperator, old_value: DataValue, - old_type: DataType, current_value: DataValue, - current_type: DataType, + data_type: DataType, expected: object, expected_type: type, ) -> None: - """Schema prediction and both job paths follow a rewired upstream description.""" + """Both job paths project values from a replacement of the same schema.""" original = DictSource( - [{"c": old_value, "x": 1}], data_schema={"c": old_type, "x": int} + [{"c": old_value, "x": 1}], data_schema={"c": data_type, "x": int} ) current = DictSource( - [{"c": current_value, "x": 1}], data_schema={"c": current_type, "x": int} + [{"c": current_value, "x": 1}], data_schema={"c": data_type, "x": int} ) job = PipelineJob(name="rewired", database=InMemoryArrowDatabase()) with job: diff --git a/tests/test_core/operators/test_semijoin_tag_keys.py b/tests/test_core/operators/test_semijoin_tag_keys.py index e5d324b2d..01db7e07e 100644 --- a/tests/test_core/operators/test_semijoin_tag_keys.py +++ b/tests/test_core/operators/test_semijoin_tag_keys.py @@ -425,19 +425,20 @@ async def test_direct_unknown_pair_refuses_before_emitting_a_warning() -> None: @pytest.mark.asyncio async def test_empty_right_after_operator_node_is_rewired() -> None: - """A node rewired to an unkeyed pair passes through its left rows.""" - left, other, right = _shared_operator_inputs(False, False) + """A rewired unkeyed node with an empty right passes through its new left rows.""" + _, left, right = _shared_operator_inputs(False, False) + filtered = left.polars_filter(m=4) empty = right.polars_filter(u=0) job = PipelineJob(name="rewired_semijoin", database=InMemoryArrowDatabase()) with job: _ = SemiJoin()(left, empty, label="step") node = job.nodes["step"] assert isinstance(node, OperatorJobNode) - node.upstreams = (other, empty) + node.upstreams = (filtered, empty) - actual = await _execute_node_rows(node, other, empty, run_async=True) - expected = list(node.execute(other, empty).iter_data()) - assert len(expected) == 3 + actual = await _execute_node_rows(node, filtered, empty, run_async=True) + expected = list(node.execute(filtered, empty).iter_data()) + assert len(expected) == 1 assert_equivalent(expected, actual) assert_same_provenance(expected, actual) @@ -483,10 +484,8 @@ async def test_rewired_semijoin_warns_once_for_the_same_names(run_async: bool) - assert [tag["id"] for tag, _ in rows] == [1] -@pytest.mark.parametrize("run_async", [False, True], ids=["sync", "async"]) -@pytest.mark.asyncio -async def test_rewired_semijoin_new_warning_is_retried(run_async: bool) -> None: - """A new ignored name warns, including after each failed attempt to warn.""" +def test_semijoin_rejects_a_new_right_schema_atomically() -> None: + """A mismatch in the second input preserves even the compatible first input.""" left, right = left_source(), right_same_tag_other_y() job = PipelineJob(name="rewired_new_warning", database=InMemoryArrowDatabase()) with job: @@ -494,21 +493,16 @@ async def test_rewired_semijoin_new_warning_is_retried(run_async: bool) -> None: node = job.nodes["step"] assert isinstance(node, OperatorJobNode) filtered = left.polars_filter(x=10) - node.upstreams = (filtered, right) + before = node.upstreams - with warnings.catch_warnings(): - warnings.simplefilter("error", SemiJoinIgnoredColumnWarning) - for _ in range(2): - with pytest.raises(SemiJoinIgnoredColumnWarning, match="'y'"): - _ = await _execute_node_rows(node, filtered, right, run_async=run_async) - with pytest.warns(SemiJoinIgnoredColumnWarning, match="'y'") as record: - rows = await _execute_node_rows(node, filtered, right, run_async=run_async) - assert len(record) == 1 - assert [tag["id"] for tag, _ in rows] == [1] - with warnings.catch_warnings(): - warnings.simplefilter("error", SemiJoinIgnoredColumnWarning) - repeated = await _execute_node_rows(node, filtered, right, run_async=run_async) - assert [tag["id"] for tag, _ in repeated] == [1] + for stream in (*before, filtered, right): + _ = stream.output_schema(columns={"system_tags": True}) + with pytest.raises( + ValueError, match=r"'step'.*different schema multiset.*'z'.*'y'" + ): + node.upstreams = (filtered, right) + + assert node.upstreams is before @pytest.mark.parametrize("shared_tags", [True, False], ids=["keyed", "unkeyed"]) diff --git a/tests/test_pipeline/test_graph_walk_cost.py b/tests/test_pipeline/test_graph_walk_cost.py index 359830e71..618df7f4f 100644 --- a/tests/test_pipeline/test_graph_walk_cost.py +++ b/tests/test_pipeline/test_graph_walk_cost.py @@ -26,10 +26,13 @@ from pathlib import Path from typing import Any +import pyarrow as pa import pytest from orcapod import PipelineJob, function_pod -from orcapod.core.sources import DictSource +from orcapod.core.nodes import FunctionJobNode, OperatorJobNode +from orcapod.core.operators import Join +from orcapod.core.sources import ArrowTableSource, DictSource from orcapod.core.streams.base import StreamBase from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import InputValidationError, SourceSpecMismatchError @@ -574,21 +577,64 @@ def test_a_source_of_another_column_type_is_refused_and_moves_no_schema( } assert after == before - def test_setting_an_operator_nodes_upstreams_changes_its_schema(self) -> None: - """Setting an operator node's ``upstreams`` changes its own schema.""" + @pytest.mark.parametrize( + "other", + [ + _one_row_source(1.5), + DictSource( + [{"id": 1, "x": 1}], + tag_columns=["id", "x"], + tag_only_columns=False, + ), + DictSource( + [{"id": 1, "other": 1}], tag_columns=["id"], tag_only_columns=True + ), + DictSource( + [{"id": 1, "x": None}, {"id": 2, "x": 1}], + tag_columns=["id"], + tag_only_columns=True, + ), + ], + ids=["type", "role", "name", "nullability"], + ) + def test_operator_rewiring_to_another_schema_is_atomic( + self, other: DictSource + ) -> None: + """A refused rewire preserves the wired graph's schemas and table identities.""" job = _rename_job() node = job.nodes["renamed"] - assert node.output_schema()[1]["y"] is int - - node.upstreams = (_one_row_source(1.5),) - - assert node.output_schema()[1]["y"] is float - - def test_setting_a_function_nodes_upstreams_changes_its_schema(self) -> None: - """Setting a function node's ``upstreams`` changes its own schema.""" - job = _function_job() - node = job.nodes["plus_one"] - assert node.output_schema()[0]["id"] is int + downstream = job.nodes["renamed_again"] + assert isinstance(node, OperatorJobNode) + assert isinstance(downstream, OperatorJobNode) + upstreams = node.upstreams + before = [ + (step.output_schema(), step.pipeline_hash()) for step in (node, downstream) + ] + assert before[1][0][1]["z"] is int + + columns = {"system_tags": True} + _ = upstreams[0].output_schema(columns=columns) + _ = other.output_schema(columns=columns) + with pytest.raises(ValueError, match="'renamed'") as error: + node.upstreams = (other,) + + for original, replacement in zip( + upstreams[0].output_schema(columns=columns), + other.output_schema(columns=columns), + strict=True, + ): + assert repr(original) in str(error.value) + assert repr(replacement) in str(error.value) + assert node.upstreams is upstreams + for step, (schema, pipeline_hash) in zip((node, downstream), before): + assert step.output_schema() is schema + assert step.pipeline_hash() == pipeline_hash + + def test_function_rewiring_to_another_tag_schema_is_refused(self) -> None: + """A function node refuses changing its upstream's tag type.""" + node = _function_job().nodes["plus_one"] + assert isinstance(node, FunctionJobNode) + before = node.upstreams[0] other = DictSource( [{"id": "one", "x": 1}], tag_columns=["id"], @@ -596,23 +642,92 @@ def test_setting_a_function_nodes_upstreams_changes_its_schema(self) -> None: source_id="other", ) - node.upstreams = (other,) + _ = before.output_schema(columns={"system_tags": True}) + _ = other.output_schema(columns={"system_tags": True}) + with pytest.raises(ValueError, match="'plus_one'"): + node.upstreams = (other,) + + assert node.upstreams[0] is before + assert node.output_schema()[0]["id"] is int + + def test_rewiring_refuses_changed_system_tag_names_from_arrow_types( + self, + ) -> None: + """A source's Arrow width can change the names in its declared tag schema.""" + node = _rename_job().nodes["renamed"] + assert isinstance(node, OperatorJobNode) + before = node.upstreams + other = ArrowTableSource( + pa.table( + {"id": [1], "x": [2]}, + schema=pa.schema( + [ + pa.field("id", pa.int64(), False), + pa.field("x", pa.int32(), False), + ] + ), + ), + tag_columns=["id"], + tag_only_columns=True, + ) + assert other.output_schema() == before[0].output_schema() + columns = {"system_tags": True} + assert other.output_schema(columns=columns) != before[0].output_schema( + columns=columns + ) + + with pytest.raises(ValueError, match=r"'renamed'.*system-tag"): + node.upstreams = (other,) + + assert node.upstreams is before - assert node.output_schema()[0]["id"] is str + def test_rewiring_to_a_join_with_different_system_tags_is_atomic(self) -> None: + """A new provenance schema must leave downstream predictions untouched.""" + original = DictSource( + [{"id": 1, "x": 1, "extra": 2}], tag_columns=["id"], tag_only_columns=True + ) + right = DictSource( + [{"id": 1, "extra": 2}], tag_columns=["id"], tag_only_columns=True + ) + replacement = Join()(_one_row_source(1), right) + assert original.output_schema() == replacement.output_schema() + + job = PipelineJob(name="rewire_system_tags") + with job: + selected = original.select_data_columns("x", label="selected") + _ = selected.map_data({"x": "y"}, label="renamed") + node = job.nodes["selected"] + downstream = job.nodes["renamed"] + assert isinstance(node, OperatorJobNode) + assert isinstance(downstream, OperatorJobNode) + before = node.upstreams + columns = {"system_tags": True} + old_tags = before[0].output_schema(columns=columns)[0] + new_tags = replacement.output_schema(columns=columns)[0] + assert len(old_tags) == 3 + assert len(new_tags) == 5 + downstream_schema = downstream.output_schema(columns=columns) + + with pytest.raises(ValueError, match="'selected'.*system-tag") as error: + node.upstreams = (replacement,) + + assert all(name in str(error.value) for name in {*old_tags, *new_tags} - {"id"}) + assert node.upstreams is before + assert downstream.output_schema(columns=columns) is downstream_schema - @pytest.mark.xfail( - strict=True, - reason=( - "Setting a wired node's upstreams clears its own memo only; the nodes " - "downstream of it keep theirs (ITL-1111). Nothing in orcapod sets " - "upstreams after construction." - ), + @pytest.mark.parametrize( + ("build_job", "label"), [(_rename_job, "renamed"), (_function_job, "plus_one")] ) - def test_setting_upstreams_changes_downstream_schemas(self) -> None: - """Setting a node's ``upstreams`` should change the schemas downstream of it.""" - job = _rename_job() - assert job.nodes["renamed_again"].output_schema()[1]["z"] is int + def test_rewiring_to_the_same_schema_replaces_the_input( + self, build_job: Callable[[], PipelineJob], label: str + ) -> None: + """Both setters accept a different stream with equivalent upstream schemas.""" + node = build_job().nodes[label] + assert isinstance(node, (FunctionJobNode, OperatorJobNode)) + before = node.output_schema() + other = _one_row_source(2) - job.nodes["renamed"].upstreams = (_one_row_source(1.5),) + node.upstreams = (other,) - assert job.nodes["renamed_again"].output_schema()[1]["z"] is float + assert node.upstreams[0] is other + assert node.output_schema() == before diff --git a/tests/test_pipeline/test_upstream_schema.py b/tests/test_pipeline/test_upstream_schema.py new file mode 100644 index 000000000..4f10d79e1 --- /dev/null +++ b/tests/test_pipeline/test_upstream_schema.py @@ -0,0 +1,885 @@ +"""The upstream setters preserve the schemas of a wired node (ITL-1125).""" + +from pathlib import Path +from typing import cast +from unittest.mock import MagicMock, call, patch + +import pyarrow as pa +import pytest + +from orcapod import Pipeline, PipelineJob, function_pod +from orcapod.core.function_pod import FunctionPod +from orcapod.core.nodes import ( + FunctionJobNode, + FunctionNode, + OperatorJobNode, + OperatorNode, + SourceNode, +) +from orcapod.core.operators import Index, Join, MapData, MergeJoin, SemiJoin +from orcapod.core.sources import DictSource, PollingSource +from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.system_constants import OPERATOR_DB_SCHEMA_VERSION +from orcapod.types import CacheMode, ColumnConfig, Cursor, Schema + +_SYSTEM_TAGS = {"system_tags": True} + + +@function_pod(output_keys="total") +def _total(x: int | None, y: int | None) -> int: + """Add the two data values.""" + return (x or 0) + (y or 0) + + +def _raw( + x: int, + reverse: bool, + *, + note: int | str | None = None, + system_type: pa.DataType | None = None, +) -> ArrowTableStream: + """Make a raw stream with two tags and two data columns.""" + items = [("id", 1), ("group", "a"), ("x", x), ("y", 5)] + row = dict(reversed(items) if reverse else items) + if note is not None: + row["__note"] = note + table = pa.Table.from_pylist([row]) + if system_type is not None: + table = table.append_column("custom_id", pa.array([100], type=system_type)) + return ArrowTableStream( + table, + tag_columns=["group", "id"] if reverse else ["id", "group"], + system_tag_columns=["custom_id"] if system_type is not None else [], + ) + + +class _PollingFeed: + """A feed whose initial fetch may be empty and whose schema is optional.""" + + def __init__(self, value: int | str | None, schema: Schema | None = None) -> None: + self.value = value + self._schema = schema + self.polls = 0 + self.fetches = 0 + + def identity(self) -> str: + return "rewire-feed" + + def to_config(self) -> None: + return None + + @classmethod + def from_config(cls, config: dict[str, object]) -> "_PollingFeed": + return cls(None) + + def schema(self) -> Schema | None: + return self._schema + + async def poll(self, cursor: Cursor[int] | None = None) -> bool: + self.polls += 1 + return self.value is not None and (cursor is None or cursor.value == 0) + + async def fetch( + self, cursor: Cursor[int] | None = None + ) -> tuple[Cursor[int], list[dict[str, int | str]]]: + self.fetches += 1 + if self.value is None: + return Cursor(value=0), [] + return Cursor(value=1), [{"id": 1, "group": "a", "x": self.value, "y": 5}] + + async def close(self) -> None: + pass + + +@pytest.mark.parametrize("initial_value", [None, 4, "four"]) +@pytest.mark.parametrize("kind", ["operator", "function"]) +def test_rewiring_to_unpolled_source_does_not_fetch( + kind: str, initial_value: int | str | None +) -> None: + """A first batch cannot determine whether assignment is accepted.""" + before = DictSource( + [{"id": 1, "group": "a", "x": 2, "y": 5}], + tag_columns=["id", "group"], + tag_only_columns=True, + ) + feed = _PollingFeed(initial_value) + after = PollingSource(feed, ["id", "group"], record_id_columns="id") + if kind == "operator": + node = OperatorJobNode(MapData({"x": "xx"}), (before,), label="step") + else: + pod = _total.pod + assert isinstance(pod, FunctionPod) + node = FunctionNode(pod, before, label="step") + + node.upstreams = (after,) + + assert node.upstreams == (after,) + assert (feed.polls, feed.fetches) == (0, 0) + if isinstance(node, OperatorJobNode) and initial_value is None: + feed.value = 4 + node.run() + assert node.as_table().column("xx").to_pylist() == [4] + + +def test_rewiring_refuses_different_declared_polling_schema_without_fetch() -> None: + """A prior schema read makes a declared mismatch detectable without fetching.""" + before = DictSource( + [{"id": 1, "group": "a", "x": 2, "y": 5}], + tag_columns=["id", "group"], + tag_only_columns=True, + ) + feed = _PollingFeed("four", Schema({"id": int, "group": str, "x": str, "y": int})) + after = PollingSource(feed, ["id", "group"], record_id_columns="id") + _ = before.output_schema(columns=_SYSTEM_TAGS) + _ = after.output_schema(columns=_SYSTEM_TAGS) + node = OperatorNode(MapData({"x": "xx"}), (before,), label="step") + + with pytest.raises(ValueError, match=r"'step'.*different schema"): + node.upstreams = (after,) + + assert node.upstreams == (before,) + assert (feed.polls, feed.fetches) == (0, 0) + + +@pytest.mark.parametrize("source_kind", ["polling", "slot"]) +@pytest.mark.parametrize("assignment", ["compatible", "incompatible", "wrong_arity"]) +def test_rewiring_leaves_cold_source_schema_memos_untouched( + source_kind: str, assignment: str +) -> None: + """Assignments leave source schema memos as they were before the call.""" + tags = Schema(id=int, group=str) + old_data = Schema(x=int, y=int) + new_data = Schema(x=int if assignment == "compatible" else str, y=int) + if source_kind == "polling": + old_feed = _PollingFeed(4, Schema({**tags, **old_data})) + new_feed = _PollingFeed(None, Schema({**tags, **new_data})) + original = PollingSource(old_feed, ["id", "group"], record_id_columns="id") + replacement = PollingSource(new_feed, ["id", "group"], record_id_columns="id") + hash_memo = "_declared_schema_hash" + else: + original = SourceNode("original", tags, old_data) + replacement = SourceNode("replacement", tags, new_data) + hash_memo = "_schema_hash_str" + + if assignment == "wrong_arity": + pod = _total.pod + assert isinstance(pod, FunctionPod) + node = FunctionNode(pod, original, label="step") + else: + node = OperatorNode(MapData({"x": "xx"}), (original,), label="step") + memos = (hash_memo, "_output_schema_memo") + for stream in (original, replacement): + assert all(name not in vars(stream) for name in memos) + + if assignment == "wrong_arity": + with pytest.raises(ValueError): + node.upstreams = (replacement, original) + assert node.upstreams[0] is original + else: + node.upstreams = (replacement,) + assert node.upstreams[0] is replacement + + for stream in (original, replacement): + assert all(name not in vars(stream) for name in memos) + _ = replacement.output_schema(columns=_SYSTEM_TAGS) + assert hash_memo in vars(replacement) + + +@pytest.mark.parametrize("known_schema", [False, True]) +def test_function_rewiring_arity_error_includes_node_and_schemas( + known_schema: bool, +) -> None: + """Report the current and proposed inputs without fetching an unknown schema.""" + before = _raw(2, False) + feed = _PollingFeed(None) + after = ( + ArrowTableStream(pa.table({"id": [1], "new_value": [5]}), tag_columns=["id"]) + if known_schema + else PollingSource(feed, ["id", "group"], record_id_columns="id") + ) + _ = before.output_schema(columns=_SYSTEM_TAGS) + if known_schema: + _ = after.output_schema(columns=_SYSTEM_TAGS) + pod = _total.pod + assert isinstance(pod, FunctionPod) + node = FunctionNode(pod, before, label="named") + + with pytest.raises( + ValueError, + match=r"'named'.*different upstream count.*current schemas.*'x'.*replacement schemas", + ) as error: + node.upstreams = (before, after) + + replacement_schema = str(error.value).split("replacement schemas", 1)[1] + assert ("new_value" if known_schema else "unavailable") in replacement_schema + assert node.upstreams == (before,) + assert (feed.polls, feed.fetches) == (0, 0) + + +@pytest.mark.parametrize("wrong_arity", [False, True]) +def test_rewiring_loaded_function_blueprint(tmp_path: Path, wrong_arity: bool) -> None: + """A loaded function accepts one upstream on every assignment, as on main.""" + source = DictSource( + [{"id": 1, "group": "a", "x": 2, "y": 5}], + tag_columns=["id", "group"], + tag_only_columns=True, + ) + pipeline = Pipeline(name="rewire") + with pipeline: + _ = _total.pod(source, label="total") + path = tmp_path / "pipeline.json" + pipeline.save(path) + loaded = Pipeline.load(path) + node = loaded.nodes["total"] + assert isinstance(node, FunctionNode) + original = node.upstreams + (predecessor,) = loaded.dag.predecessors(node) + assert predecessor.output_schema(columns=_SYSTEM_TAGS) == source.output_schema( + columns=_SYSTEM_TAGS + ) + + if wrong_arity: + with pytest.raises(ValueError, match="FunctionPod can only have one upstream"): + node.upstreams = () + assert node.upstreams == original + else: + node.upstreams = (source,) + assert node.upstreams[0] is source + different = DictSource( + [{"id": 1, "group": "a", "x": "two", "y": 5}], + tag_columns=["id", "group"], + tag_only_columns=True, + ) + node.upstreams = (different,) + assert node.upstreams[0] is different + + +def test_rewiring_loaded_operator_blueprint(tmp_path: Path) -> None: + """A loaded Index accepts both initial and subsequent assignments as on main.""" + source = DictSource( + [{"id": 1, "group": "a", "x": [2], "y": 5}], + tag_columns=["id", "group"], + tag_only_columns=True, + ) + pipeline = Pipeline(name="rewire") + with pipeline: + _ = Index("x", 0)(source, label="index") + path = tmp_path / "pipeline.json" + pipeline.save(path) + loaded = Pipeline.load(path) + node = loaded.nodes["index"] + assert isinstance(node, OperatorNode) + (predecessor,) = loaded.dag.predecessors(node) + assert node.upstreams == () + schema = node.output_schema() + + node.upstreams = (predecessor,) + + assert node.upstreams[0] is predecessor + assert node.output_schema() == schema + different = DictSource( + [{"id": 1, "group": "a", "x": [2], "y": "five"}], + tag_columns=["id", "group"], + tag_only_columns=True, + ) + + node.upstreams = (different,) + + assert node.upstreams[0] is different + assert node.output_schema() == schema + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("kind", ["operator", "function"]) +@pytest.mark.parametrize("blueprint", [False, True]) +def test_rewiring_raw_stream_ignores_data_meta( + kind: str, reverse: bool, blueprint: bool +) -> None: + """A raw stream's data meta columns do not restrict a replacement.""" + before = _raw(4, reverse, note=8 if kind == "operator" else None) + after = _raw(14, not reverse, note="replacement" if reverse else 18) + _ = before.output_schema(columns=_SYSTEM_TAGS) + _ = after.output_schema(columns=_SYSTEM_TAGS) + if kind == "operator": + node_class = OperatorNode if blueprint else OperatorJobNode + node = node_class(MapData({"x": "xx", "y": "yy"}), (before,), label="step") + expected = {"id": 1, "group": "a", "xx": 14, "yy": 5} + else: + pod = _total.pod + assert isinstance(pod, FunctionPod) + if blueprint: + node = FunctionNode(pod, before, label="step") + else: + node = FunctionJobNode( + pod, before, label="step", pipeline_database=InMemoryArrowDatabase() + ) + expected = {"id": 1, "group": "a", "total": 19} + + node.upstreams = (after,) + + assert node.upstreams == (after,) + tag, data = node.output_schema() + assert set(tag) | set(data) == set(expected) + if isinstance(node, (OperatorJobNode, FunctionJobNode)): + node.run() + assert node.as_table().to_pylist() == [expected] + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_rewiring_accepts_undeclared_system_tag_arrow_width(reverse: bool) -> None: + """The declared schema does not expose a system-tag field's Arrow width.""" + before = _raw(4, reverse, system_type=pa.int32()) + after = _raw(14, not reverse, system_type=pa.int64()) + assert before.output_schema(columns=_SYSTEM_TAGS) == after.output_schema( + columns=_SYSTEM_TAGS + ) + node = OperatorJobNode(MapData({"x": "xx", "y": "yy"}), (before,), label="step") + assert ( + before.as_table(columns=_SYSTEM_TAGS).schema.field("_tag_custom_id").type + == pa.int32() + ) + assert ( + after.as_table(columns=_SYSTEM_TAGS).schema.field("_tag_custom_id").type + == pa.int64() + ) + + node.upstreams = (after,) + + assert node.upstreams[0] is after + _ = node.run() + assert node.as_table().column("xx").to_pylist() == [14] + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize( + "orchestrator", [None, SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +) +def test_rewiring_join_accepts_permuted_operands( + orchestrator: type[SyncPipelineOrchestrator] + | type[AsyncPipelineOrchestrator] + | None, + reverse: bool, +) -> None: + """Swapping the same operands preserves the prediction, identity and stored rows.""" + tags = [("id", 1), ("group", "a")] + rows = [[*tags, ("x", 4), ("y", 5)], [*tags, ("q", 8), ("z", 9)]] + if reverse: + rows = [list(reversed(row)) for row in reversed(rows)] + tags.reverse() + sources = [ + DictSource( + [dict(row)], + tag_columns=[name for name, _ in tags], + tag_only_columns=True, + ) + for row in rows + ] + db = InMemoryArrowDatabase() + pipeline = ( + Pipeline(name="rewire") + if orchestrator is None + else PipelineJob(name="rewire", database=db) + ) + with pipeline: + _ = Join()(*sources, label="join") + node = pipeline.nodes["join"] + assert isinstance(node, (OperatorNode, OperatorJobNode)) + if isinstance(node, OperatorJobNode): + node.attach_databases(db, CacheMode.LOG) + replacements = tuple(reversed(node.upstreams)) + schema = node.output_schema(columns=_SYSTEM_TAGS) + pipeline_hash = node.pipeline_hash() + path = node.node_identity_path if isinstance(node, OperatorJobNode) else None + + node.upstreams = replacements + + assert all( + old is new for old, new in zip(node.upstreams, replacements, strict=True) + ) + assert node.output_schema(columns=_SYSTEM_TAGS) == schema + assert node.pipeline_hash() == pipeline_hash + if orchestrator is not None: + assert isinstance(pipeline, PipelineJob) + assert isinstance(node, OperatorJobNode) + assert node.node_identity_path == path + assert pipeline.run(orchestrator=orchestrator()).ok + assert node.as_source().as_table().to_pylist() == [ + {"id": 1, "group": "a", "x": 4, "y": 5, "q": 8, "z": 9} + ] + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_rewiring_join_accepts_permutation_with_replacement(reverse: bool) -> None: + """A permuted LOG Join writes the replacement's rows at the expected path.""" + tags = [("id", 1), ("group", "a")] + if reverse: + tags.reverse() + + def source(name: str, columns: tuple[str, str], value: int) -> DictSource: + row = [*tags, *((column, value) for column in columns)] + return DictSource( + [dict(reversed(row) if reverse else row)], + tag_columns=[key for key, _ in tags], + tag_only_columns=True, + source_id=name, + ) + + left = source("left", ("x", "y"), 2) + replacement = source("replacement", ("x", "y"), 20) + right = source("right", ("q", "z"), 3) + db = InMemoryArrowDatabase() + node = OperatorJobNode( + Join(), + (left, right), + label="join", + pipeline_database=db, + cache_mode=CacheMode.LOG, + ) + fresh = OperatorJobNode(Join(), (right, replacement), label="fresh") + path = node.node_identity_path + schema = node.output_schema(columns=_SYSTEM_TAGS) + assert schema == fresh.output_schema(columns=_SYSTEM_TAGS) + assert node.pipeline_hash() == fresh.pipeline_hash() + + node.upstreams = (right, replacement) + + assert node.upstreams[0] is right + assert node.upstreams[1] is replacement + assert node.output_schema(columns=_SYSTEM_TAGS) == schema + assert node.pipeline_hash() == fresh.pipeline_hash() + assert node.node_identity_path == fresh.node_identity_path == path + node.run() + assert db.get_table_schema(path + (OPERATOR_DB_SCHEMA_VERSION,)) is not None + assert node.as_source().as_table().to_pylist() == [ + {"id": 1, "group": "a", "x": 20, "y": 20, "q": 3, "z": 3} + ] + + +def test_rewiring_join_permutation_does_not_hash_nested_raw_rows( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A cold nested Join's pipeline hash can require hashing the raw input rows.""" + + def inner(value: int) -> OperatorNode: + left = ArrowTableStream( + pa.table({"id": [1], "group": ["a"], "x": [value], "y": [2]}), + tag_columns=["id", "group"], + ) + right = ArrowTableStream( + pa.table({"id": [1], "group": ["a"], "q": [3], "z": [4]}), + tag_columns=["id", "group"], + ) + return OperatorNode(Join(), (left, right), label="inner") + + original = inner(1) + replacement = inner(20) + right = DictSource( + [{"id": 1, "group": "a", "r": 8, "s": 9}], + tag_columns=["id", "group"], + tag_only_columns=True, + ) + node = OperatorNode(Join(), (original, right), label="outer") + + def require_no_rows(self: ArrowTableStream) -> pa.Table: + raise AssertionError("The setter hashed raw input rows") + + monkeypatch.setattr(ArrowTableStream, "_identity_table", require_no_rows) + node.upstreams = (right, replacement) + + assert node.upstreams[0] is right + assert node.upstreams[1] is replacement + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +) +def test_refused_multi_input_rewire_preserves_job_output( + orchestrator: type[SyncPipelineOrchestrator] | type[AsyncPipelineOrchestrator], + reverse: bool, +) -> None: + """A refusal leaves both real job paths able to write the original output.""" + tags = [("id", 1), ("group", "a")] + rows = [[*tags, ("x", 4), ("y", 5)], [*tags, ("q", 8), ("z", 9)]] + if reverse: + rows = [list(reversed(row)) for row in reversed(rows)] + tags.reverse() + sources = [ + DictSource( + [dict(row)], + tag_columns=[name for name, _ in tags], + tag_only_columns=["id"] if reverse else True, + source_id=f"src_{index}", + ) + for index, row in enumerate(rows) + ] + db = InMemoryArrowDatabase() + job = PipelineJob(name="rewire", database=db) + with job: + joined = Join()(*sources, label="join") + mapped_columns = [("x", "xx"), ("q", "qq")] + if reverse: + mapped_columns.reverse() + MapData(dict(mapped_columns))(joined, label="mapped") + node, downstream = job.nodes["join"], job.nodes["mapped"] + assert isinstance(node, OperatorJobNode) + assert isinstance(downstream, OperatorJobNode) + downstream.attach_databases(db, CacheMode.LOG) + upstreams = node.upstreams + first_replacement = next( + source + for source in sources + if source.output_schema() == upstreams[0].output_schema() + ) + assert first_replacement is not upstreams[0] + schema = downstream.output_schema(columns=_SYSTEM_TAGS) + pipeline_hash = downstream.pipeline_hash() + path = downstream.node_identity_path + + with pytest.raises(ValueError, match=r"'join'.*different schema multiset"): + node.upstreams = (first_replacement, upstreams[0]) + + assert node.upstreams is upstreams + assert downstream.output_schema(columns=_SYSTEM_TAGS) is schema + assert downstream.pipeline_hash() == pipeline_hash + assert downstream.node_identity_path == path + assert job.run(orchestrator=orchestrator()).ok + expected = {"id": 1, "group": "a", "xx": 4, "y": 5, "qq": 8, "z": 9} + assert downstream.as_table().to_pylist() == [expected] + stored = db.get_table_schema(path + (OPERATOR_DB_SCHEMA_VERSION,)) + assert stored is not None + assert set(expected) <= set(stored.names) + assert downstream.as_source().as_table().to_pylist() == [expected] + + +def test_rewiring_refuses_a_different_input_count() -> None: + """Adding a Join input adds a system-tag pair even if its user schema matches.""" + sources = tuple( + DictSource( + [{"id": 1, "group": "a"}], + tag_columns=["id", "group"], + tag_only_columns=False, + source_id=name, + ) + for name in ("left", "right") + ) + for source in sources: + _ = source.output_schema(columns=_SYSTEM_TAGS) + node = OperatorJobNode(Join(), sources[:1], label="step") + original = node.upstreams + + with pytest.raises(ValueError, match="'step'.*different upstream count"): + node.upstreams = sources + + assert node.upstreams is original + + +def test_rewiring_join_accepts_permuted_filter_replacement() -> None: + """A same-schema Filter can replace either position of a permuted Join.""" + left = DictSource( + [{"id": 1, "group": "a", "x": 1, "y": 2}], + tag_columns=["id", "group"], + tag_only_columns=True, + ) + right = DictSource( + [{"id": 1, "group": "a", "q": 3, "z": 4}], + tag_columns=["id", "group"], + tag_only_columns=True, + ) + job = PipelineJob(name="filter") + with job: + _ = left.filter(id=1, label="filtered") + filtered = job.nodes["filtered"] + assert isinstance(filtered, OperatorJobNode) + assert left.output_schema(columns=_SYSTEM_TAGS) == filtered.output_schema( + columns=_SYSTEM_TAGS + ) + + schemas: list[tuple[Schema, Schema]] = [] + rows: list[list[dict[str, object]]] = [] + for replacements in ((filtered, right), (right, filtered)): + node = OperatorJobNode( + Join(), + (left, right), + label="join", + pipeline_database=InMemoryArrowDatabase(), + cache_mode=CacheMode.LOG, + ) + node.upstreams = replacements + _ = node.run() + schemas.append(node.output_schema(columns=_SYSTEM_TAGS)) + rows.append(node.as_table().to_pylist()) + + assert schemas[0] == schemas[1] + assert ( + rows[0] == rows[1] == [{"id": 1, "group": "a", "x": 1, "y": 2, "q": 3, "z": 4}] + ) + + +def test_rewiring_below_cold_merge_join_does_not_read_arrow_rows( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Typing a replacement cannot run a MergeJoin or hash its nested raw inputs.""" + + def merge(value: int) -> OperatorNode: + left = _raw(value, False) + right = ArrowTableStream( + pa.table({"id": [1], "group": ["a"], "q": [3], "z": [4]}), + tag_columns=["id", "group"], + ) + inner = OperatorNode(Join(), (left, right), label="inner") + last = ArrowTableStream( + pa.table({"id": [1], "group": ["a"], "h": [8], "k": [9]}), + tag_columns=["id", "group"], + ) + return OperatorNode(MergeJoin(), (inner, last), label="middle") + + node = OperatorNode(MapData({"x": "xx"}), (merge(1),), label="map") + replacement = merge(20) + + def require_no_hash(self: ArrowTableStream) -> pa.Table: + raise AssertionError("The setter hashed raw input rows") + + def require_no_table(self: ArrowTableStream, **columns: object) -> pa.Table: + raise AssertionError("The setter materialized an Arrow table") + + monkeypatch.setattr(ArrowTableStream, "_identity_table", require_no_hash) + monkeypatch.setattr(ArrowTableStream, "as_table", require_no_table) + node.upstreams = (replacement,) + + assert node.upstreams[0] is replacement + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("refused", [False, True]) +def test_rewiring_probe_does_not_memoize_upstream_schema( + reverse: bool, refused: bool +) -> None: + """An assignment cannot warm a schema prediction on an upstream Filter.""" + left_data = [("id", 1), ("group", "a"), ("x", 4), ("y", 5)] + right_data = [("id", 1), ("group", "a"), ("q", 8), ("z", 9)] + tags = ["group", "id"] if reverse else ["id", "group"] + left = DictSource( + [dict(reversed(left_data) if reverse else left_data)], + tag_columns=tags, + tag_only_columns=True, + source_id="left", + ) + right = DictSource( + [dict(reversed(right_data) if reverse else right_data)], + tag_columns=tags, + tag_only_columns=True, + source_id="right", + ) + with PipelineJob(name="cold_schemas") as job: + semi = SemiJoin()(left, right, label="semi") + middle = semi.filter(id=1, label="middle") + _ = middle.filter(id=1, label="tail") + + semi = job.nodes["semi"] + middle = job.nodes["middle"] + tail = job.nodes["tail"] + assert isinstance(semi, OperatorJobNode) + assert isinstance(middle, OperatorJobNode) + assert isinstance(tail, OperatorJobNode) + original = tail.upstreams + if refused: + with pytest.raises(ValueError, match="different schema"): + tail.upstreams = (right,) + assert tail.upstreams is original + else: + tail.upstreams = original + + semi.upstreams = tuple(reversed(semi.upstreams)) + + assert set(semi.output_schema(columns=_SYSTEM_TAGS)[1]) == {"q", "z"} + assert set(middle.output_schema(columns=_SYSTEM_TAGS)[1]) == {"q", "z"} + with pytest.raises(ValueError, match="different schema"): + tail.upstreams = (left,) + assert tail.upstreams is original + tail.upstreams = (right,) + assert tail.upstreams[0] is right + + +def _tag_by_rewire_sources(reverse: bool) -> tuple[DictSource, DictSource]: + """Build two tagged sources with disjoint data columns.""" + left_items = [("id", 1), ("group", "a"), ("x", 4), ("y", 5)] + right_items = [("id", 1), ("group", "a"), ("q", 8), ("z", 9)] + tags = ["group", "id"] if reverse else ["id", "group"] + left = DictSource( + [dict(reversed(left_items) if reverse else left_items)], + tag_columns=tags, + tag_only_columns=True, + source_id="left", + ) + right = DictSource( + [dict(reversed(right_items) if reverse else right_items)], + tag_columns=tags, + tag_only_columns=True, + source_id="right", + ) + return left, right + + +@pytest.mark.parametrize("kind", ["filter", "function"]) +def test_rewiring_repairs_tail_below_a_stale_tag_by(kind: str) -> None: + """A stale TagBy prediction cannot block a repair that runs successfully.""" + left, right = _tag_by_rewire_sources(False) + with PipelineJob(name="repair") as job: + semi = SemiJoin()(left, right, label="semi") + tagged = semi.tag_by("x", label="tagged") + if kind == "filter": + _ = tagged.filter(id=1, label="tail") + else: + _ = _total.pod(tagged, strict_columns=True, label="tail") + _ = left.tag_by("x", label="replacement") + + semi = job.nodes["semi"] + tail = job.nodes["tail"] + replacement = job.nodes["replacement"] + assert isinstance(semi, OperatorJobNode) + assert isinstance(tail, (OperatorJobNode, FunctionJobNode)) + semi.upstreams = tuple(reversed(semi.upstreams)) + assert set(semi.output_schema()[1]) == {"q", "z"} + + tail.upstreams = (replacement,) + + assert tail.upstreams == (replacement,) + if kind == "filter": + assert set(tail.output_schema()[1]) == {"x", "y"} + assert tail.run().table.to_pylist() == [{"id": 1, "group": "a", "x": 4, "y": 5}] + else: + assert set(tail.output_schema()[1]) == {"total"} + assert tail.run().table.to_pylist() == [ + {"id": 1, "group": "a", "x": 4, "total": 9} + ] + + +@pytest.mark.parametrize("kind", ["unary", "binary", "variadic"]) +@pytest.mark.parametrize("reverse", [False, True]) +def test_rewiring_operator_matches_main_when_schema_read_fails( + kind: str, reverse: bool +) -> None: + """Main accepts assignment with an unreadable old or replacement declaration.""" + left, right = _tag_by_rewire_sources(reverse) + with PipelineJob(name="unavailable_operator_schema") as job: + semi = SemiJoin()(left, right, label="semi") + tagged = semi.tag_by("x", label="tagged") + if kind == "unary": + _ = tagged.filter(id=1, label="tail") + elif kind == "binary": + _ = SemiJoin()(tagged, right, label="tail") + else: + _ = Join()(tagged, right, label="tail") + _ = left.tag_by("x", label="replacement") + + semi = job.nodes["semi"] + tail = job.nodes["tail"] + replacement = job.nodes["replacement"] + assert isinstance(semi, OperatorJobNode) + assert isinstance(tail, OperatorJobNode) + original = tail.upstreams + repaired = (replacement, *original[1:]) + semi.upstreams = tuple(reversed(semi.upstreams)) + + tail.upstreams = repaired + assert tail.upstreams == repaired + + tail.upstreams = original + assert tail.upstreams == original + + +@pytest.mark.parametrize("swapped", [False, True]) +def test_rewiring_with_an_unavailable_schema_skips_the_whole_comparison( + swapped: bool, +) -> None: + """An unpolled operand makes the multiset unavailable in either order.""" + before = _raw(2, False) + bad = ArrowTableStream( + pa.table({"id": [1], "group": ["a"], "x": ["four"], "y": [5]}), + tag_columns=["id", "group"], + ) + feed = _PollingFeed(4) + opaque = PollingSource(feed, ["id", "group"], record_id_columns="id") + right = DictSource( + [{"id": 1, "group": "a", "q": 3, "z": 4}], + tag_columns=["id", "group"], + tag_only_columns=True, + ) + node = OperatorNode(Join(), (before, right), label="join") + node.upstreams = (before, opaque) + replacements = (opaque, bad) if swapped else (bad, opaque) + + node.upstreams = replacements + + assert node.upstreams is replacements + assert (feed.polls, feed.fetches) == (0, 0) + + node.upstreams = (opaque,) + + assert node.upstreams[0] is opaque + assert (feed.polls, feed.fetches) == (0, 0) + + +def test_rewiring_only_requests_declared_output_schemas( + caplog: pytest.LogCaptureFixture, +) -> None: + """Only the schema read is attempted, and assignment never converts Arrow types.""" + current = _raw(2, False) + compatible = _raw(4, True) + incompatible = ArrowTableStream( + pa.table({"id": [1], "group": ["a"], "x": ["four"], "y": [5]}), + tag_columns=["id", "group"], + ) + cold = ArrowTableStream( + pa.table( + { + "id": [1], + "group": ["a"], + "x": [4], + "y": [5], + "__note": pa.array([0], type=pa.duration("ms")), + } + ), + tag_columns=["id", "group"], + ) + for stream in (current, compatible, incompatible): + _ = stream.output_schema(columns=_SYSTEM_TAGS) + + converter = current.data_context.type_converter + for replacement, refused in ( + (compatible, False), + (incompatible, True), + (cold, False), + ): + old_spy = MagicMock(spec_set=StreamProtocol, wraps=current) + new_spy = MagicMock(spec_set=StreamProtocol, wraps=replacement) + original = (cast(StreamProtocol, old_spy),) + proposed = (cast(StreamProtocol, new_spy),) + node = OperatorNode(MapData({"x": "xx"}), original, label="step") + old_spy.reset_mock() + with ( + caplog.at_level("DEBUG"), + patch.object( + converter, + "arrow_schema_to_python_schema", + wraps=converter.arrow_schema_to_python_schema, + ) as convert, + ): + caplog.clear() + if refused: + with pytest.raises(ValueError, match="different schema multiset"): + node.upstreams = proposed + else: + node.upstreams = proposed + + convert.assert_not_called() + assert not caplog.records + assert node.upstreams is (original if refused else proposed) + for spy in (old_spy, new_spy): + assert spy.mock_calls == [ + call.output_schema(columns=ColumnConfig(system_tags=True)) + ]