From d207369937f75f27d05b57d49d52764845940f83 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:36:16 -0800 Subject: [PATCH 01/12] fix(nodes)!: refuse upstream reassignment across schemas Fixes ITL-1125 BREAKING CHANGE: operator and function node upstreams require matching input schemas. --- changelog.d/ITL-1125.md | 5 + docs/dev/design_issues/ITL-1111-GW1.md | 12 +- docs/dev/design_issues/ITL-1125-USC1.md | 15 +++ src/orcapod/core/nodes/function_node.py | 7 + src/orcapod/core/nodes/operator_node.py | 9 +- src/orcapod/core/nodes/upstream_schema.py | 56 ++++++++ .../operators/test_index_pick_arrow_types.py | 17 +-- .../operators/test_semijoin_tag_keys.py | 38 ++---- tests/test_pipeline/test_graph_walk_cost.py | 127 ++++++++++++++---- 9 files changed, 212 insertions(+), 74 deletions(-) create mode 100644 changelog.d/ITL-1125.md create mode 100644 docs/dev/design_issues/ITL-1125-USC1.md create mode 100644 src/orcapod/core/nodes/upstream_schema.py diff --git a/changelog.d/ITL-1125.md b/changelog.d/ITL-1125.md new file mode 100644 index 000000000..e509235e3 --- /dev/null +++ b/changelog.d/ITL-1125.md @@ -0,0 +1,5 @@ +### Breaking changes and migration + +- Assigning `upstreams` on an operator or function node now requires each replacement + to preserve the existing tag and data schemas, including field nullability. Build a + new pipeline when the inputs have different schemas. diff --git a/docs/dev/design_issues/ITL-1111-GW1.md b/docs/dev/design_issues/ITL-1111-GW1.md index 7746e42a2..103b66972 100644 --- a/docs/dev/design_issues/ITL-1111-GW1.md +++ b/docs/dev/design_issues/ITL-1111-GW1.md @@ -25,12 +25,8 @@ 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 now refuses a replacement with another schema (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..9d8a551a6 --- /dev/null +++ b/docs/dev/design_issues/ITL-1125-USC1.md @@ -0,0 +1,15 @@ +## `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:** Operator and function node setters check the existing and replacement input +schemas before changing the wiring or clearing the schema memo. The comparison checks +tag and data roles, equivalent Python types, and canonical Arrow field types and nullable +flags. Replacements with matching schemas remain supported. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 9809760af..44e85f535 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -34,6 +34,7 @@ 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.function_pod import ( fall_through_tags, function_input, @@ -554,8 +555,14 @@ def upstreams(self) -> tuple[StreamProtocol, ...]: @upstreams.setter def upstreams(self, value: tuple[StreamProtocol, ...]) -> None: + """Replace the node's input with one of the same schema. + + Raises: + ValueError: If there is not exactly one input or its schema differs. + """ if len(value) != 1: raise ValueError("FunctionPod can only have one upstream") + require_same_upstream_schemas(self, value) self._input_stream = value[0] self._forget_output_schema() diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 4f4632f3d..2862aee3e 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -30,6 +30,7 @@ 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.data_tags import ( mark_data_tags, data_tag_names, @@ -363,15 +364,17 @@ def cache_mode(self) -> CacheMode: @upstreams.setter def upstreams(self, value: tuple[StreamProtocol, ...]) -> None: - """Replace the node's inputs. + """Replace the node's inputs with inputs of the same schemas. Raises: - ValueError: If the node caches (``LOG`` or ``REPLAY``) and a source - feeding ``value`` is restricted (ITL-1218); nothing changes. + ValueError: If the input count or a schema differs, 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) + require_same_upstream_schemas(self, value) self._input_streams = value self._forget_output_schema() diff --git a/src/orcapod/core/nodes/upstream_schema.py b/src/orcapod/core/nodes/upstream_schema.py new file mode 100644 index 000000000..89d67f337 --- /dev/null +++ b/src/orcapod/core/nodes/upstream_schema.py @@ -0,0 +1,56 @@ +"""Schema validation for node upstream setters.""" + +from orcapod.core.streams.base import StreamBase, typed_arrow_schemas +from orcapod.logical_types.user_class_identity import equivalent_hints +from orcapod.protocols.core_protocols import StreamProtocol + + +def require_same_upstream_schemas( + node: StreamBase, replacements: tuple[StreamProtocol, ...] +) -> None: + """Require each replacement to preserve the schema of its input position. + + Args: + node: The wired node. + replacements: The proposed upstreams, in input order. + + Raises: + ValueError: If the upstream count or a tag or data schema changes. + """ + upstreams = node.upstreams + if len(upstreams) != len(replacements): + current = tuple(stream.output_schema() for stream in upstreams) + proposed = tuple(stream.output_schema() for stream in replacements) + raise ValueError( + f"Cannot rewire node {node.label!r} with a different upstream count: " + + f"current schemas {current!r}, replacement schemas {proposed!r}" + ) + + for index, (upstream, replacement) in enumerate(zip(upstreams, replacements)): + if upstream is replacement: + continue + current = upstream.output_schema() + proposed = replacement.output_schema() + if any( + old.keys() != new.keys() + or any(not equivalent_hints(old[name], new[name]) for name in old) + for old, new in zip(current, proposed) + ): + raise ValueError( + f"Cannot rewire node {node.label!r}: upstream {index} has a different " + + f"schema: current (tag={current[0]!r}, data={current[1]!r}), " + + f"replacement (tag={proposed[0]!r}, data={proposed[1]!r})" + ) + + current_arrow = typed_arrow_schemas(upstream) + proposed_arrow = typed_arrow_schemas(replacement) + hasher = node.data_context.arrow_hasher + if any( + hasher.hash_schema(old) != hasher.hash_schema(new) + for old, new in zip(current_arrow, proposed_arrow) + ): + raise ValueError( + f"Cannot rewire node {node.label!r}: upstream {index} has a different " + + f"Arrow schema: current (tag={current_arrow[0]}, data={current_arrow[1]}), " + + f"replacement (tag={proposed_arrow[0]}, data={proposed_arrow[1]})" + ) 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..fa8808577 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,12 @@ 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] + with pytest.raises(ValueError, match=r"'step'.*upstream 1.*'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..e15a184d6 100644 --- a/tests/test_pipeline/test_graph_walk_cost.py +++ b/tests/test_pipeline/test_graph_walk_cost.py @@ -26,10 +26,12 @@ 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.sources import ArrowTableSource, DictSource from orcapod.core.streams.base import StreamBase from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import InputValidationError, SourceSpecMismatchError @@ -574,21 +576,59 @@ 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 + + with pytest.raises(ValueError, match="'renamed'") as error: + node.upstreams = (other,) + + for original, replacement in zip( + upstreams[0].output_schema(), other.output_schema() + ): + 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 +636,52 @@ def test_setting_a_function_nodes_upstreams_changes_its_schema(self) -> None: source_id="other", ) - node.upstreams = (other,) + with pytest.raises(ValueError, match="'plus_one'"): + node.upstreams = (other,) + + assert node.upstreams[0] is before + assert node.output_schema()[0]["id"] is int - assert node.output_schema()[0]["id"] is str + def test_rewiring_refuses_a_different_arrow_type_for_the_same_python_type( + self, + ) -> None: + """A change of integer width is also a change of input 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() + + with pytest.raises(ValueError, match=r"(?s)'renamed'.*int64.*int32"): + node.upstreams = (other,) - @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." - ), + assert node.upstreams is before + + @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 From 50664a47b1e20ed34c808a45806649836d9995d1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:53:56 -0800 Subject: [PATCH 02/12] fix(nodes): refuse upstream system-tag schema changes Refs ITL-1125 --- changelog.d/ITL-1125.md | 4 +-- docs/dev/design_issues/ITL-1125-USC1.md | 4 +-- src/orcapod/core/nodes/upstream_schema.py | 20 +++++++++++- tests/test_pipeline/test_graph_walk_cost.py | 35 +++++++++++++++++++++ 4 files changed, 58 insertions(+), 5 deletions(-) diff --git a/changelog.d/ITL-1125.md b/changelog.d/ITL-1125.md index e509235e3..6dbd116e7 100644 --- a/changelog.d/ITL-1125.md +++ b/changelog.d/ITL-1125.md @@ -1,5 +1,5 @@ ### Breaking changes and migration - Assigning `upstreams` on an operator or function node now requires each replacement - to preserve the existing tag and data schemas, including field nullability. Build a - new pipeline when the inputs have different schemas. + to preserve the existing tag and data schemas, including field nullability and + system-tag columns. Build a new pipeline when the inputs have different schemas. diff --git a/docs/dev/design_issues/ITL-1125-USC1.md b/docs/dev/design_issues/ITL-1125-USC1.md index 9d8a551a6..a2c7a20fc 100644 --- a/docs/dev/design_issues/ITL-1125-USC1.md +++ b/docs/dev/design_issues/ITL-1125-USC1.md @@ -11,5 +11,5 @@ A stale pipeline hash still names the table for the old schema. **Fix:** Operator and function node setters check the existing and replacement input schemas before changing the wiring or clearing the schema memo. The comparison checks -tag and data roles, equivalent Python types, and canonical Arrow field types and nullable -flags. Replacements with matching schemas remain supported. +tag and data roles, equivalent Python types, canonical Arrow field types and nullable +flags, and the system-tag schema. Replacements with matching schemas remain supported. diff --git a/src/orcapod/core/nodes/upstream_schema.py b/src/orcapod/core/nodes/upstream_schema.py index 89d67f337..40769bf58 100644 --- a/src/orcapod/core/nodes/upstream_schema.py +++ b/src/orcapod/core/nodes/upstream_schema.py @@ -15,7 +15,7 @@ def require_same_upstream_schemas( replacements: The proposed upstreams, in input order. Raises: - ValueError: If the upstream count or a tag or data schema changes. + ValueError: If the upstream count or a tag, data, or system-tag schema changes. """ upstreams = node.upstreams if len(upstreams) != len(replacements): @@ -54,3 +54,21 @@ def require_same_upstream_schemas( + f"Arrow schema: current (tag={current_arrow[0]}, data={current_arrow[1]}), " + f"replacement (tag={proposed_arrow[0]}, data={proposed_arrow[1]})" ) + + columns = {"system_tags": True} + current_system_tags = { + name: hint + for name, hint in upstream.output_schema(columns=columns)[0].items() + if name not in current[0] + } + proposed_system_tags = { + name: hint + for name, hint in replacement.output_schema(columns=columns)[0].items() + if name not in proposed[0] + } + if current_system_tags != proposed_system_tags: + raise ValueError( + f"Cannot rewire node {node.label!r}: upstream {index} has a different " + + f"system-tag schema: current {current_system_tags!r}, " + + f"replacement {proposed_system_tags!r}" + ) diff --git a/tests/test_pipeline/test_graph_walk_cost.py b/tests/test_pipeline/test_graph_walk_cost.py index e15a184d6..a613231a0 100644 --- a/tests/test_pipeline/test_graph_walk_cost.py +++ b/tests/test_pipeline/test_graph_walk_cost.py @@ -31,6 +31,7 @@ from orcapod import PipelineJob, function_pod 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 @@ -669,6 +670,40 @@ def test_rewiring_refuses_a_different_arrow_type_for_the_same_python_type( assert node.upstreams is before + 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.parametrize( ("build_job", "label"), [(_rename_job, "renamed"), (_function_job, "plus_one")] ) From cd69913cdbf01070e08f67075d03a47399376a06 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 05:17:50 -0800 Subject: [PATCH 03/12] fix(nodes): complete upstream schema validation --- changelog.d/ITL-1125.md | 7 +- docs/dev/design_issues/ITL-1125-USC1.md | 5 +- docs/reference/hashing.md | 1 + src/orcapod/core/nodes/upstream_schema.py | 70 ++++++- src/orcapod/core/streams/base.py | 11 +- tests/test_hashing/hash_site_trace.py | 7 + tests/test_pipeline/test_upstream_schema.py | 193 ++++++++++++++++++++ 7 files changed, 282 insertions(+), 12 deletions(-) create mode 100644 tests/test_pipeline/test_upstream_schema.py diff --git a/changelog.d/ITL-1125.md b/changelog.d/ITL-1125.md index 6dbd116e7..609eb55db 100644 --- a/changelog.d/ITL-1125.md +++ b/changelog.d/ITL-1125.md @@ -1,5 +1,6 @@ ### Breaking changes and migration -- Assigning `upstreams` on an operator or function node now requires each replacement - to preserve the existing tag and data schemas, including field nullability and - system-tag columns. Build a new pipeline when the inputs have different schemas. +- Assigning `upstreams` on an operator or function node now requires the same number + of inputs and preserves the tag, data and system-tag schemas at each position, + including Arrow field types and nullability. Data meta columns do not enter the + comparison. Build a new pipeline to change the number or schemas of its inputs. diff --git a/docs/dev/design_issues/ITL-1125-USC1.md b/docs/dev/design_issues/ITL-1125-USC1.md index a2c7a20fc..f92dc2eee 100644 --- a/docs/dev/design_issues/ITL-1125-USC1.md +++ b/docs/dev/design_issues/ITL-1125-USC1.md @@ -11,5 +11,6 @@ A stale pipeline hash still names the table for the old schema. **Fix:** Operator and function node setters check the existing and replacement input schemas before changing the wiring or clearing the schema memo. The comparison checks -tag and data roles, equivalent Python types, canonical Arrow field types and nullable -flags, and the system-tag schema. Replacements with matching schemas remain supported. +input count, tag and data roles, equivalent Python types, and canonical Arrow field +types and nullable flags, including for system tags. Data meta columns are ignored. +Replacements with matching schemas remain supported. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index bd752c850..8c57a63a8 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -404,6 +404,7 @@ A record id is the row identifier (rule 8), built from row positions or key valu | canonical input order (sort by digest). Inputs with equal pipeline hashes (developer decision, November 16, 2026, ITL-1154: kept as it is): system-tag column names follow the stable pipeline-hash sort; each row's values are sorted by (source id, record id) by `sort_system_tag_values`, so the result does not depend on argument order; the operator's identity holds its inputs as a frozenset | `core/operators/join.py:Join.order_input_streams..` | | in-memory identity and repr | `core/base.py:ContentIdentifiableBase.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__eq__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__repr__` | | comparing a stored hash with the computed one; comparing two schema hashes (bind, a stored read, a polled batch); error text | `core/nodes/source_node.py:SourceNodeBase._arrow_type_issue`, `core/sources/derived_source.py:DerivedSource._require_origin_types`, `core/sources/polling_source.py:PollingSource._require_declared_types`, `core/nodes/operator_node.py:OperatorJobNode._read_run_records`, `core/sources/source_proxy.py:SourceProxy.bind`, `core/data_function_proxy.py:DataFunctionProxy.bind`, `pipeline/job.py:PipelineJob.bind`, `errors.py:EphemeralResultMissingError.__init__` | +| comparing tag, data and system-tag schema hashes before upstream reassignment | `core/nodes/upstream_schema.py:require_same_upstream_schemas..`, `core/nodes/upstream_schema.py:require_same_upstream_schemas` | --- diff --git a/src/orcapod/core/nodes/upstream_schema.py b/src/orcapod/core/nodes/upstream_schema.py index 40769bf58..c0e7da9e8 100644 --- a/src/orcapod/core/nodes/upstream_schema.py +++ b/src/orcapod/core/nodes/upstream_schema.py @@ -1,10 +1,33 @@ """Schema validation for node upstream setters.""" -from orcapod.core.streams.base import StreamBase, typed_arrow_schemas +import pyarrow as pa + +from orcapod.core.streams.base import ( + StreamBase, + shared_zero_row_memo, + typed_arrow_schemas, + typed_zero_row_table, +) from orcapod.logical_types.user_class_identity import equivalent_hints from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol +from orcapod.system_constants import constants +from orcapod.types import DataType, Schema +from orcapod.utils.schema_utils import declared_arrow_schema + +def _user_schemas(stream: StreamProtocol) -> tuple[Schema, Schema]: + """Return tag and data schemas without data-only meta fields.""" + tag, data = stream.output_schema() + 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 + +@shared_zero_row_memo() def require_same_upstream_schemas( node: StreamBase, replacements: tuple[StreamProtocol, ...] ) -> None: @@ -29,8 +52,8 @@ def require_same_upstream_schemas( for index, (upstream, replacement) in enumerate(zip(upstreams, replacements)): if upstream is replacement: continue - current = upstream.output_schema() - proposed = replacement.output_schema() + current = _user_schemas(upstream) + proposed = _user_schemas(replacement) if any( old.keys() != new.keys() or any(not equivalent_hints(old[name], new[name]) for name in old) @@ -42,8 +65,10 @@ def require_same_upstream_schemas( + f"replacement (tag={proposed[0]!r}, data={proposed[1]!r})" ) - current_arrow = typed_arrow_schemas(upstream) - proposed_arrow = typed_arrow_schemas(replacement) + current_arrow = typed_arrow_schemas(upstream, data_fields=tuple(current[1])) + proposed_arrow = typed_arrow_schemas( + replacement, data_fields=tuple(proposed[1]) + ) hasher = node.data_context.arrow_hasher if any( hasher.hash_schema(old) != hasher.hash_schema(new) @@ -72,3 +97,38 @@ def require_same_upstream_schemas( + f"system-tag schema: current {current_system_tags!r}, " + f"replacement {proposed_system_tags!r}" ) + if current_system_tags: + converter = node.data_context.type_converter + old_system_arrow = _system_tag_arrow_schema( + typed_zero_row_table(upstream), current_system_tags, converter + ) + new_system_arrow = _system_tag_arrow_schema( + typed_zero_row_table(replacement), proposed_system_tags, converter + ) + if hasher.hash_schema(old_system_arrow) != hasher.hash_schema( + new_system_arrow + ): + raise ValueError( + f"Cannot rewire node {node.label!r}: upstream {index} has a different " + + f"system-tag Arrow schema: current {old_system_arrow}, " + + f"replacement {new_system_arrow}" + ) + + +def _system_tag_arrow_schema( + table: pa.Table | None, + system_tags: dict[str, DataType], + converter: TypeConverterProtocol, +) -> pa.Schema: + """Use the system-tag Arrow fields when known, or their declared types.""" + if table is None: + return declared_arrow_schema(system_tags, converter) + schema = table.schema + available = set(schema.names) + missing = { + name: hint for name, hint in system_tags.items() if name not in available + } + fields = [schema.field(name) for name in system_tags if name in available] + if missing: + fields.extend(declared_arrow_schema(missing, converter)) + return pa.schema(fields) diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 9f8b731f7..6324fad85 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -595,7 +595,7 @@ def opened_on(self) -> StreamProtocol | None: def typed_arrow_schemas( - stream: object, *, own: bool = True + stream: object, *, own: bool = True, data_fields: Sequence[str] | None = None ) -> tuple[pa.Schema, pa.Schema]: """Return the Arrow schemas of ``stream``'s tag and data columns (ITL-640). @@ -614,6 +614,8 @@ def typed_arrow_schemas( stream: The stream, source or node. own: Whether to return the ``arrow_schemas`` the stream states, when it has them; ``False`` derives them (the stream's own derivation). + data_fields: The data fields to select, if comparing only part of the + advertised data schema. Returns: The tag and data Arrow schemas. @@ -621,11 +623,16 @@ def typed_arrow_schemas( if own: stated = getattr(stream, "arrow_schemas", None) if isinstance(stated, tuple): - return cast("tuple[pa.Schema, pa.Schema]", stated) + tag_arrow, data_arrow = cast("tuple[pa.Schema, pa.Schema]", stated) + if data_fields is not None: + data_arrow = pa.schema([data_arrow.field(name) for name in data_fields]) + return tag_arrow, data_arrow typed = cast(StreamProtocol, stream) # The columns are those of the Python output schema, which the identity has always # named; only their types come from the zero-row table. tag_schema, data_schema = typed.output_schema() + if data_fields is not None: + data_schema = data_schema.select(*data_fields) table = typed_zero_row_table(stream) if table is None: from orcapod.utils.schema_utils import declared_arrow_schema diff --git a/tests/test_hashing/hash_site_trace.py b/tests/test_hashing/hash_site_trace.py index 6d83ffe04..91ec92f51 100644 --- a/tests/test_hashing/hash_site_trace.py +++ b/tests/test_hashing/hash_site_trace.py @@ -259,9 +259,16 @@ def run_scenario() -> None: warnings.filterwarnings("ignore") import orcapod as op from orcapod.contexts import get_default_context + from orcapod.core.nodes import OperatorNode + from orcapod.core.operators import MapData + from orcapod.core.sources import DictSource from tests.test_hashing.golden import cases _ = cases.compute_all() + source = DictSource([{"x": 1, "y": 2}]) + replacement = DictSource([{"y": 3, "x": 4}]) + node = OperatorNode(MapData({"x": "xx", "y": "yy"}), (source,)) + node.upstreams = (replacement,) hasher = get_default_context().semantic_hasher with tempfile.TemporaryDirectory() as tmp: root = _Path(tmp) diff --git a/tests/test_pipeline/test_upstream_schema.py b/tests/test_pipeline/test_upstream_schema.py new file mode 100644 index 000000000..a565aec35 --- /dev/null +++ b/tests/test_pipeline/test_upstream_schema.py @@ -0,0 +1,193 @@ +"""The upstream setters preserve the schemas of a wired node (ITL-1125).""" + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.function_pod import FunctionPod +from orcapod.core.nodes import ( + FunctionJobNode, + FunctionNode, + OperatorJobNode, + OperatorNode, +) +from orcapod.core.operators import Join, MapData +from orcapod.core.sources import DictSource +from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.system_constants import OPERATOR_DB_SCHEMA_VERSION +from orcapod.types import CacheMode + +_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 [], + ) + + +@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) + 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_refuses_system_tag_arrow_width(reverse: bool) -> None: + """Equal Python hints can conceal a change to a system-tag Arrow field.""" + 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") + original = node.upstreams + schema = node.output_schema(columns=_SYSTEM_TAGS) + identity = node.node_identity_path + + with pytest.raises(ValueError, match=r"(?s)'step'.*system-tag.*int32.*int64"): + node.upstreams = (after,) + + assert node.upstreams is original + assert node.output_schema(columns=_SYSTEM_TAGS) is schema + assert node.node_identity_path == identity + assert ( + before.as_table(columns=_SYSTEM_TAGS).schema.field("_tag_custom_id").type + == pa.int32() + ) + node.run() + assert node.as_table().column("xx").to_pylist() == [4] + + +@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'.*upstream 1"): + 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") + ) + 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 From 1560d1db46297686f3d7c9bc5ffa42f030979386 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 05:55:41 -0800 Subject: [PATCH 04/12] fix(nodes): validate upstreams without polling sources --- changelog.d/ITL-1125.md | 8 +- docs/dev/design_issues/ITL-1125-USC1.md | 3 +- src/orcapod/core/nodes/function_node.py | 6 +- src/orcapod/core/nodes/operator_node.py | 4 +- src/orcapod/core/nodes/upstream_schema.py | 32 ++++-- tests/test_pipeline/test_upstream_schema.py | 118 +++++++++++++++++++- 6 files changed, 151 insertions(+), 20 deletions(-) diff --git a/changelog.d/ITL-1125.md b/changelog.d/ITL-1125.md index 609eb55db..190890f9d 100644 --- a/changelog.d/ITL-1125.md +++ b/changelog.d/ITL-1125.md @@ -1,6 +1,8 @@ ### Breaking changes and migration - Assigning `upstreams` on an operator or function node now requires the same number - of inputs and preserves the tag, data and system-tag schemas at each position, - including Arrow field types and nullability. Data meta columns do not enter the - comparison. Build a new pipeline to change the number or schemas of its inputs. + of inputs. Where both schemas at a position are known without reading rows, the + setter compares tags, data and system tags, including Arrow field types and + nullability. Data meta columns do not enter the comparison. Assigning an unpolled + source without a declared schema leaves its first fetch to normal data access. + Build a new pipeline to change the number or known schemas of its inputs. diff --git a/docs/dev/design_issues/ITL-1125-USC1.md b/docs/dev/design_issues/ITL-1125-USC1.md index f92dc2eee..05acafc2d 100644 --- a/docs/dev/design_issues/ITL-1125-USC1.md +++ b/docs/dev/design_issues/ITL-1125-USC1.md @@ -13,4 +13,5 @@ A stale pipeline hash still names the table for the old schema. schemas before changing the wiring or clearing the schema memo. The comparison checks input count, tag and data roles, equivalent Python types, and canonical Arrow field types and nullable flags, including for system tags. Data meta columns are ignored. -Replacements with matching schemas remain supported. +Only pairs of schemas available without reading rows are compared. Replacements with +matching schemas remain supported. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 44e85f535..1cf6ea546 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -555,13 +555,11 @@ def upstreams(self) -> tuple[StreamProtocol, ...]: @upstreams.setter def upstreams(self, value: tuple[StreamProtocol, ...]) -> None: - """Replace the node's input with one of the same schema. + """Replace the node's input, preserving its schema when both are known. Raises: - ValueError: If there is not exactly one input or its schema differs. + ValueError: If there is not exactly one input or the known schemas differ. """ - if len(value) != 1: - raise ValueError("FunctionPod can only have one upstream") require_same_upstream_schemas(self, value) self._input_stream = value[0] self._forget_output_schema() diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 2862aee3e..95ffb0cab 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -364,10 +364,10 @@ def cache_mode(self) -> CacheMode: @upstreams.setter def upstreams(self, value: tuple[StreamProtocol, ...]) -> None: - """Replace the node's inputs with inputs of the same schemas. + """Replace the node's inputs, preserving schemas known without reading rows. Raises: - ValueError: If the input count or a schema differs, or if the node + ValueError: If the input count or two known schemas differ, or if the node caches (``LOG`` or ``REPLAY``) and a source feeding ``value`` is restricted (ITL-1218). """ diff --git a/src/orcapod/core/nodes/upstream_schema.py b/src/orcapod/core/nodes/upstream_schema.py index c0e7da9e8..ea3051ffa 100644 --- a/src/orcapod/core/nodes/upstream_schema.py +++ b/src/orcapod/core/nodes/upstream_schema.py @@ -4,6 +4,7 @@ from orcapod.core.streams.base import ( StreamBase, + schema_requires_io, shared_zero_row_memo, typed_arrow_schemas, typed_zero_row_table, @@ -12,9 +13,11 @@ from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol from orcapod.system_constants import constants -from orcapod.types import DataType, Schema +from orcapod.types import ColumnConfig, DataType, Schema from orcapod.utils.schema_utils import declared_arrow_schema +_SCHEMA_COLUMNS = ColumnConfig(system_tags=True) + def _user_schemas(stream: StreamProtocol) -> tuple[Schema, Schema]: """Return tag and data schemas without data-only meta fields.""" @@ -27,23 +30,31 @@ def _user_schemas(stream: StreamProtocol) -> tuple[Schema, Schema]: return tag, data.drop(*meta) if meta else data +def _schema_for_diagnostic(stream: StreamProtocol) -> tuple[Schema, Schema] | str: + """Describe an input schema without reading, computing or polling a row.""" + if schema_requires_io(stream, _SCHEMA_COLUMNS): + return "" + return stream.output_schema(columns=_SCHEMA_COLUMNS) + + @shared_zero_row_memo() def require_same_upstream_schemas( node: StreamBase, replacements: tuple[StreamProtocol, ...] ) -> None: - """Require each replacement to preserve the schema of its input position. + """Require replacements to preserve schemas that are known without reading rows. Args: node: The wired node. replacements: The proposed upstreams, in input order. Raises: - ValueError: If the upstream count or a tag, data, or system-tag schema changes. + ValueError: If the upstream count changes or two known schemas disagree in + tag, data, or system-tag fields. """ upstreams = node.upstreams if len(upstreams) != len(replacements): - current = tuple(stream.output_schema() for stream in upstreams) - proposed = tuple(stream.output_schema() for stream in replacements) + current = tuple(_schema_for_diagnostic(stream) for stream in upstreams) + proposed = tuple(_schema_for_diagnostic(stream) for stream in replacements) raise ValueError( f"Cannot rewire node {node.label!r} with a different upstream count: " + f"current schemas {current!r}, replacement schemas {proposed!r}" @@ -52,6 +63,10 @@ def require_same_upstream_schemas( for index, (upstream, replacement) in enumerate(zip(upstreams, replacements)): if upstream is replacement: continue + if schema_requires_io(upstream, _SCHEMA_COLUMNS) or schema_requires_io( + replacement, _SCHEMA_COLUMNS + ): + continue current = _user_schemas(upstream) proposed = _user_schemas(replacement) if any( @@ -80,15 +95,16 @@ def require_same_upstream_schemas( + f"replacement (tag={proposed_arrow[0]}, data={proposed_arrow[1]})" ) - columns = {"system_tags": True} current_system_tags = { name: hint - for name, hint in upstream.output_schema(columns=columns)[0].items() + for name, hint in upstream.output_schema(columns=_SCHEMA_COLUMNS)[0].items() if name not in current[0] } proposed_system_tags = { name: hint - for name, hint in replacement.output_schema(columns=columns)[0].items() + for name, hint in replacement.output_schema(columns=_SCHEMA_COLUMNS)[ + 0 + ].items() if name not in proposed[0] } if current_system_tags != proposed_system_tags: diff --git a/tests/test_pipeline/test_upstream_schema.py b/tests/test_pipeline/test_upstream_schema.py index a565aec35..5ae0ec7e4 100644 --- a/tests/test_pipeline/test_upstream_schema.py +++ b/tests/test_pipeline/test_upstream_schema.py @@ -12,12 +12,12 @@ OperatorNode, ) from orcapod.core.operators import Join, MapData -from orcapod.core.sources import DictSource +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.system_constants import OPERATOR_DB_SCHEMA_VERSION -from orcapod.types import CacheMode +from orcapod.types import CacheMode, Cursor, Schema _SYSTEM_TAGS = {"system_tags": True} @@ -50,6 +50,120 @@ def _raw( ) +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: + """An unpolled source can still have a schema known at assignment time.""" + 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") + 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("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") + ) + 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("reverse", [False, True]) @pytest.mark.parametrize("kind", ["operator", "function"]) @pytest.mark.parametrize("blueprint", [False, True]) From 137f5deea24c3100aef358bd4df35ba4b17aa9ef Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 07:03:06 -0800 Subject: [PATCH 05/12] fix(nodes): restore Join permutations and loaded function rewires --- changelog.d/ITL-1125.md | 7 +- docs/dev/design_issues/ITL-1125-USC1.md | 8 +- src/orcapod/core/nodes/operator_node.py | 9 +- src/orcapod/core/nodes/upstream_schema.py | 16 ++-- tests/test_pipeline/test_upstream_schema.py | 94 ++++++++++++++++++++- 5 files changed, 121 insertions(+), 13 deletions(-) diff --git a/changelog.d/ITL-1125.md b/changelog.d/ITL-1125.md index 190890f9d..46f718c24 100644 --- a/changelog.d/ITL-1125.md +++ b/changelog.d/ITL-1125.md @@ -2,7 +2,8 @@ - Assigning `upstreams` on an operator or function node now requires the same number of inputs. Where both schemas at a position are known without reading rows, the - setter compares tags, data and system tags, including Arrow field types and - nullability. Data meta columns do not enter the comparison. Assigning an unpolled - source without a declared schema leaves its first fetch to normal data access. + setter compares tags, data and system tags by name, including Arrow field types + and nullability. Data meta columns do not enter the comparison. Join and Rejoin + accept permutations of the same operands. Assigning an unpolled source without + a declared schema leaves its first fetch to normal data access. Build a new pipeline to change the number or known schemas of its inputs. diff --git a/docs/dev/design_issues/ITL-1125-USC1.md b/docs/dev/design_issues/ITL-1125-USC1.md index 05acafc2d..539b91a47 100644 --- a/docs/dev/design_issues/ITL-1125-USC1.md +++ b/docs/dev/design_issues/ITL-1125-USC1.md @@ -12,6 +12,8 @@ A stale pipeline hash still names the table for the old schema. **Fix:** Operator and function node setters check the existing and replacement input schemas before changing the wiring or clearing the schema memo. The comparison checks input count, tag and data roles, equivalent Python types, and canonical Arrow field -types and nullable flags, including for system tags. Data meta columns are ignored. -Only pairs of schemas available without reading rows are compared. Replacements with -matching schemas remain supported. +types and nullable flags, including for system tags. It compares columns by name +within each role and ignores data meta columns. Only pairs of schemas available +without reading rows are compared, including when a loaded function blueprint has +no live input. Replacements with matching schemas and permutations of the same +Join or Rejoin operands remain supported. diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 95ffb0cab..60a50a5ac 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -371,10 +371,17 @@ def upstreams(self, value: tuple[StreamProtocol, ...]) -> None: caches (``LOG`` or ``REPLAY``) and a source feeding ``value`` is restricted (ITL-1218). """ + from orcapod.core.operators.join import Join from orcapod.pipeline.restrictions import refuse_restricted_operator_cache refuse_restricted_operator_cache(self, self.cache_mode, streams=value) - require_same_upstream_schemas(self, value) + # Join (including Rejoin) treats its operands as an unordered group. + # Check object identities without hashing streams, which can read rows. + same_join_operands = isinstance(self._operator, Join) and sorted( + map(id, self._input_streams) + ) == sorted(map(id, value)) + if not same_join_operands: + require_same_upstream_schemas(self, value) self._input_streams = value self._forget_output_schema() diff --git a/src/orcapod/core/nodes/upstream_schema.py b/src/orcapod/core/nodes/upstream_schema.py index ea3051ffa..988c1d674 100644 --- a/src/orcapod/core/nodes/upstream_schema.py +++ b/src/orcapod/core/nodes/upstream_schema.py @@ -1,5 +1,7 @@ """Schema validation for node upstream setters.""" +from typing import cast + import pyarrow as pa from orcapod.core.streams.base import ( @@ -30,9 +32,11 @@ def _user_schemas(stream: StreamProtocol) -> tuple[Schema, Schema]: return tag, data.drop(*meta) if meta else data -def _schema_for_diagnostic(stream: StreamProtocol) -> tuple[Schema, Schema] | str: +def _schema_for_diagnostic( + stream: StreamProtocol | None, +) -> tuple[Schema, Schema] | str: """Describe an input schema without reading, computing or polling a row.""" - if schema_requires_io(stream, _SCHEMA_COLUMNS): + if stream is None or schema_requires_io(stream, _SCHEMA_COLUMNS): return "" return stream.output_schema(columns=_SCHEMA_COLUMNS) @@ -51,7 +55,8 @@ def require_same_upstream_schemas( ValueError: If the upstream count changes or two known schemas disagree in tag, data, or system-tag fields. """ - upstreams = node.upstreams + # A read-only function blueprint loaded without its pod has a missing input. + upstreams = cast("tuple[StreamProtocol | None, ...]", node.upstreams) if len(upstreams) != len(replacements): current = tuple(_schema_for_diagnostic(stream) for stream in upstreams) proposed = tuple(_schema_for_diagnostic(stream) for stream in replacements) @@ -61,7 +66,7 @@ def require_same_upstream_schemas( ) for index, (upstream, replacement) in enumerate(zip(upstreams, replacements)): - if upstream is replacement: + if upstream is None or upstream is replacement: continue if schema_requires_io(upstream, _SCHEMA_COLUMNS) or schema_requires_io( replacement, _SCHEMA_COLUMNS @@ -70,7 +75,7 @@ def require_same_upstream_schemas( current = _user_schemas(upstream) proposed = _user_schemas(replacement) if any( - old.keys() != new.keys() + set(old) != set(new) or any(not equivalent_hints(old[name], new[name]) for name in old) for old, new in zip(current, proposed) ): @@ -85,6 +90,7 @@ def require_same_upstream_schemas( replacement, data_fields=tuple(proposed[1]) ) hasher = node.data_context.arrow_hasher + # Canonical Arrow schema digests compare fields by name, independent of order. if any( hasher.hash_schema(old) != hasher.hash_schema(new) for old, new in zip(current_arrow, proposed_arrow) diff --git a/tests/test_pipeline/test_upstream_schema.py b/tests/test_pipeline/test_upstream_schema.py index 5ae0ec7e4..3f8d670b4 100644 --- a/tests/test_pipeline/test_upstream_schema.py +++ b/tests/test_pipeline/test_upstream_schema.py @@ -1,9 +1,11 @@ """The upstream setters preserve the schemas of a wired node (ITL-1125).""" +from pathlib import Path + import pyarrow as pa import pytest -from orcapod import PipelineJob, function_pod +from orcapod import Pipeline, PipelineJob, function_pod from orcapod.core.function_pod import FunctionPod from orcapod.core.nodes import ( FunctionJobNode, @@ -164,6 +166,38 @@ def test_function_rewiring_arity_error_includes_node_and_schemas( 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 with a missing live input still accepts one upstream.""" + 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="different upstream count") as error: + node.upstreams = () + assert "unavailable" in str(error.value) + assert node.upstreams == original + else: + node.upstreams = (source,) + assert node.upstreams[0] is source + + @pytest.mark.parametrize("reverse", [False, True]) @pytest.mark.parametrize("kind", ["operator", "function"]) @pytest.mark.parametrize("blueprint", [False, True]) @@ -225,6 +259,64 @@ def test_rewiring_refuses_system_tag_arrow_width(reverse: bool) -> None: assert node.as_table().column("xx").to_pylist() == [4] +@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]) @pytest.mark.parametrize( "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] From e81274c9e997b2938ee9f9c6e6f2b77fe804422b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 08:19:22 -0800 Subject: [PATCH 06/12] fix(nodes): accept compatible join permutations and loaded blueprint inputs --- changelog.d/ITL-1125.md | 6 +- docs/dev/design_issues/ITL-1125-USC1.md | 7 +- docs/reference/hashing.md | 2 +- src/orcapod/core/nodes/operator_node.py | 23 +-- src/orcapod/core/nodes/upstream_schema.py | 173 +++++++++++++------- tests/test_pipeline/test_upstream_schema.py | 74 ++++++++- 6 files changed, 209 insertions(+), 76 deletions(-) diff --git a/changelog.d/ITL-1125.md b/changelog.d/ITL-1125.md index 46f718c24..a512e3b77 100644 --- a/changelog.d/ITL-1125.md +++ b/changelog.d/ITL-1125.md @@ -4,6 +4,8 @@ of inputs. Where both schemas at a position are known without reading rows, the setter compares tags, data and system tags by name, including Arrow field types and nullability. Data meta columns do not enter the comparison. Join and Rejoin - accept permutations of the same operands. Assigning an unpolled source without - a declared schema leaves its first fetch to normal data access. + accept permutations with same-schema replacements when the output prediction is + preserved. A read-only operator blueprint without a live operator can still be + assigned its serialized predecessor. Assigning an unpolled source without a + declared schema leaves its first fetch to normal data access. Build a new pipeline to change the number or known schemas of its inputs. diff --git a/docs/dev/design_issues/ITL-1125-USC1.md b/docs/dev/design_issues/ITL-1125-USC1.md index 539b91a47..5300ea802 100644 --- a/docs/dev/design_issues/ITL-1125-USC1.md +++ b/docs/dev/design_issues/ITL-1125-USC1.md @@ -14,6 +14,7 @@ schemas before changing the wiring or clearing the schema memo. The comparison c input count, tag and data roles, equivalent Python types, and canonical Arrow field types and nullable flags, including for system tags. It compares columns by name within each role and ignores data meta columns. Only pairs of schemas available -without reading rows are compared, including when a loaded function blueprint has -no live input. Replacements with matching schemas and permutations of the same -Join or Rejoin operands remain supported. +without reading rows are compared. A loaded function blueprint with no live input +still accepts one upstream, and a read-only operator blueprint can take its serialized +predecessor. Join and Rejoin accept a permutation with same-schema replacements when +it preserves the predicted output schema. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 8c57a63a8..bd2e69921 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -404,7 +404,7 @@ A record id is the row identifier (rule 8), built from row positions or key valu | canonical input order (sort by digest). Inputs with equal pipeline hashes (developer decision, November 16, 2026, ITL-1154: kept as it is): system-tag column names follow the stable pipeline-hash sort; each row's values are sorted by (source id, record id) by `sort_system_tag_values`, so the result does not depend on argument order; the operator's identity holds its inputs as a frozenset | `core/operators/join.py:Join.order_input_streams..` | | in-memory identity and repr | `core/base.py:ContentIdentifiableBase.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__eq__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__repr__` | | comparing a stored hash with the computed one; comparing two schema hashes (bind, a stored read, a polled batch); error text | `core/nodes/source_node.py:SourceNodeBase._arrow_type_issue`, `core/sources/derived_source.py:DerivedSource._require_origin_types`, `core/sources/polling_source.py:PollingSource._require_declared_types`, `core/nodes/operator_node.py:OperatorJobNode._read_run_records`, `core/sources/source_proxy.py:SourceProxy.bind`, `core/data_function_proxy.py:DataFunctionProxy.bind`, `pipeline/job.py:PipelineJob.bind`, `errors.py:EphemeralResultMissingError.__init__` | -| comparing tag, data and system-tag schema hashes before upstream reassignment | `core/nodes/upstream_schema.py:require_same_upstream_schemas..`, `core/nodes/upstream_schema.py:require_same_upstream_schemas` | +| comparing tag, data and system-tag schema hashes before upstream reassignment | `core/nodes/upstream_schema.py:_schema_difference..`, `core/nodes/upstream_schema.py:_schema_difference` | --- diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 60a50a5ac..fbd30f5cc 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -367,21 +367,24 @@ def upstreams(self, value: tuple[StreamProtocol, ...]) -> None: """Replace the node's inputs, preserving schemas known without reading rows. Raises: - ValueError: If the input count or two known schemas differ, or if the node - caches (``LOG`` or ``REPLAY``) and a source feeding ``value`` is - restricted (ITL-1218). + ValueError: If a live operator's input count or known schemas change, or if + the node caches (``LOG`` or ``REPLAY``) and a source feeding ``value`` + is restricted (ITL-1218). """ + from orcapod.core.operators.base import BinaryOperator from orcapod.core.operators.join import Join from orcapod.pipeline.restrictions import refuse_restricted_operator_cache refuse_restricted_operator_cache(self, self.cache_mode, streams=value) - # Join (including Rejoin) treats its operands as an unordered group. - # Check object identities without hashing streams, which can read rows. - same_join_operands = isinstance(self._operator, Join) and sorted( - map(id, self._input_streams) - ) == sorted(map(id, value)) - if not same_join_operands: - require_same_upstream_schemas(self, value) + operator = self._operator + # A read-only blueprint has no live inputs or operator to predict with. + if operator is not None or not isinstance(self, OperatorNode): + commutative = isinstance(operator, Join) or ( + isinstance(operator, BinaryOperator) and operator.is_commutative() + ) + require_same_upstream_schemas( + self, value, commutative_operator=operator if commutative else None + ) self._input_streams = value self._forget_output_schema() diff --git a/src/orcapod/core/nodes/upstream_schema.py b/src/orcapod/core/nodes/upstream_schema.py index 988c1d674..10d978674 100644 --- a/src/orcapod/core/nodes/upstream_schema.py +++ b/src/orcapod/core/nodes/upstream_schema.py @@ -13,6 +13,7 @@ ) from orcapod.logical_types.user_class_identity import equivalent_hints from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.protocols.core_protocols.operator_pod import OperatorPodProtocol from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, DataType, Schema @@ -43,13 +44,17 @@ def _schema_for_diagnostic( @shared_zero_row_memo() def require_same_upstream_schemas( - node: StreamBase, replacements: tuple[StreamProtocol, ...] + node: StreamBase, + replacements: tuple[StreamProtocol, ...], + *, + commutative_operator: OperatorPodProtocol | None = None, ) -> None: """Require replacements to preserve schemas that are known without reading rows. Args: node: The wired node. replacements: The proposed upstreams, in input order. + commutative_operator: The operator when its input order is interchangeable. Raises: ValueError: If the upstream count changes or two known schemas disagree in @@ -65,6 +70,11 @@ def require_same_upstream_schemas( + f"current schemas {current!r}, replacement schemas {proposed!r}" ) + if commutative_operator is not None and sorted(map(id, upstreams)) == sorted( + map(id, replacements) + ): + return + for index, (upstream, replacement) in enumerate(zip(upstreams, replacements)): if upstream is None or upstream is replacement: continue @@ -72,69 +82,114 @@ def require_same_upstream_schemas( replacement, _SCHEMA_COLUMNS ): continue - current = _user_schemas(upstream) - proposed = _user_schemas(replacement) - if any( - set(old) != set(new) - or any(not equivalent_hints(old[name], new[name]) for name in old) - for old, new in zip(current, proposed) + difference = _schema_difference(node, upstream, replacement) + if difference is None: + continue + if commutative_operator is not None and _matches_after_permutation( + node, commutative_operator, node.upstreams, replacements ): - raise ValueError( - f"Cannot rewire node {node.label!r}: upstream {index} has a different " - + f"schema: current (tag={current[0]!r}, data={current[1]!r}), " - + f"replacement (tag={proposed[0]!r}, data={proposed[1]!r})" - ) + return + raise ValueError( + f"Cannot rewire node {node.label!r}: upstream {index} has a different " + + difference + ) - current_arrow = typed_arrow_schemas(upstream, data_fields=tuple(current[1])) - proposed_arrow = typed_arrow_schemas( - replacement, data_fields=tuple(proposed[1]) + +def _matches_after_permutation( + node: StreamBase, + operator: OperatorPodProtocol, + upstreams: tuple[StreamProtocol, ...], + replacements: tuple[StreamProtocol, ...], +) -> bool: + """Match each input schema once, then check the predicted output when available.""" + remaining = list(replacements) + for upstream in upstreams: + for index, replacement in enumerate(remaining): + if upstream is replacement or ( + not schema_requires_io(upstream, _SCHEMA_COLUMNS) + and not schema_requires_io(replacement, _SCHEMA_COLUMNS) + and _schema_difference(node, upstream, replacement) is None + ): + remaining.pop(index) + break + else: + return False + + if any(schema_requires_io(s, _SCHEMA_COLUMNS) for s in (*upstreams, *replacements)): + return True + + old_tag, old_data = operator.output_schema(*upstreams) + new_tag, new_data = operator.output_schema(*replacements) + old_with_system, _ = operator.output_schema(*upstreams, columns=_SCHEMA_COLUMNS) + new_with_system, _ = operator.output_schema(*replacements, columns=_SCHEMA_COLUMNS) + return ( + _same_fields(old_tag, new_tag) + and _same_fields(old_data, new_data) + and set(old_with_system) - set(old_tag) == set(new_with_system) - set(new_tag) + ) + + +def _same_fields(old: Schema, new: Schema) -> bool: + """Compare field names and types without regard to column order.""" + return set(old) == set(new) and all( + equivalent_hints(old[name], new[name]) for name in old + ) + + +def _schema_difference( + node: StreamBase, upstream: StreamProtocol, replacement: StreamProtocol +) -> str | None: + """Describe a mismatch between two inputs with row-free schemas.""" + current = _user_schemas(upstream) + proposed = _user_schemas(replacement) + if any(not _same_fields(old, new) for old, new in zip(current, proposed)): + return ( + f"schema: current (tag={current[0]!r}, data={current[1]!r}), " + + f"replacement (tag={proposed[0]!r}, data={proposed[1]!r})" ) - hasher = node.data_context.arrow_hasher - # Canonical Arrow schema digests compare fields by name, independent of order. - if any( - hasher.hash_schema(old) != hasher.hash_schema(new) - for old, new in zip(current_arrow, proposed_arrow) - ): - raise ValueError( - f"Cannot rewire node {node.label!r}: upstream {index} has a different " - + f"Arrow schema: current (tag={current_arrow[0]}, data={current_arrow[1]}), " - + f"replacement (tag={proposed_arrow[0]}, data={proposed_arrow[1]})" - ) - current_system_tags = { - name: hint - for name, hint in upstream.output_schema(columns=_SCHEMA_COLUMNS)[0].items() - if name not in current[0] - } - proposed_system_tags = { - name: hint - for name, hint in replacement.output_schema(columns=_SCHEMA_COLUMNS)[ - 0 - ].items() - if name not in proposed[0] - } - if current_system_tags != proposed_system_tags: - raise ValueError( - f"Cannot rewire node {node.label!r}: upstream {index} has a different " - + f"system-tag schema: current {current_system_tags!r}, " - + f"replacement {proposed_system_tags!r}" - ) - if current_system_tags: - converter = node.data_context.type_converter - old_system_arrow = _system_tag_arrow_schema( - typed_zero_row_table(upstream), current_system_tags, converter - ) - new_system_arrow = _system_tag_arrow_schema( - typed_zero_row_table(replacement), proposed_system_tags, converter + current_arrow = typed_arrow_schemas(upstream, data_fields=tuple(current[1])) + proposed_arrow = typed_arrow_schemas(replacement, data_fields=tuple(proposed[1])) + hasher = node.data_context.arrow_hasher + # Canonical Arrow schema digests compare fields by name, independent of order. + if any( + hasher.hash_schema(old) != hasher.hash_schema(new) + for old, new in zip(current_arrow, proposed_arrow) + ): + return ( + f"Arrow schema: current (tag={current_arrow[0]}, data={current_arrow[1]}), " + + f"replacement (tag={proposed_arrow[0]}, data={proposed_arrow[1]})" + ) + + current_system_tags = { + name: hint + for name, hint in upstream.output_schema(columns=_SCHEMA_COLUMNS)[0].items() + if name not in current[0] + } + proposed_system_tags = { + name: hint + for name, hint in replacement.output_schema(columns=_SCHEMA_COLUMNS)[0].items() + if name not in proposed[0] + } + if current_system_tags != proposed_system_tags: + return ( + f"system-tag schema: current {current_system_tags!r}, " + + f"replacement {proposed_system_tags!r}" + ) + if current_system_tags: + converter = node.data_context.type_converter + old_system_arrow = _system_tag_arrow_schema( + typed_zero_row_table(upstream), current_system_tags, converter + ) + new_system_arrow = _system_tag_arrow_schema( + typed_zero_row_table(replacement), proposed_system_tags, converter + ) + if hasher.hash_schema(old_system_arrow) != hasher.hash_schema(new_system_arrow): + return ( + f"system-tag Arrow schema: current {old_system_arrow}, " + + f"replacement {new_system_arrow}" ) - if hasher.hash_schema(old_system_arrow) != hasher.hash_schema( - new_system_arrow - ): - raise ValueError( - f"Cannot rewire node {node.label!r}: upstream {index} has a different " - + f"system-tag Arrow schema: current {old_system_arrow}, " - + f"replacement {new_system_arrow}" - ) + return None def _system_tag_arrow_schema( diff --git a/tests/test_pipeline/test_upstream_schema.py b/tests/test_pipeline/test_upstream_schema.py index 3f8d670b4..0f3624440 100644 --- a/tests/test_pipeline/test_upstream_schema.py +++ b/tests/test_pipeline/test_upstream_schema.py @@ -13,7 +13,7 @@ OperatorJobNode, OperatorNode, ) -from orcapod.core.operators import Join, MapData +from orcapod.core.operators import Index, Join, MapData from orcapod.core.sources import DictSource, PollingSource from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.databases import InMemoryArrowDatabase @@ -198,6 +198,31 @@ def test_rewiring_loaded_function_blueprint(tmp_path: Path, wrong_arity: bool) - assert node.upstreams[0] is source +def test_rewiring_loaded_operator_blueprint(tmp_path: Path) -> None: + """A loaded Index can take the predecessor serialized with its blueprint.""" + 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 + + @pytest.mark.parametrize("reverse", [False, True]) @pytest.mark.parametrize("kind", ["operator", "function"]) @pytest.mark.parametrize("blueprint", [False, True]) @@ -317,6 +342,53 @@ def test_rewiring_join_accepts_permuted_operands( ] +@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} + ] + + @pytest.mark.parametrize("reverse", [False, True]) @pytest.mark.parametrize( "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] From f1fcf6607d9b6419930f75555fbd36cccc8a2566 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 08:23:16 -0800 Subject: [PATCH 07/12] fix(nodes): avoid reading raw rows during join rewire predictions --- src/orcapod/core/nodes/upstream_schema.py | 28 +++++++++++++++-- tests/test_pipeline/test_upstream_schema.py | 35 +++++++++++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) diff --git a/src/orcapod/core/nodes/upstream_schema.py b/src/orcapod/core/nodes/upstream_schema.py index 10d978674..0e68f60c1 100644 --- a/src/orcapod/core/nodes/upstream_schema.py +++ b/src/orcapod/core/nodes/upstream_schema.py @@ -4,6 +4,7 @@ import pyarrow as pa +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( StreamBase, schema_requires_io, @@ -110,12 +111,15 @@ def _matches_after_permutation( and not schema_requires_io(replacement, _SCHEMA_COLUMNS) and _schema_difference(node, upstream, replacement) is None ): - remaining.pop(index) + _ = remaining.pop(index) break else: return False - if any(schema_requires_io(s, _SCHEMA_COLUMNS) for s in (*upstreams, *replacements)): + inputs = (*upstreams, *replacements) + if any(schema_requires_io(s, _SCHEMA_COLUMNS) for s in inputs) or ( + _has_nested_raw_arrow(inputs) + ): return True old_tag, old_data = operator.output_schema(*upstreams) @@ -129,6 +133,26 @@ def _matches_after_permutation( ) +def _has_nested_raw_arrow(inputs: tuple[StreamProtocol, ...]) -> bool: + """Find raw tables that an input's pipeline hash may hash by contents. + + A direct raw input's pipeline hash uses only its schema. A nested Join builds + a frozenset of its operands, which can hash raw Arrow rows before computing + the pipeline hash. Treat a prediction above nested raw inputs as unavailable. + """ + pending = [child for stream in inputs for child in stream.upstreams] + seen: set[int] = set() + while pending: + stream = pending.pop() + if id(stream) in seen: + continue + seen.add(id(stream)) + if isinstance(stream, ArrowTableStream) and stream.producer is None: + return True + pending.extend(stream.upstreams) + return False + + def _same_fields(old: Schema, new: Schema) -> bool: """Compare field names and types without regard to column order.""" return set(old) == set(new) and all( diff --git a/tests/test_pipeline/test_upstream_schema.py b/tests/test_pipeline/test_upstream_schema.py index 0f3624440..8df4c920e 100644 --- a/tests/test_pipeline/test_upstream_schema.py +++ b/tests/test_pipeline/test_upstream_schema.py @@ -389,6 +389,41 @@ def source(name: str, columns: tuple[str, str], value: int) -> DictSource: ] +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] From 0dfc278ac64d32b850895f465997e6a88679c9b7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 09:31:45 -0800 Subject: [PATCH 08/12] fix(nodes): compare only declared upstream schemas --- changelog.d/ITL-1125.md | 23 +- docs/dev/design_issues/ITL-1111-GW1.md | 3 +- docs/dev/design_issues/ITL-1125-USC1.md | 17 +- docs/reference/hashing.md | 1 - src/orcapod/core/base.py | 4 + src/orcapod/core/nodes/function_node.py | 5 +- src/orcapod/core/nodes/operator_node.py | 20 +- src/orcapod/core/nodes/upstream_schema.py | 250 ++++-------------- .../core/operators/static_output_pod.py | 2 + src/orcapod/core/schema_read.py | 27 ++ src/orcapod/core/sources/polling_source.py | 2 + src/orcapod/core/streams/base.py | 13 +- .../operators/test_semijoin_tag_keys.py | 4 +- tests/test_hashing/hash_site_trace.py | 7 - tests/test_pipeline/test_graph_walk_cost.py | 15 +- tests/test_pipeline/test_upstream_schema.py | 162 ++++++++++-- 16 files changed, 281 insertions(+), 274 deletions(-) create mode 100644 src/orcapod/core/schema_read.py diff --git a/changelog.d/ITL-1125.md b/changelog.d/ITL-1125.md index a512e3b77..f99dae864 100644 --- a/changelog.d/ITL-1125.md +++ b/changelog.d/ITL-1125.md @@ -1,11 +1,16 @@ ### Breaking changes and migration -- Assigning `upstreams` on an operator or function node now requires the same number - of inputs. Where both schemas at a position are known without reading rows, the - setter compares tags, data and system tags by name, including Arrow field types - and nullability. Data meta columns do not enter the comparison. Join and Rejoin - accept permutations with same-schema replacements when the output prediction is - preserved. A read-only operator blueprint without a live operator can still be - assigned its serialized predecessor. Assigning an unpolled source without a - declared schema leaves its first fetch to normal data access. - Build a new pipeline to change the number or known schemas of its inputs. +- 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. 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 103b66972..9e70bc6ec 100644 --- a/docs/dev/design_issues/ITL-1111-GW1.md +++ b/docs/dev/design_issues/ITL-1111-GW1.md @@ -27,6 +27,7 @@ Call-count tests over 20 stages: `tests/test_pipeline/test_graph_walk_cost.py`. 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 now refuses a replacement with another schema (ITL-1125). Each join keeps both inputs' +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 index 5300ea802..783e5e03a 100644 --- a/docs/dev/design_issues/ITL-1125-USC1.md +++ b/docs/dev/design_issues/ITL-1125-USC1.md @@ -9,12 +9,11 @@ Assigning an upstream with a different schema could change the rewired node's ou 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:** Operator and function node setters check the existing and replacement input -schemas before changing the wiring or clearing the schema memo. The comparison checks -input count, tag and data roles, equivalent Python types, and canonical Arrow field -types and nullable flags, including for system tags. It compares columns by name -within each role and ignores data meta columns. Only pairs of schemas available -without reading rows are compared. A loaded function blueprint with no live input -still accepts one upstream, and a read-only operator blueprint can take its serialized -predecessor. Join and Rejoin accept a permutation with same-schema replacements when -it preserves the predicted output 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. A refusal +preserves the wiring and the node's schema memo. Unavailable declarations and read-only +blueprints retain the previous setter behavior, including function nodes' one-input +requirement. Arrow widths that produce identical declarations are outside this check. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index bd2e69921..bd752c850 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -404,7 +404,6 @@ A record id is the row identifier (rule 8), built from row positions or key valu | canonical input order (sort by digest). Inputs with equal pipeline hashes (developer decision, November 16, 2026, ITL-1154: kept as it is): system-tag column names follow the stable pipeline-hash sort; each row's values are sorted by (source id, record id) by `sort_system_tag_values`, so the result does not depend on argument order; the operator's identity holds its inputs as a frozenset | `core/operators/join.py:Join.order_input_streams..` | | in-memory identity and repr | `core/base.py:ContentIdentifiableBase.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__eq__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__repr__` | | comparing a stored hash with the computed one; comparing two schema hashes (bind, a stored read, a polled batch); error text | `core/nodes/source_node.py:SourceNodeBase._arrow_type_issue`, `core/sources/derived_source.py:DerivedSource._require_origin_types`, `core/sources/polling_source.py:PollingSource._require_declared_types`, `core/nodes/operator_node.py:OperatorJobNode._read_run_records`, `core/sources/source_proxy.py:SourceProxy.bind`, `core/data_function_proxy.py:DataFunctionProxy.bind`, `pipeline/job.py:PipelineJob.bind`, `errors.py:EphemeralResultMissingError.__init__` | -| comparing tag, data and system-tag schema hashes before upstream reassignment | `core/nodes/upstream_schema.py:_schema_difference..`, `core/nodes/upstream_schema.py:_schema_difference` | --- 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 1cf6ea546..0848963dc 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -560,7 +560,10 @@ def upstreams(self, value: tuple[StreamProtocol, ...]) -> None: Raises: ValueError: If there is not exactly one input or the known schemas differ. """ - require_same_upstream_schemas(self, value) + 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() diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index fbd30f5cc..ad03a6036 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -367,24 +367,16 @@ def upstreams(self, value: tuple[StreamProtocol, ...]) -> None: """Replace the node's inputs, preserving schemas known without reading rows. Raises: - ValueError: If a live operator's input count or known schemas change, or if - the node caches (``LOG`` or ``REPLAY``) and a source feeding ``value`` - is restricted (ITL-1218). + 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.core.operators.base import BinaryOperator - from orcapod.core.operators.join import Join from orcapod.pipeline.restrictions import refuse_restricted_operator_cache refuse_restricted_operator_cache(self, self.cache_mode, streams=value) - operator = self._operator - # A read-only blueprint has no live inputs or operator to predict with. - if operator is not None or not isinstance(self, OperatorNode): - commutative = isinstance(operator, Join) or ( - isinstance(operator, BinaryOperator) and operator.is_commutative() - ) - require_same_upstream_schemas( - self, value, commutative_operator=operator if commutative else None - ) + if self._operator is not None: + require_same_upstream_schemas(self, value) self._input_streams = value self._forget_output_schema() diff --git a/src/orcapod/core/nodes/upstream_schema.py b/src/orcapod/core/nodes/upstream_schema.py index 0e68f60c1..5dd27695c 100644 --- a/src/orcapod/core/nodes/upstream_schema.py +++ b/src/orcapod/core/nodes/upstream_schema.py @@ -1,31 +1,26 @@ """Schema validation for node upstream setters.""" -from typing import cast - -import pyarrow as pa - -from orcapod.core.streams.arrow_table_stream import ArrowTableStream -from orcapod.core.streams.base import ( - StreamBase, - schema_requires_io, - shared_zero_row_memo, - typed_arrow_schemas, - typed_zero_row_table, -) +from orcapod.core.schema_read import SchemaWorkRequired, declared_schema_only +from orcapod.core.streams.base import StreamBase +from orcapod.errors import InputValidationError from orcapod.logical_types.user_class_identity import equivalent_hints from orcapod.protocols.core_protocols import StreamProtocol -from orcapod.protocols.core_protocols.operator_pod import OperatorPodProtocol -from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol from orcapod.system_constants import constants -from orcapod.types import ColumnConfig, DataType, Schema -from orcapod.utils.schema_utils import declared_arrow_schema +from orcapod.types import ColumnConfig, Schema _SCHEMA_COLUMNS = ColumnConfig(system_tags=True) - - -def _user_schemas(stream: StreamProtocol) -> tuple[Schema, Schema]: - """Return tag and data schemas without data-only meta fields.""" - tag, data = stream.output_schema() +_SchemaPair = tuple[Schema, Schema] + + +def _available_schema(stream: StreamProtocol | None) -> _SchemaPair | None: + """Read the tag and data declarations, omitting data-only meta fields.""" + if stream is None: + return None + try: + with declared_schema_only(): + tag, data = stream.output_schema(columns=_SCHEMA_COLUMNS) + except (SchemaWorkRequired, InputValidationError, TypeError, ValueError): + return None meta = [ name for name in data @@ -34,202 +29,61 @@ def _user_schemas(stream: StreamProtocol) -> tuple[Schema, Schema]: return tag, data.drop(*meta) if meta else data -def _schema_for_diagnostic( - stream: StreamProtocol | None, -) -> tuple[Schema, Schema] | str: - """Describe an input schema without reading, computing or polling a row.""" - if stream is None or schema_requires_io(stream, _SCHEMA_COLUMNS): - return "" - return stream.output_schema(columns=_SCHEMA_COLUMNS) +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 _same_fields(old: Schema, new: Schema) -> bool: + """Compare column names and type hints, including nullability, in any order.""" + return set(old) == set(new) and all( + equivalent_hints(old[name], new[name]) for name in old + ) -@shared_zero_row_memo() def require_same_upstream_schemas( node: StreamBase, replacements: tuple[StreamProtocol, ...], *, - commutative_operator: OperatorPodProtocol | None = None, + fixed_arity: bool = False, ) -> None: - """Require replacements to preserve schemas that are known without reading rows. + """Require a wired node to keep its input count and multiset of known schemas. Args: node: The wired node. - replacements: The proposed upstreams, in input order. - commutative_operator: The operator when its input order is interchangeable. + replacements: The proposed upstreams. + fixed_arity: Whether the node already requires a fixed input count even + when some schemas are unavailable. Raises: - ValueError: If the upstream count changes or two known schemas disagree in - tag, data, or system-tag fields. + ValueError: If all schemas are available and their counts or schema pairs + differ, or if the node has fixed arity and the count changes. """ - # A read-only function blueprint loaded without its pod has a missing input. - upstreams = cast("tuple[StreamProtocol | None, ...]", node.upstreams) - if len(upstreams) != len(replacements): - current = tuple(_schema_for_diagnostic(stream) for stream in upstreams) - proposed = tuple(_schema_for_diagnostic(stream) for stream in replacements) + current = tuple(_available_schema(stream) for stream in node.upstreams) + proposed = tuple(_available_schema(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 {current!r}, replacement schemas {proposed!r}" + + f"current schemas {_describe(current)!r}, " + + f"replacement schemas {_describe(proposed)!r}" ) - if commutative_operator is not None and sorted(map(id, upstreams)) == sorted( - map(id, replacements) - ): + if not available: return - - for index, (upstream, replacement) in enumerate(zip(upstreams, replacements)): - if upstream is None or upstream is replacement: - continue - if schema_requires_io(upstream, _SCHEMA_COLUMNS) or schema_requires_io( - replacement, _SCHEMA_COLUMNS - ): - continue - difference = _schema_difference(node, upstream, replacement) - if difference is None: - continue - if commutative_operator is not None and _matches_after_permutation( - node, commutative_operator, node.upstreams, replacements - ): - return - raise ValueError( - f"Cannot rewire node {node.label!r}: upstream {index} has a different " - + difference - ) - - -def _matches_after_permutation( - node: StreamBase, - operator: OperatorPodProtocol, - upstreams: tuple[StreamProtocol, ...], - replacements: tuple[StreamProtocol, ...], -) -> bool: - """Match each input schema once, then check the predicted output when available.""" - remaining = list(replacements) - for upstream in upstreams: - for index, replacement in enumerate(remaining): - if upstream is replacement or ( - not schema_requires_io(upstream, _SCHEMA_COLUMNS) - and not schema_requires_io(replacement, _SCHEMA_COLUMNS) - and _schema_difference(node, upstream, replacement) is None - ): + 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 _same_fields(old[0], new[0]) and _same_fields(old[1], new[1]): _ = remaining.pop(index) break else: - return False - - inputs = (*upstreams, *replacements) - if any(schema_requires_io(s, _SCHEMA_COLUMNS) for s in inputs) or ( - _has_nested_raw_arrow(inputs) - ): - return True - - old_tag, old_data = operator.output_schema(*upstreams) - new_tag, new_data = operator.output_schema(*replacements) - old_with_system, _ = operator.output_schema(*upstreams, columns=_SCHEMA_COLUMNS) - new_with_system, _ = operator.output_schema(*replacements, columns=_SCHEMA_COLUMNS) - return ( - _same_fields(old_tag, new_tag) - and _same_fields(old_data, new_data) - and set(old_with_system) - set(old_tag) == set(new_with_system) - set(new_tag) - ) - - -def _has_nested_raw_arrow(inputs: tuple[StreamProtocol, ...]) -> bool: - """Find raw tables that an input's pipeline hash may hash by contents. - - A direct raw input's pipeline hash uses only its schema. A nested Join builds - a frozenset of its operands, which can hash raw Arrow rows before computing - the pipeline hash. Treat a prediction above nested raw inputs as unavailable. - """ - pending = [child for stream in inputs for child in stream.upstreams] - seen: set[int] = set() - while pending: - stream = pending.pop() - if id(stream) in seen: - continue - seen.add(id(stream)) - if isinstance(stream, ArrowTableStream) and stream.producer is None: - return True - pending.extend(stream.upstreams) - return False - - -def _same_fields(old: Schema, new: Schema) -> bool: - """Compare field names and types without regard to column order.""" - return set(old) == set(new) and all( - equivalent_hints(old[name], new[name]) for name in old - ) - - -def _schema_difference( - node: StreamBase, upstream: StreamProtocol, replacement: StreamProtocol -) -> str | None: - """Describe a mismatch between two inputs with row-free schemas.""" - current = _user_schemas(upstream) - proposed = _user_schemas(replacement) - if any(not _same_fields(old, new) for old, new in zip(current, proposed)): - return ( - f"schema: current (tag={current[0]!r}, data={current[1]!r}), " - + f"replacement (tag={proposed[0]!r}, data={proposed[1]!r})" - ) - - current_arrow = typed_arrow_schemas(upstream, data_fields=tuple(current[1])) - proposed_arrow = typed_arrow_schemas(replacement, data_fields=tuple(proposed[1])) - hasher = node.data_context.arrow_hasher - # Canonical Arrow schema digests compare fields by name, independent of order. - if any( - hasher.hash_schema(old) != hasher.hash_schema(new) - for old, new in zip(current_arrow, proposed_arrow) - ): - return ( - f"Arrow schema: current (tag={current_arrow[0]}, data={current_arrow[1]}), " - + f"replacement (tag={proposed_arrow[0]}, data={proposed_arrow[1]})" - ) - - current_system_tags = { - name: hint - for name, hint in upstream.output_schema(columns=_SCHEMA_COLUMNS)[0].items() - if name not in current[0] - } - proposed_system_tags = { - name: hint - for name, hint in replacement.output_schema(columns=_SCHEMA_COLUMNS)[0].items() - if name not in proposed[0] - } - if current_system_tags != proposed_system_tags: - return ( - f"system-tag schema: current {current_system_tags!r}, " - + f"replacement {proposed_system_tags!r}" - ) - if current_system_tags: - converter = node.data_context.type_converter - old_system_arrow = _system_tag_arrow_schema( - typed_zero_row_table(upstream), current_system_tags, converter - ) - new_system_arrow = _system_tag_arrow_schema( - typed_zero_row_table(replacement), proposed_system_tags, converter - ) - if hasher.hash_schema(old_system_arrow) != hasher.hash_schema(new_system_arrow): - return ( - f"system-tag Arrow schema: current {old_system_arrow}, " - + f"replacement {new_system_arrow}" + 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}" ) - return None - - -def _system_tag_arrow_schema( - table: pa.Table | None, - system_tags: dict[str, DataType], - converter: TypeConverterProtocol, -) -> pa.Schema: - """Use the system-tag Arrow fields when known, or their declared types.""" - if table is None: - return declared_arrow_schema(system_tags, converter) - schema = table.schema - available = set(schema.names) - missing = { - name: hint for name, hint in system_tags.items() if name not in available - } - fields = [schema.field(name) for name in system_tags if name in available] - if missing: - fields.extend(declared_arrow_schema(missing, converter)) - return pa.schema(fields) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index cae6813fe..24d88eaaf 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..ade24ad07 --- /dev/null +++ b/src/orcapod/core/schema_read.py @@ -0,0 +1,27 @@ +"""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 _declared_only.get(): + raise SchemaWorkRequired diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 3b4f65398..d350c37bf 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 @@ -767,6 +768,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/base.py b/src/orcapod/core/streams/base.py index 6324fad85..7324ade93 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -24,6 +24,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 ( @@ -199,6 +200,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 @@ -595,7 +597,7 @@ def opened_on(self) -> StreamProtocol | None: def typed_arrow_schemas( - stream: object, *, own: bool = True, data_fields: Sequence[str] | None = None + stream: object, *, own: bool = True ) -> tuple[pa.Schema, pa.Schema]: """Return the Arrow schemas of ``stream``'s tag and data columns (ITL-640). @@ -614,8 +616,6 @@ def typed_arrow_schemas( stream: The stream, source or node. own: Whether to return the ``arrow_schemas`` the stream states, when it has them; ``False`` derives them (the stream's own derivation). - data_fields: The data fields to select, if comparing only part of the - advertised data schema. Returns: The tag and data Arrow schemas. @@ -623,16 +623,11 @@ def typed_arrow_schemas( if own: stated = getattr(stream, "arrow_schemas", None) if isinstance(stated, tuple): - tag_arrow, data_arrow = cast("tuple[pa.Schema, pa.Schema]", stated) - if data_fields is not None: - data_arrow = pa.schema([data_arrow.field(name) for name in data_fields]) - return tag_arrow, data_arrow + return cast("tuple[pa.Schema, pa.Schema]", stated) typed = cast(StreamProtocol, stream) # The columns are those of the Python output schema, which the identity has always # named; only their types come from the zero-row table. tag_schema, data_schema = typed.output_schema() - if data_fields is not None: - data_schema = data_schema.select(*data_fields) table = typed_zero_row_table(stream) if table is None: from orcapod.utils.schema_utils import declared_arrow_schema diff --git a/tests/test_core/operators/test_semijoin_tag_keys.py b/tests/test_core/operators/test_semijoin_tag_keys.py index fa8808577..ec22415a2 100644 --- a/tests/test_core/operators/test_semijoin_tag_keys.py +++ b/tests/test_core/operators/test_semijoin_tag_keys.py @@ -495,7 +495,9 @@ def test_semijoin_rejects_a_new_right_schema_atomically() -> None: filtered = left.polars_filter(x=10) before = node.upstreams - with pytest.raises(ValueError, match=r"'step'.*upstream 1.*'z'.*'y'"): + with pytest.raises( + ValueError, match=r"'step'.*different schema multiset.*'z'.*'y'" + ): node.upstreams = (filtered, right) assert node.upstreams is before diff --git a/tests/test_hashing/hash_site_trace.py b/tests/test_hashing/hash_site_trace.py index 91ec92f51..6d83ffe04 100644 --- a/tests/test_hashing/hash_site_trace.py +++ b/tests/test_hashing/hash_site_trace.py @@ -259,16 +259,9 @@ def run_scenario() -> None: warnings.filterwarnings("ignore") import orcapod as op from orcapod.contexts import get_default_context - from orcapod.core.nodes import OperatorNode - from orcapod.core.operators import MapData - from orcapod.core.sources import DictSource from tests.test_hashing.golden import cases _ = cases.compute_all() - source = DictSource([{"x": 1, "y": 2}]) - replacement = DictSource([{"y": 3, "x": 4}]) - node = OperatorNode(MapData({"x": "xx", "y": "yy"}), (source,)) - node.upstreams = (replacement,) hasher = get_default_context().semantic_hasher with tempfile.TemporaryDirectory() as tmp: root = _Path(tmp) diff --git a/tests/test_pipeline/test_graph_walk_cost.py b/tests/test_pipeline/test_graph_walk_cost.py index a613231a0..5f782a126 100644 --- a/tests/test_pipeline/test_graph_walk_cost.py +++ b/tests/test_pipeline/test_graph_walk_cost.py @@ -615,8 +615,11 @@ def test_operator_rewiring_to_another_schema_is_atomic( with pytest.raises(ValueError, match="'renamed'") as error: node.upstreams = (other,) + columns = {"system_tags": True} for original, replacement in zip( - upstreams[0].output_schema(), other.output_schema() + 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) @@ -643,10 +646,10 @@ def test_function_rewiring_to_another_tag_schema_is_refused(self) -> None: assert node.upstreams[0] is before assert node.output_schema()[0]["id"] is int - def test_rewiring_refuses_a_different_arrow_type_for_the_same_python_type( + def test_rewiring_refuses_changed_system_tag_names_from_arrow_types( self, ) -> None: - """A change of integer width is also a change of input schema.""" + """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 @@ -664,8 +667,12 @@ def test_rewiring_refuses_a_different_arrow_type_for_the_same_python_type( 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"(?s)'renamed'.*int64.*int32"): + with pytest.raises(ValueError, match=r"'renamed'.*system-tag"): node.upstreams = (other,) assert node.upstreams is before diff --git a/tests/test_pipeline/test_upstream_schema.py b/tests/test_pipeline/test_upstream_schema.py index 8df4c920e..41d98102e 100644 --- a/tests/test_pipeline/test_upstream_schema.py +++ b/tests/test_pipeline/test_upstream_schema.py @@ -13,7 +13,7 @@ OperatorJobNode, OperatorNode, ) -from orcapod.core.operators import Index, Join, MapData +from orcapod.core.operators import Index, Join, MapData, MergeJoin from orcapod.core.sources import DictSource, PollingSource from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.databases import InMemoryArrowDatabase @@ -168,7 +168,7 @@ def test_function_rewiring_arity_error_includes_node_and_schemas( @pytest.mark.parametrize("wrong_arity", [False, True]) def test_rewiring_loaded_function_blueprint(tmp_path: Path, wrong_arity: bool) -> None: - """A loaded function with a missing live input still accepts one upstream.""" + """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"], @@ -189,17 +189,23 @@ def test_rewiring_loaded_function_blueprint(tmp_path: Path, wrong_arity: bool) - ) if wrong_arity: - with pytest.raises(ValueError, match="different upstream count") as error: + with pytest.raises(ValueError, match="FunctionPod can only have one upstream"): node.upstreams = () - assert "unavailable" in str(error.value) 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 can take the predecessor serialized with its blueprint.""" + """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"], @@ -221,6 +227,16 @@ def test_rewiring_loaded_operator_blueprint(tmp_path: Path) -> None: 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]) @@ -258,30 +274,28 @@ def test_rewiring_raw_stream_ignores_data_meta( @pytest.mark.parametrize("reverse", [False, True]) -def test_rewiring_refuses_system_tag_arrow_width(reverse: bool) -> None: - """Equal Python hints can conceal a change to a system-tag Arrow field.""" +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") - original = node.upstreams - schema = node.output_schema(columns=_SYSTEM_TAGS) - identity = node.node_identity_path - - with pytest.raises(ValueError, match=r"(?s)'step'.*system-tag.*int32.*int64"): - node.upstreams = (after,) - - assert node.upstreams is original - assert node.output_schema(columns=_SYSTEM_TAGS) is schema - assert node.node_identity_path == identity assert ( before.as_table(columns=_SYSTEM_TAGS).schema.field("_tag_custom_id").type == pa.int32() ) - node.run() - assert node.as_table().column("xx").to_pylist() == [4] + 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]) @@ -470,7 +484,7 @@ def test_refused_multi_input_rewire_preserves_job_output( pipeline_hash = downstream.pipeline_hash() path = downstream.node_identity_path - with pytest.raises(ValueError, match=r"'join'.*upstream 1"): + with pytest.raises(ValueError, match=r"'join'.*different schema multiset"): node.upstreams = (first_replacement, upstreams[0]) assert node.upstreams is upstreams @@ -504,3 +518,111 @@ def test_rewiring_refuses_a_different_input_count() -> None: 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("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) From 47b493d51e696edd95cee24ef11e2ef59e9028da Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 10:42:29 -0800 Subject: [PATCH 09/12] fix(nodes): keep upstream schema probes out of persistent memos --- docs/dev/design_issues/ITL-1125-USC1.md | 5 +- src/orcapod/core/nodes/upstream_schema.py | 4 +- src/orcapod/core/streams/base.py | 31 ++++++++++-- tests/test_pipeline/test_upstream_schema.py | 53 ++++++++++++++++++++- 4 files changed, 84 insertions(+), 9 deletions(-) diff --git a/docs/dev/design_issues/ITL-1125-USC1.md b/docs/dev/design_issues/ITL-1125-USC1.md index 783e5e03a..a967e9621 100644 --- a/docs/dev/design_issues/ITL-1125-USC1.md +++ b/docs/dev/design_issues/ITL-1125-USC1.md @@ -13,7 +13,8 @@ A stale pipeline hash still names the table for the old schema. 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. A refusal -preserves the wiring and the node's schema memo. Unavailable declarations and read-only +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 refusal preserves the wiring. Unavailable declarations and read-only blueprints retain the previous setter behavior, including function nodes' one-input requirement. Arrow widths that produce identical declarations are outside this check. diff --git a/src/orcapod/core/nodes/upstream_schema.py b/src/orcapod/core/nodes/upstream_schema.py index 5dd27695c..37f9adab6 100644 --- a/src/orcapod/core/nodes/upstream_schema.py +++ b/src/orcapod/core/nodes/upstream_schema.py @@ -1,7 +1,7 @@ """Schema validation for node upstream setters.""" from orcapod.core.schema_read import SchemaWorkRequired, declared_schema_only -from orcapod.core.streams.base import StreamBase +from orcapod.core.streams.base import StreamBase, temporary_output_schema_memos from orcapod.errors import InputValidationError from orcapod.logical_types.user_class_identity import equivalent_hints from orcapod.protocols.core_protocols import StreamProtocol @@ -17,7 +17,7 @@ def _available_schema(stream: StreamProtocol | None) -> _SchemaPair | None: if stream is None: return None try: - with declared_schema_only(): + with declared_schema_only(), temporary_output_schema_memos(): tag, data = stream.output_schema(columns=_SCHEMA_COLUMNS) except (SchemaWorkRequired, InputValidationError, TypeError, ValueError): return None diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 7324ade93..db7b557c1 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -153,6 +153,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]: @@ -1419,7 +1434,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, @@ -1455,9 +1470,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_pipeline/test_upstream_schema.py b/tests/test_pipeline/test_upstream_schema.py index 41d98102e..bb2dfa3b3 100644 --- a/tests/test_pipeline/test_upstream_schema.py +++ b/tests/test_pipeline/test_upstream_schema.py @@ -13,7 +13,7 @@ OperatorJobNode, OperatorNode, ) -from orcapod.core.operators import Index, Join, MapData, MergeJoin +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 @@ -596,6 +596,57 @@ def require_no_table(self: ArrowTableStream, **columns: object) -> pa.Table: 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 + + @pytest.mark.parametrize("swapped", [False, True]) def test_rewiring_with_an_unavailable_schema_skips_the_whole_comparison( swapped: bool, From 160d0767498c52271b6cc85ed42cf4797f4867d4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 11:17:12 -0800 Subject: [PATCH 10/12] fix(nodes): allow rewiring when upstream schema reads fail --- changelog.d/ITL-1125.md | 7 +- docs/dev/design_issues/ITL-1125-USC1.md | 3 +- src/orcapod/core/nodes/upstream_schema.py | 12 +-- tests/test_pipeline/test_upstream_schema.py | 88 +++++++++++++++++++++ 4 files changed, 100 insertions(+), 10 deletions(-) diff --git a/changelog.d/ITL-1125.md b/changelog.d/ITL-1125.md index f99dae864..90e6e488f 100644 --- a/changelog.d/ITL-1125.md +++ b/changelog.d/ITL-1125.md @@ -6,9 +6,10 @@ 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. Function nodes - still require exactly one input. Build a new pipeline to change known input - schemas. + inputs with unavailable schemas to the existing setter behavior. If any schema + read raises an exception, the setter treats the declaration as unavailable. + Function nodes still require exactly one input. Build a new pipeline to change + known input schemas. ### Known limitations diff --git a/docs/dev/design_issues/ITL-1125-USC1.md b/docs/dev/design_issues/ITL-1125-USC1.md index a967e9621..7dcdd700b 100644 --- a/docs/dev/design_issues/ITL-1125-USC1.md +++ b/docs/dev/design_issues/ITL-1125-USC1.md @@ -17,4 +17,5 @@ nullability. Data meta fields and input order do not enter the comparison. The s read existing schema predictions and keep any new predictions local to the check. A refusal preserves the wiring. Unavailable declarations and read-only blueprints retain the previous setter behavior, including function nodes' one-input -requirement. Arrow widths that produce identical declarations are outside this check. +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/nodes/upstream_schema.py b/src/orcapod/core/nodes/upstream_schema.py index 37f9adab6..58ded8060 100644 --- a/src/orcapod/core/nodes/upstream_schema.py +++ b/src/orcapod/core/nodes/upstream_schema.py @@ -1,8 +1,7 @@ """Schema validation for node upstream setters.""" -from orcapod.core.schema_read import SchemaWorkRequired, declared_schema_only +from orcapod.core.schema_read import declared_schema_only from orcapod.core.streams.base import StreamBase, temporary_output_schema_memos -from orcapod.errors import InputValidationError from orcapod.logical_types.user_class_identity import equivalent_hints from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants @@ -16,11 +15,12 @@ def _available_schema(stream: StreamProtocol | None) -> _SchemaPair | None: """Read the tag and data declarations, omitting data-only meta fields.""" if stream is None: return None - try: - with declared_schema_only(), temporary_output_schema_memos(): + with declared_schema_only(), temporary_output_schema_memos(): + try: tag, data = stream.output_schema(columns=_SCHEMA_COLUMNS) - except (SchemaWorkRequired, InputValidationError, TypeError, ValueError): - return None + except Exception: + # An unreadable declaration must fall back to the original setter behavior. + return None meta = [ name for name in data diff --git a/tests/test_pipeline/test_upstream_schema.py b/tests/test_pipeline/test_upstream_schema.py index bb2dfa3b3..c5c0b7ac0 100644 --- a/tests/test_pipeline/test_upstream_schema.py +++ b/tests/test_pipeline/test_upstream_schema.py @@ -647,6 +647,94 @@ def test_rewiring_probe_does_not_memoize_upstream_schema( 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, From 63c7959b47855cadbd95fc6309fbe222048500c3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 12:05:58 -0800 Subject: [PATCH 11/12] fix(nodes): leave cold source schema hashes uncached on rewire --- changelog.d/ITL-1125.md | 2 + docs/dev/design_issues/ITL-1125-USC1.md | 2 + src/orcapod/core/nodes/source_node.py | 3 ++ src/orcapod/core/sources/polling_source.py | 1 + tests/test_pipeline/test_upstream_schema.py | 48 ++++++++++++++++++++- 5 files changed, 55 insertions(+), 1 deletion(-) diff --git a/changelog.d/ITL-1125.md b/changelog.d/ITL-1125.md index 90e6e488f..908281d5b 100644 --- a/changelog.d/ITL-1125.md +++ b/changelog.d/ITL-1125.md @@ -8,6 +8,8 @@ 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 + and cache its schema hash. Function nodes still require exactly one input. Build a new pipeline to change known input schemas. diff --git a/docs/dev/design_issues/ITL-1125-USC1.md b/docs/dev/design_issues/ITL-1125-USC1.md index 7dcdd700b..4a9d97031 100644 --- a/docs/dev/design_issues/ITL-1125-USC1.md +++ b/docs/dev/design_issues/ITL-1125-USC1.md @@ -15,6 +15,8 @@ setters compare the old and new input counts and multisets of declared schema pa 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. 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 diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 5b69d510d..c7d0ba09b 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -26,6 +26,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 ( @@ -679,6 +680,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, @@ -877,6 +879,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/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index d350c37bf..d05fd97f9 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -400,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 diff --git a/tests/test_pipeline/test_upstream_schema.py b/tests/test_pipeline/test_upstream_schema.py index c5c0b7ac0..fda2b7a77 100644 --- a/tests/test_pipeline/test_upstream_schema.py +++ b/tests/test_pipeline/test_upstream_schema.py @@ -12,6 +12,7 @@ FunctionNode, OperatorJobNode, OperatorNode, + SourceNode, ) from orcapod.core.operators import Index, Join, MapData, MergeJoin, SemiJoin from orcapod.core.sources import DictSource, PollingSource @@ -121,7 +122,7 @@ def test_rewiring_to_unpolled_source_does_not_fetch( def test_rewiring_refuses_different_declared_polling_schema_without_fetch() -> None: - """An unpolled source can still have a schema known at assignment time.""" + """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"], @@ -129,6 +130,7 @@ def test_rewiring_refuses_different_declared_polling_schema_without_fetch() -> N ) feed = _PollingFeed("four", Schema({"id": int, "group": str, "x": str, "y": int})) after = PollingSource(feed, ["id", "group"], record_id_columns="id") + _ = after.output_schema(columns=_SYSTEM_TAGS) node = OperatorNode(MapData({"x": "xx"}), (before,), label="step") with pytest.raises(ValueError, match=r"'step'.*different schema"): @@ -138,6 +140,50 @@ def test_rewiring_refuses_different_declared_polling_schema_without_fetch() -> N 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, From e6d250c7bfd1808d7f31649c58ad925a4e177b27 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 12:37:19 -0800 Subject: [PATCH 12/12] fix(nodes): keep upstream schema checks free of Arrow conversion --- changelog.d/ITL-1125.md | 4 +- docs/dev/design_issues/ITL-1125-USC1.md | 3 + src/orcapod/core/nodes/function_node.py | 2 + src/orcapod/core/nodes/operator_node.py | 2 + src/orcapod/core/nodes/upstream_schema.py | 22 +++--- src/orcapod/core/schema_read.py | 7 +- src/orcapod/core/sources/derived_source.py | 2 + .../core/streams/arrow_table_stream.py | 39 +++++++--- .../operators/test_semijoin_tag_keys.py | 2 + tests/test_pipeline/test_graph_walk_cost.py | 6 +- tests/test_pipeline/test_upstream_schema.py | 74 ++++++++++++++++++- 11 files changed, 136 insertions(+), 27 deletions(-) diff --git a/changelog.d/ITL-1125.md b/changelog.d/ITL-1125.md index 908281d5b..d39fe3a30 100644 --- a/changelog.d/ITL-1125.md +++ b/changelog.d/ITL-1125.md @@ -9,7 +9,9 @@ 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 - and cache its schema hash. + 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. diff --git a/docs/dev/design_issues/ITL-1125-USC1.md b/docs/dev/design_issues/ITL-1125-USC1.md index 4a9d97031..70f9d5092 100644 --- a/docs/dev/design_issues/ITL-1125-USC1.md +++ b/docs/dev/design_issues/ITL-1125-USC1.md @@ -17,6 +17,9 @@ nullability. Data meta fields and input order do not enter the comparison. The s 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 diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index c85d34dcc..7f2d91c36 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -35,6 +35,7 @@ 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, @@ -607,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 4784231c0..0d047e148 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -31,6 +31,7 @@ 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, @@ -479,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/upstream_schema.py b/src/orcapod/core/nodes/upstream_schema.py index 58ded8060..79b9239b0 100644 --- a/src/orcapod/core/nodes/upstream_schema.py +++ b/src/orcapod/core/nodes/upstream_schema.py @@ -2,7 +2,6 @@ from orcapod.core.schema_read import declared_schema_only from orcapod.core.streams.base import StreamBase, temporary_output_schema_memos -from orcapod.logical_types.user_class_identity import equivalent_hints from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema @@ -11,9 +10,13 @@ _SchemaPair = tuple[Schema, Schema] -def _available_schema(stream: StreamProtocol | None) -> _SchemaPair | None: +def _available_schema( + node: StreamBase, stream: StreamProtocol | None +) -> _SchemaPair | None: """Read the tag and data declarations, omitting data-only meta fields.""" - if stream is None: + # 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: @@ -37,13 +40,6 @@ def _describe(schemas: tuple[_SchemaPair | None, ...]) -> tuple[_SchemaPair | st ) -def _same_fields(old: Schema, new: Schema) -> bool: - """Compare column names and type hints, including nullability, in any order.""" - return set(old) == set(new) and all( - equivalent_hints(old[name], new[name]) for name in old - ) - - def require_same_upstream_schemas( node: StreamBase, replacements: tuple[StreamProtocol, ...], @@ -62,8 +58,8 @@ def require_same_upstream_schemas( 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(stream) for stream in node.upstreams) - proposed = tuple(_available_schema(stream) for stream in replacements) + 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( @@ -78,7 +74,7 @@ def require_same_upstream_schemas( for old in current: assert old is not None for index, new in enumerate(remaining): - if _same_fields(old[0], new[0]) and _same_fields(old[1], new[1]): + if old == new: _ = remaining.pop(index) break else: diff --git a/src/orcapod/core/schema_read.py b/src/orcapod/core/schema_read.py index ade24ad07..6be0835ea 100644 --- a/src/orcapod/core/schema_read.py +++ b/src/orcapod/core/schema_read.py @@ -23,5 +23,10 @@ def declared_schema_only() -> Iterator[None]: def require_schema_work_allowed() -> None: """Raise when a declared-schema read tries to perform additional work.""" - if _declared_only.get(): + 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/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/tests/test_core/operators/test_semijoin_tag_keys.py b/tests/test_core/operators/test_semijoin_tag_keys.py index ec22415a2..01db7e07e 100644 --- a/tests/test_core/operators/test_semijoin_tag_keys.py +++ b/tests/test_core/operators/test_semijoin_tag_keys.py @@ -495,6 +495,8 @@ def test_semijoin_rejects_a_new_right_schema_atomically() -> None: filtered = left.polars_filter(x=10) before = node.upstreams + 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'" ): diff --git a/tests/test_pipeline/test_graph_walk_cost.py b/tests/test_pipeline/test_graph_walk_cost.py index 5f782a126..618df7f4f 100644 --- a/tests/test_pipeline/test_graph_walk_cost.py +++ b/tests/test_pipeline/test_graph_walk_cost.py @@ -612,10 +612,12 @@ def test_operator_rewiring_to_another_schema_is_atomic( ] 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,) - columns = {"system_tags": True} for original, replacement in zip( upstreams[0].output_schema(columns=columns), other.output_schema(columns=columns), @@ -640,6 +642,8 @@ def test_function_rewiring_to_another_tag_schema_is_refused(self) -> None: source_id="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,) diff --git a/tests/test_pipeline/test_upstream_schema.py b/tests/test_pipeline/test_upstream_schema.py index fda2b7a77..4f10d79e1 100644 --- a/tests/test_pipeline/test_upstream_schema.py +++ b/tests/test_pipeline/test_upstream_schema.py @@ -1,6 +1,8 @@ """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 @@ -19,8 +21,9 @@ 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, Cursor, Schema +from orcapod.types import CacheMode, ColumnConfig, Cursor, Schema _SYSTEM_TAGS = {"system_tags": True} @@ -130,6 +133,7 @@ def test_rewiring_refuses_different_declared_polling_schema_without_fetch() -> N ) 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") @@ -196,6 +200,9 @@ def test_function_rewiring_arity_error_includes_node_and_schemas( 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") @@ -294,6 +301,8 @@ def test_rewiring_raw_stream_ignores_data_meta( """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") @@ -557,6 +566,8 @@ def test_rewiring_refuses_a_different_input_count() -> None: ) 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 @@ -811,3 +822,64 @@ def test_rewiring_with_an_unavailable_schema_skips_the_whole_comparison( 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)) + ]