From 4938378108ce9d56844f94c273afab9ba38c5054 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 13:51:47 -0800 Subject: [PATCH 01/42] fix(pipeline): reject conflicting fixed source rows (ITL-1469) --- changelog.d/ITL-1469.md | 6 + docs/concepts/identity.md | 9 +- docs/concepts/sources.md | 33 ++ .../core/sources/arrow_table_source.py | 4 +- src/orcapod/core/sources/base.py | 39 ++ src/orcapod/core/sources/data_frame_source.py | 4 +- src/orcapod/core/sources/derived_source.py | 11 + src/orcapod/core/sources/dict_source.py | 4 +- src/orcapod/core/sources/list_source.py | 4 +- src/orcapod/core/sources/source_proxy.py | 8 + src/orcapod/errors.py | 13 +- src/orcapod/pipeline/base.py | 32 +- src/orcapod/pipeline/job.py | 31 +- src/orcapod/pipeline/source_consistency.py | 108 +++++ .../test_pipeline_base_recording.py | 6 +- .../test_pipeline/test_source_id_conflicts.py | 440 ++++++++++++++++++ 16 files changed, 719 insertions(+), 33 deletions(-) create mode 100644 changelog.d/ITL-1469.md create mode 100644 src/orcapod/pipeline/source_consistency.py create mode 100644 tests/test_pipeline/test_source_id_conflicts.py diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md new file mode 100644 index 000000000..14de9d1ae --- /dev/null +++ b/changelog.d/ITL-1469.md @@ -0,0 +1,6 @@ +### Fixed + +- Pipeline capture and job binding reject two in-memory sources that share a + source ID and schema but contain different rows. The error names the + conflicting steps or slots. Job binding and loading also reject different + schemas at a shared source ID. diff --git a/docs/concepts/identity.md b/docs/concepts/identity.md index cedf58b29..9b5e6da73 100644 --- a/docs/concepts/identity.md +++ b/docs/concepts/identity.md @@ -13,7 +13,7 @@ The content hash captures schema, topology, and the **identity of the sources** pipeline. It is computed recursively: each element's content hash depends on its own identity plus the content hashes of all its upstream elements, all the way back to the sources. -A source's identity is its class, its schema, its `source_id` and its key columns (the +A source's identity is its schema, its `source_id` and its key columns (the `record_id_columns` that name its rows, or none when rows are named by position). What the `source_id` is depends on how the source was created: @@ -23,9 +23,10 @@ A source's identity is its class, its schema, its `source_id` and its key column - File- and table-backed sources default to a name derived from their location (the file path for `CSVSource`, the table folder's path or URI for `DeltaTableSource`), not from the rows. -- If you pass `source_id` yourself, you are naming the source: two sources with the same - class, schema, `source_id` and key columns have the same content hash even when their rows - differ. +- If you pass `source_id` yourself, you are naming the source. The kind is part of the + canonical ID. Two sources with the same ID, schema and key columns have the same + content hash even when their rows differ. A pipeline checks reused IDs separately + when it captures or binds sources. Two sources that differ only in their key columns name the same rows differently, so they are two sources: different content hashes (each gets its own cache), the same pipeline hash diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index de39979ad..d3e13ba03 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -78,6 +78,39 @@ same rows read by another kind, or by another version of one kind, are another s record id names a row within its source and never holds the source id. A job names an input slot by the source's name (`job.bind(sources={"units": ...})`). +Within a pipeline or job, sources sharing a `source_id` must have the same Arrow schema. +If both sources hold their rows in memory, their tags, data and record IDs must also +agree. This applies to `ArrowTableSource`, `DictSource`, `ListSource`, +`DataFrameSource` and wrappers over their fixed rows. Row order counts with positional +IDs (`row_0`, `row_1`, and so on). With key columns, the same rows can arrive in any +order. The comparison follows Orcapod's Arrow value rule, which treats signed zeros +as equal and all NaNs as equal. Sources that read again later, including files, +databases, caches and stored job outputs, use the ID and schema without a row +comparison. Capture and binding reject conflicts with `InconsistentSourceError`. +Give the conflicting sources different `source_id` values. + +```python +from orcapod import Pipeline, function_pod +from orcapod.errors import InconsistentSourceError +from orcapod.sources import DictSource + + +@function_pod(output_keys="adjusted") +def adjust(rate: float) -> float: + return rate + 1 + + +first = DictSource([{"rate": 3.5}], source_id="rates") +second = DictSource([{"rate": 7.25}], source_id="rates") +try: + with Pipeline("rates"): + adjust.pod(first, label="first") + adjust.pod(second, label="second") +except InconsistentSourceError as error: + print(error) +# Source 'dict_v1:rates' has different rows in step 'first' and step 'second'. Give the sources different source_id values. +``` + A kind's version moves when a row read before a change of its implementation could read differently after it (other values, other Arrow types, another record id). Saved jobs keep each source's name and version apart; a job loaded where a kind's version moved rebuilds the diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index f05485472..62f65b9e5 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -4,7 +4,7 @@ from collections.abc import Collection from typing import TYPE_CHECKING, Any, ClassVar -from orcapod.core.sources.base import RootSource +from orcapod.core.sources.base import FixedTableSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.stream_builder import SourceStreamBuilder from orcapod.core.sources.stream_builder import ( @@ -19,7 +19,7 @@ logger = logging.getLogger(__name__) -class ArrowTableSource(RootSource): +class ArrowTableSource(FixedTableSource): """A source backed by an in-memory PyArrow Table. Uses ``SourceStreamBuilder`` to strip system columns, add per-row diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 07221924c..2ae69fa9d 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -4,6 +4,8 @@ from collections.abc import Callable from typing import TYPE_CHECKING, Any, ClassVar, TypeVar +from typing_extensions import override + from orcapod import contexts from orcapod.config import OrcapodConfig from orcapod.core.streams.base import ( @@ -416,6 +418,33 @@ def _schema_identity(self) -> tuple[ContentHash, ContentHash]: """ return arrow_schema_identity(*self.arrow_schemas, self.data_context) + @property + def fixed_content(self) -> bytes | None: + """Digest of held rows for collision checks, or None for a live read. + + Sources that hold immutable rows opt in. A wrapper can opt in if its + delegate holds fixed rows. The digest is separate from source identity. + """ + return None + + def _digest_fixed_rows(self) -> bytes: + """Compare tags, data and record IDs under the normal Arrow float rule.""" + from orcapod.hashing.starfix_digest import digest_orcapod_table + from orcapod.utils.arrow_utils import key_row_order + + table = self.as_table(columns={"system_tags": True}) + if self._key_columns and table.num_rows > 1: + table = key_row_order(table, self._key_columns) + # The schemas are checked separately, including logical type identifiers. + # Compare encoded values directly without converting nested or extension + # columns to Python objects. Starfix reads their Arrow storage. + return digest_orcapod_table( + table, + include_metadata=False, + ordered_columns=False, + ordered_struct_fields=False, + ) + def identity_structure(self) -> Any: """Identity from the ``source_id``, the Arrow schema and the key columns. @@ -637,3 +666,13 @@ def cached( cache_path_prefix=cache_path_prefix, **kwargs, ) + + +class FixedTableSource(RootSource): + """A root that holds an Arrow table for its entire lifetime.""" + + @property + @override + def fixed_content(self) -> bytes: + """Digest of the table this source holds.""" + return self._digest_fixed_rows() diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 6c65bf64d..27855a5d3 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -7,7 +7,7 @@ import polars as pl import pyarrow as pa -from orcapod.core.sources.base import RootSource +from orcapod.core.sources.base import FixedTableSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.stream_builder import SourceStreamBuilder from orcapod.core.sources.stream_builder import ( @@ -22,7 +22,7 @@ logger = logging.getLogger(__name__) -class DataFrameSource(RootSource): +class DataFrameSource(FixedTableSource): """A source backed by a Polars DataFrame (or any Polars-compatible data). The DataFrame is converted to an Arrow table and enriched by diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1c4a57228..d169b5258 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -305,6 +305,17 @@ def __init__( # Identity # ------------------------------------------------------------------------- + @property + @override + def fixed_content(self) -> bytes | None: + """Rows are fixed only when the origin itself holds fixed content.""" + if ( + isinstance(self._origin, RootSource) + and self._origin.fixed_content is not None + ): + return self._digest_fixed_rows() + return None + def identity_structure(self) -> Any: """Return what the content hash is built from. diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index fdf7c1f34..05f369e03 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -5,7 +5,7 @@ import pyarrow as pa -from orcapod.core.sources.base import RootSource +from orcapod.core.sources.base import FixedTableSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.stream_builder import SourceStreamBuilder from orcapod.core.sources.stream_builder import ( @@ -17,7 +17,7 @@ from orcapod.utils.tensor_conversions import warn_source_tensor_conversions -class DictSource(RootSource): +class DictSource(FixedTableSource): """A source backed by a collection of Python dictionaries. Each dict becomes one (tag, data) pair in the stream. The dicts are diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index f18da3433..1c1eb12a4 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -3,7 +3,7 @@ from collections.abc import Callable, Collection from typing import TYPE_CHECKING, Any, ClassVar -from orcapod.core.sources.base import RootSource +from orcapod.core.sources.base import FixedTableSource from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, @@ -17,7 +17,7 @@ pass -class ListSource(RootSource): +class ListSource(FixedTableSource): """A source backed by a Python list. Each element in the list becomes one (tag, data) pair. The element is diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 83eb6238d..526e5d4bd 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -95,6 +95,14 @@ def delegate(self) -> SourceProtocol | None: """The bound live source, or ``None`` if no source has been bound.""" return self._delegate + @property + @override + def fixed_content(self) -> bytes | None: + """The bound source's fixed rows, if it holds them.""" + if isinstance(self._delegate, RootSource): + return self._delegate.fixed_content + return None + @property def is_bound(self) -> bool: """``True`` if a live source has been bound via `bind`.""" diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 7720e7980..00a922708 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -557,14 +557,11 @@ class SourceSpecMismatchError(InputValidationError, ValueError): class InconsistentSourceError(ValueError): - """Raised when two source nodes in the same pipeline share a name but differ in schema. - - Source node names are identity-forming: the same name in a given pipeline - must always refer to the same input slot (same schema). If ``compile()`` - finds two source nodes with identical names but different schemas — which - can happen when two ``RootSource`` objects share the same ``source_id`` but - produce different column sets — it raises this error rather than silently - renaming one of them. + """Raised when two sources in a pipeline disagree at a shared address. + + Sources sharing a ``source_id`` must have the same schema. If both hold + fixed content, their tags, data and record IDs must also agree. Two + different schemas competing for one input slot also raise this error. Resolution: assign distinct ``source_id`` values to the conflicting sources so each slot has a unique, stable identity. diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 966809d94..cee05bc78 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -4,7 +4,7 @@ import logging from abc import ABC, abstractmethod -from collections.abc import Hashable +from collections.abc import Hashable, Iterator from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar @@ -17,6 +17,10 @@ PodInvocation, SideEffectInvocation, ) +from orcapod.pipeline.source_consistency import ( + invocation_source_uses, + require_consistent_sources, +) from orcapod.side_effects import SideEffectNode from orcapod.protocols import core_protocols as cp from orcapod.utils.lazy_module import LazyModule @@ -26,6 +30,7 @@ from orcapod.pipeline.diagram import PipelineDiagram from orcapod.types.provenance import Highlight from orcapod.protocols.database_protocols import ArrowDatabaseProtocol + from orcapod.pipeline.source_consistency import SourceUse else: nx = LazyModule("networkx") @@ -125,6 +130,9 @@ def __init__( # --- Additive recording state (never cleared) ----------------- # Maps content-hash-string → PodInvocation for each recorded invocation. self._invocation_lut: dict[str, PodInvocation] = {} + # Keep the original input objects for validation even when a live source + # and a fixed source share one address and their invocations coalesce. + self._recorded_source_uses: dict[int, SourceUse] = {} # Maps content-hash-string → raw stream for each unregistered upstream. self._source_streams: dict[str, Any] = {} # Topology graph — vertices and edges are content-hash strings. @@ -350,6 +358,7 @@ def _record_invocation(self, invocation: PodInvocation) -> None: # every source the pipeline's streams read now (nothing is remembered: a # slot rebound since the last invocation changes what they read). require_one_restriction([*self._held_streams(), *inputs]) + require_consistent_sources(self._source_uses(invocation)) self._remember_invocation(key, invocation) self._hash_graph.add_node(key) for upstream, upstream_hash in upstreams: @@ -359,6 +368,8 @@ def _record_invocation(self, invocation: PodInvocation) -> None: def _remember_invocation(self, key: str, invocation: PodInvocation) -> None: """Keep the smallest explicit label when identical invocations share a node.""" + for location, stream in invocation_source_uses(invocation): + self._recorded_source_uses[id(stream)] = (location, stream) previous = self._invocation_lut.get(key) if previous is not None and previous.label is not None: if invocation.label is None or previous.label < invocation.label: @@ -376,6 +387,17 @@ def _held_streams(self) -> list[Any]: ), ] + def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse]: + """Inputs before hash deduplication, with their original step names.""" + # Prefer the labelled endpoint of a chain over an implicit projection. + for invocation in reversed(self._invocation_lut.values()): + yield from invocation_source_uses(invocation) + yield from self._recorded_source_uses.values() + if extra is not None: + yield from invocation_source_uses(extra) + for stream in self._source_streams.values(): + yield f"source {stream.label!r}", stream + # ------------------------------------------------------------------ # Diagram (ITL-1197) # ------------------------------------------------------------------ @@ -446,7 +468,7 @@ def reset(self) -> None: """No-op — all recording state is additive and persists across with-blocks. Note: - ``_invocation_lut``, ``_source_streams``, and ``_hash_graph`` + ``_invocation_lut``, ``_recorded_source_uses``, ``_source_streams``, and ``_hash_graph`` intentionally accumulate across ``with`` blocks. ``_persistent_node_map``, ``_node_lut``, ``_upstreams``, and ``_graph_edges`` are compiled artifacts overwritten by each @@ -509,6 +531,7 @@ def compile(self) -> None: # the last invocation would otherwise connect a branch recorded over one # restriction to another (ITL-1218). require_one_restriction(self._held_streams()) + require_consistent_sources(self._source_uses()) source_node_cls = self.source_node_class @@ -800,6 +823,11 @@ def from_invocations( A compiled instance of ``cls``. """ instance = cls(name=name) + require_consistent_sources( + use + for invocation in graph.invocations + for use in invocation_source_uses(invocation) + ) instance._source_streams = dict(graph.source_streams) for inv in graph.invocations: key = inv.content_hash().to_string() diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 2f80d1fa0..96f741ecd 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -44,6 +44,7 @@ run_node_summaries, warn_row_failures, ) +from orcapod.pipeline.source_consistency import require_consistent_sources from orcapod.protocols import core_protocols as cp from orcapod.databases.utils import as_table_committing from orcapod.types import NodeConfig @@ -392,7 +393,7 @@ def from_pipeline( bound_sources: dict[str, cp.StreamProtocol] = dict(sources or {}) - # Validate sources against SourceNode schemas. + # Report unknown names against the blueprint. Bind checks the sources. if bound_sources: source_names = { node.name @@ -405,9 +406,6 @@ def from_pipeline( f"from_pipeline() received source keys with no matching SourceNode: " f"{sorted(unknown)}. Known names: {sorted(source_names)}" ) - for node in pipeline._persistent_node_map.values(): - if isinstance(node, SourceNodeBase) and node.name in bound_sources: - node.validate(bound_sources[node.name]) # Reconstruct via InvocationGraph (creates unbound SourceJobNodes). # _compiled_pipeline is intentionally left as None here so the lazy @@ -468,6 +466,8 @@ def bind( the job's own database again, at ``/_result`` (ITL-1408). Raises: + InconsistentSourceError: If two sources sharing a source ID have + different schemas, or both hold fixed rows and those rows differ. SourceSpecMismatchError: If any source's columns differ from its slot's declared names, roles or types. ValueError: If a source key has no matching ``SourceJobNode`` slot, or an @@ -503,9 +503,6 @@ def bind( f"(SourceJobNode): {sorted(unknown)}. " f"Known slot names: {sorted(source_names)}" ) - for node in (self._persistent_node_map or {}).values(): - if isinstance(node, SourceNodeBase) and node.name in sources: - node.validate(sources[node.name]) # A database that cannot store a node's tables is refused before anything # changes too (ITL-1162), and so is a caching operator over a restricted @@ -519,6 +516,15 @@ def bind( for node in (self._persistent_node_map or {}).values() if isinstance(node, SourceJobNode) and node.name in to_bind ] + require_consistent_sources( + ( + (f"node {node.label!r}", node) + for node in self._persistent_node_map.values() + ), + rebinding, + ) + for node, source in rebinding: + node.validate(source) refuse_restriction_conflicts( (self._persistent_node_map or {}).values(), rebinding=rebinding ) @@ -1297,6 +1303,11 @@ def _prepare_run( ) # --- Build hash-keyed OrcaDAG for topological ordering + exclusion --- + # A caller can change a slot or proxy directly after binding the job. + require_consistent_sources( + (f"node {node.label!r}", node) + for node in self._persistent_node_map.values() + ) hash_dag: OrcaDAG[str] = OrcaDAG() for u, v in self._graph_edges: hash_dag.add_edge(u, v) @@ -1756,6 +1767,8 @@ def load( results. Raises: + InconsistentSourceError: If reconstructed sources sharing a source ID + have different schemas. ValueError: If the file's format version is not the one this Orcapod writes (an earlier format is refused, never migrated), or if it was saved before the database key was renamed (``bindings.store`` @@ -1876,6 +1889,10 @@ def load( spec_name, ) + require_consistent_sources( + (f"slot {name!r}", source) for name, source in sources.items() + ) + # Reconstruct database effective_database = database if effective_database is None: diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py new file mode 100644 index 000000000..2f14881d2 --- /dev/null +++ b/src/orcapod/pipeline/source_consistency.py @@ -0,0 +1,108 @@ +"""Validation of sources sharing a canonical source ID within one graph.""" + +from __future__ import annotations + +from collections.abc import Iterable +from typing import TYPE_CHECKING + +from orcapod.errors import InconsistentSourceError +from orcapod.utils.schema_utils import arrow_schema_identity + +if TYPE_CHECKING: + from orcapod.core.sources.base import RootSource + from orcapod.pipeline.pod_invocation import PodInvocation + from orcapod.pipeline.restrictions import Rebinding + from orcapod.protocols.core_protocols import StreamProtocol + +SourceUse = tuple[str, "StreamProtocol"] + + +def invocation_source_uses(invocation: PodInvocation) -> Iterable[SourceUse]: + """Name the input streams of a recorded step for diagnostics.""" + label = invocation.label or getattr( + invocation.pod, "label", type(invocation.pod).__name__ + ) + for index, stream in enumerate(invocation.input_streams, 1): + name = f"step {label!r}" + if len(invocation.input_streams) > 1: + name += f" input {index}" + yield name, stream + + +def _root_uses( + uses: Iterable[SourceUse], + rebinding: Rebinding, +) -> Iterable[tuple[str, RootSource]]: + """Walk to each source object, carrying its step or slot name.""" + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.sources.base import RootSource + + replacements = {id(slot): source for slot, source in rebinding} + visited: set[int] = set() + pending = list(reversed(list(uses))) + while pending: + location, stream = pending.pop() + if id(stream) in visited: + continue + visited.add(id(stream)) + if isinstance(stream, RootSource): + yield location, stream + elif isinstance(stream, SourceJobNode): + bound = replacements.get(id(stream), stream.bound_source) + if bound is not None: + pending.append((f"slot {stream.name!r}", bound)) + else: + # Loaded nodes can have inputs that could not be reconstructed. + upstreams: tuple[StreamProtocol | None, ...] = stream.upstreams + pending.extend( + (location, upstream) + for upstream in reversed(upstreams) + if upstream is not None + ) + + +def require_consistent_sources( + uses: Iterable[SourceUse], + rebinding: Rebinding = (), +) -> None: + """Refuse schema differences and conflicting fixed rows at a shared address. + + Compare distinct objects only. A live source has no fixed rows to compare, + but does not prevent comparing two fixed sources that share its address. + For a bind, use the prospective sources alongside every unchanged binding. + + Raises: + InconsistentSourceError: Naming the sources and remedy for a conflict. + """ + by_id: dict[str, list[tuple[str, RootSource]]] = {} + for location, source in _root_uses(uses, rebinding): + by_id.setdefault(source.source_id, []).append((location, source)) + + for source_id, group in by_id.items(): + if len(group) < 2: + continue + first_location, first = group[0] + schema = arrow_schema_identity(*first.arrow_schemas, first.data_context) + for location, source in group[1:]: + if ( + arrow_schema_identity(*source.arrow_schemas, source.data_context) + != schema + ): + raise InconsistentSourceError( + f"Source {source_id!r} has different schemas in {first_location} " + f"and {location}. Give the sources different source_id values." + ) + + fixed = None + fixed_location = first_location + for location, source in group: + content = source.fixed_content + if content is None: + continue + if fixed is None: + fixed, fixed_location = content, location + elif fixed != content: + raise InconsistentSourceError( + f"Source {source_id!r} has different rows in {fixed_location} " + f"and {location}. Give the sources different source_id values." + ) diff --git a/tests/test_pipeline/test_pipeline_base_recording.py b/tests/test_pipeline/test_pipeline_base_recording.py index 577038223..a21cbd21f 100644 --- a/tests/test_pipeline/test_pipeline_base_recording.py +++ b/tests/test_pipeline/test_pipeline_base_recording.py @@ -240,11 +240,9 @@ def test_same_source_id_different_schema_raises_inconsistent_source_error(self): ) join = Join() pipeline = Pipeline(name="test", auto_compile=False) - with pipeline: - join(s1, s2, label="joined") - with pytest.raises(InconsistentSourceError, match="shared_id"): - pipeline.compile() + with pipeline: + join(s1, s2, label="joined") class TestRecordOperatorPodInvocation: diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py new file mode 100644 index 000000000..a8dfafdd6 --- /dev/null +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -0,0 +1,440 @@ +"""Sources sharing an address must agree on any rows held in memory (ITL-1469).""" + +from __future__ import annotations + +import json +from pathlib import Path +import struct + +import numpy as np +import pyarrow as pa +import pytest + +from orcapod import Pipeline, PipelineJob, function_pod +from orcapod.core.function_pod import _FunctionPodBase +from orcapod.core.sources.base import RootSource +from orcapod.core.sources.source_proxy import SourceProxy +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import ( + InconsistentSourceError, + InputValidationError, + SourceSlotNameCollisionError, +) +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator +from orcapod.sources import ( + ArrowTableSource, + CSVSource, + DataFrameSource, + DerivedSource, + DictSource, + ListSource, +) + + +@function_pod(output_keys="out") +def increment(x: int) -> int: + return x + 1 + + +@function_pod(output_keys="out") +def increment_again(x: int) -> int: + return x + 2 + + +@function_pod(output_keys="out") +def both(x: int, y: int) -> int: + return x + y + + +@function_pod(output_keys="out") +def with_copy(x: int, tag_value: str) -> int: + return x + len(tag_value) + + +@function_pod(output_keys="out") +def with_nested(x: int, y: list[float | None] | None) -> int: + return x + len(y or []) + + +@function_pod(output_keys="out") +def with_array(x: list[np.ndarray]) -> int: # pyright: ignore[reportMissingTypeArgument] # the logical ndarray type is under test + return len(x) + + +@function_pod(output_keys="out") +def with_string(x: str) -> int: + return len(x) + + +def _dict(x: int, name: str = "shared") -> DictSource: + return DictSource(data=[{"x": x}], source_id=name) + + +def _refused( + first: RootSource, + second: RootSource, + graph: Pipeline | PipelineJob, + pod: _FunctionPodBase = increment.pod, +) -> None: + with graph: + pod(first, label="fa") + with pytest.raises(InconsistentSourceError, match="different rows") as error: + pod(second, label="fb") + for part in (first.source_id, "fa", "fb", "source_id"): + assert part in str(error.value) + assert "fb" not in graph.nodes + + +@pytest.mark.parametrize("graph", [Pipeline, PipelineJob]) +def test_issue_reproduction(graph: type[Pipeline] | type[PipelineJob]) -> None: + first, second = _dict(1), _dict(100) + assert first.content_hash() == second.content_hash() + _refused(first, second, graph("conflicts")) + + +@pytest.mark.parametrize("kind", ["arrow", "dict", "frame", "list"]) +@pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +) +def test_fixed_types(kind: str, orchestrator: type) -> None: + def source(x: int) -> RootSource: + rows = [{"t1": "a", "t2": "b", "x": x}] + if kind == "list": + return ListSource( + "x", + [x], + tag_function=lambda _x, _i: {"t1": "a", "t2": "b"}, + source_id="shared", + ) + rows[0]["y"] = 10 + if kind == "arrow": + return ArrowTableSource( + pa.Table.from_pylist(rows), + infer_nullable=True, + tag_columns=["t1", "t2"], + tag_only_columns=True, + source_id="shared", + ) + cls = DictSource if kind == "dict" else DataFrameSource + return cls( + data=rows, + tag_columns=["t1", "t2"], + tag_only_columns=True, + source_id="shared", + ) + + job = PipelineJob(database=InMemoryArrowDatabase()) + pod = increment.pod if kind == "list" else both.pod + _refused(source(1), source(100), job, pod) + job.run(orchestrator=orchestrator()) + assert job.fa.as_table()["out"].to_pylist() == ([2] if kind == "list" else [11]) + + +@pytest.mark.parametrize("column", ["t1", "t2", "x", "y"]) +def test_all_tag_and_data_columns_are_checked(column: str) -> None: + row = {"t1": 1, "t2": 2, "x": 3, "y": 4} + layout = {"t2": 2, "y": 4, "t1": 1, "x": 3} + left = DictSource( + [row], tag_columns=["t1", "t2"], tag_only_columns=True, source_id="shared" + ) + right = DictSource( + [{**layout, column: 100}], + tag_columns=["t2", "t1"], + tag_only_columns=True, + source_id="shared", + ) + _refused(left, right, Pipeline("conflicts"), both.pod) + + +def test_fixed_sources_can_be_wrapped() -> None: + left, right = _dict(1), _dict(100) + wrapper = SourceProxy( + right.source_id, + right.content_hash().to_string(), + right.pipeline_hash().to_string(), + *right.output_schema(), + ) + wrapper.bind(right) + _refused(left, wrapper, PipelineJob()) + + +def test_derived_from_fixed_sources() -> None: + def derived(x: int) -> DerivedSource: + origin = DictSource( + [{"t": "a", "x": x}], + tag_columns="t", + tag_only_columns=True, + source_id="origin", + ) + return DerivedSource( + origin, tags_as_data={"t": "tag_value"}, source_id="shared" + ) + + _refused(derived(1), derived(100), PipelineJob(), with_copy.pod) + + +def test_same_name_across_kinds_still_collides_at_capture_but_can_bind_separate_slots() -> ( + None +): + table = ArrowTableSource( + pa.table({"x": [100]}), infer_nullable=True, source_id="shared" + ) + dictionary = _dict(1) + with pytest.raises(SourceSlotNameCollisionError): + with Pipeline("conflicts"): + increment.pod(dictionary, label="fa") + increment.pod(table, label="fb") + job = _job() + job.bind(sources={"left": dictionary, "right": table}) + assert job.sources["left"] is dictionary + assert job.sources["right"] is table + + +@pytest.mark.parametrize("keyed", [False, True]) +def test_row_order_counts_only_for_positional_ids(keyed: bool) -> None: + rows = [{"k": "a", "t": 10, "x": 1, "y": 3}, {"k": "b", "t": 20, "x": 2, "y": 4}] + + def source(data: list[dict[str, str | int]], tags: list[str]) -> DictSource: + return DictSource( + data, + tag_columns=tags, + tag_only_columns=True, + record_id_columns=["k", "t"] if keyed else None, + source_id="shared", + ) + + first = source(rows, ["k", "t"]) + second = source(list(reversed(rows)), ["t", "k"]) + if keyed: + with PipelineJob() as job: + both.pod(first, label="fa") + both.pod(second, label="fb") + assert set(job.function_pods) == {"fa"} + _refused( + first, + source([rows[1], {**rows[0], "y": 100}], ["t", "k"]), + Pipeline("conflicts"), + both.pod, + ) + else: + _refused(first, second, Pipeline("conflicts"), both.pod) + + +def test_record_ids_count_at_bind() -> None: + job = _job() + positional = _dict(1) + keyed = DictSource([{"x": 1}], record_id_columns="x", source_id="shared") + with pytest.raises(InconsistentSourceError, match="different rows"): + job.bind(sources={"left": positional, "right": keyed}) + + +def test_nulls_nan_signed_zero_and_nested_values() -> None: + nan = struct.unpack("d", struct.pack("Q", 0x7FF8000000000001))[0] + alternate_nan = struct.unpack("d", struct.pack("Q", 0x7FF8000000000002))[0] + layout = pa.schema( + [ + pa.field("x", pa.int64(), nullable=False), + pa.field("y", pa.list_(pa.float64())), + ] + ) + + def source(values: list[float | None]) -> ArrowTableSource: + table = pa.Table.from_pylist([{"x": 1, "y": values}], schema=layout) + return ArrowTableSource(table, source_id="shared") + + first, second = source([nan, -0.0, None]), source([alternate_nan, 0.0, None]) + with PipelineJob() as job: + with_nested.pod(first, label="fa") + with_nested.pod(second, label="fb") + assert set(job.function_pods) == {"fa"} + _refused(first, source([nan, -0.0, 1.0]), PipelineJob(), with_nested.pod) + + +def test_dictionary_columns_are_already_unsupported() -> None: + table = pa.table({"x": pa.array([1, 2]).dictionary_encode()}) + with pytest.raises(InputValidationError, match="dictionary"): + ArrowTableSource(table, source_id="shared") + + +def test_nested_logical_values_are_compared_as_encoded() -> None: + def source(value: int) -> DictSource: + return DictSource( + [{"x": [np.array([value], dtype=np.int64)]}], source_id="shared" + ) + + with Pipeline("conflicts") as pipeline: + with_array.pod(source(1), label="fa") + with_array.pod(source(1), label="fb") + assert set(pipeline.function_pods) == {"fa"} + _refused(source(1), source(100), Pipeline("conflicts"), with_array.pod) + + +def test_zero_rows_use_the_declared_schema() -> None: + def source(values: list[int]) -> ArrowTableSource: + return ArrowTableSource( + pa.Table.from_arrays( + [pa.array(values, type=pa.int64())], + schema=pa.schema([pa.field("x", pa.int64(), nullable=False)]), + ), + source_id="shared", + ) + + with PipelineJob() as job: + increment.pod(source([]), label="fa") + increment.pod(source([]), label="fb") + assert set(job.function_pods) == {"fa"} + _refused(source([]), source([1]), Pipeline("conflicts")) + + +def _job() -> PipelineJob: + with PipelineJob(database=InMemoryArrowDatabase()) as job: + increment.pod(_dict(2, "left"), label="fa") + increment.pod(_dict(3, "right"), label="fb") + return job + + +@pytest.mark.parametrize("loaded", [False, True]) +def test_bind_checks_all_prospective_slots_atomically( + tmp_path: Path, loaded: bool +) -> None: + job = _job() + if loaded: + path = tmp_path / "job.json" + job.save(path) + job = PipelineJob.load(path) + first, second = _dict(1), _dict(100) + before = dict(job.sources) + with pytest.raises(InconsistentSourceError, match="different rows") as error: + job.bind(sources={"left": first, "right": second}) + for part in (first.source_id, "left", "right", "source_id"): + assert part in str(error.value) + assert job.sources == before + job.bind(sources={"left": first}) + job.bind(sources={"left": second}) + assert job.sources["left"] is second + with pytest.raises(InconsistentSourceError, match="different rows"): + job.bind(sources={"right": first}) + job.bind(sources={"right": second}) + assert job.sources["right"] is second + job.bind(sources={"left": _dict(100)}) + + +def test_from_pipeline_checks_the_initial_bind() -> None: + with Pipeline("conflicts") as graph: + increment.pod(_dict(2, "left"), label="fa") + increment.pod(_dict(3, "right"), label="fb") + with pytest.raises(InconsistentSourceError, match="different rows"): + PipelineJob.from_pipeline( + graph, sources={"left": _dict(1), "right": _dict(100)} + ) + + +@pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +) +def test_run_checks_slots_changed_outside_job_bind(orchestrator: type) -> None: + job = _job() + job.nodes["left"].bound_source = _dict(1) + job.nodes["right"].bound_source = _dict(100) + with pytest.raises(InconsistentSourceError, match="different rows"): + job.run(orchestrator=orchestrator()) + assert not job.fa.as_table().num_rows + assert not job.fb.as_table().num_rows + + +def test_load_checks_schema_of_reconstructed_sources(tmp_path: Path) -> None: + left, right = tmp_path / "left.csv", tmp_path / "right.csv" + left.write_text("x\n1\n") + right.write_text("x\ntext\n") + with PipelineJob() as job: + increment.pod(CSVSource(str(left), source_id="left"), label="fa") + with_string.pod(CSVSource(str(right), source_id="right"), label="fb") + path = tmp_path / "job.json" + job.save(path) + saved = json.loads(path.read_text()) + saved["bindings"]["sources"]["right"]["source_name"] = "left" + path.write_text(json.dumps(saved)) + with pytest.raises(InconsistentSourceError, match="different schemas") as error: + PipelineJob.load(path) + for part in ("csv_v1:left", "slot 'left'", "slot 'right'", "source_id"): + assert part in str(error.value) + + +def test_schema_conflicts_at_capture_and_bind() -> None: + def source(kind: pa.DataType, name: str) -> ArrowTableSource: + return ArrowTableSource( + pa.table({"x": pa.array([1], type=kind)}), + infer_nullable=True, + source_id=name, + ) + + first, second = source(pa.int32(), "shared"), source(pa.int64(), "shared") + with pytest.raises(InconsistentSourceError, match="different schemas"): + with Pipeline("conflicts"): + increment.pod(first, label="fa") + increment.pod(second, label="fb") + + with PipelineJob() as job: + increment.pod(source(pa.int32(), "left"), label="fa") + increment.pod(source(pa.int64(), "right"), label="fb") + with pytest.raises(InconsistentSourceError, match="different schemas") as error: + job.bind(sources={"left": first, "right": second}) + for part in (first.source_id, "left", "right", "source_id"): + assert part in str(error.value) + + +def test_one_object_is_allowed_in_several_steps() -> None: + source = _dict(1) + with PipelineJob() as job: + increment.pod(source, label="fa") + increment_again.pod(source, label="fb") + assert set(job.nodes) == {"shared", "fa", "fb"} + + +def test_dynamic_csv_and_cached_sources_are_allowed(tmp_path: Path) -> None: + first_path, second_path = tmp_path / "first.csv", tmp_path / "second.csv" + first_path.write_text("x\n1\n") + second_path.write_text("x\n100\n") + with PipelineJob() as job: + increment.pod(CSVSource(str(first_path), source_id="shared"), label="fa") + increment.pod(CSVSource(str(second_path), source_id="shared"), label="fb") + assert set(job.function_pods) == {"fa"} + + with PipelineJob() as job: + increment.pod(_dict(1).cached(InMemoryArrowDatabase()), label="fa") + increment.pod(_dict(100).cached(InMemoryArrowDatabase()), label="fb") + assert "fa" in job.nodes + + +def test_a_live_source_does_not_hide_two_conflicting_fixed_sources() -> None: + live = _dict(2).cached(InMemoryArrowDatabase()) + with PipelineJob(): + increment.pod(live, label="fa") + increment.pod(_dict(1), label="fb") + with pytest.raises(InconsistentSourceError, match="different rows") as error: + increment.pod(_dict(100), label="fc") + assert "step 'fb'" in str(error.value) + assert "step 'fc'" in str(error.value) + + +def test_issue_derived_job_sources_are_dynamic() -> None: + def derived(x: int) -> DerivedSource: + with PipelineJob(database=InMemoryArrowDatabase()) as job: + increment.pod(_dict(x), label="result") + job.run() + return job.result.as_source() + + first, second = derived(1), derived(100) + assert first.source_id == second.source_id + assert first.as_table()["out"].to_pylist() == [2] + assert second.as_table()["out"].to_pylist() == [101] + + @function_pod(output_keys="value") + def downstream(out: int) -> int: + return out + 1 + + with PipelineJob() as job: + downstream.pod(first, label="fa") + downstream.pod(second, label="fb") + assert "fa" in job.nodes From 18abc8ef3e7436cf092838b73e5f71ea5cf39037 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 13:53:28 -0800 Subject: [PATCH 02/42] fix(pipeline): name the function step in projection conflicts --- src/orcapod/core/function_pod.py | 13 +++++++++++-- tests/test_pipeline/test_source_id_conflicts.py | 6 ++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 8a24c3b49..49091757a 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -36,7 +36,11 @@ StreamView, ) from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER -from orcapod.errors import OrcapodDatabaseError, TypeIdentityError +from orcapod.errors import ( + InconsistentSourceError, + OrcapodDatabaseError, + TypeIdentityError, +) from orcapod.utils.database_errors import keep_database_error, note_callback_failure from orcapod.protocols.core_protocols import ( ArgumentGroup, @@ -855,7 +859,12 @@ def __call__( # The select is Orcapod's own step: the data-tags it turns into # plain tags are not reported (ITL-1023). with materialization_diagnostic_off(): - input_stream = SelectDataColumns(columns=kept)(input_stream) + try: + input_stream = SelectDataColumns(columns=kept)(input_stream) + except InconsistentSourceError as exc: + raise InconsistentSourceError( + f"While capturing step {label or self.label!r}: {exc}" + ) from exc if fall_through_pod is not None and data_tags: return FallThroughPod(fall_through_pod, data_tags).process( input_stream, label=label diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index a8dfafdd6..ae2761a13 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -159,6 +159,12 @@ def test_fixed_sources_can_be_wrapped() -> None: _refused(left, wrapper, PipelineJob()) +def test_implicit_projection_conflict_names_both_function_steps() -> None: + first = DictSource([{"x": 1, "y": 2}], source_id="shared") + second = DictSource([{"x": 100, "y": 2}], source_id="shared") + _refused(first, second, PipelineJob()) + + def test_derived_from_fixed_sources() -> None: def derived(x: int) -> DerivedSource: origin = DictSource( From 51acf6d27f5cff6f739c080905fe35327f8721b0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 02:27:16 -0800 Subject: [PATCH 03/42] fix(pipeline): validate refreshed and rebound source rows --- src/orcapod/pipeline/base.py | 6 +- src/orcapod/pipeline/job.py | 40 ++++- src/orcapod/pipeline/source_consistency.py | 40 +++-- .../test_pipeline_base_recording.py | 45 +++--- .../test_pipeline/test_source_id_conflicts.py | 150 +++++++++++++++--- 5 files changed, 214 insertions(+), 67 deletions(-) diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index cee05bc78..3095b7d86 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -398,6 +398,10 @@ def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse for stream in self._source_streams.values(): yield f"source {stream.label!r}", stream + def _source_node_from_recording(self, key: str) -> Any: + """Create the source node for a recorded leaf.""" + return self.source_node_class.from_stream(self._source_streams[key]) + # ------------------------------------------------------------------ # Diagram (ITL-1197) # ------------------------------------------------------------------ @@ -538,7 +542,7 @@ def compile(self) -> None: # 1. Resolve source nodes in hash order, then insert them by their slot # labels. The original stream hash breaks ties between identical labels. sources = [ - (h, source_node_cls.from_stream(self._source_streams[h])) + (h, self._source_node_from_recording(h)) for h in sorted(self._source_streams.keys() - self._invocation_lut.keys()) ] node_map: dict[str, Any] = dict( diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 96f741ecd..4f312114f 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -44,7 +44,11 @@ run_node_summaries, warn_row_failures, ) -from orcapod.pipeline.source_consistency import require_consistent_sources +from orcapod.pipeline.source_consistency import ( + invocation_source_uses, + require_consistent_sources, + root_source_uses, +) from orcapod.protocols import core_protocols as cp from orcapod.databases.utils import as_table_committing from orcapod.types import NodeConfig @@ -56,6 +60,8 @@ from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.execution_context import ExecutionContext from orcapod.pipeline.graph import Pipeline + from orcapod.pipeline.pod_invocation import PodInvocation + from orcapod.pipeline.source_consistency import SourceUse from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.observability_protocols import ExecutionObserverProtocol @@ -193,6 +199,7 @@ def __init__( # hash; avoids name collisions when multiple concrete sources share # the same class name (e.g. two ArrowTableSource objects). self._sources_by_hash: dict[str, cp.StreamProtocol] = {} + self._rebound_source_keys: set[str] = set() self._has_run: bool = False # True only while the last run started has finished and committed its writes: # what the database then holds for each node is what that run left (ITL-1043). @@ -220,6 +227,29 @@ def __exit__(self, exc_type=None, exc_value=None, traceback=None) -> None: if exc_type is None and self._auto_compile: self.compile() + def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse]: + """Use current bindings for history and check new inputs as supplied.""" + bound_leaves = { + key: slot + for key in self._rebound_source_keys + if isinstance(slot := self._persistent_node_map.get(key), SourceJobNode) + } + recorded = super()._source_uses() + if bound_leaves: + yield from root_source_uses(recorded, bound_leaves=bound_leaves) + else: + yield from recorded + if extra is not None: + yield from invocation_source_uses(extra) + + def _source_node_from_recording(self, key: str) -> SourceJobNode: + """Preserve an explicit binding when recompiling its slot.""" + if key in self._rebound_source_keys: + slot = self._persistent_node_map.get(key) + if isinstance(slot, SourceJobNode): + return self.source_node_class.from_stream(slot) + return self.source_node_class.from_stream(self._source_streams[key]) + def compile(self) -> None: """Compile recorded invocations into a frozen DAG of job nodes. @@ -549,6 +579,7 @@ def bind( for h, job_node in (self._persistent_node_map or {}).items(): if isinstance(job_node, SourceJobNode) and job_node.name in sources: job_node.bound_source = sources[job_node.name] + self._rebound_source_keys.add(h) self._sources_by_hash[h] = sources[job_node.name] # Also index by schema-based hash (matches blueprint pipeline keys). schema_hash = job_node.as_node().content_hash().to_string() @@ -1304,10 +1335,11 @@ def _prepare_run( # --- Build hash-keyed OrcaDAG for topological ordering + exclusion --- # A caller can change a slot or proxy directly after binding the job. - require_consistent_sources( + source_uses = [ (f"node {node.label!r}", node) for node in self._persistent_node_map.values() - ) + ] + require_consistent_sources(source_uses) hash_dag: OrcaDAG[str] = OrcaDAG() for u, v in self._graph_edges: hash_dag.add_edge(u, v) @@ -1397,6 +1429,8 @@ def _prepare_run( # Every source first takes in any new data, moving its modified time, before # the state rule judges any node (ITL-1102). unchecked = check_sources(exec_dag.nodes()) + # Refresh can replace cached derived rows after their initial comparison. + require_consistent_sources(source_uses) # A restricted source under an aggregation is allowed, and said (ITL-1218). warn_restricted_aggregation(exec_dag) # The state rule (ITL-1095): a node that holds a current run is not run again. diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index 2f14881d2..a79d50d54 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -2,13 +2,14 @@ from __future__ import annotations -from collections.abc import Iterable -from typing import TYPE_CHECKING +from collections.abc import Iterable, Mapping +from typing import TYPE_CHECKING, cast from orcapod.errors import InconsistentSourceError from orcapod.utils.schema_utils import arrow_schema_identity if TYPE_CHECKING: + from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources.base import RootSource from orcapod.pipeline.pod_invocation import PodInvocation from orcapod.pipeline.restrictions import Rebinding @@ -29,33 +30,44 @@ def invocation_source_uses(invocation: PodInvocation) -> Iterable[SourceUse]: yield name, stream -def _root_uses( +def root_source_uses( uses: Iterable[SourceUse], - rebinding: Rebinding, + rebinding: Rebinding = (), + *, + bound_leaves: Mapping[str, SourceJobNode] | None = None, ) -> Iterable[tuple[str, RootSource]]: - """Walk to each source object, carrying its step or slot name.""" + """Walk to each source object, using live bindings for replaced graph leaves.""" from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources.base import RootSource replacements = {id(slot): source for slot, source in rebinding} - visited: set[int] = set() - pending = list(reversed(list(uses))) + visited: set[tuple[int, bool]] = set() + pending = [ + (location, stream, bool(bound_leaves)) + for location, stream in reversed(list(uses)) + ] while pending: - location, stream = pending.pop() - if id(stream) in visited: + location, stream, recorded = pending.pop() + key = (id(stream), recorded) + if key in visited: continue - visited.add(id(stream)) + visited.add(key) + if recorded and bound_leaves is not None: + slot = bound_leaves.get(stream.content_hash().to_string()) + if slot is not None: + pending.append((location, slot, False)) + continue if isinstance(stream, RootSource): yield location, stream elif isinstance(stream, SourceJobNode): bound = replacements.get(id(stream), stream.bound_source) if bound is not None: - pending.append((f"slot {stream.name!r}", bound)) + pending.append((f"slot {stream.name!r}", bound, False)) else: # Loaded nodes can have inputs that could not be reconstructed. - upstreams: tuple[StreamProtocol | None, ...] = stream.upstreams + upstreams = cast("tuple[StreamProtocol | None, ...]", stream.upstreams) pending.extend( - (location, upstream) + (location, upstream, recorded) for upstream in reversed(upstreams) if upstream is not None ) @@ -75,7 +87,7 @@ def require_consistent_sources( InconsistentSourceError: Naming the sources and remedy for a conflict. """ by_id: dict[str, list[tuple[str, RootSource]]] = {} - for location, source in _root_uses(uses, rebinding): + for location, source in root_source_uses(uses, rebinding): by_id.setdefault(source.source_id, []).append((location, source)) for source_id, group in by_id.items(): diff --git a/tests/test_pipeline/test_pipeline_base_recording.py b/tests/test_pipeline/test_pipeline_base_recording.py index a21cbd21f..770e23d25 100644 --- a/tests/test_pipeline/test_pipeline_base_recording.py +++ b/tests/test_pipeline/test_pipeline_base_recording.py @@ -15,6 +15,15 @@ from orcapod.core.sources import ArrowTableSource from orcapod.pipeline import Pipeline +from ..test_core.operators.several_items import ( + DATA_FIRST_REVERSED, + MAIN, + P, + PLAIN, + Arrangement, + make_source, +) + def _src(tag_col: str, data_col: str) -> ArrowTableSource: table = pa.table( @@ -208,41 +217,25 @@ def test_explicit_source_id_overrides_hash_name(self): ) assert names == ["left_input", "right_input"] - def test_same_source_id_different_schema_raises_inconsistent_source_error(self): + @pytest.mark.parametrize("reverse", [False, True]) + def test_same_source_id_different_schema_raises_inconsistent_source_error( + self, reverse: bool + ) -> None: """Two sources with the same source_id but different schemas raise an error.""" from orcapod.errors import InconsistentSourceError - s1 = ArrowTableSource( - pa.table( - { - "key": pa.array(["a"], type=pa.large_string()), - "value": pa.array([1], type=pa.int64()), - } - ), - tag_columns=["key"], - tag_only_columns=True, + main = make_source(MAIN, source_id="shared_id") + partner = make_source( + P, + Arrangement(tuple(reversed(P.tags)), DATA_FIRST_REVERSED, PLAIN), source_id="shared_id", - infer_nullable=True, - ) - s2 = ArrowTableSource( - pa.table( - { - "key": pa.array(["a"], type=pa.large_string()), - "score": pa.array( - [1.0], type=pa.float64() - ), # different data column - } - ), - tag_columns=["key"], - tag_only_columns=True, - source_id="shared_id", - infer_nullable=True, ) + inputs = (partner, main) if reverse else (main, partner) join = Join() pipeline = Pipeline(name="test", auto_compile=False) with pytest.raises(InconsistentSourceError, match="shared_id"): with pipeline: - join(s1, s2, label="joined") + join(*inputs, label="joined") class TestRecordOperatorPodInvocation: diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index ae2761a13..4b7e95ae4 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -31,6 +31,17 @@ ListSource, ) +from ..test_core.operators.several_items import ( + DATA_FIRST_REVERSED, + MIXED, + P, + PLAIN, + ROLES, + TAGS_FIRST, + Arrangement, + make_table, +) + @function_pod(output_keys="out") def increment(x: int) -> int: @@ -47,6 +58,11 @@ def both(x: int, y: int) -> int: return x + y +@function_pod(output_keys="out") +def with_pair(p1: int, p2: str) -> int: + return p1 + len(p2) + + @function_pod(output_keys="out") def with_copy(x: int, tag_value: str) -> int: return x + len(tag_value) @@ -67,6 +83,11 @@ def with_string(x: str) -> int: return len(x) +@function_pod(output_keys="next") +def consume_output(out: int) -> int: + return out * 2 + + def _dict(x: int, name: str = "shared") -> DictSource: return DictSource(data=[{"x": x}], source_id=name) @@ -93,42 +114,69 @@ def test_issue_reproduction(graph: type[Pipeline] | type[PipelineJob]) -> None: _refused(first, second, graph("conflicts")) -@pytest.mark.parametrize("kind", ["arrow", "dict", "frame", "list"]) +@pytest.mark.parametrize("kind", ["arrow", "dict", "frame"]) +@pytest.mark.parametrize("role", ROLES) +@pytest.mark.parametrize("reverse", [False, True]) @pytest.mark.parametrize( "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] ) -def test_fixed_types(kind: str, orchestrator: type) -> None: - def source(x: int) -> RootSource: - rows = [{"t1": "a", "t2": "b", "x": x}] - if kind == "list": - return ListSource( - "x", - [x], - tag_function=lambda _x, _i: {"t1": "a", "t2": "b"}, - source_id="shared", - ) - rows[0]["y"] = 10 +def test_fixed_types(kind: str, role: str, reverse: bool, orchestrator: type) -> None: + def source(row: int, arrangement: Arrangement) -> RootSource: + table = make_table(P, arrangement, rows=[row]) + tag_only = True if role == PLAIN else [P.mixed_plain] if role == MIXED else [] if kind == "arrow": return ArrowTableSource( - pa.Table.from_pylist(rows), - infer_nullable=True, - tag_columns=["t1", "t2"], - tag_only_columns=True, + table, + tag_columns=arrangement.tag_order, + tag_only_columns=tag_only, source_id="shared", ) cls = DictSource if kind == "dict" else DataFrameSource return cls( - data=rows, - tag_columns=["t1", "t2"], - tag_only_columns=True, + data=table.to_pylist(), + tag_columns=arrangement.tag_order, + tag_only_columns=tag_only, + source_id="shared", + ) + + arrangements = [ + Arrangement(P.tags, TAGS_FIRST, role), + Arrangement(tuple(reversed(P.tags)), DATA_FIRST_REVERSED, role), + ] + first, second = arrangements[::-1] if reverse else arrangements + with PipelineJob(database=InMemoryArrowDatabase()) as job: + with_pair.pod(source(0, first), label="fa") + with_pair.pod(source(0, second), label="same") + with pytest.raises(InconsistentSourceError, match="different rows"): + with_pair.pod(source(1, second), label="conflict") + assert set(job.function_pods) == {"fa"} + job.run(orchestrator=orchestrator()) + assert job.fa.as_table()["out"].to_pylist() == [8] + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +) +def test_fixed_list_source(reverse: bool, orchestrator: type) -> None: + def source(x: int, tag_order: tuple[str, ...]) -> ListSource: + tags = {"t1": "a", "t2": "b"} + return ListSource( + "x", + [x], + tag_function=lambda _x, _i: {name: tags[name] for name in tag_order}, source_id="shared", ) - job = PipelineJob(database=InMemoryArrowDatabase()) - pod = increment.pod if kind == "list" else both.pod - _refused(source(1), source(100), job, pod) + tags = ("t2", "t1") if reverse else ("t1", "t2") + with PipelineJob(database=InMemoryArrowDatabase()) as job: + increment.pod(source(1, tags), label="fa") + increment.pod(source(1, tags[::-1]), label="same") + with pytest.raises(InconsistentSourceError, match="different rows"): + increment.pod(source(100, tags[::-1]), label="conflict") + assert set(job.function_pods) == {"fa"} job.run(orchestrator=orchestrator()) - assert job.fa.as_table()["out"].to_pylist() == ([2] if kind == "list" else [11]) + assert job.fa.as_table()["out"].to_pylist() == [2] @pytest.mark.parametrize("column", ["t1", "t2", "x", "y"]) @@ -349,6 +397,62 @@ def test_run_checks_slots_changed_outside_job_bind(orchestrator: type) -> None: assert not job.fb.as_table().num_rows +@pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +) +def test_run_rechecks_derived_rows_after_refresh(orchestrator: type) -> None: + def origin(x: int) -> DictSource: + return DictSource( + [{"t1": "a", "t2": "b", "x": x, "y": 2}], + tag_columns=["t1", "t2"], + tag_only_columns=True, + source_id="origin", + ) + + def derived(source: RootSource, name: str) -> DerivedSource: + return DerivedSource(source, tags_as_data={"t1": "tag_value"}, source_id=name) + + original = origin(1) + proxy = SourceProxy( + original.source_id, + original.content_hash().to_string(), + original.pipeline_hash().to_string(), + *original.output_schema(), + ) + proxy.bind(original) + first, second = derived(original, "shared"), derived(proxy, "shared") + with PipelineJob(database=InMemoryArrowDatabase()) as job: + with_copy.pod(derived(original, "left"), label="fa") + with_copy.pod(derived(original, "right"), label="fb") + + job.bind(sources={"left": first, "right": second}) + proxy.bind(origin(100)) + assert second.as_table()["x"].to_pylist() == [1] + with pytest.raises(InconsistentSourceError, match="different rows") as error: + job.run(orchestrator=orchestrator()) + assert "slot 'left'" in str(error.value) + assert "slot 'right'" in str(error.value) + assert second.as_table()["x"].to_pylist() == [100] + assert job.last_run is None + + +def test_additive_recording_uses_the_current_binding() -> None: + with PipelineJob(database=InMemoryArrowDatabase()) as job: + increment.pod(_dict(1), label="fa") + + replacement = _dict(100) + job.bind(sources={"shared": replacement}) + with job: + with pytest.raises(InconsistentSourceError, match="different rows"): + increment.pod(_dict(2), label="conflict") + consume_output.pod(job.fa, label="next") + + assert job.nodes["shared"].bound_source is replacement + job.run() + assert job.fa.as_table()["out"].to_pylist() == [101] + assert job.next.as_table()["next"].to_pylist() == [202] + + def test_load_checks_schema_of_reconstructed_sources(tmp_path: Path) -> None: left, right = tmp_path / "left.csv", tmp_path / "right.csv" left.write_text("x\n1\n") From 4bfcc2c12dcc714d43d052b77e4b9244625234d5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 02:54:23 -0800 Subject: [PATCH 04/42] fix(pipeline): compare a bound proxy using its live schema --- src/orcapod/pipeline/source_consistency.py | 21 +++++++++--- .../test_pipeline/test_source_id_conflicts.py | 34 +++++++++++++++++++ 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index a79d50d54..b39f15ad0 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -14,6 +14,7 @@ from orcapod.pipeline.pod_invocation import PodInvocation from orcapod.pipeline.restrictions import Rebinding from orcapod.protocols.core_protocols import StreamProtocol + from orcapod.types import ContentHash SourceUse = tuple[str, "StreamProtocol"] @@ -73,6 +74,19 @@ def root_source_uses( ) +def _comparison_schema(source: RootSource) -> tuple[ContentHash, ContentHash]: + """Use the live proxy schema for the comparison, even after an unbound read.""" + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.core.streams.base import typed_arrow_schemas + + if isinstance(source, SourceProxy) and source.is_bound: + # The cached schema can describe the unbound proxy's Python types. + schemas = typed_arrow_schemas(source, own=False) + else: + schemas = source.arrow_schemas + return arrow_schema_identity(*schemas, source.data_context) + + def require_consistent_sources( uses: Iterable[SourceUse], rebinding: Rebinding = (), @@ -94,12 +108,9 @@ def require_consistent_sources( if len(group) < 2: continue first_location, first = group[0] - schema = arrow_schema_identity(*first.arrow_schemas, first.data_context) + schema = _comparison_schema(first) for location, source in group[1:]: - if ( - arrow_schema_identity(*source.arrow_schemas, source.data_context) - != schema - ): + if _comparison_schema(source) != schema: raise InconsistentSourceError( f"Source {source_id!r} has different schemas in {first_location} " f"and {location}. Give the sources different source_id values." diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index 4b7e95ae4..204a546a4 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -207,6 +207,40 @@ def test_fixed_sources_can_be_wrapped() -> None: _refused(left, wrapper, PipelineJob()) +@pytest.mark.parametrize("value", [1, 100]) +def test_bound_proxy_uses_its_live_arrow_schema_for_collision_checks( + value: int, +) -> None: + def source(x: int) -> ArrowTableSource: + return ArrowTableSource( + pa.table({"x": pa.array([x], type=pa.int32())}), + infer_nullable=True, + source_id="shared", + ) + + first, delegate = source(1), source(value) + proxy = SourceProxy( + delegate.source_id, + delegate.content_hash().to_string(), + delegate.pipeline_hash().to_string(), + *delegate.output_schema(), + ) + # An unbound proxy knows only the Python type, which defaults to int64. + assert proxy.arrow_schemas[1].field("x").type == pa.int64() + proxy.bind(delegate) + + if value != 1: + _refused(first, proxy, PipelineJob()) + return + + with PipelineJob(database=InMemoryArrowDatabase()) as job: + increment.pod(first, label="fa") + increment.pod(proxy, label="fb") + assert set(job.function_pods) == {"fa"} + job.run() + assert job.fa.as_table()["out"].to_pylist() == [2] + + def test_implicit_projection_conflict_names_both_function_steps() -> None: first = DictSource([{"x": 1, "y": 2}], source_id="shared") second = DictSource([{"x": 100, "y": 2}], source_id="shared") From 2f44c80eefb9f0f0ee89cbf534b16ad31a2c447e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 18:02:14 -0800 Subject: [PATCH 05/42] test(pipeline): cover the shared source ID key-column stopgap --- .../test_pipeline/test_source_id_conflicts.py | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index 204a546a4..f15c75e2f 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -279,6 +279,33 @@ def test_same_name_across_kinds_still_collides_at_capture_but_can_bind_separate_ assert job.sources["right"] is table +@pytest.mark.parametrize("reverse", [False, True]) +def test_same_source_id_with_different_key_columns_is_refused_at_build( + tmp_path: Path, reverse: bool +) -> None: + path = tmp_path / "shared.csv" + path.write_text("t1,t2,x,y\na,b,1,2\nc,d,3,4\n") + sources = [ + CSVSource( + str(path), + source_id="shared", + tag_columns=["t1", "t2"], + tag_only_columns=True, + record_id_columns=keys, + ) + for keys in (["t1", "x"], ["t2", "y"]) + ] + first, second = sources[::-1] if reverse else sources + assert first.source_id == second.source_id + assert first.arrow_schemas == second.arrow_schemas + assert first.content_hash() != second.content_hash() + + with pytest.raises(SourceSlotNameCollisionError, match="ITL-1506"): + with Pipeline("conflicts"): + both.pod(first, label="fa") + both.pod(second, label="fb") + + @pytest.mark.parametrize("keyed", [False, True]) def test_row_order_counts_only_for_positional_ids(keyed: bool) -> None: rows = [{"k": "a", "t": 10, "x": 1, "y": 3}, {"k": "b", "t": 20, "x": 2, "y": 4}] From 3e8544f41ab1ef390489d025c1c595b05236f0c6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 18:03:58 -0800 Subject: [PATCH 06/42] fix(pipeline): explain the temporary key-column slot collision --- changelog.d/ITL-1469.md | 5 +++++ docs/concepts/sources.md | 4 ++++ src/orcapod/errors.py | 2 ++ src/orcapod/pipeline/base.py | 15 +++++++++++++++ 4 files changed, 26 insertions(+) diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index 14de9d1ae..2afe8d17b 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -4,3 +4,8 @@ source ID and schema but contain different rows. The error names the conflicting steps or slots. Job binding and loading also reject different schemas at a shared source ID. + +### Known limitations + +- A pipeline still refuses sources that share a source ID and differ only in + their key columns. ITL-1506 will allow them in distinct named slots. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 18612f721..5d1882ed1 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1009,6 +1009,10 @@ order or content can vary between runs, pass an explicit, stable `source_id` **a key columns that are unique per row; this avoids both the duplicate entries and the repeated deliveries. +A pipeline currently refuses sources that share a `source_id` and differ only in their +key columns. ITL-1506 will allow them to share that ID when each reading has a distinct +slot name. + An in-memory source with key columns and no `source_id` can instead hash its rows in key order: pass `hash_in_key_order=True` (`ArrowTableSource`, `DictSource`, `DataFrameSource`, `ListSource`; ITL-1272). The table is hashed sorted by the key columns, in the order you list diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 00a922708..b79124ca9 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -766,6 +766,8 @@ class SourceSlotNameCollisionError(ValueError): different sources (another kind, another version or another id) whose names are equal would share one slot and one would replace the other. The job refuses them; give one of them its own name (``source_id=`` when it is built). + ITL-1506 will lift this refusal for sources that differ only in key columns + when they have distinct named slots. """ diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 3095b7d86..c7c3f43d9 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -50,6 +50,8 @@ def _refuse_sources_sharing_a_slot_name( would share one ``job.sources`` and ``bind`` key, and one would replace the other. Only sources are refused here: a slot of another stream is named by its label and content hash. + ITL-1506 will lift the refusal for sources that differ only in key columns + once they can occupy distinct named slots. Raises: SourceSlotNameCollisionError: Naming every full source id and the remedy. @@ -62,6 +64,19 @@ def _refuse_sources_sharing_a_slot_name( from orcapod.errors import SourceSlotNameCollisionError ids = sorted({s.source_id for s in sources}) + if len(ids) == 1: + keys = {getattr(s, "_key_columns", None) for s in sources} + # Schema agreement was checked before slot naming. ITL-1506 will let + # readings with different keys occupy distinct named slots. + if None not in keys and len(keys) == len(sources): + raise SourceSlotNameCollisionError( + f"{len(sources)} sources with source id {ids[0]!r} share one schema " + f"and differ only in key columns (record_id_columns). They would " + f"take the same slot name {slot_name!r}, so this is refused for now. " + "A later version will allow this with distinct slot names (ITL-1506). " + "For now, give each source its own name with source_id=... when it " + "is built." + ) described = ( ", ".join(repr(i) for i in ids) if len(ids) > 1 From f2dfb385937108bdd6c5be15e87e22a1ec6582bd Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 18:12:32 -0800 Subject: [PATCH 07/42] test(pipeline): compare readings of one dataset by rows when key columns differ Co-Authored-By: Claude Opus 5.5 --- .../test_pipeline/test_source_id_conflicts.py | 199 +++++++++++++++++- 1 file changed, 197 insertions(+), 2 deletions(-) diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index f15c75e2f..d8849275e 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -336,12 +336,20 @@ def source(data: list[dict[str, str | int]], tags: list[str]) -> DictSource: _refused(first, second, Pipeline("conflicts"), both.pod) -def test_record_ids_count_at_bind() -> None: +def test_bind_compares_rows_without_record_ids_when_keys_differ() -> None: + # A source id names a dataset; key columns only name its rows. Two readings of + # the same rows with other keys bind into distinct named slots; other rows do not. job = _job() positional = _dict(1) keyed = DictSource([{"x": 1}], record_id_columns="x", source_id="shared") + job.bind(sources={"left": positional, "right": keyed}) + assert job.sources["left"] is positional + assert job.sources["right"] is keyed + + job = _job() + other = DictSource([{"x": 100}], record_id_columns="x", source_id="shared") with pytest.raises(InconsistentSourceError, match="different rows"): - job.bind(sources={"left": positional, "right": keyed}) + job.bind(sources={"left": positional, "right": other}) def test_nulls_nan_signed_zero_and_nested_values() -> None: @@ -609,3 +617,190 @@ def downstream(out: int) -> int: downstream.pod(first, label="fa") downstream.pod(second, label="fb") assert "fa" in job.nodes + + +# ITL-1469 review: a source id names a dataset; key columns only name its rows. + +_ROWS = [ + {"t1": "a", "t2": "p", "x": 1, "y": 10}, + {"t1": "b", "t2": "q", "x": 2, "y": 20}, + {"t1": "c", "t2": "r", "x": 3, "y": 30}, +] + + +def _keyed( + rows: list[dict[str, str | int]], + keys: list[str] | None, + tags: list[str] | None = None, +) -> DictSource: + return DictSource( + rows, + tag_columns=tags or ["t1", "t2"], + tag_only_columns=True, + record_id_columns=keys, + source_id="shared", + ) + + +def _capture(first: RootSource, second: RootSource, pod: _FunctionPodBase) -> str: + with pytest.raises(SourceSlotNameCollisionError) as error: + with Pipeline("conflicts"): + pod(first, label="fa") + pod(second, label="fb") + return str(error.value) + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize( + "keys", [(["t1"], ["t2", "x"]), (None, ["t2", "t1"]), (["x", "y"], None)] +) +def test_fixed_same_rows_with_different_keys_differ_only_in_key_columns( + reverse: bool, keys: tuple[list[str] | None, list[str] | None] +) -> None: + first = _keyed(_ROWS, keys[0]) + # Another row order and tag order: the same dataset, read with other keys. + second = _keyed(list(reversed(_ROWS)), keys[1], tags=["t2", "t1"]) + if reverse: + first, second = second, first + assert first.content_hash() != second.content_hash() + message = _capture(first, second, both.pod) + assert "differ only in key columns" in message + assert "ITL-1506" in message + assert "source_id=" in message + + +def test_fixed_same_rows_with_signed_zero_and_nan_differ_only_in_key_columns() -> ( + None +): + @function_pod(output_keys="out") + def with_float(x: int, y: float) -> float: + return x + y + + def source(ys: list[float], keys: list[str] | None) -> DictSource: + return DictSource( + [{"t": f"r{i}", "x": i, "y": y} for i, y in enumerate(ys)], + tag_columns="t", + tag_only_columns=True, + record_id_columns=keys, + source_id="shared", + ) + + nan = struct.unpack(">d", bytes.fromhex("7ff8000000000001"))[0] + first = source([0.0, float("nan"), 1.5], ["t"]) + second = source([-0.0, nan, 1.5], None) + assert "differ only in key columns" in _capture(first, second, with_float.pod) + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_fixed_different_rows_with_different_keys_are_different_rows( + reverse: bool, +) -> None: + changed = [*_ROWS[:2], {**_ROWS[2], "y": 300}] + first, second = _keyed(_ROWS, ["t1"]), _keyed(changed, ["t2", "x"]) + if reverse: + first, second = second, first + _refused(first, second, Pipeline("conflicts"), both.pod) + + +def test_fixed_row_multiset_counts_duplicates_and_ignores_order() -> None: + a, b = _ROWS[0], _ROWS[1] + assert ( + _keyed([a, a, b], None).fixed_row_multiset + == _keyed([a, b, a], None).fixed_row_multiset + ) + assert ( + _keyed([a, a, b], None).fixed_row_multiset + != _keyed([a, b, b], None).fixed_row_multiset + ) + assert _keyed([a, b], None).fixed_row_multiset != _keyed([a], None).fixed_row_multiset + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_live_sources_with_different_keys_do_not_claim_only_key_columns( + tmp_path: Path, reverse: bool +) -> None: + first_path, second_path = tmp_path / "first.csv", tmp_path / "second.csv" + first_path.write_text("t1,t2,x,y\na,p,1,2\n") + second_path.write_text("t1,t2,x,y\nb,q,3,4\n") + sources = [ + CSVSource( + str(path), + source_id="shared", + tag_columns=["t1", "t2"], + tag_only_columns=True, + record_id_columns=keys, + ) + for path, keys in ((first_path, ["t1", "x"]), (second_path, ["t2", "y"])) + ] + first, second = sources[::-1] if reverse else sources + message = _capture(first, second, both.pod) + assert "differ only" not in message + assert "different key columns" in message + assert "not compared" in message + assert "ITL-1506" in message + assert "source_id=" in message + + +def _derived( + origin: RootSource, tag: str, keys: list[str] | None +) -> DerivedSource: + return DerivedSource( + origin, + tags_as_data={tag: "tag_value"}, + record_id_columns=keys, + source_id="shared", + ) + + +def test_derived_sources_over_live_origins_with_other_mapping_and_keys( + tmp_path: Path, +) -> None: + path = tmp_path / "origin.csv" + path.write_text("t1,t2,x\na,p,1\nb,q,2\n") + origin = CSVSource( + str(path), + source_id="origin", + tag_columns=["t1", "t2"], + tag_only_columns=True, + ) + first, second = _derived(origin, "t1", ["t1"]), _derived(origin, "t2", ["t2"]) + assert first.arrow_schemas == second.arrow_schemas + message = _capture(first, second, with_copy.pod) + assert "differ only" not in message + assert "not compared" in message + assert "ITL-1506" in message + + +def test_derived_sources_over_fixed_origins_compare_rows_without_record_ids() -> None: + origin = DictSource( + [{"t1": "a", "t2": "p", "x": 1}, {"t1": "b", "t2": "q", "x": 2}], + tag_columns=["t1", "t2"], + tag_only_columns=True, + source_id="origin", + ) + same = _capture( + _derived(origin, "t1", ["t1"]), _derived(origin, "t1", ["t2"]), with_copy.pod + ) + assert "differ only in key columns" in same + # Another mapping copies other values: the rows differ. + _refused( + _derived(origin, "t1", ["t1"]), + _derived(origin, "t2", ["t2"]), + Pipeline("conflicts"), + with_copy.pod, + ) + + +def test_equal_keys_still_compare_record_ids() -> None: + # Equal key columns: today's comparison, record ids included, row order counting + # for positional ids. + _refused( + _keyed(_ROWS, None), + _keyed(list(reversed(_ROWS)), None), + Pipeline("conflicts"), + both.pod, + ) + with PipelineJob() as job: + both.pod(_keyed(_ROWS, ["t1"]), label="fa") + both.pod(_keyed(list(reversed(_ROWS)), ["t1"]), label="fb") + assert set(job.function_pods) == {"fa"} From cad47d9837817d74e75187bb04359fdb6bb3844a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 18:19:31 -0800 Subject: [PATCH 08/42] fix(pipeline): compare one dataset's readings by rows, not record ids A source id names a dataset; key columns only name its rows. Fixed sources with different key columns are compared as a multiset of tags and data, and the slot-name refusal claims they differ only in key columns only when every source is fixed. Adds RootSource.key_columns. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1469.md | 14 ++++--- docs/concepts/sources.md | 26 ++++++++----- src/orcapod/core/sources/base.py | 38 +++++++++++++++++++ src/orcapod/core/sources/cached_source.py | 8 ++++ src/orcapod/core/sources/source_proxy.py | 8 ++++ src/orcapod/pipeline/base.py | 36 +++++++++++++----- src/orcapod/pipeline/source_consistency.py | 37 +++++++++++++++--- .../test_pipeline/test_source_id_conflicts.py | 12 +++--- 8 files changed, 142 insertions(+), 37 deletions(-) diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index 2afe8d17b..3ab510379 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -1,11 +1,15 @@ ### Fixed - Pipeline capture and job binding reject two in-memory sources that share a - source ID and schema but contain different rows. The error names the - conflicting steps or slots. Job binding and loading also reject different - schemas at a shared source ID. + source ID and schema but contain different rows. With different key columns + the rows are compared without their record IDs, as a multiset of tags and + data. The error names the conflicting steps or slots. Job binding and loading + also reject different schemas at a shared source ID. ### Known limitations -- A pipeline still refuses sources that share a source ID and differ only in - their key columns. ITL-1506 will allow them in distinct named slots. +- A pipeline still refuses sources that share a source ID and schema but have + different key columns, since they would take one slot name. In-memory sources + with the same rows are reported as differing only in key columns; the rows of + sources read later are not compared. ITL-1506 will allow distinct readings of + one dataset in distinct named slots. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 5d1882ed1..3d4520989 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -79,12 +79,16 @@ record id names a row within its source and never holds the source id. A job nam slot by the source's name (`job.bind(sources={"units": ...})`). Within a pipeline or job, sources sharing a `source_id` must have the same Arrow schema. -If both sources hold their rows in memory, their tags, data and record IDs must also -agree. This applies to `ArrowTableSource`, `DictSource`, `ListSource`, -`DataFrameSource` and wrappers over their fixed rows. Row order counts with positional -IDs (`row_0`, `row_1`, and so on). With key columns, the same rows can arrive in any -order. The comparison follows Orcapod's Arrow value rule, which treats signed zeros -as equal and all NaNs as equal. Sources that read again later, including files, +If both sources hold their rows in memory, their rows must also agree. This applies to +`ArrowTableSource`, `DictSource`, `ListSource`, `DataFrameSource` and wrappers over +their fixed rows. A source id names a dataset, and key columns only name its rows, so +what is compared depends on the key columns. With the same key columns, tags, data and +record IDs must agree: row order counts with positional IDs (`row_0`, `row_1`, and so +on), and with key columns the same rows can arrive in any order. With different key +columns the record IDs necessarily differ, so the rows are compared as a multiset of +tags and data: every row counts as often as it occurs, and order does not count. The +comparison follows Orcapod's Arrow value rule, which treats signed zeros as equal and +all NaNs as equal. Sources that read again later, including files, databases, caches and stored job outputs, use the ID and schema without a row comparison. Capture and binding reject conflicts with `InconsistentSourceError`. Give the conflicting sources different `source_id` values. @@ -1009,9 +1013,13 @@ order or content can vary between runs, pass an explicit, stable `source_id` **a key columns that are unique per row; this avoids both the duplicate entries and the repeated deliveries. -A pipeline currently refuses sources that share a `source_id` and differ only in their -key columns. ITL-1506 will allow them to share that ID when each reading has a distinct -slot name. +A pipeline currently refuses sources that share a `source_id` and schema but have +different key columns: they are two readings of one dataset that would take one slot +name. When both hold their rows in memory, the rows are compared first (as a multiset, +above), so the error says they differ only in key columns; the rows of a source read +later (a file, a database) are not compared, and the error says so. ITL-1506 will allow +distinct readings of one dataset in distinct named slots. Until then, give each source +its own `source_id`. An in-memory source with key columns and no `source_id` can instead hash its rows in key order: pass `hash_in_key_order=True` (`ArrowTableSource`, `DictSource`, `DataFrameSource`, diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 2ae69fa9d..b6192d479 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -427,6 +427,44 @@ def fixed_content(self) -> bytes | None: """ return None + @property + def key_columns(self) -> tuple[str, ...] | None: + """The resolved key columns that name this source's rows, in key order. + + ``()`` means a row is named by its position. Key columns belong to how the + rows are read, not to the dataset the source id names. A source over another + (``CachedSource``, ``SourceProxy``) answers with what it wraps, or ``None`` + when that is unknown (an unbound proxy). + """ + return self._key_columns + + @property + def fixed_row_multiset(self) -> bytes | None: + """Digest of the held rows as a multiset of tags and data, or None for a live read. + + Used to compare two fixed readings of one dataset whose key columns differ + (ITL-1506): record ids, which follow the key columns, are left out, and so is + row order. Every row counts as often as it occurs. Rows are put in the + canonical row order of an identity table + (``arrow_utils.canonical_identity_row_order``) and digested under the Arrow + float rule, so ``-0.0`` equals ``0.0`` and every NaN equals every other. It is + ``None`` exactly when ``fixed_content`` is. + """ + if self.fixed_content is None: + return None + from orcapod.hashing.starfix_digest import digest_orcapod_table + from orcapod.utils.arrow_utils import canonical_identity_row_order + + table = canonical_identity_row_order( + self.as_table(), tuple(self.keys()[0]), self.data_context.arrow_hasher + ) + return digest_orcapod_table( + table, + include_metadata=False, + ordered_columns=False, + ordered_struct_fields=False, + ) + def _digest_fixed_rows(self) -> bytes: """Compare tags, data and record IDs under the normal Arrow float rule.""" from orcapod.hashing.starfix_digest import digest_orcapod_table diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 55065699b..674d1b002 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -267,6 +267,14 @@ def source_name(self) -> str: """The name part of the wrapped source's source id.""" return parse_source_id(self._source.source_id).name + @property + @override + def key_columns(self) -> tuple[str, ...] | None: + """The wrapped source's key columns, or ``None`` when it is not a root source.""" + if isinstance(self._source, RootSource): + return self._source.key_columns + return None + def _compute_arrow_schemas(self) -> "tuple[pa.Schema, pa.Schema]": """The wrapped source's Arrow schemas: the cache stores that source's rows.""" return typed_arrow_schemas(self._source) diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 526e5d4bd..08355e9b4 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -103,6 +103,14 @@ def fixed_content(self) -> bytes | None: return self._delegate.fixed_content return None + @property + @override + def key_columns(self) -> tuple[str, ...] | None: + """The bound source's key columns, or ``None`` while unbound.""" + if isinstance(self._delegate, RootSource): + return self._delegate.key_columns + return None + @property def is_bound(self) -> bool: """``True`` if a live source has been bound via `bind`.""" diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index c7c3f43d9..120994d8a 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -50,8 +50,14 @@ def _refuse_sources_sharing_a_slot_name( would share one ``job.sources`` and ``bind`` key, and one would replace the other. Only sources are refused here: a slot of another stream is named by its label and content hash. - ITL-1506 will lift the refusal for sources that differ only in key columns - once they can occupy distinct named slots. + + Sources with one source id and schema whose key columns differ are distinct + readings of one dataset. ``require_consistent_sources`` has already compared the + rows of fixed sources (as a multiset of tags and data, since record ids follow the + key columns), so when every source is fixed they differ only in key columns. A + source read later (a file, a database) has no rows to compare, and the message + says so instead of claiming the rows agree. ITL-1506 will allow such readings in + distinct named slots. Raises: SourceSlotNameCollisionError: Naming every full source id and the remedy. @@ -65,17 +71,27 @@ def _refuse_sources_sharing_a_slot_name( ids = sorted({s.source_id for s in sources}) if len(ids) == 1: - keys = {getattr(s, "_key_columns", None) for s in sources} - # Schema agreement was checked before slot naming. ITL-1506 will let - # readings with different keys occupy distinct named slots. + keys = {s.key_columns for s in sources} + # Schema agreement (and, for fixed sources, row agreement) was checked + # before slot naming. if None not in keys and len(keys) == len(sources): + remedy = ( + "A later version will allow distinct readings of one dataset in " + "distinct named slots (ITL-1506). For now, give each source its own " + "name with source_id=... when it is built." + ) + if all(s.fixed_content is not None for s in sources): + raise SourceSlotNameCollisionError( + f"{len(sources)} sources with source id {ids[0]!r} share one " + "schema and the same rows, and differ only in key columns " + f"(record_id_columns). They would take the same slot name " + f"{slot_name!r}, so this is refused for now. {remedy}" + ) raise SourceSlotNameCollisionError( f"{len(sources)} sources with source id {ids[0]!r} share one schema " - f"and differ only in key columns (record_id_columns). They would " - f"take the same slot name {slot_name!r}, so this is refused for now. " - "A later version will allow this with distinct slot names (ITL-1506). " - "For now, give each source its own name with source_id=... when it " - "is built." + "and have different key columns (record_id_columns). The rows of a " + "source read later are not compared. They would take the same slot " + f"name {slot_name!r}, so this is refused for now. {remedy}" ) described = ( ", ".join(repr(i) for i in ids) diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index b39f15ad0..f5a3a09d4 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -87,6 +87,30 @@ def _comparison_schema(source: RootSource) -> tuple[ContentHash, ContentHash]: return arrow_schema_identity(*schemas, source.data_context) +def _same_fixed_rows(first: RootSource, other: RootSource) -> bool: + """Tell whether two fixed readings of one source id hold the same rows. + + A source id names a dataset; key columns only name its rows and belong to the + reading. With equal (or unknown) key columns, compare tags, data and record ids + (``fixed_content``), so positional row order counts as it always has. With + different key columns the record ids necessarily differ, so compare the rows as a + multiset of tags and data (``fixed_row_multiset``): every occurrence counts, order + does not, and floats compare by the Arrow value rule (``-0.0`` equals ``0.0``, NaN + equals NaN). + + Args: + first: A source whose ``fixed_content`` is not ``None``. + other: Another such source with the same source id and schema. + + Returns: + ``True`` when the two readings hold the same rows. + """ + first_keys, other_keys = first.key_columns, other.key_columns + if first_keys is None or other_keys is None or first_keys == other_keys: + return first.fixed_content == other.fixed_content + return first.fixed_row_multiset == other.fixed_row_multiset + + def require_consistent_sources( uses: Iterable[SourceUse], rebinding: Rebinding = (), @@ -95,7 +119,9 @@ def require_consistent_sources( Compare distinct objects only. A live source has no fixed rows to compare, but does not prevent comparing two fixed sources that share its address. - For a bind, use the prospective sources alongside every unchanged binding. + Fixed sources are compared by ``_same_fixed_rows``: record ids count only when + their key columns are equal. For a bind, use the prospective sources alongside + every unchanged binding. Raises: InconsistentSourceError: Naming the sources and remedy for a conflict. @@ -116,15 +142,14 @@ def require_consistent_sources( f"and {location}. Give the sources different source_id values." ) - fixed = None + fixed: RootSource | None = None fixed_location = first_location for location, source in group: - content = source.fixed_content - if content is None: + if source.fixed_content is None: continue if fixed is None: - fixed, fixed_location = content, location - elif fixed != content: + fixed, fixed_location = source, location + elif not _same_fixed_rows(fixed, source): raise InconsistentSourceError( f"Source {source_id!r} has different rows in {fixed_location} " f"and {location}. Give the sources different source_id values." diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index d8849275e..0506156dd 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -669,9 +669,7 @@ def test_fixed_same_rows_with_different_keys_differ_only_in_key_columns( assert "source_id=" in message -def test_fixed_same_rows_with_signed_zero_and_nan_differ_only_in_key_columns() -> ( - None -): +def test_fixed_same_rows_with_signed_zero_and_nan_differ_only_in_key_columns() -> None: @function_pod(output_keys="out") def with_float(x: int, y: float) -> float: return x + y @@ -712,7 +710,9 @@ def test_fixed_row_multiset_counts_duplicates_and_ignores_order() -> None: _keyed([a, a, b], None).fixed_row_multiset != _keyed([a, b, b], None).fixed_row_multiset ) - assert _keyed([a, b], None).fixed_row_multiset != _keyed([a], None).fixed_row_multiset + assert ( + _keyed([a, b], None).fixed_row_multiset != _keyed([a], None).fixed_row_multiset + ) @pytest.mark.parametrize("reverse", [False, True]) @@ -741,9 +741,7 @@ def test_live_sources_with_different_keys_do_not_claim_only_key_columns( assert "source_id=" in message -def _derived( - origin: RootSource, tag: str, keys: list[str] | None -) -> DerivedSource: +def _derived(origin: RootSource, tag: str, keys: list[str] | None) -> DerivedSource: return DerivedSource( origin, tags_as_data={tag: "tag_value"}, From b197756f870765eb0461ca1be4cb17f0b0984ab4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 18:27:40 -0800 Subject: [PATCH 09/42] fix(pipeline): refuse one source id with different key columns in any slots Developer decision (2026-11-26): until ITL-1506, sources sharing a source id and schema with different key columns are refused at capture, bind, load and run, by require_consistent_sources. Fixed sources with equal rows are reported as differing only in key columns; a source read later is not compared. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1469.md | 4 +- docs/concepts/sources.md | 14 +++--- src/orcapod/errors.py | 7 +-- src/orcapod/pipeline/base.py | 32 +----------- src/orcapod/pipeline/source_consistency.py | 49 +++++++++++++++++- .../test_pipeline/test_source_id_conflicts.py | 50 +++++++++++++++---- 6 files changed, 101 insertions(+), 55 deletions(-) diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index 3ab510379..e88061c69 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -8,8 +8,8 @@ ### Known limitations -- A pipeline still refuses sources that share a source ID and schema but have - different key columns, since they would take one slot name. In-memory sources +- Sources that share a source ID and schema but have different key columns are + refused at capture, binding (into any slots) and loading. In-memory sources with the same rows are reported as differing only in key columns; the rows of sources read later are not compared. ITL-1506 will allow distinct readings of one dataset in distinct named slots. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 3d4520989..7466b21e9 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1013,13 +1013,13 @@ order or content can vary between runs, pass an explicit, stable `source_id` **a key columns that are unique per row; this avoids both the duplicate entries and the repeated deliveries. -A pipeline currently refuses sources that share a `source_id` and schema but have -different key columns: they are two readings of one dataset that would take one slot -name. When both hold their rows in memory, the rows are compared first (as a multiset, -above), so the error says they differ only in key columns; the rows of a source read -later (a file, a database) are not compared, and the error says so. ITL-1506 will allow -distinct readings of one dataset in distinct named slots. Until then, give each source -its own `source_id`. +Sources that share a `source_id` and schema but have different key columns are two +readings of one dataset, and are refused for now everywhere: at capture, `bind` (into any +slots) and load, with `InconsistentSourceError`. When both hold their rows in memory, the +rows are compared first (as a multiset, above): different rows are reported as such, and +equal rows as differing only in key columns. The rows of a source read later (a file, a +database) are not compared, and the error says so. ITL-1506 will allow distinct readings +of one dataset in distinct named slots. Until then, give each source its own `source_id`. An in-memory source with key columns and no `source_id` can instead hash its rows in key order: pass `hash_in_key_order=True` (`ArrowTableSource`, `DictSource`, `DataFrameSource`, diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index b79124ca9..bbedba0f9 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -560,7 +560,10 @@ class InconsistentSourceError(ValueError): """Raised when two sources in a pipeline disagree at a shared address. Sources sharing a ``source_id`` must have the same schema. If both hold - fixed content, their tags, data and record IDs must also agree. Two + fixed content, their rows must also agree: tags, data and record IDs with + equal key columns, tags and data as a multiset with different ones. Sources + sharing a ``source_id`` and schema with different key columns are refused + for now, in any slots (ITL-1506 will allow them in distinct named slots). Two different schemas competing for one input slot also raise this error. Resolution: assign distinct ``source_id`` values to the conflicting sources @@ -766,8 +769,6 @@ class SourceSlotNameCollisionError(ValueError): different sources (another kind, another version or another id) whose names are equal would share one slot and one would replace the other. The job refuses them; give one of them its own name (``source_id=`` when it is built). - ITL-1506 will lift this refusal for sources that differ only in key columns - when they have distinct named slots. """ diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 120994d8a..60420a164 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -51,13 +51,8 @@ def _refuse_sources_sharing_a_slot_name( Only sources are refused here: a slot of another stream is named by its label and content hash. - Sources with one source id and schema whose key columns differ are distinct - readings of one dataset. ``require_consistent_sources`` has already compared the - rows of fixed sources (as a multiset of tags and data, since record ids follow the - key columns), so when every source is fixed they differ only in key columns. A - source read later (a file, a database) has no rows to compare, and the message - says so instead of claiming the rows agree. ITL-1506 will allow such readings in - distinct named slots. + Sources with one source id and schema whose key columns differ never get here: + ``require_consistent_sources`` refuses them first (ITL-1506). Raises: SourceSlotNameCollisionError: Naming every full source id and the remedy. @@ -70,29 +65,6 @@ def _refuse_sources_sharing_a_slot_name( from orcapod.errors import SourceSlotNameCollisionError ids = sorted({s.source_id for s in sources}) - if len(ids) == 1: - keys = {s.key_columns for s in sources} - # Schema agreement (and, for fixed sources, row agreement) was checked - # before slot naming. - if None not in keys and len(keys) == len(sources): - remedy = ( - "A later version will allow distinct readings of one dataset in " - "distinct named slots (ITL-1506). For now, give each source its own " - "name with source_id=... when it is built." - ) - if all(s.fixed_content is not None for s in sources): - raise SourceSlotNameCollisionError( - f"{len(sources)} sources with source id {ids[0]!r} share one " - "schema and the same rows, and differ only in key columns " - f"(record_id_columns). They would take the same slot name " - f"{slot_name!r}, so this is refused for now. {remedy}" - ) - raise SourceSlotNameCollisionError( - f"{len(sources)} sources with source id {ids[0]!r} share one schema " - "and have different key columns (record_id_columns). The rows of a " - "source read later are not compared. They would take the same slot " - f"name {slot_name!r}, so this is refused for now. {remedy}" - ) described = ( ", ".join(repr(i) for i in ids) if len(ids) > 1 diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index f5a3a09d4..a3e194882 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -111,6 +111,46 @@ def _same_fixed_rows(first: RootSource, other: RootSource) -> bool: return first.fixed_row_multiset == other.fixed_row_multiset +def _key_columns_conflict( + source_id: str, group: list[tuple[str, RootSource]] +) -> str | None: + """Describe sources of one id and schema whose key columns differ, if any. + + Such sources are distinct readings of one dataset. They are refused everywhere for + now (capture, bind, load, run), whatever slots they would take: allowing them in + distinct named slots is ITL-1506, after the multi-slot binding work (ITL-1442). + Call only after the schemas and fixed rows of ``group`` were found to agree. A + source whose key columns are unknown (an unbound proxy) is not compared. + + Args: + source_id: The shared source id. + group: Every distinct source with that id, with where it is used. + + Returns: + The error message, or ``None`` when the key columns agree. + """ + keys = {source.key_columns for _, source in group} + if None in keys or len(keys) < 2: + return None + where = ", ".join(location for location, _ in group) + remedy = ( + "A later version will allow distinct readings of one dataset in distinct " + "named slots (ITL-1506). For now, give each source its own name with " + "source_id=... when it is built." + ) + if all(source.fixed_content is not None for _, source in group): + return ( + f"Sources with source id {source_id!r} in {where} share one schema and " + "the same rows, and differ only in key columns (record_id_columns), so " + f"this is refused for now. {remedy}" + ) + return ( + f"Sources with source id {source_id!r} in {where} share one schema and have " + "different key columns (record_id_columns). The rows of a source read later " + f"are not compared. This is refused for now. {remedy}" + ) + + def require_consistent_sources( uses: Iterable[SourceUse], rebinding: Rebinding = (), @@ -120,8 +160,9 @@ def require_consistent_sources( Compare distinct objects only. A live source has no fixed rows to compare, but does not prevent comparing two fixed sources that share its address. Fixed sources are compared by ``_same_fixed_rows``: record ids count only when - their key columns are equal. For a bind, use the prospective sources alongside - every unchanged binding. + their key columns are equal. Sources whose schemas and fixed rows agree but whose + key columns differ are then refused too (``_key_columns_conflict``, ITL-1506). + For a bind, use the prospective sources alongside every unchanged binding. Raises: InconsistentSourceError: Naming the sources and remedy for a conflict. @@ -154,3 +195,7 @@ def require_consistent_sources( f"Source {source_id!r} has different rows in {fixed_location} " f"and {location}. Give the sources different source_id values." ) + + message = _key_columns_conflict(source_id, group) + if message is not None: + raise InconsistentSourceError(message) diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index 0506156dd..846c2825d 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -300,7 +300,7 @@ def test_same_source_id_with_different_key_columns_is_refused_at_build( assert first.arrow_schemas == second.arrow_schemas assert first.content_hash() != second.content_hash() - with pytest.raises(SourceSlotNameCollisionError, match="ITL-1506"): + with pytest.raises(InconsistentSourceError, match="ITL-1506"): with Pipeline("conflicts"): both.pod(first, label="fa") both.pod(second, label="fb") @@ -336,20 +336,48 @@ def source(data: list[dict[str, str | int]], tags: list[str]) -> DictSource: _refused(first, second, Pipeline("conflicts"), both.pod) -def test_bind_compares_rows_without_record_ids_when_keys_differ() -> None: - # A source id names a dataset; key columns only name its rows. Two readings of - # the same rows with other keys bind into distinct named slots; other rows do not. - job = _job() +@pytest.mark.parametrize("reverse", [False, True]) +def test_bind_refuses_same_rows_with_different_keys(reverse: bool) -> None: + # Refused in any slots for now: distinct slots for distinct readings of one + # dataset are ITL-1506, after the multi-slot binding work (ITL-1442). positional = _dict(1) keyed = DictSource([{"x": 1}], record_id_columns="x", source_id="shared") - job.bind(sources={"left": positional, "right": keyed}) - assert job.sources["left"] is positional - assert job.sources["right"] is keyed - + pair = (keyed, positional) if reverse else (positional, keyed) job = _job() + before = dict(job.sources) + with pytest.raises(InconsistentSourceError) as error: + job.bind(sources={"left": pair[0], "right": pair[1]}) + message = str(error.value) + assert "differ only in key columns" in message + assert "ITL-1506" in message + assert "slot 'left'" in message and "slot 'right'" in message + assert dict(job.sources) == before + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_bind_refuses_different_rows_with_different_keys(reverse: bool) -> None: + positional = _dict(1) other = DictSource([{"x": 100}], record_id_columns="x", source_id="shared") + pair = (other, positional) if reverse else (positional, other) with pytest.raises(InconsistentSourceError, match="different rows"): - job.bind(sources={"left": positional, "right": other}) + _job().bind(sources={"left": pair[0], "right": pair[1]}) + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_bind_refuses_live_sources_with_different_keys( + tmp_path: Path, reverse: bool +) -> None: + path = tmp_path / "shared.csv" + path.write_text("x\n1\n2\n") + positional = CSVSource(str(path), source_id="shared") + keyed = CSVSource(str(path), source_id="shared", record_id_columns="x") + pair = (keyed, positional) if reverse else (positional, keyed) + with pytest.raises(InconsistentSourceError) as error: + _job().bind(sources={"left": pair[0], "right": pair[1]}) + message = str(error.value) + assert "differ only" not in message + assert "not compared" in message + assert "ITL-1506" in message def test_nulls_nan_signed_zero_and_nested_values() -> None: @@ -643,7 +671,7 @@ def _keyed( def _capture(first: RootSource, second: RootSource, pod: _FunctionPodBase) -> str: - with pytest.raises(SourceSlotNameCollisionError) as error: + with pytest.raises(InconsistentSourceError) as error: with Pipeline("conflicts"): pod(first, label="fa") pod(second, label="fb") From 2addf679abcb0fd02a205eae4acad562bad5a0dd Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 18:32:42 -0800 Subject: [PATCH 10/42] test(pipeline): unknown keys, three-way order and node run source checks Co-Authored-By: Claude Opus 5.5 --- .../test_pipeline/test_source_id_conflicts.py | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index 846c2825d..b9f808b24 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -2,6 +2,7 @@ from __future__ import annotations +import itertools import json from pathlib import Path import struct @@ -20,7 +21,9 @@ InputValidationError, SourceSlotNameCollisionError, ) +from orcapod.operators import SemiJoin from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.pipeline.source_consistency import require_consistent_sources from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.sources import ( ArrowTableSource, @@ -830,3 +833,108 @@ def test_equal_keys_still_compare_record_ids() -> None: both.pod(_keyed(_ROWS, ["t1"]), label="fa") both.pod(_keyed(list(reversed(_ROWS)), ["t1"]), label="fb") assert set(job.function_pods) == {"fa"} + + +# Re-review of b197756f. + + +def test_unknown_key_columns_never_hide_a_conflict_between_known_ones() -> None: + # An unbound proxy of the same id and schema has unknown key columns: it neither + # causes nor suppresses a refusal between the sources whose keys are known. + positional = DictSource([{"x": 1}, {"x": 2}], source_id="shared") + keyed = DictSource([{"x": 1}, {"x": 2}], record_id_columns="x", source_id="shared") + proxy = SourceProxy( + positional.source_id, + positional.content_hash().to_string(), + positional.pipeline_hash().to_string(), + *positional.output_schema(), + ) + assert proxy.key_columns is None + for uses in itertools.permutations( + [("slot 'p'", proxy), ("slot 'a'", positional), ("slot 'b'", keyed)] + ): + with pytest.raises(InconsistentSourceError) as error: + require_consistent_sources(uses) + assert "differ only in key columns" in str(error.value) + # Alone with either known source, the proxy causes nothing. + require_consistent_sources([("slot 'p'", proxy), ("slot 'a'", positional)]) + require_consistent_sources([("slot 'p'", proxy), ("slot 'b'", keyed)]) + + +def _three_slot_job() -> PipelineJob: + with PipelineJob(database=InMemoryArrowDatabase()) as job: + increment.pod(_dict(2, "a"), label="fa") + increment.pod(_dict(3, "b"), label="fb") + increment.pod(_dict(4, "c"), label="fc") + return job + + +@pytest.mark.parametrize( + "order", list(itertools.permutations(["keyed", "forward", "backward"])) +) +def test_three_way_diagnosis_does_not_follow_slot_order(order: tuple[str, ...]) -> None: + sources = { + "keyed": DictSource( + [{"x": 1}, {"x": 2}], record_id_columns="x", source_id="shared" + ), + "forward": DictSource([{"x": 1}, {"x": 2}], source_id="shared"), + # Positional ids: another order is other rows than "forward". + "backward": DictSource([{"x": 2}, {"x": 1}], source_id="shared"), + } + job = _three_slot_job() + with pytest.raises(InconsistentSourceError, match="different rows"): + job.bind(sources=dict(zip("abc", (sources[name] for name in order)))) + + +@function_pod(output_keys="out") +def increment_matched(x: int) -> int: + return x + 1 + + +def _semi_join_job() -> PipelineJob: + def source(name: str) -> DictSource: + return DictSource( + [{"k": "a", "x": 1}, {"k": "b", "x": 2}], + tag_columns="k", + tag_only_columns=True, + source_id=name, + ) + + with PipelineJob(database=InMemoryArrowDatabase()) as job: + matched = SemiJoin()(source("left"), source("right"), label="matched") + increment_matched.pod(matched, label="fm") + return job + + +def _rebind_outside_bind(job: PipelineJob, right_keys: str | None, x: int) -> None: + job.nodes["left"].bound_source = DictSource( + [{"k": "a", "x": 1}, {"k": "b", "x": 2}], + tag_columns="k", + tag_only_columns=True, + source_id="shared", + ) + job.nodes["right"].bound_source = DictSource( + [{"k": "a", "x": 1}, {"k": "b", "x": x}], + tag_columns="k", + tag_only_columns=True, + record_id_columns=right_keys, + source_id="shared", + ) + + +@pytest.mark.parametrize("node", ["matched", "fm"]) +@pytest.mark.parametrize( + ("right_keys", "x", "message"), + [("k", 2, "differ only in key columns"), (None, 200, "different rows")], +) +def test_node_run_checks_its_sources_like_job_run( + node: str, right_keys: str | None, x: int, message: str +) -> None: + job = _semi_join_job() + _rebind_outside_bind(job, right_keys, x) + with pytest.raises(InconsistentSourceError, match=message): + job.run() + with pytest.raises(InconsistentSourceError, match=message): + job.nodes[node].run() + assert not job.matched.as_table().num_rows + assert not job.fm.as_table().num_rows From 3c17de44dd010d2c8a5a9dfb01d05caa6532e819 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 18:47:06 -0800 Subject: [PATCH 11/42] fix(pipeline): order-free source checks, unknown keys, and node run checks Every pair of fixed sources is compared by its own rule, so the diagnosis no longer follows slot order; unknown key columns neither cause nor hide a key-column refusal; a job node's run() checks the sources it reads as job.run() does. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1469.md | 12 +- docs/concepts/sources.md | 2 +- src/orcapod/core/nodes/function_node.py | 13 ++- src/orcapod/core/nodes/operator_node.py | 9 ++ src/orcapod/pipeline/job.py | 7 +- src/orcapod/pipeline/source_consistency.py | 107 ++++++++++-------- .../test_pipeline/test_source_id_conflicts.py | 16 +-- 7 files changed, 104 insertions(+), 62 deletions(-) diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index e88061c69..d42e6f08e 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -3,13 +3,15 @@ - Pipeline capture and job binding reject two in-memory sources that share a source ID and schema but contain different rows. With different key columns the rows are compared without their record IDs, as a multiset of tags and - data. The error names the conflicting steps or slots. Job binding and loading - also reject different schemas at a shared source ID. + data. A node's `run()` checks the sources it reads as `job.run()` does. The + error names the conflicting steps or slots. Job binding and loading also + reject different schemas at a shared source ID. ### Known limitations - Sources that share a source ID and schema but have different key columns are - refused at capture, binding (into any slots) and loading. In-memory sources - with the same rows are reported as differing only in key columns; the rows of - sources read later are not compared. ITL-1506 will allow distinct readings of + refused at capture, binding (into any slots), loading and run (`job.run()` + and a node's `run()`). In-memory sources with the same rows are reported as + differing only in key columns; the rows of sources read later are not + compared. ITL-1506 will allow distinct readings of one dataset in distinct named slots. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 7466b21e9..3dea22d39 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1015,7 +1015,7 @@ deliveries. Sources that share a `source_id` and schema but have different key columns are two readings of one dataset, and are refused for now everywhere: at capture, `bind` (into any -slots) and load, with `InconsistentSourceError`. When both hold their rows in memory, the +slots), load and run (`job.run()` and a node's `run()`), with `InconsistentSourceError`. When both hold their rows in memory, the rows are compared first (as a multiset, above): different rows are reported as such, and equal rows as differing only in key columns. The rows of a source read later (a file, a database) are not compared, and the error says so. ITL-1506 will allow distinct readings diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 9a0353053..8d4442227 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -361,7 +361,9 @@ def run_job_node( ) -> None: """Run a job node as its ``run()`` does (developer, November 13, 2026; ITL-1095). - Every source feeding the node is first checked for new data (``check_sources``, + Sources it reads that share a source id must agree, as ``job.run()`` requires + (``require_consistent_sources``, before and after the check for new data). Every + source feeding the node is first checked for new data (``check_sources``, ITL-1102). Nothing runs when the node then holds a current run (``holds_current_run``). Otherwise a node that depends on job nodes runs with them (``run_with_dependencies``) and one built over streams outside a job runs alone @@ -384,13 +386,19 @@ def run_job_node( ) from orcapod.pipeline.restrictions import refuse_restriction_conflicts from orcapod.pipeline.run_summary import warn_row_failures + from orcapod.pipeline.source_consistency import require_consistent_sources # A source read under two restrictions, or a caching operator over a restricted # source, is refused before any source is checked and before anything is # computed or written (ITL-1218). refuse_restriction_conflicts([node]) + # Sources sharing a source id must agree, as job.run() requires (ITL-1469); + # checked again after the check for new data, which can replace held rows. + uses = [(f"node {node.label!r}", node)] + require_consistent_sources(uses) # Every source feeding the run first takes in any new data (ITL-1102). unchecked = check_sources([node]) + require_consistent_sources(uses) if node.holds_current_run(load_only=load_only): return if depends_on_job_nodes(node): @@ -4292,6 +4300,9 @@ def run(self, *, load_only: bool = False) -> StreamView: compute (loaded without a function pod, or a placeholder pod) and ``load_only`` is false; or if its input is unavailable (``CACHE_ONLY``): read its stored rows with ``as_source()``. + InconsistentSourceError: If sources it reads share a source ID and + disagree (schema, fixed rows or key columns), as ``job.run()`` + refuses; nothing has run. """ from orcapod.pipeline.serialization import LoadStatus diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index b2134184a..c9a999727 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1881,6 +1881,9 @@ def run(self, *, load_only: bool = False) -> StreamView: ``load_only`` is false. ValueError: If this node or one it depends on caches (``LOG`` or ``REPLAY``) over a restricted source (ITL-1218); nothing has run. + InconsistentSourceError: If sources it reads share a source ID and + disagree (schema, fixed rows or key columns), as ``job.run()`` + refuses; nothing has run. """ from orcapod.pipeline.node_run import ( check_sources, @@ -1890,6 +1893,7 @@ def run(self, *, load_only: bool = False) -> StreamView: ) from orcapod.pipeline.restrictions import refuse_restriction_conflicts from orcapod.pipeline.run_summary import warn_row_failures + from orcapod.pipeline.source_consistency import require_consistent_sources if self._loaded and not load_only: raise self._cannot_compute_error() @@ -1897,8 +1901,13 @@ def run(self, *, load_only: bool = False) -> StreamView: # source, is refused before any source is checked and before anything is # computed or written (ITL-1218). refuse_restriction_conflicts([self]) + # Sources sharing a source id must agree, as job.run() requires (ITL-1469); + # checked again after the check for new data, which can replace held rows. + uses = [(f"node {self.label!r}", self)] + require_consistent_sources(uses) # Every source feeding the run first takes in any new data (ITL-1102). unchecked = check_sources([self]) + require_consistent_sources(uses) if self.holds_current_run(load_only=load_only): return self._run_view(computed=False) if depends_on_job_nodes(self): diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 4f312114f..371c1608e 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -497,7 +497,9 @@ def bind( Raises: InconsistentSourceError: If two sources sharing a source ID have - different schemas, or both hold fixed rows and those rows differ. + different schemas, both hold fixed rows and those rows differ, or + they have different key columns (refused in any slots for now, + ITL-1506); the job is left as it was. SourceSpecMismatchError: If any source's columns differ from its slot's declared names, roles or types. ValueError: If a source key has no matching ``SourceJobNode`` slot, or an @@ -1802,7 +1804,8 @@ def load( Raises: InconsistentSourceError: If reconstructed sources sharing a source ID - have different schemas. + have different schemas, fixed rows that differ, or different key + columns (ITL-1506). ValueError: If the file's format version is not the one this Orcapod writes (an earlier format is refused, never migrated), or if it was saved before the database key was renamed (``bindings.store`` diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index a3e194882..199a1eca9 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -87,30 +87,6 @@ def _comparison_schema(source: RootSource) -> tuple[ContentHash, ContentHash]: return arrow_schema_identity(*schemas, source.data_context) -def _same_fixed_rows(first: RootSource, other: RootSource) -> bool: - """Tell whether two fixed readings of one source id hold the same rows. - - A source id names a dataset; key columns only name its rows and belong to the - reading. With equal (or unknown) key columns, compare tags, data and record ids - (``fixed_content``), so positional row order counts as it always has. With - different key columns the record ids necessarily differ, so compare the rows as a - multiset of tags and data (``fixed_row_multiset``): every occurrence counts, order - does not, and floats compare by the Arrow value rule (``-0.0`` equals ``0.0``, NaN - equals NaN). - - Args: - first: A source whose ``fixed_content`` is not ``None``. - other: Another such source with the same source id and schema. - - Returns: - ``True`` when the two readings hold the same rows. - """ - first_keys, other_keys = first.key_columns, other.key_columns - if first_keys is None or other_keys is None or first_keys == other_keys: - return first.fixed_content == other.fixed_content - return first.fixed_row_multiset == other.fixed_row_multiset - - def _key_columns_conflict( source_id: str, group: list[tuple[str, RootSource]] ) -> str | None: @@ -119,26 +95,27 @@ def _key_columns_conflict( Such sources are distinct readings of one dataset. They are refused everywhere for now (capture, bind, load, run), whatever slots they would take: allowing them in distinct named slots is ITL-1506, after the multi-slot binding work (ITL-1442). - Call only after the schemas and fixed rows of ``group`` were found to agree. A - source whose key columns are unknown (an unbound proxy) is not compared. + Call only after the schemas and fixed rows of ``group`` were found to agree. Only + the sources whose key columns are known are compared: one whose key columns are + unknown (an unbound proxy) neither causes nor suppresses a refusal. Args: source_id: The shared source id. group: Every distinct source with that id, with where it is used. Returns: - The error message, or ``None`` when the key columns agree. + The error message, or ``None`` when the known key columns agree. """ - keys = {source.key_columns for _, source in group} - if None in keys or len(keys) < 2: + known = [(where, s) for where, s in group if s.key_columns is not None] + if len({source.key_columns for _, source in known}) < 2: return None - where = ", ".join(location for location, _ in group) + where = ", ".join(location for location, _ in known) remedy = ( "A later version will allow distinct readings of one dataset in distinct " "named slots (ITL-1506). For now, give each source its own name with " "source_id=... when it is built." ) - if all(source.fixed_content is not None for _, source in group): + if all(source.fixed_content is not None for _, source in known): return ( f"Sources with source id {source_id!r} in {where} share one schema and " "the same rows, and differ only in key columns (record_id_columns), so " @@ -151,6 +128,51 @@ def _key_columns_conflict( ) +def _differing_fixed_rows( + group: list[tuple[str, RootSource]], +) -> tuple[str, str] | None: + """Find two fixed sources of one id and schema that hold different rows. + + A source id names a dataset; key columns only name its rows and belong to the + reading. Every pair of fixed sources is compared by the rule for that pair, so the + answer never depends on the order of ``group``: + + - equal key columns (or unknown ones): tags, data and record ids + (``fixed_content``), so positional row order counts as it always has; + - different key columns: the record ids necessarily differ, so the rows are + compared as a multiset of tags and data (``fixed_row_multiset``): every + occurrence counts, order does not, and floats compare by the Arrow value rule + (``-0.0`` equals ``0.0``, NaN equals NaN). + + Each digest is computed at most once per source. + + Args: + group: Every distinct source with that id, with where it is used. + + Returns: + The locations of the first such pair, or ``None`` when all fixed rows agree. + """ + contents = [(where, s, s.fixed_content) for where, s in group] + fixed = [(where, s, c) for where, s, c in contents if c is not None] + multisets: dict[int, bytes | None] = {} + + def multiset(source: RootSource) -> bytes | None: + if id(source) not in multisets: + multisets[id(source)] = source.fixed_row_multiset + return multisets[id(source)] + + for index, (first_location, first, first_content) in enumerate(fixed): + for location, source, content in fixed[index + 1 :]: + first_keys, keys = first.key_columns, source.key_columns + if first_keys is None or keys is None or first_keys == keys: + same = first_content == content + else: + same = multiset(first) == multiset(source) + if not same: + return first_location, location + return None + + def require_consistent_sources( uses: Iterable[SourceUse], rebinding: Rebinding = (), @@ -159,8 +181,9 @@ def require_consistent_sources( Compare distinct objects only. A live source has no fixed rows to compare, but does not prevent comparing two fixed sources that share its address. - Fixed sources are compared by ``_same_fixed_rows``: record ids count only when - their key columns are equal. Sources whose schemas and fixed rows agree but whose + Every pair of fixed sources is compared by ``_differing_fixed_rows`` (record ids + count only when their key columns are equal), so different rows are reported whatever + the order of the uses. Sources whose schemas and fixed rows agree but whose known key columns differ are then refused too (``_key_columns_conflict``, ITL-1506). For a bind, use the prospective sources alongside every unchanged binding. @@ -183,18 +206,12 @@ def require_consistent_sources( f"and {location}. Give the sources different source_id values." ) - fixed: RootSource | None = None - fixed_location = first_location - for location, source in group: - if source.fixed_content is None: - continue - if fixed is None: - fixed, fixed_location = source, location - elif not _same_fixed_rows(fixed, source): - raise InconsistentSourceError( - f"Source {source_id!r} has different rows in {fixed_location} " - f"and {location}. Give the sources different source_id values." - ) + differing = _differing_fixed_rows(group) + if differing is not None: + raise InconsistentSourceError( + f"Source {source_id!r} has different rows in {differing[0]} " + f"and {differing[1]}. Give the sources different source_id values." + ) message = _key_columns_conflict(source_id, group) if message is not None: diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index b9f808b24..0c1536dac 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -863,9 +863,9 @@ def test_unknown_key_columns_never_hide_a_conflict_between_known_ones() -> None: def _three_slot_job() -> PipelineJob: with PipelineJob(database=InMemoryArrowDatabase()) as job: - increment.pod(_dict(2, "a"), label="fa") - increment.pod(_dict(3, "b"), label="fb") - increment.pod(_dict(4, "c"), label="fc") + _ = increment.pod(_dict(2, "a"), label="fa") + _ = increment.pod(_dict(3, "b"), label="fb") + _ = increment.pod(_dict(4, "c"), label="fc") return job @@ -902,7 +902,7 @@ def source(name: str) -> DictSource: with PipelineJob(database=InMemoryArrowDatabase()) as job: matched = SemiJoin()(source("left"), source("right"), label="matched") - increment_matched.pod(matched, label="fm") + _ = increment_matched.pod(matched, label="fm") return job @@ -933,8 +933,8 @@ def test_node_run_checks_its_sources_like_job_run( job = _semi_join_job() _rebind_outside_bind(job, right_keys, x) with pytest.raises(InconsistentSourceError, match=message): - job.run() + _ = job.run() with pytest.raises(InconsistentSourceError, match=message): - job.nodes[node].run() - assert not job.matched.as_table().num_rows - assert not job.fm.as_table().num_rows + _ = job.nodes[node].run() + for name in ("matched", "fm"): + assert job.nodes[name].as_table().num_rows == 0 From 8e21ee2c5138582ba55534dcf57addc4685a6896 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 18:51:13 -0800 Subject: [PATCH 12/42] test(pipeline): count fixed-row digests per consistency check Co-Authored-By: Claude Opus 5.5 --- .../test_pipeline/test_source_id_conflicts.py | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index 0c1536dac..949488fee 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -938,3 +938,53 @@ def test_node_run_checks_its_sources_like_job_run( _ = job.nodes[node].run() for name in ("matched", "fm"): assert job.nodes[name].as_table().num_rows == 0 + + +def test_each_digest_is_computed_at_most_once_per_source( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from collections import Counter + + calls: Counter[tuple[str, int]] = Counter() + exact = RootSource._digest_fixed_rows # pyright: ignore[reportPrivateUsage] # counted + multiset = RootSource._digest_fixed_row_multiset # pyright: ignore[reportPrivateUsage] # counted + + def counted_exact(self: RootSource) -> bytes: + calls["exact", id(self)] += 1 + return exact(self) + + def counted_multiset(self: RootSource) -> bytes: + calls["multiset", id(self)] += 1 + return multiset(self) + + monkeypatch.setattr(RootSource, "_digest_fixed_rows", counted_exact) + monkeypatch.setattr(RootSource, "_digest_fixed_row_multiset", counted_multiset) + + rows = [{"x": 1}, {"x": 2}] + first = DictSource(rows, source_id="shared") + second = DictSource(rows, source_id="shared") + keyed = DictSource(rows, record_id_columns="x", source_id="shared") + uses = [("slot 'a'", first), ("slot 'b'", second), ("slot 'c'", keyed)] + for _ in range(2): + # A second check computes nothing: a fixed table's digests are held. + with pytest.raises(InconsistentSourceError, match="differ only in key"): + require_consistent_sources(uses) + # Equal keys need the exact digest, different keys the multiset digest. + assert calls == { + ("exact", id(first)): 1, + ("exact", id(second)): 1, + ("multiset", id(first)): 1, + ("multiset", id(second)): 1, + ("multiset", id(keyed)): 1, + } + + # Two sources whose key columns differ need only the multiset digest. + calls.clear() + pair = [ + ("slot 'a'", DictSource(rows, source_id="shared")), + ("slot 'b'", DictSource(rows, record_id_columns="x", source_id="shared")), + ] + with pytest.raises(InconsistentSourceError, match="differ only in key"): + require_consistent_sources(pair) + assert sorted(calls.values()) == [1, 1] + assert {kind for kind, _ in calls} == {"multiset"} From 08bb4102cb9b2a962c4555eab6bacf6760cd3103 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 19:04:52 -0800 Subject: [PATCH 13/42] perf(pipeline): compute each fixed-row digest at most once per check RootSource.holds_fixed_rows answers without a digest; the consistency check memoizes the exact and multiset digests a pair needs; in-memory tables hold their digests. Documents InconsistentSourceError on side-effect run(). Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/sources/base.py | 54 ++++++++++++++++++--- src/orcapod/core/sources/derived_source.py | 14 +++--- src/orcapod/core/sources/source_proxy.py | 16 ++++++ src/orcapod/pipeline/loaded_side_effects.py | 3 ++ src/orcapod/pipeline/source_consistency.py | 34 +++++++------ src/orcapod/side_effects.py | 3 ++ 6 files changed, 93 insertions(+), 31 deletions(-) diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index b6192d479..8c5cc4cab 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -418,14 +418,25 @@ def _schema_identity(self) -> tuple[ContentHash, ContentHash]: """ return arrow_schema_identity(*self.arrow_schemas, self.data_context) + @property + def holds_fixed_rows(self) -> bool: + """Whether this source holds rows that never change, so they can be compared. + + Answered without reading or digesting any row. Sources that hold immutable + rows opt in; a wrapper can opt in if what it wraps holds fixed rows. + """ + return False + @property def fixed_content(self) -> bytes | None: """Digest of held rows for collision checks, or None for a live read. - Sources that hold immutable rows opt in. A wrapper can opt in if its - delegate holds fixed rows. The digest is separate from source identity. + Tags, data and record ids (``_digest_fixed_rows``), computed on each read + unless a subclass holds it. The digest is separate from source identity. """ - return None + if not self.holds_fixed_rows: + return None + return self._digest_fixed_rows() @property def key_columns(self) -> tuple[str, ...] | None: @@ -448,10 +459,15 @@ def fixed_row_multiset(self) -> bytes | None: canonical row order of an identity table (``arrow_utils.canonical_identity_row_order``) and digested under the Arrow float rule, so ``-0.0`` equals ``0.0`` and every NaN equals every other. It is - ``None`` exactly when ``fixed_content`` is. + ``None`` exactly when ``holds_fixed_rows`` is false; computed on each read + unless a subclass holds it. """ - if self.fixed_content is None: + if not self.holds_fixed_rows: return None + return self._digest_fixed_row_multiset() + + def _digest_fixed_row_multiset(self) -> bytes: + """Digest the rows as a multiset of tags and data (``fixed_row_multiset``).""" from orcapod.hashing.starfix_digest import digest_orcapod_table from orcapod.utils.arrow_utils import canonical_identity_row_order @@ -707,10 +723,32 @@ def cached( class FixedTableSource(RootSource): - """A root that holds an Arrow table for its entire lifetime.""" + """A root that holds an Arrow table for its entire lifetime. + + Its rows never change, so each digest of them is computed once and held. + """ + + _held_fixed_content: bytes | None = None + _held_fixed_row_multiset: bytes | None = None + + @property + @override + def holds_fixed_rows(self) -> bool: + """Always: the table is held for the source's lifetime.""" + return True @property @override def fixed_content(self) -> bytes: - """Digest of the table this source holds.""" - return self._digest_fixed_rows() + """Digest of the table this source holds, computed once.""" + if self._held_fixed_content is None: + self._held_fixed_content = self._digest_fixed_rows() + return self._held_fixed_content + + @property + @override + def fixed_row_multiset(self) -> bytes: + """Multiset digest of the table this source holds, computed once.""" + if self._held_fixed_row_multiset is None: + self._held_fixed_row_multiset = self._digest_fixed_row_multiset() + return self._held_fixed_row_multiset diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index d169b5258..dcad18264 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -307,14 +307,12 @@ def __init__( @property @override - def fixed_content(self) -> bytes | None: - """Rows are fixed only when the origin itself holds fixed content.""" - if ( - isinstance(self._origin, RootSource) - and self._origin.fixed_content is not None - ): - return self._digest_fixed_rows() - return None + def holds_fixed_rows(self) -> bool: + """Rows are fixed only when the origin itself holds fixed rows. + + The digests are not held: a check for new data can refresh the rows. + """ + return isinstance(self._origin, RootSource) and self._origin.holds_fixed_rows def identity_structure(self) -> Any: """Return what the content hash is built from. diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 08355e9b4..dd9ba1e17 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -95,6 +95,14 @@ def delegate(self) -> SourceProtocol | None: """The bound live source, or ``None`` if no source has been bound.""" return self._delegate + @property + @override + def holds_fixed_rows(self) -> bool: + """Whether the bound source holds fixed rows.""" + return ( + isinstance(self._delegate, RootSource) and self._delegate.holds_fixed_rows + ) + @property @override def fixed_content(self) -> bytes | None: @@ -103,6 +111,14 @@ def fixed_content(self) -> bytes | None: return self._delegate.fixed_content return None + @property + @override + def fixed_row_multiset(self) -> bytes | None: + """The bound source's multiset digest, if it holds fixed rows.""" + if isinstance(self._delegate, RootSource): + return self._delegate.fixed_row_multiset + return None + @property @override def key_columns(self) -> tuple[str, ...] | None: diff --git a/src/orcapod/pipeline/loaded_side_effects.py b/src/orcapod/pipeline/loaded_side_effects.py index aa5182742..b4fa3b0c9 100644 --- a/src/orcapod/pipeline/loaded_side_effects.py +++ b/src/orcapod/pipeline/loaded_side_effects.py @@ -336,6 +336,9 @@ def run(self, *, load_only: bool = False) -> StreamView: Raises: RuntimeError: If ``load_only`` is false; nothing runs then. + InconsistentSourceError: If sources it reads share a source ID and + disagree (schema, fixed rows or key columns), as ``job.run()`` + refuses; nothing has run. """ import sys diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index 199a1eca9..2ed4fcb36 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -115,7 +115,7 @@ def _key_columns_conflict( "named slots (ITL-1506). For now, give each source its own name with " "source_id=... when it is built." ) - if all(source.fixed_content is not None for _, source in known): + if all(source.holds_fixed_rows for _, source in known): return ( f"Sources with source id {source_id!r} in {where} share one schema and " "the same rows, and differ only in key columns (record_id_columns), so " @@ -144,7 +144,9 @@ def _differing_fixed_rows( occurrence counts, order does not, and floats compare by the Arrow value rule (``-0.0`` equals ``0.0``, NaN equals NaN). - Each digest is computed at most once per source. + Only the digests a pair needs are computed, each at most once per source in one + check (a source that holds its digests, ``FixedTableSource``, computes each once + in its lifetime). Args: group: Every distinct source with that id, with where it is used. @@ -152,23 +154,25 @@ def _differing_fixed_rows( Returns: The locations of the first such pair, or ``None`` when all fixed rows agree. """ - contents = [(where, s, s.fixed_content) for where, s in group] - fixed = [(where, s, c) for where, s, c in contents if c is not None] + fixed = [(where, s) for where, s in group if s.holds_fixed_rows] + exact: dict[int, bytes | None] = {} multisets: dict[int, bytes | None] = {} - def multiset(source: RootSource) -> bytes | None: - if id(source) not in multisets: - multisets[id(source)] = source.fixed_row_multiset - return multisets[id(source)] + def digest(source: RootSource, *, record_ids: bool) -> bytes | None: + held = exact if record_ids else multisets + if id(source) not in held: + held[id(source)] = ( + source.fixed_content if record_ids else source.fixed_row_multiset + ) + return held[id(source)] - for index, (first_location, first, first_content) in enumerate(fixed): - for location, source, content in fixed[index + 1 :]: + for index, (first_location, first) in enumerate(fixed): + for location, source in fixed[index + 1 :]: first_keys, keys = first.key_columns, source.key_columns - if first_keys is None or keys is None or first_keys == keys: - same = first_content == content - else: - same = multiset(first) == multiset(source) - if not same: + record_ids = first_keys is None or keys is None or first_keys == keys + if digest(first, record_ids=record_ids) != digest( + source, record_ids=record_ids + ): return first_location, location return None diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 071aa82ac..374761105 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -1434,6 +1434,9 @@ def run(self, *, load_only: bool = False) -> StreamView: Raises: SideEffectLogDataContextError: As for ``execute``. OrcapodDatabaseWriteError: If committing the invocation log fails. + InconsistentSourceError: If sources it reads share a source ID and + disagree (schema, fixed rows or key columns), as ``job.run()`` + refuses; nothing has run. """ import sys From 9d32705e867a1a8c9acbe922b8d706ea1e7f4de6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 19:10:04 -0800 Subject: [PATCH 14/42] test(pipeline): digest per check, proxies once, mutated frames rechecked Co-Authored-By: Claude Opus 5.5 --- .../test_pipeline/test_source_id_conflicts.py | 67 +++++++++++++++++-- 1 file changed, 61 insertions(+), 6 deletions(-) diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index 949488fee..fbe90c98b 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -4,6 +4,7 @@ import itertools import json +from collections import Counter from pathlib import Path import struct @@ -940,11 +941,8 @@ def test_node_run_checks_its_sources_like_job_run( assert job.nodes[name].as_table().num_rows == 0 -def test_each_digest_is_computed_at_most_once_per_source( - monkeypatch: pytest.MonkeyPatch, -) -> None: - from collections import Counter - +def _count_digests(monkeypatch: pytest.MonkeyPatch) -> Counter[tuple[str, int]]: + """Count each kind of fixed-row digest by the source object that computes it.""" calls: Counter[tuple[str, int]] = Counter() exact = RootSource._digest_fixed_rows # pyright: ignore[reportPrivateUsage] # counted multiset = RootSource._digest_fixed_row_multiset # pyright: ignore[reportPrivateUsage] # counted @@ -959,14 +957,22 @@ def counted_multiset(self: RootSource) -> bytes: monkeypatch.setattr(RootSource, "_digest_fixed_rows", counted_exact) monkeypatch.setattr(RootSource, "_digest_fixed_row_multiset", counted_multiset) + return calls + +def test_each_digest_is_computed_at_most_once_per_source_per_check( + monkeypatch: pytest.MonkeyPatch, +) -> None: + calls = _count_digests(monkeypatch) rows = [{"x": 1}, {"x": 2}] first = DictSource(rows, source_id="shared") second = DictSource(rows, source_id="shared") keyed = DictSource(rows, record_id_columns="x", source_id="shared") uses = [("slot 'a'", first), ("slot 'b'", second), ("slot 'c'", keyed)] for _ in range(2): - # A second check computes nothing: a fixed table's digests are held. + # Every check digests again (a held table can share memory with the + # caller's data), but each digest at most once per source. + calls.clear() with pytest.raises(InconsistentSourceError, match="differ only in key"): require_consistent_sources(uses) # Equal keys need the exact digest, different keys the multiset digest. @@ -988,3 +994,52 @@ def counted_multiset(self: RootSource) -> bytes: require_consistent_sources(pair) assert sorted(calls.values()) == [1, 1] assert {kind for kind, _ in calls} == {"multiset"} + + +def test_a_proxy_and_its_source_are_digested_once_per_check( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def derived() -> DerivedSource: + origin = DictSource( + [{"t": "a", "x": 1}, {"t": "b", "x": 2}], + tag_columns="t", + tag_only_columns=True, + source_id="origin", + ) + return DerivedSource( + origin, tags_as_data={"t": "tag_value"}, source_id="shared" + ) + + source, other = derived(), derived() + proxy = SourceProxy( + source.source_id, + source.content_hash().to_string(), + source.pipeline_hash().to_string(), + *source.output_schema(), + ) + proxy.bind(source) + calls = _count_digests(monkeypatch) + for uses in itertools.permutations( + [("slot 'p'", proxy), ("slot 'd'", source), ("slot 'o'", other)] + ): + calls.clear() + require_consistent_sources(uses) + assert calls == {("exact", id(source)): 1, ("exact", id(other)): 1} + + +def test_a_mutated_frame_is_compared_again_at_the_next_bind() -> None: + import pandas as pd + + def frame() -> pd.DataFrame: + return pd.DataFrame({"x": np.array([1, 2], dtype=np.int64)}) + + first_frame, second_frame = frame(), frame() + first = DataFrameSource(first_frame, source_id="shared") + second = DataFrameSource(second_frame, source_id="shared") + job = _job() + job.bind(sources={"left": first, "right": second}) + first_frame.iloc[0, 0] = 100 + if first.as_table()["x"].to_pylist() == [1, 2]: + pytest.skip("this pandas copies the frame; nothing is shared to mutate") + with pytest.raises(InconsistentSourceError, match="different rows"): + job.bind(sources={"left": first, "right": second}) From 98a8ed9b0000e4de10ef3004e45bbc8e40eb1ba5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 19:23:26 -0800 Subject: [PATCH 15/42] fix(pipeline): memoize fixed-row digests per check by underlying source Drops the lifetime digest cache on in-memory tables, which can share memory with a caller's frame or array; a check digests each underlying source (a bound proxy as its delegate) at most once. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/sources/base.py | 30 +++++----------------- src/orcapod/pipeline/source_consistency.py | 25 +++++++++++++++--- 2 files changed, 28 insertions(+), 27 deletions(-) diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 8c5cc4cab..80018835c 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -431,8 +431,8 @@ def holds_fixed_rows(self) -> bool: def fixed_content(self) -> bytes | None: """Digest of held rows for collision checks, or None for a live read. - Tags, data and record ids (``_digest_fixed_rows``), computed on each read - unless a subclass holds it. The digest is separate from source identity. + Tags, data and record ids (``_digest_fixed_rows``), computed on each read. + The digest is separate from source identity. """ if not self.holds_fixed_rows: return None @@ -459,8 +459,7 @@ def fixed_row_multiset(self) -> bytes | None: canonical row order of an identity table (``arrow_utils.canonical_identity_row_order``) and digested under the Arrow float rule, so ``-0.0`` equals ``0.0`` and every NaN equals every other. It is - ``None`` exactly when ``holds_fixed_rows`` is false; computed on each read - unless a subclass holds it. + ``None`` exactly when ``holds_fixed_rows`` is false; computed on each read. """ if not self.holds_fixed_rows: return None @@ -725,30 +724,13 @@ def cached( class FixedTableSource(RootSource): """A root that holds an Arrow table for its entire lifetime. - Its rows never change, so each digest of them is computed once and held. + Its digests are never held: the table can share memory with the caller's data (a + pandas frame, a NumPy array), which the caller can still change. A consistency + check digests it at most once per check. """ - _held_fixed_content: bytes | None = None - _held_fixed_row_multiset: bytes | None = None - @property @override def holds_fixed_rows(self) -> bool: """Always: the table is held for the source's lifetime.""" return True - - @property - @override - def fixed_content(self) -> bytes: - """Digest of the table this source holds, computed once.""" - if self._held_fixed_content is None: - self._held_fixed_content = self._digest_fixed_rows() - return self._held_fixed_content - - @property - @override - def fixed_row_multiset(self) -> bytes: - """Multiset digest of the table this source holds, computed once.""" - if self._held_fixed_row_multiset is None: - self._held_fixed_row_multiset = self._digest_fixed_row_multiset() - return self._held_fixed_row_multiset diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index 2ed4fcb36..dd00d7129 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -128,6 +128,23 @@ def _key_columns_conflict( ) +def _underlying(source: RootSource) -> RootSource: + """The source whose rows ``source`` presents: a bound proxy's delegate, unwrapped. + + Args: + source: A source in a consistency check. + + Returns: + The innermost bound root source behind any proxies, or ``source`` itself. + """ + from orcapod.core.sources.base import RootSource + from orcapod.core.sources.source_proxy import SourceProxy + + while isinstance(source, SourceProxy) and isinstance(source.delegate, RootSource): + source = source.delegate + return source + + def _differing_fixed_rows( group: list[tuple[str, RootSource]], ) -> tuple[str, str] | None: @@ -144,9 +161,10 @@ def _differing_fixed_rows( occurrence counts, order does not, and floats compare by the Arrow value rule (``-0.0`` equals ``0.0``, NaN equals NaN). - Only the digests a pair needs are computed, each at most once per source in one - check (a source that holds its digests, ``FixedTableSource``, computes each once - in its lifetime). + Only the digests a pair needs are computed, each at most once per check for each + underlying source: a bound proxy is digested as the source it stands in for + (``_underlying``). Nothing is held across checks: an in-memory table can share + memory with the caller's data, which the caller can change between checks. Args: group: Every distinct source with that id, with where it is used. @@ -159,6 +177,7 @@ def _differing_fixed_rows( multisets: dict[int, bytes | None] = {} def digest(source: RootSource, *, record_ids: bool) -> bytes | None: + source = _underlying(source) held = exact if record_ids else multisets if id(source) not in held: held[id(source)] = ( From aa8b0ff0913ac5246725e99e06ab6f25799e55ad Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 19:25:31 -0800 Subject: [PATCH 16/42] docs(sources): holds_fixed_rows does not assume constant values Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/sources/base.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 80018835c..132ef8f67 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -420,10 +420,13 @@ def _schema_identity(self) -> tuple[ContentHash, ContentHash]: @property def holds_fixed_rows(self) -> bool: - """Whether this source holds rows that never change, so they can be compared. + """Whether this source holds its table, so its rows can be compared. - Answered without reading or digesting any row. Sources that hold immutable - rows opt in; a wrapper can opt in if what it wraps holds fixed rows. + A source that holds its table gives its rows without a read or a poll. Its + values are not assumed constant: the table can share memory with a caller's + frame or array whose values change, so they are compared again at each check. + Answered without reading or digesting any row. A wrapper opts in if what it + wraps holds its table. """ return False From 38b2537d3f5d497aa6c13fb1337588d50b4da8b6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 19:26:59 -0800 Subject: [PATCH 17/42] test(pipeline): capture-time refusals, two-copy derived sources, node run on several columns Co-Authored-By: Claude Opus 5.5 --- .../test_pipeline/test_source_id_conflicts.py | 157 ++++++++++++++---- 1 file changed, 126 insertions(+), 31 deletions(-) diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index fbe90c98b..da87ab128 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -675,10 +675,13 @@ def _keyed( def _capture(first: RootSource, second: RootSource, pod: _FunctionPodBase) -> str: - with pytest.raises(InconsistentSourceError) as error: - with Pipeline("conflicts"): - pod(first, label="fa") - pod(second, label="fb") + """Refused when the second step is captured, not later at compile.""" + graph = Pipeline("conflicts") + with graph: + _ = pod(first, label="fa") + with pytest.raises(InconsistentSourceError) as error: + _ = pod(second, label="fb") + assert "fb" not in graph.nodes return str(error.value) @@ -773,52 +776,72 @@ def test_live_sources_with_different_keys_do_not_claim_only_key_columns( assert "source_id=" in message -def _derived(origin: RootSource, tag: str, keys: list[str] | None) -> DerivedSource: +@function_pod(output_keys="out") +def with_copies(x: int, y: int, c1: str, c2: str) -> int: + return x + y + len(c1) + len(c2) + + +def _derived( + origin: RootSource, mapping: dict[str, str], keys: list[str] | None +) -> DerivedSource: return DerivedSource( - origin, - tags_as_data={tag: "tag_value"}, - record_id_columns=keys, - source_id="shared", + origin, tags_as_data=mapping, record_id_columns=keys, source_id="shared" ) +# Two copies, given in both orders; the conflict changes only the second copy (c2 +# copies t3 instead of t2: same type, other values). +_COPIES = {"t1": "c1", "t2": "c2"} +_COPIES_REVERSED = {"t2": "c2", "t1": "c1"} +_SECOND_COPY_CHANGED = {"t1": "c1", "t3": "c2"} +_ORIGIN_TEXT = "t1,t2,t3,x,y\na,p,u,1,10\nb,q,v,2,20\n" + + def test_derived_sources_over_live_origins_with_other_mapping_and_keys( tmp_path: Path, ) -> None: path = tmp_path / "origin.csv" - path.write_text("t1,t2,x\na,p,1\nb,q,2\n") + path.write_text(_ORIGIN_TEXT) origin = CSVSource( str(path), source_id="origin", - tag_columns=["t1", "t2"], + tag_columns=["t1", "t2", "t3"], tag_only_columns=True, ) - first, second = _derived(origin, "t1", ["t1"]), _derived(origin, "t2", ["t2"]) - assert first.arrow_schemas == second.arrow_schemas - message = _capture(first, second, with_copy.pod) - assert "differ only" not in message - assert "not compared" in message - assert "ITL-1506" in message + for mapping in (_COPIES_REVERSED, _SECOND_COPY_CHANGED): + first = _derived(origin, _COPIES, ["t1", "t2"]) + second = _derived(origin, mapping, ["t3", "t1"]) + assert first.arrow_schemas == second.arrow_schemas + message = _capture(first, second, with_copies.pod) + assert "differ only" not in message + assert "not compared" in message + assert "ITL-1506" in message -def test_derived_sources_over_fixed_origins_compare_rows_without_record_ids() -> None: +@pytest.mark.parametrize("reverse", [False, True]) +def test_derived_sources_over_fixed_origins_compare_rows_without_record_ids( + reverse: bool, +) -> None: origin = DictSource( - [{"t1": "a", "t2": "p", "x": 1}, {"t1": "b", "t2": "q", "x": 2}], - tag_columns=["t1", "t2"], + [ + {"t1": "a", "t2": "p", "t3": "u", "x": 1, "y": 10}, + {"t1": "b", "t2": "q", "t3": "v", "x": 2, "y": 20}, + ], + tag_columns=["t1", "t2", "t3"], tag_only_columns=True, source_id="origin", ) - same = _capture( - _derived(origin, "t1", ["t1"]), _derived(origin, "t1", ["t2"]), with_copy.pod - ) + + def pair(mapping: dict[str, str]) -> tuple[DerivedSource, DerivedSource]: + first = _derived(origin, _COPIES, ["t1", "t2"]) + second = _derived(origin, mapping, ["t3", "t1"]) + return (second, first) if reverse else (first, second) + + # The mapping given in the other order copies the same values. + same = _capture(*pair(_COPIES_REVERSED), with_copies.pod) assert "differ only in key columns" in same - # Another mapping copies other values: the rows differ. - _refused( - _derived(origin, "t1", ["t1"]), - _derived(origin, "t2", ["t2"]), - Pipeline("conflicts"), - with_copy.pod, - ) + # Only the second copy changed: the rows differ. + _refused(*pair(_SECOND_COPY_CHANGED), Pipeline("conflicts"), with_copies.pod) def test_equal_keys_still_compare_record_ids() -> None: @@ -856,7 +879,11 @@ def test_unknown_key_columns_never_hide_a_conflict_between_known_ones() -> None: ): with pytest.raises(InconsistentSourceError) as error: require_consistent_sources(uses) - assert "differ only in key columns" in str(error.value) + # The proxy's rows were not compared, so the rows are not claimed equal. + message = str(error.value) + assert "different key columns" in message + assert "differ only" not in message + assert "not compared" in message # Alone with either known source, the proxy causes nothing. require_consistent_sources([("slot 'p'", proxy), ("slot 'a'", positional)]) require_consistent_sources([("slot 'p'", proxy), ("slot 'b'", keyed)]) @@ -1043,3 +1070,71 @@ def frame() -> pd.DataFrame: pytest.skip("this pandas copies the frame; nothing is shared to mutate") with pytest.raises(InconsistentSourceError, match="different rows"): job.bind(sources={"left": first, "right": second}) + + +def _arranged( + arrangement: Arrangement, + source_id: str, + keys: list[str] | None, + changed: bool = False, +) -> ArrowTableSource: + """``P`` (two tags, two data columns) in ``arrangement``; ``changed`` alters p2.""" + table = make_table(P, arrangement) + if changed: + index = table.schema.get_field_index("p2") + values = table["p2"].to_pylist() + values[-1] = "changed" + table = table.set_column( + index, table.schema.field(index), pa.array(values, pa.large_string()) + ) + role = arrangement.roles + return ArrowTableSource( + table, + tag_columns=list(arrangement.tag_order), + tag_only_columns=True + if role == PLAIN + else [P.mixed_plain] + if role == MIXED + else [], + record_id_columns=keys, + source_id=source_id, + ) + + +@pytest.mark.parametrize("role", ROLES) +@pytest.mark.parametrize( + ("left_keys", "right_keys", "changed", "message"), + [ + (["t1", "t2"], ["t2", "t1"], False, "differ only in key columns"), + (None, ["t2", "t1"], False, "differ only in key columns"), + (["t1", "t2"], ["t2", "t1"], True, "different rows"), + (None, None, True, "different rows"), + ], +) +@pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +) +def test_node_run_checks_its_sources_on_several_columns( + role: str, + left_keys: list[str] | None, + right_keys: list[str] | None, + changed: bool, + message: str, + orchestrator: type, +) -> None: + left = Arrangement(P.tags, TAGS_FIRST, role) + right = Arrangement(tuple(reversed(P.tags)), DATA_FIRST_REVERSED, role) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + matched = SemiJoin()( + _arranged(left, "left", None), _arranged(right, "right", None), label="m" + ) + _ = with_pair.pod(matched, label="fm") + # Rebound outside bind, so only the run-time checks can refuse. + job.nodes["left"].bound_source = _arranged(left, "shared", left_keys) + job.nodes["right"].bound_source = _arranged(right, "shared", right_keys, changed) + with pytest.raises(InconsistentSourceError, match=message): + _ = job.run(orchestrator=orchestrator()) + for node in ("m", "fm"): + with pytest.raises(InconsistentSourceError, match=message): + _ = job.nodes[node].run() + assert job.nodes[node].as_table().num_rows == 0 From a40296cb54dffec65abcec6beb3d04b3a9e2e740 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 19:33:08 -0800 Subject: [PATCH 18/42] fix(pipeline): claim key-only differences only when every source was compared Co-Authored-By: Claude Opus 5.5 --- src/orcapod/pipeline/source_consistency.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index dd00d7129..c34362350 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -97,7 +97,10 @@ def _key_columns_conflict( distinct named slots is ITL-1506, after the multi-slot binding work (ITL-1442). Call only after the schemas and fixed rows of ``group`` were found to agree. Only the sources whose key columns are known are compared: one whose key columns are - unknown (an unbound proxy) neither causes nor suppresses a refusal. + unknown (an unbound proxy) neither causes nor suppresses a refusal. The message + says they differ only in key columns when every source of the group holds fixed + rows (all compared and equal); any other source, read later or unbound, means + its rows were not compared, and the message says so. Args: source_id: The shared source id. @@ -115,7 +118,9 @@ def _key_columns_conflict( "named slots (ITL-1506). For now, give each source its own name with " "source_id=... when it is built." ) - if all(source.holds_fixed_rows for _, source in known): + # "Only" claims the rows are equal: true only when every source of the group, + # known key columns or not, holds rows that ``_differing_fixed_rows`` compared. + if all(source.holds_fixed_rows for _, source in group): return ( f"Sources with source id {source_id!r} in {where} share one schema and " "the same rows, and differ only in key columns (record_id_columns), so " From 0312a9e2e0db91a4975efa4be7676c824c35003f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 11:43:57 -0800 Subject: [PATCH 19/42] refactor(sources): keep source consistency properties private --- changelog.d/ITL-1469.md | 9 +++--- docs/concepts/identity.md | 6 ++-- docs/concepts/sources.md | 21 +++++++------- docs/reference/hashing.md | 8 +++--- src/orcapod/core/sources/base.py | 18 ++++++------ src/orcapod/core/sources/cached_source.py | 4 +-- src/orcapod/core/sources/derived_source.py | 4 +-- src/orcapod/core/sources/source_proxy.py | 16 +++++------ src/orcapod/errors.py | 11 ++++---- src/orcapod/pipeline/source_consistency.py | 28 ++++++++++++------- .../test_pipeline/test_source_id_conflicts.py | 19 +++++-------- 11 files changed, 75 insertions(+), 69 deletions(-) diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index d42e6f08e..65359fa58 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -11,7 +11,8 @@ - Sources that share a source ID and schema but have different key columns are refused at capture, binding (into any slots), loading and run (`job.run()` - and a node's `run()`). In-memory sources with the same rows are reported as - differing only in key columns; the rows of sources read later are not - compared. ITL-1506 will allow distinct readings of - one dataset in distinct named slots. + and a node's `run()`). The error reports a difference only in key columns + when all sources hold the same rows in memory. + ITL-1506 tracks the design for using different key columns under one source + ID. The row comparison only applies to sources that hold their rows in + memory. ITL-1531 tracks sources that read their rows later. diff --git a/docs/concepts/identity.md b/docs/concepts/identity.md index 9b5e6da73..79ca594ff 100644 --- a/docs/concepts/identity.md +++ b/docs/concepts/identity.md @@ -26,11 +26,11 @@ A source's identity is its schema, its `source_id` and its key columns (the - If you pass `source_id` yourself, you are naming the source. The kind is part of the canonical ID. Two sources with the same ID, schema and key columns have the same content hash even when their rows differ. A pipeline checks reused IDs separately - when it captures or binds sources. + at capture, binding, loading and execution. See [source consistency](sources.md#source-ids-name-the-kind-that-reads-the-data). Two sources that differ only in their key columns name the same rows differently, so they -are two sources: different content hashes (each gets its own cache), the same pipeline hash -and the same `source_id`. +have different content hashes and the same pipeline hash and `source_id`. A pipeline or +job currently refuses to use both readings under that shared ID (ITL-1506). Rows are still identified individually. Each row carries its own content hash, and that per-row hash is what caching uses. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 3dea22d39..d7cf74917 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -88,9 +88,10 @@ on), and with key columns the same rows can arrive in any order. With different columns the record IDs necessarily differ, so the rows are compared as a multiset of tags and data: every row counts as often as it occurs, and order does not count. The comparison follows Orcapod's Arrow value rule, which treats signed zeros as equal and -all NaNs as equal. Sources that read again later, including files, -databases, caches and stored job outputs, use the ID and schema without a row -comparison. Capture and binding reject conflicts with `InconsistentSourceError`. +all NaNs as equal. Only sources that hold their rows in memory take part in the +content check. Sources that read rows later, including files, databases, caches and +stored job outputs, skip the content check. Comparing those sources is tracked in +ITL-1531. Capture and binding reject conflicts with `InconsistentSourceError`. Give the conflicting sources different `source_id` values. ```python @@ -1013,13 +1014,13 @@ order or content can vary between runs, pass an explicit, stable `source_id` **a key columns that are unique per row; this avoids both the duplicate entries and the repeated deliveries. -Sources that share a `source_id` and schema but have different key columns are two -readings of one dataset, and are refused for now everywhere: at capture, `bind` (into any -slots), load and run (`job.run()` and a node's `run()`), with `InconsistentSourceError`. When both hold their rows in memory, the -rows are compared first (as a multiset, above): different rows are reported as such, and -equal rows as differing only in key columns. The rows of a source read later (a file, a -database) are not compared, and the error says so. ITL-1506 will allow distinct readings -of one dataset in distinct named slots. Until then, give each source its own `source_id`. +Sources that share a `source_id` and schema but have different key columns raise +`InconsistentSourceError` during capture, binding into any slots, loading, and execution +through `job.run()` or a node's `run()`. Orcapod compares the in-memory rows first, as +described above. The error reports different rows when it finds a mismatch. It reports +a difference only in key columns when all sources hold the same rows in memory. +ITL-1506 tracks how to support multiple readings of one dataset with different key +columns. Until that design is settled, give each source its own `source_id`. An in-memory source with key columns and no `source_id` can instead hash its rows in key order: pass `hash_in_key_order=True` (`ArrowTableSource`, `DictSource`, `DataFrameSource`, diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 6130f2dd5..3d6c8132e 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -606,11 +606,11 @@ The table below shows what each class returns from `identity_structure()`. | `FunctionPod` | `self.data_function` (bare object) when no ctx arg; `(self.data_function, self._ctx_arg_name)` when ctx arg present | `ctx_arg_name` is included when present so a ctx-aware pod has a distinct `content_hash` from a plain pod using the same data function | | `FallThroughPod` (`pod(stream)` over data-tags) | `(plain_pod, ("fall_through_tags", sorted names))` | The data-tags that fall through are a set: sorted by name, so the order of the input's tag columns never moves the pod's hashes or its node's table paths (ITL-1246). The pod's config and a saved job's `fall_through_tags` list them sorted too | | `ArrowTableStream` | `(producer, argument_symmetry(upstreams))` | With no producer (a raw stream), or a producer that is not a `PipelineElementProtocol`: `(class_name, identity table in canonical row order, sorted tag columns)`, plus `("data_tags", sorted names)` when it has any. See "The identity of a raw stream" below | -| `RootSource` (`ArrowTableSource`, `ListSource` and every other root source without its own rule) | `(source_id, (hash_schema(tag), hash_schema(data)), key_columns)`, the Arrow schemas of its rows (ITL-640) | `source_id` is `_v:`, the name being the explicit user-supplied value; when not provided it defaults to `::` of the Arrow hash of the raw table (site 4). The class name is not part of it (ITL-1425): the kind part names the kind and implementation version, and the kind enters a datum's identity there only. `PollingSource` is `(source_id, impl.identity(), sorted tag columns, key_columns)` (provisional, ITL-1316). `key_columns` is the resolved tuple of record-id key columns in key order (`record_id_columns`, or a database or SpiralDB table's primary key), `()` for the position: two sources that differ only in how they name their rows are two sources (developer decision, November 16, 2026, ITL-1154). Data-inclusive base case of the Merkle chain. A `ListSource` has no rule of its own (developer, November 21, 2026, ITL-1272): its elements and tags enter its identity only through its default source id and its Arrow schema (their types), and with a given `source_id` it is an address like every other source (other elements of the same types leave its content hash unchanged); it used to hold its elements and a hash of its tag function (and took `tag_function_hash_mode`), and with a given `source_id` its content hash did not depend on that id at all. A review of every built-in source's identity is ITL-1311 | +| `RootSource` (`ArrowTableSource`, `ListSource` and every other root source without its own rule) | `(source_id, (hash_schema(tag), hash_schema(data)), record ID key tuple)`, the Arrow schemas of its rows (ITL-640) | `source_id` is `_v:`, the name being the explicit user-supplied value; when not provided it defaults to `::` of the Arrow hash of the raw table (site 4). The class name is not part of it (ITL-1425): the kind part names the kind and implementation version, and the kind enters a datum's identity there only. `PollingSource` is `(source_id, impl.identity(), sorted tag columns, record ID key tuple)` (provisional, ITL-1316). The record ID key tuple lists the columns used to identify rows, in key order (`record_id_columns`, or a database or SpiralDB table's primary key), `()` for the position: two sources that differ only in how they name their rows are two sources (developer decision, November 16, 2026, ITL-1154). Data-inclusive base case of the Merkle chain. A `ListSource` has no rule of its own (developer, November 21, 2026, ITL-1272): its elements and tags enter its identity only through its default source id and its Arrow schema (their types), and with a given `source_id` it is an address like every other source (other elements of the same types leave its content hash unchanged); it used to hold its elements and a hash of its tag function (and took `tag_function_hash_mode`), and with a given `source_id` its content hash did not depend on that id at all. A review of every built-in source's identity is ITL-1311 | | `DerivedSource` | Origin node's `content_hash` | Inherits its generating node's identity | -| `DerivedSource` with `tags_as_data` | `(source_id, Arrow schema identity, key_columns, ("tags_as_data", sorted items))`; a `source_id` is required (ITL-1313), and the full id is `derived_v1:` | The rule of every root source plus the mapping, which enters the `content_hash` directly (two mappings can give one schema and one `source_id`); the origin enters only through the output schema, so the source is an address like every other source with a given `source_id` | -| `PollingSource` | `(source_id, impl.identity(), sorted tag_columns, key_columns)` | The source id (`polling_source_v1:`) first, as for every root source (ITL-1425), so a given `source_id` tells two polling sources apart; then the implementer's identity; the tag columns in name order, so their declared order changes nothing; `key_columns` (always given for a polling source, in key order) as for every root source. Provisional (`PROVISIONAL_SOURCES`, ITL-1314): this identity may change in a later release (ITL-1316) | -| `SpiralDBTableSource` | `(source_id, Arrow schema identity, key_columns)`, the rule of every root source (no class name, ITL-1425), then the sorted `tags_as_data` items when given | A restriction (`where`, `limit`, `asof`) chooses rows of the same table and adds nothing | +| `DerivedSource` with `tags_as_data` | `(source_id, Arrow schema identity, record ID key tuple, ("tags_as_data", sorted items))`; a `source_id` is required (ITL-1313), and the full id is `derived_v1:` | The rule of every root source plus the mapping, which enters the `content_hash` directly (two mappings can give one schema and one `source_id`); the origin enters only through the output schema, so the source is an address like every other source with a given `source_id` | +| `PollingSource` | `(source_id, impl.identity(), sorted tag_columns, record ID key tuple)` | The source id (`polling_source_v1:`) first, as for every root source (ITL-1425), so a given `source_id` tells two polling sources apart; then the implementer's identity; the tag columns in name order, so their declared order changes nothing; the record ID key tuple (required for a polling source) as for every root source. Provisional (`PROVISIONAL_SOURCES`, ITL-1314): this identity may change in a later release (ITL-1316) | +| `SpiralDBTableSource` | `(source_id, Arrow schema identity, record ID key tuple)`, the rule of every root source (no class name, ITL-1425), then the sorted `tags_as_data` items when given | A restriction (`where`, `limit`, `asof`) chooses rows of the same table and adds nothing | | `CachedSource` | the wrapped source's identity | | | Operators (unary) | `(operator_class_name, upstream_stream)` | Stream reference resolved via `content_resolver` | | Operators (binary/N-ary) | `(operator_class_name, argument_symmetry(streams))` | `frozenset` for commutative (Join); `tuple` for ordered (SemiJoin, MergeJoin: ITL-1281) | diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 132ef8f67..30db3ea4e 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -419,7 +419,7 @@ def _schema_identity(self) -> tuple[ContentHash, ContentHash]: return arrow_schema_identity(*self.arrow_schemas, self.data_context) @property - def holds_fixed_rows(self) -> bool: + def _holds_fixed_rows(self) -> bool: """Whether this source holds its table, so its rows can be compared. A source that holds its table gives its rows without a read or a poll. Its @@ -431,18 +431,18 @@ def holds_fixed_rows(self) -> bool: return False @property - def fixed_content(self) -> bytes | None: + def _fixed_content(self) -> bytes | None: """Digest of held rows for collision checks, or None for a live read. Tags, data and record ids (``_digest_fixed_rows``), computed on each read. The digest is separate from source identity. """ - if not self.holds_fixed_rows: + if not self._holds_fixed_rows: return None return self._digest_fixed_rows() @property - def key_columns(self) -> tuple[str, ...] | None: + def _resolved_key_columns(self) -> tuple[str, ...] | None: """The resolved key columns that name this source's rows, in key order. ``()`` means a row is named by its position. Key columns belong to how the @@ -453,7 +453,7 @@ def key_columns(self) -> tuple[str, ...] | None: return self._key_columns @property - def fixed_row_multiset(self) -> bytes | None: + def _fixed_row_multiset(self) -> bytes | None: """Digest of the held rows as a multiset of tags and data, or None for a live read. Used to compare two fixed readings of one dataset whose key columns differ @@ -462,14 +462,14 @@ def fixed_row_multiset(self) -> bytes | None: canonical row order of an identity table (``arrow_utils.canonical_identity_row_order``) and digested under the Arrow float rule, so ``-0.0`` equals ``0.0`` and every NaN equals every other. It is - ``None`` exactly when ``holds_fixed_rows`` is false; computed on each read. + ``None`` exactly when ``_holds_fixed_rows`` is false; computed on each read. """ - if not self.holds_fixed_rows: + if not self._holds_fixed_rows: return None return self._digest_fixed_row_multiset() def _digest_fixed_row_multiset(self) -> bytes: - """Digest the rows as a multiset of tags and data (``fixed_row_multiset``).""" + """Digest the rows as a multiset of tags and data (``_fixed_row_multiset``).""" from orcapod.hashing.starfix_digest import digest_orcapod_table from orcapod.utils.arrow_utils import canonical_identity_row_order @@ -734,6 +734,6 @@ class FixedTableSource(RootSource): @property @override - def holds_fixed_rows(self) -> bool: + def _holds_fixed_rows(self) -> bool: """Always: the table is held for the source's lifetime.""" return True diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 674d1b002..77d4ed579 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -269,10 +269,10 @@ def source_name(self) -> str: @property @override - def key_columns(self) -> tuple[str, ...] | None: + def _resolved_key_columns(self) -> tuple[str, ...] | None: """The wrapped source's key columns, or ``None`` when it is not a root source.""" if isinstance(self._source, RootSource): - return self._source.key_columns + return self._source._resolved_key_columns return None def _compute_arrow_schemas(self) -> "tuple[pa.Schema, pa.Schema]": diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index dcad18264..20a16be50 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -307,12 +307,12 @@ def __init__( @property @override - def holds_fixed_rows(self) -> bool: + def _holds_fixed_rows(self) -> bool: """Rows are fixed only when the origin itself holds fixed rows. The digests are not held: a check for new data can refresh the rows. """ - return isinstance(self._origin, RootSource) and self._origin.holds_fixed_rows + return isinstance(self._origin, RootSource) and self._origin._holds_fixed_rows def identity_structure(self) -> Any: """Return what the content hash is built from. diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index dd9ba1e17..373cc91bf 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -97,34 +97,34 @@ def delegate(self) -> SourceProtocol | None: @property @override - def holds_fixed_rows(self) -> bool: + def _holds_fixed_rows(self) -> bool: """Whether the bound source holds fixed rows.""" return ( - isinstance(self._delegate, RootSource) and self._delegate.holds_fixed_rows + isinstance(self._delegate, RootSource) and self._delegate._holds_fixed_rows ) @property @override - def fixed_content(self) -> bytes | None: + def _fixed_content(self) -> bytes | None: """The bound source's fixed rows, if it holds them.""" if isinstance(self._delegate, RootSource): - return self._delegate.fixed_content + return self._delegate._fixed_content return None @property @override - def fixed_row_multiset(self) -> bytes | None: + def _fixed_row_multiset(self) -> bytes | None: """The bound source's multiset digest, if it holds fixed rows.""" if isinstance(self._delegate, RootSource): - return self._delegate.fixed_row_multiset + return self._delegate._fixed_row_multiset return None @property @override - def key_columns(self) -> tuple[str, ...] | None: + def _resolved_key_columns(self) -> tuple[str, ...] | None: """The bound source's key columns, or ``None`` while unbound.""" if isinstance(self._delegate, RootSource): - return self._delegate.key_columns + return self._delegate._resolved_key_columns return None @property diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index bbedba0f9..e19317ed5 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -560,11 +560,12 @@ class InconsistentSourceError(ValueError): """Raised when two sources in a pipeline disagree at a shared address. Sources sharing a ``source_id`` must have the same schema. If both hold - fixed content, their rows must also agree: tags, data and record IDs with - equal key columns, tags and data as a multiset with different ones. Sources - sharing a ``source_id`` and schema with different key columns are refused - for now, in any slots (ITL-1506 will allow them in distinct named slots). Two - different schemas competing for one input slot also raise this error. + their rows in memory, their rows must also agree: tags, data and record IDs + with equal key columns, tags and data as a multiset with different ones. + ITL-1531 tracks content checks for sources that read their rows later. + Sources sharing a ``source_id`` and schema with different key columns are + refused in any slots while the design is pending (ITL-1506). Two different + schemas competing for one input slot also raise this error. Resolution: assign distinct ``source_id`` values to the conflicting sources so each slot has a unique, stable identity. diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index c34362350..5e6947e66 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -93,8 +93,8 @@ def _key_columns_conflict( """Describe sources of one id and schema whose key columns differ, if any. Such sources are distinct readings of one dataset. They are refused everywhere for - now (capture, bind, load, run), whatever slots they would take: allowing them in - distinct named slots is ITL-1506, after the multi-slot binding work (ITL-1442). + now (capture, bind, load, run), whatever slots they would take. ITL-1506 tracks + the design for different key columns under one source id. Call only after the schemas and fixed rows of ``group`` were found to agree. Only the sources whose key columns are known are compared: one whose key columns are unknown (an unbound proxy) neither causes nor suppresses a refusal. The message @@ -109,8 +109,12 @@ def _key_columns_conflict( Returns: The error message, or ``None`` when the known key columns agree. """ - known = [(where, s) for where, s in group if s.key_columns is not None] - if len({source.key_columns for _, source in known}) < 2: + known = [ + (where, s) + for where, s in group + if s._resolved_key_columns is not None # pyright: ignore[reportPrivateUsage] # source consistency + ] + if len({source._resolved_key_columns for _, source in known}) < 2: # pyright: ignore[reportPrivateUsage] # source consistency return None where = ", ".join(location for location, _ in known) remedy = ( @@ -120,7 +124,7 @@ def _key_columns_conflict( ) # "Only" claims the rows are equal: true only when every source of the group, # known key columns or not, holds rows that ``_differing_fixed_rows`` compared. - if all(source.holds_fixed_rows for _, source in group): + if all(source._holds_fixed_rows for _, source in group): # pyright: ignore[reportPrivateUsage] # source consistency return ( f"Sources with source id {source_id!r} in {where} share one schema and " "the same rows, and differ only in key columns (record_id_columns), so " @@ -160,9 +164,9 @@ def _differing_fixed_rows( answer never depends on the order of ``group``: - equal key columns (or unknown ones): tags, data and record ids - (``fixed_content``), so positional row order counts as it always has; + (``_fixed_content``), so positional row order counts as it always has; - different key columns: the record ids necessarily differ, so the rows are - compared as a multiset of tags and data (``fixed_row_multiset``): every + compared as a multiset of tags and data (``_fixed_row_multiset``): every occurrence counts, order does not, and floats compare by the Arrow value rule (``-0.0`` equals ``0.0``, NaN equals NaN). @@ -177,7 +181,11 @@ def _differing_fixed_rows( Returns: The locations of the first such pair, or ``None`` when all fixed rows agree. """ - fixed = [(where, s) for where, s in group if s.holds_fixed_rows] + fixed = [ + (where, s) + for where, s in group + if s._holds_fixed_rows # pyright: ignore[reportPrivateUsage] # source consistency + ] exact: dict[int, bytes | None] = {} multisets: dict[int, bytes | None] = {} @@ -186,13 +194,13 @@ def digest(source: RootSource, *, record_ids: bool) -> bytes | None: held = exact if record_ids else multisets if id(source) not in held: held[id(source)] = ( - source.fixed_content if record_ids else source.fixed_row_multiset + source._fixed_content if record_ids else source._fixed_row_multiset # pyright: ignore[reportPrivateUsage] # source consistency ) return held[id(source)] for index, (first_location, first) in enumerate(fixed): for location, source in fixed[index + 1 :]: - first_keys, keys = first.key_columns, source.key_columns + first_keys, keys = first._resolved_key_columns, source._resolved_key_columns # pyright: ignore[reportPrivateUsage] # source consistency record_ids = first_keys is None or keys is None or first_keys == keys if digest(first, record_ids=record_ids) != digest( source, record_ids=record_ids diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index da87ab128..cc3fc9dbc 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -736,18 +736,13 @@ def test_fixed_different_rows_with_different_keys_are_different_rows( def test_fixed_row_multiset_counts_duplicates_and_ignores_order() -> None: + def digest(rows: list[dict[str, str | int]]) -> bytes | None: + return _keyed(rows, None)._fixed_row_multiset # pyright: ignore[reportPrivateUsage] # testing the internal digest + a, b = _ROWS[0], _ROWS[1] - assert ( - _keyed([a, a, b], None).fixed_row_multiset - == _keyed([a, b, a], None).fixed_row_multiset - ) - assert ( - _keyed([a, a, b], None).fixed_row_multiset - != _keyed([a, b, b], None).fixed_row_multiset - ) - assert ( - _keyed([a, b], None).fixed_row_multiset != _keyed([a], None).fixed_row_multiset - ) + assert digest([a, a, b]) == digest([a, b, a]) + assert digest([a, a, b]) != digest([a, b, b]) + assert digest([a, b]) != digest([a]) @pytest.mark.parametrize("reverse", [False, True]) @@ -873,7 +868,7 @@ def test_unknown_key_columns_never_hide_a_conflict_between_known_ones() -> None: positional.pipeline_hash().to_string(), *positional.output_schema(), ) - assert proxy.key_columns is None + assert proxy._resolved_key_columns is None # pyright: ignore[reportPrivateUsage] # unbound proxy state for uses in itertools.permutations( [("slot 'p'", proxy), ("slot 'a'", positional), ("slot 'b'", keyed)] ): From c6d9f72152bef33ce7959a3ba63317f0c1193dd1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 15:45:41 -0800 Subject: [PATCH 20/42] fix(pipeline): require one source object per content hash --- changelog.d/ITL-1469.md | 23 +- docs/concepts/identity.md | 5 +- docs/concepts/sources.md | 60 +- src/orcapod/core/nodes/function_node.py | 14 +- src/orcapod/core/nodes/operator_node.py | 11 +- .../core/sources/arrow_table_source.py | 4 +- src/orcapod/core/sources/base.py | 89 --- src/orcapod/core/sources/data_frame_source.py | 4 +- src/orcapod/core/sources/derived_source.py | 9 - src/orcapod/core/sources/dict_source.py | 4 +- src/orcapod/core/sources/list_source.py | 4 +- src/orcapod/core/sources/source_proxy.py | 24 - .../core/sources/spiraldb_table_source.py | 7 +- src/orcapod/errors.py | 21 +- src/orcapod/pipeline/base.py | 4 +- src/orcapod/pipeline/job.py | 29 +- src/orcapod/pipeline/loaded_side_effects.py | 5 +- src/orcapod/pipeline/source_consistency.py | 187 ++---- src/orcapod/side_effects.py | 5 +- .../data_tags/test_derived_source.py | 5 +- .../sources/test_provisional_sources.py | 5 +- .../test_spiraldb_table_source_where.py | 94 +-- .../fixtures/itl_1469_main_shared_source.json | 310 ++++++++++ .../test_job_node_rows_after_run.py | 5 +- .../test_pipeline/test_source_id_conflicts.py | 555 ++---------------- .../test_source_object_registration.py | 286 +++++++++ 26 files changed, 852 insertions(+), 917 deletions(-) create mode 100644 tests/test_pipeline/fixtures/itl_1469_main_shared_source.json create mode 100644 tests/test_pipeline/test_source_object_registration.py diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index 65359fa58..f22dce42a 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -1,18 +1,15 @@ ### Fixed -- Pipeline capture and job binding reject two in-memory sources that share a - source ID and schema but contain different rows. With different key columns - the rows are compared without their record IDs, as a multiset of tags and - data. A node's `run()` checks the sources it reads as `job.run()` does. The - error names the conflicting steps or slots. Job binding and loading also - reject different schemas at a shared source ID. +- A pipeline or job accepts one source object per content hash. Capture, binding, + loading and execution reject distinct objects with the same hash, even if + their rows agree. Build a source once and reuse it, or give each source its own + source ID. Rebinding replaces a slot's source, and loading shares one rebuilt + object across slots with identical source configurations. +- Sources with the same source ID must agree on their Arrow schema and key + columns, including when they occupy different slots. ### Known limitations -- Sources that share a source ID and schema but have different key columns are - refused at capture, binding (into any slots), loading and run (`job.run()` - and a node's `run()`). The error reports a difference only in key columns - when all sources hold the same rows in memory. - ITL-1506 tracks the design for using different key columns under one source - ID. The row comparison only applies to sources that hold their rows in - memory. ITL-1531 tracks sources that read their rows later. +- ITL-1506 tracks distinct readings of one dataset in distinct slots. ITL-1531 + tracks sources that read their rows later. ITL-1553 tracks accepting distinct + objects that represent the same source. diff --git a/docs/concepts/identity.md b/docs/concepts/identity.md index 79ca594ff..82ac38ac7 100644 --- a/docs/concepts/identity.md +++ b/docs/concepts/identity.md @@ -25,8 +25,9 @@ A source's identity is its schema, its `source_id` and its key columns (the rows. - If you pass `source_id` yourself, you are naming the source. The kind is part of the canonical ID. Two sources with the same ID, schema and key columns have the same - content hash even when their rows differ. A pipeline checks reused IDs separately - at capture, binding, loading and execution. See [source consistency](sources.md#source-ids-name-the-kind-that-reads-the-data). + content hash even when their rows differ. A pipeline or job registers one source + object per content hash at capture, binding, loading and execution. + See [source consistency](sources.md#source-ids-name-the-kind-that-reads-the-data). Two sources that differ only in their key columns name the same rows differently, so they have different content hashes and the same pipeline hash and `source_id`. A pipeline or diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index d7cf74917..a276e8531 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -78,21 +78,20 @@ same rows read by another kind, or by another version of one kind, are another s record id names a row within its source and never holds the source id. A job names an input slot by the source's name (`job.bind(sources={"units": ...})`). -Within a pipeline or job, sources sharing a `source_id` must have the same Arrow schema. -If both sources hold their rows in memory, their rows must also agree. This applies to -`ArrowTableSource`, `DictSource`, `ListSource`, `DataFrameSource` and wrappers over -their fixed rows. A source id names a dataset, and key columns only name its rows, so -what is compared depends on the key columns. With the same key columns, tags, data and -record IDs must agree: row order counts with positional IDs (`row_0`, `row_1`, and so -on), and with key columns the same rows can arrive in any order. With different key -columns the record IDs necessarily differ, so the rows are compared as a multiset of -tags and data: every row counts as often as it occurs, and order does not count. The -comparison follows Orcapod's Arrow value rule, which treats signed zeros as equal and -all NaNs as equal. Only sources that hold their rows in memory take part in the -content check. Sources that read rows later, including files, databases, caches and -stored job outputs, skip the content check. Comparing those sources is tracked in -ITL-1531. Capture and binding reject conflicts with `InconsistentSourceError`. -Give the conflicting sources different `source_id` values. +Each source content hash is registered to one Python object per pipeline or job. +Build the source once and reuse that object wherever you read it, or give each +source its own `source_id`. Two distinct objects with the same content hash raise +`InconsistentSourceError` even when their rows agree, including sources that read +rows later. Capture, binding, loading and execution all check for conflicts. +Rebinding replaces a slot's source. On load, slots with identical saved source +configurations share one reconstructed object. + +The source object can be a `SourceProxy`, a `CachedSource` or a `DerivedSource`. +Reuse the wrapper itself wherever you use that source. A wrapper and another source +with the same content hash cannot both be registered in the same pipeline. + +ITL-1553 tracks accepting distinct objects that represent the same source. +ITL-1531 tracks sources that read their rows later. ```python from orcapod import Pipeline, function_pod @@ -106,14 +105,14 @@ def adjust(rate: float) -> float: first = DictSource([{"rate": 3.5}], source_id="rates") -second = DictSource([{"rate": 7.25}], source_id="rates") +second = DictSource([{"rate": 3.5}], source_id="rates") try: with Pipeline("rates"): adjust.pod(first, label="first") adjust.pod(second, label="second") except InconsistentSourceError as error: print(error) -# Source 'dict_v1:rates' has different rows in step 'first' and step 'second'. Give the sources different source_id values. +# Source 'dict_v1:rates' has distinct source objects with one content hash in step 'first' and step 'second'. Build the source once and reuse the object, or give each source its own source_id. ``` A kind's version moves when a row read before a change of its implementation could read @@ -621,14 +620,13 @@ print(Condition.of(day=day, started=started, recorded=recorded)) inside the pipeline (`PolarsFilter`). A NaN or infinite value is saved as `{"float": "nan"}`, `{"float": "inf"}` or `{"float": "-inf"}`, since JSON has no such number. - **One restriction per table in a pipeline.** A restricted source has the unrestricted - source's identity, so a pipeline holds one restriction (or none) per source: building a - pipeline in which one table is read with two different restrictions (or with and without - one) raises `ValueError` instead of silently reading one of them, whatever streams lead to - the table: different column selections or operator chains, streams built before the - pipeline, a `CachedSource` or a `SourceProxy` bound to it. It is checked from what each - stream reads at that moment: when the pipeline is built, when it is compiled, by `bind` - before it binds (a slot bound to a stream over a table another slot reads) and when a run - starts. Use one restriction per pipeline, or build separate pipelines. + source's content hash, and each call to `where()` returns a new source object. + Call `where()` once and reuse its result when several parts of the pipeline need + the same restriction. If two distinct source objects with the same content hash + enter a pipeline, Orcapod raises `InconsistentSourceError` even when the two + restrictions are equal. The one-restriction check also looks through wrappers + such as `CachedSource` and bound `SourceProxy` objects. It rejects different + restrictions on the same source, including a restricted and an unrestricted read. - **With `limit=`.** A source built with `limit=n` reads the first `n` rows that match, in key order: the conditions are applied first. - **Conditions as values.** Two conditions are equal when they require the same columns to @@ -1014,13 +1012,11 @@ order or content can vary between runs, pass an explicit, stable `source_id` **a key columns that are unique per row; this avoids both the duplicate entries and the repeated deliveries. -Sources that share a `source_id` and schema but have different key columns raise -`InconsistentSourceError` during capture, binding into any slots, loading, and execution -through `job.run()` or a node's `run()`. Orcapod compares the in-memory rows first, as -described above. The error reports different rows when it finds a mismatch. It reports -a difference only in key columns when all sources hold the same rows in memory. -ITL-1506 tracks how to support multiple readings of one dataset with different key -columns. Until that design is settled, give each source its own `source_id`. +Sources with one `source_id` must agree on their Arrow schema and key columns. +Differences raise `InconsistentSourceError` during capture, binding, loading and +execution through `job.run()` or a node's `run()`. ITL-1506 tracks support for +distinct readings of one dataset in distinct named slots. Give each reading its +own `source_id` for now. An in-memory source with key columns and no `source_id` can instead hash its rows in key order: pass `hash_in_key_order=True` (`ArrowTableSource`, `DictSource`, `DataFrameSource`, diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 8d4442227..ccf7238f4 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -361,8 +361,7 @@ def run_job_node( ) -> None: """Run a job node as its ``run()`` does (developer, November 13, 2026; ITL-1095). - Sources it reads that share a source id must agree, as ``job.run()`` requires - (``require_consistent_sources``, before and after the check for new data). Every + Source registrations are checked as in ``job.run()`` before reading new data. Every source feeding the node is first checked for new data (``check_sources``, ITL-1102). Nothing runs when the node then holds a current run (``holds_current_run``). Otherwise a node that depends on job nodes runs with them @@ -388,17 +387,13 @@ def run_job_node( from orcapod.pipeline.run_summary import warn_row_failures from orcapod.pipeline.source_consistency import require_consistent_sources + require_consistent_sources([(f"node {node.label!r}", node)]) # A source read under two restrictions, or a caching operator over a restricted # source, is refused before any source is checked and before anything is # computed or written (ITL-1218). refuse_restriction_conflicts([node]) - # Sources sharing a source id must agree, as job.run() requires (ITL-1469); - # checked again after the check for new data, which can replace held rows. - uses = [(f"node {node.label!r}", node)] - require_consistent_sources(uses) # Every source feeding the run first takes in any new data (ITL-1102). unchecked = check_sources([node]) - require_consistent_sources(uses) if node.holds_current_run(load_only=load_only): return if depends_on_job_nodes(node): @@ -4300,9 +4295,8 @@ def run(self, *, load_only: bool = False) -> StreamView: compute (loaded without a function pod, or a placeholder pod) and ``load_only`` is false; or if its input is unavailable (``CACHE_ONLY``): read its stored rows with ``as_source()``. - InconsistentSourceError: If sources it reads share a source ID and - disagree (schema, fixed rows or key columns), as ``job.run()`` - refuses; nothing has run. + InconsistentSourceError: If distinct source objects share a content + hash, or sources with one ID differ in schema or key columns. """ from orcapod.pipeline.serialization import LoadStatus diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index c9a999727..2e5c369f6 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1881,9 +1881,8 @@ def run(self, *, load_only: bool = False) -> StreamView: ``load_only`` is false. ValueError: If this node or one it depends on caches (``LOG`` or ``REPLAY``) over a restricted source (ITL-1218); nothing has run. - InconsistentSourceError: If sources it reads share a source ID and - disagree (schema, fixed rows or key columns), as ``job.run()`` - refuses; nothing has run. + InconsistentSourceError: If distinct source objects share a content + hash, or sources with one ID differ in schema or key columns. """ from orcapod.pipeline.node_run import ( check_sources, @@ -1897,17 +1896,13 @@ def run(self, *, load_only: bool = False) -> StreamView: if self._loaded and not load_only: raise self._cannot_compute_error() + require_consistent_sources([(f"node {self.label!r}", self)]) # A source read under two restrictions, or a caching operator over a restricted # source, is refused before any source is checked and before anything is # computed or written (ITL-1218). refuse_restriction_conflicts([self]) - # Sources sharing a source id must agree, as job.run() requires (ITL-1469); - # checked again after the check for new data, which can replace held rows. - uses = [(f"node {self.label!r}", self)] - require_consistent_sources(uses) # Every source feeding the run first takes in any new data (ITL-1102). unchecked = check_sources([self]) - require_consistent_sources(uses) if self.holds_current_run(load_only=load_only): return self._run_view(computed=False) if depends_on_job_nodes(self): diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index 62f65b9e5..f05485472 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -4,7 +4,7 @@ from collections.abc import Collection from typing import TYPE_CHECKING, Any, ClassVar -from orcapod.core.sources.base import FixedTableSource +from orcapod.core.sources.base import RootSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.stream_builder import SourceStreamBuilder from orcapod.core.sources.stream_builder import ( @@ -19,7 +19,7 @@ logger = logging.getLogger(__name__) -class ArrowTableSource(FixedTableSource): +class ArrowTableSource(RootSource): """A source backed by an in-memory PyArrow Table. Uses ``SourceStreamBuilder`` to strip system columns, add per-row diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 30db3ea4e..881256c2e 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -4,8 +4,6 @@ from collections.abc import Callable from typing import TYPE_CHECKING, Any, ClassVar, TypeVar -from typing_extensions import override - from orcapod import contexts from orcapod.config import OrcapodConfig from orcapod.core.streams.base import ( @@ -418,29 +416,6 @@ def _schema_identity(self) -> tuple[ContentHash, ContentHash]: """ return arrow_schema_identity(*self.arrow_schemas, self.data_context) - @property - def _holds_fixed_rows(self) -> bool: - """Whether this source holds its table, so its rows can be compared. - - A source that holds its table gives its rows without a read or a poll. Its - values are not assumed constant: the table can share memory with a caller's - frame or array whose values change, so they are compared again at each check. - Answered without reading or digesting any row. A wrapper opts in if what it - wraps holds its table. - """ - return False - - @property - def _fixed_content(self) -> bytes | None: - """Digest of held rows for collision checks, or None for a live read. - - Tags, data and record ids (``_digest_fixed_rows``), computed on each read. - The digest is separate from source identity. - """ - if not self._holds_fixed_rows: - return None - return self._digest_fixed_rows() - @property def _resolved_key_columns(self) -> tuple[str, ...] | None: """The resolved key columns that name this source's rows, in key order. @@ -452,55 +427,6 @@ def _resolved_key_columns(self) -> tuple[str, ...] | None: """ return self._key_columns - @property - def _fixed_row_multiset(self) -> bytes | None: - """Digest of the held rows as a multiset of tags and data, or None for a live read. - - Used to compare two fixed readings of one dataset whose key columns differ - (ITL-1506): record ids, which follow the key columns, are left out, and so is - row order. Every row counts as often as it occurs. Rows are put in the - canonical row order of an identity table - (``arrow_utils.canonical_identity_row_order``) and digested under the Arrow - float rule, so ``-0.0`` equals ``0.0`` and every NaN equals every other. It is - ``None`` exactly when ``_holds_fixed_rows`` is false; computed on each read. - """ - if not self._holds_fixed_rows: - return None - return self._digest_fixed_row_multiset() - - def _digest_fixed_row_multiset(self) -> bytes: - """Digest the rows as a multiset of tags and data (``_fixed_row_multiset``).""" - from orcapod.hashing.starfix_digest import digest_orcapod_table - from orcapod.utils.arrow_utils import canonical_identity_row_order - - table = canonical_identity_row_order( - self.as_table(), tuple(self.keys()[0]), self.data_context.arrow_hasher - ) - return digest_orcapod_table( - table, - include_metadata=False, - ordered_columns=False, - ordered_struct_fields=False, - ) - - def _digest_fixed_rows(self) -> bytes: - """Compare tags, data and record IDs under the normal Arrow float rule.""" - from orcapod.hashing.starfix_digest import digest_orcapod_table - from orcapod.utils.arrow_utils import key_row_order - - table = self.as_table(columns={"system_tags": True}) - if self._key_columns and table.num_rows > 1: - table = key_row_order(table, self._key_columns) - # The schemas are checked separately, including logical type identifiers. - # Compare encoded values directly without converting nested or extension - # columns to Python objects. Starfix reads their Arrow storage. - return digest_orcapod_table( - table, - include_metadata=False, - ordered_columns=False, - ordered_struct_fields=False, - ) - def identity_structure(self) -> Any: """Identity from the ``source_id``, the Arrow schema and the key columns. @@ -722,18 +648,3 @@ def cached( cache_path_prefix=cache_path_prefix, **kwargs, ) - - -class FixedTableSource(RootSource): - """A root that holds an Arrow table for its entire lifetime. - - Its digests are never held: the table can share memory with the caller's data (a - pandas frame, a NumPy array), which the caller can still change. A consistency - check digests it at most once per check. - """ - - @property - @override - def _holds_fixed_rows(self) -> bool: - """Always: the table is held for the source's lifetime.""" - return True diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 27855a5d3..6c65bf64d 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -7,7 +7,7 @@ import polars as pl import pyarrow as pa -from orcapod.core.sources.base import FixedTableSource +from orcapod.core.sources.base import RootSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.stream_builder import SourceStreamBuilder from orcapod.core.sources.stream_builder import ( @@ -22,7 +22,7 @@ logger = logging.getLogger(__name__) -class DataFrameSource(FixedTableSource): +class DataFrameSource(RootSource): """A source backed by a Polars DataFrame (or any Polars-compatible data). The DataFrame is converted to an Arrow table and enriched by diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 20a16be50..1c4a57228 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -305,15 +305,6 @@ def __init__( # Identity # ------------------------------------------------------------------------- - @property - @override - def _holds_fixed_rows(self) -> bool: - """Rows are fixed only when the origin itself holds fixed rows. - - The digests are not held: a check for new data can refresh the rows. - """ - return isinstance(self._origin, RootSource) and self._origin._holds_fixed_rows - def identity_structure(self) -> Any: """Return what the content hash is built from. diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index 05f369e03..fdf7c1f34 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -5,7 +5,7 @@ import pyarrow as pa -from orcapod.core.sources.base import FixedTableSource +from orcapod.core.sources.base import RootSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.stream_builder import SourceStreamBuilder from orcapod.core.sources.stream_builder import ( @@ -17,7 +17,7 @@ from orcapod.utils.tensor_conversions import warn_source_tensor_conversions -class DictSource(FixedTableSource): +class DictSource(RootSource): """A source backed by a collection of Python dictionaries. Each dict becomes one (tag, data) pair in the stream. The dicts are diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index 1c1eb12a4..f18da3433 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -3,7 +3,7 @@ from collections.abc import Callable, Collection from typing import TYPE_CHECKING, Any, ClassVar -from orcapod.core.sources.base import FixedTableSource +from orcapod.core.sources.base import RootSource from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, @@ -17,7 +17,7 @@ pass -class ListSource(FixedTableSource): +class ListSource(RootSource): """A source backed by a Python list. Each element in the list becomes one (tag, data) pair. The element is diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 373cc91bf..271c07ecc 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -95,30 +95,6 @@ def delegate(self) -> SourceProtocol | None: """The bound live source, or ``None`` if no source has been bound.""" return self._delegate - @property - @override - def _holds_fixed_rows(self) -> bool: - """Whether the bound source holds fixed rows.""" - return ( - isinstance(self._delegate, RootSource) and self._delegate._holds_fixed_rows - ) - - @property - @override - def _fixed_content(self) -> bytes | None: - """The bound source's fixed rows, if it holds them.""" - if isinstance(self._delegate, RootSource): - return self._delegate._fixed_content - return None - - @property - @override - def _fixed_row_multiset(self) -> bytes | None: - """The bound source's multiset digest, if it holds fixed rows.""" - if isinstance(self._delegate, RootSource): - return self._delegate._fixed_row_multiset - return None - @property @override def _resolved_key_columns(self) -> tuple[str, ...] | None: diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 8d534e5a3..2a27dace7 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -550,9 +550,10 @@ def where( built beforehand is accepted as it is. The source's ``limit`` is its own and is not changed. - This source is not changed. ``where`` is a copy of the source with the - restriction applied to the copy in place; a later version offers those two - steps (``copy()`` and ``apply_restriction``) on their own. + Each call to ``where()`` makes a new source object. Call it once and reuse + the resulting object when the same restriction feeds multiple parts of a + pipeline. A later version offers ``copy()`` and ``apply_restriction`` as + separate steps. Args: mapping: Column name to value, or a ``Condition``. Positional only, so diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index e19317ed5..2448cd586 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -557,18 +557,15 @@ class SourceSpecMismatchError(InputValidationError, ValueError): class InconsistentSourceError(ValueError): - """Raised when two sources in a pipeline disagree at a shared address. - - Sources sharing a ``source_id`` must have the same schema. If both hold - their rows in memory, their rows must also agree: tags, data and record IDs - with equal key columns, tags and data as a multiset with different ones. - ITL-1531 tracks content checks for sources that read their rows later. - Sources sharing a ``source_id`` and schema with different key columns are - refused in any slots while the design is pending (ITL-1506). Two different - schemas competing for one input slot also raise this error. - - Resolution: assign distinct ``source_id`` values to the conflicting sources - so each slot has a unique, stable identity. + """Raised when sources conflict in a pipeline or job. + + Each content hash can be registered by one source object. Sources + sharing a ``source_id`` must have the same schema and key columns + (ITL-1506). Two different schemas competing for one input slot also + raise this error. + + Build a source once and reuse that object, or give each source its + own ``source_id``. """ diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 60420a164..5cf61fad6 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -360,8 +360,8 @@ def _record_invocation(self, invocation: PodInvocation) -> None: # streams lead to it: every source this invocation reads is checked with # every source the pipeline's streams read now (nothing is remembered: a # slot rebound since the last invocation changes what they read). - require_one_restriction([*self._held_streams(), *inputs]) require_consistent_sources(self._source_uses(invocation)) + require_one_restriction([*self._held_streams(), *inputs]) self._remember_invocation(key, invocation) self._hash_graph.add_node(key) for upstream, upstream_hash in upstreams: @@ -537,8 +537,8 @@ def compile(self) -> None: # Checked again here, from what the streams read now: a slot rebound after # the last invocation would otherwise connect a branch recorded over one # restriction to another (ITL-1218). - require_one_restriction(self._held_streams()) require_consistent_sources(self._source_uses()) + require_one_restriction(self._held_streams()) source_node_cls = self.source_node_class diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 371c1608e..0a7aaac3d 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -496,10 +496,9 @@ def bind( the job's own database again, at ``/_result`` (ITL-1408). Raises: - InconsistentSourceError: If two sources sharing a source ID have - different schemas, both hold fixed rows and those rows differ, or - they have different key columns (refused in any slots for now, - ITL-1506); the job is left as it was. + InconsistentSourceError: If distinct source objects share a content + hash, or sources with one ID differ in schema or key columns + (ITL-1506). The job is left as it was. SourceSpecMismatchError: If any source's columns differ from its slot's declared names, roles or types. ValueError: If a source key has no matching ``SourceJobNode`` slot, or an @@ -1337,11 +1336,10 @@ def _prepare_run( # --- Build hash-keyed OrcaDAG for topological ordering + exclusion --- # A caller can change a slot or proxy directly after binding the job. - source_uses = [ + require_consistent_sources( (f"node {node.label!r}", node) for node in self._persistent_node_map.values() - ] - require_consistent_sources(source_uses) + ) hash_dag: OrcaDAG[str] = OrcaDAG() for u, v in self._graph_edges: hash_dag.add_edge(u, v) @@ -1431,8 +1429,6 @@ def _prepare_run( # Every source first takes in any new data, moving its modified time, before # the state rule judges any node (ITL-1102). unchecked = check_sources(exec_dag.nodes()) - # Refresh can replace cached derived rows after their initial comparison. - require_consistent_sources(source_uses) # A restricted source under an aggregation is allowed, and said (ITL-1218). warn_restricted_aggregation(exec_dag) # The state rule (ITL-1095): a node that holds a current run is not run again. @@ -1803,9 +1799,9 @@ def load( results. Raises: - InconsistentSourceError: If reconstructed sources sharing a source ID - have different schemas, fixed rows that differ, or different key - columns (ITL-1506). + InconsistentSourceError: If distinct reconstructed source objects + share a content hash, or sources with one ID differ in schema + or key columns (ITL-1506). ValueError: If the file's format version is not the one this Orcapod writes (an earlier format is refused, never migrated), or if it was saved before the database key was renamed (``bindings.store`` @@ -1864,6 +1860,7 @@ def load( if isinstance(node, SourceNodeBase) } sources: dict[str, cp.StreamProtocol] = {} + sources_by_config: dict[str, cp.StreamProtocol | None] = {} for spec_name, src_config in ( data.get("bindings", {}).get("sources", {}).items() ): @@ -1888,7 +1885,13 @@ def load( except ValueError as exc: raise ValueError(f"{path}: source {spec_name!r}: {exc}") from exc try: - source = resolve_source_from_config(src_config) + # Slots written with the same complete config share one rebuild. + config_key = _json.dumps(src_config, sort_keys=True) + if config_key not in sources_by_config: + sources_by_config[config_key] = resolve_source_from_config( + src_config + ) + source = sources_by_config[config_key] if source is not None: # A rebuilt source its slot refuses (a file whose column types # changed) is one that could not be rebuilt (ITL-1112). diff --git a/src/orcapod/pipeline/loaded_side_effects.py b/src/orcapod/pipeline/loaded_side_effects.py index b4fa3b0c9..d77155a30 100644 --- a/src/orcapod/pipeline/loaded_side_effects.py +++ b/src/orcapod/pipeline/loaded_side_effects.py @@ -336,9 +336,8 @@ def run(self, *, load_only: bool = False) -> StreamView: Raises: RuntimeError: If ``load_only`` is false; nothing runs then. - InconsistentSourceError: If sources it reads share a source ID and - disagree (schema, fixed rows or key columns), as ``job.run()`` - refuses; nothing has run. + InconsistentSourceError: If distinct source objects share a content + hash, or sources with one ID differ in schema or key columns. """ import sys diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index 5e6947e66..1dd1aabb7 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -1,4 +1,4 @@ -"""Validation of sources sharing a canonical source ID within one graph.""" +"""Validate source object registrations within one graph.""" from __future__ import annotations @@ -67,11 +67,13 @@ def root_source_uses( else: # Loaded nodes can have inputs that could not be reconstructed. upstreams = cast("tuple[StreamProtocol | None, ...]", stream.upstreams) - pending.extend( - (location, upstream, recorded) - for upstream in reversed(upstreams) - if upstream is not None - ) + for index in reversed(range(len(upstreams))): + upstream = upstreams[index] + if upstream is not None: + upstream_location = location + if len(upstreams) > 1: + upstream_location += f", {stream.label!r} input {index + 1}" + pending.append((upstream_location, upstream, recorded)) def _comparison_schema(source: RootSource) -> tuple[ContentHash, ContentHash]: @@ -87,147 +89,33 @@ def _comparison_schema(source: RootSource) -> tuple[ContentHash, ContentHash]: return arrow_schema_identity(*schemas, source.data_context) -def _key_columns_conflict( - source_id: str, group: list[tuple[str, RootSource]] -) -> str | None: - """Describe sources of one id and schema whose key columns differ, if any. - - Such sources are distinct readings of one dataset. They are refused everywhere for - now (capture, bind, load, run), whatever slots they would take. ITL-1506 tracks - the design for different key columns under one source id. - Call only after the schemas and fixed rows of ``group`` were found to agree. Only - the sources whose key columns are known are compared: one whose key columns are - unknown (an unbound proxy) neither causes nor suppresses a refusal. The message - says they differ only in key columns when every source of the group holds fixed - rows (all compared and equal); any other source, read later or unbound, means - its rows were not compared, and the message says so. - - Args: - source_id: The shared source id. - group: Every distinct source with that id, with where it is used. - - Returns: - The error message, or ``None`` when the known key columns agree. - """ - known = [ - (where, s) - for where, s in group - if s._resolved_key_columns is not None # pyright: ignore[reportPrivateUsage] # source consistency - ] - if len({source._resolved_key_columns for _, source in known}) < 2: # pyright: ignore[reportPrivateUsage] # source consistency - return None - where = ", ".join(location for location, _ in known) - remedy = ( - "A later version will allow distinct readings of one dataset in distinct " - "named slots (ITL-1506). For now, give each source its own name with " - "source_id=... when it is built." - ) - # "Only" claims the rows are equal: true only when every source of the group, - # known key columns or not, holds rows that ``_differing_fixed_rows`` compared. - if all(source._holds_fixed_rows for _, source in group): # pyright: ignore[reportPrivateUsage] # source consistency - return ( - f"Sources with source id {source_id!r} in {where} share one schema and " - "the same rows, and differ only in key columns (record_id_columns), so " - f"this is refused for now. {remedy}" - ) - return ( - f"Sources with source id {source_id!r} in {where} share one schema and have " - "different key columns (record_id_columns). The rows of a source read later " - f"are not compared. This is refused for now. {remedy}" - ) - - -def _underlying(source: RootSource) -> RootSource: - """The source whose rows ``source`` presents: a bound proxy's delegate, unwrapped. - - Args: - source: A source in a consistency check. - - Returns: - The innermost bound root source behind any proxies, or ``source`` itself. - """ - from orcapod.core.sources.base import RootSource - from orcapod.core.sources.source_proxy import SourceProxy - - while isinstance(source, SourceProxy) and isinstance(source.delegate, RootSource): - source = source.delegate - return source - - -def _differing_fixed_rows( - group: list[tuple[str, RootSource]], -) -> tuple[str, str] | None: - """Find two fixed sources of one id and schema that hold different rows. - - A source id names a dataset; key columns only name its rows and belong to the - reading. Every pair of fixed sources is compared by the rule for that pair, so the - answer never depends on the order of ``group``: - - - equal key columns (or unknown ones): tags, data and record ids - (``_fixed_content``), so positional row order counts as it always has; - - different key columns: the record ids necessarily differ, so the rows are - compared as a multiset of tags and data (``_fixed_row_multiset``): every - occurrence counts, order does not, and floats compare by the Arrow value rule - (``-0.0`` equals ``0.0``, NaN equals NaN). - - Only the digests a pair needs are computed, each at most once per check for each - underlying source: a bound proxy is digested as the source it stands in for - (``_underlying``). Nothing is held across checks: an in-memory table can share - memory with the caller's data, which the caller can change between checks. - - Args: - group: Every distinct source with that id, with where it is used. - - Returns: - The locations of the first such pair, or ``None`` when all fixed rows agree. - """ - fixed = [ - (where, s) - for where, s in group - if s._holds_fixed_rows # pyright: ignore[reportPrivateUsage] # source consistency - ] - exact: dict[int, bytes | None] = {} - multisets: dict[int, bytes | None] = {} - - def digest(source: RootSource, *, record_ids: bool) -> bytes | None: - source = _underlying(source) - held = exact if record_ids else multisets - if id(source) not in held: - held[id(source)] = ( - source._fixed_content if record_ids else source._fixed_row_multiset # pyright: ignore[reportPrivateUsage] # source consistency - ) - return held[id(source)] - - for index, (first_location, first) in enumerate(fixed): - for location, source in fixed[index + 1 :]: - first_keys, keys = first._resolved_key_columns, source._resolved_key_columns # pyright: ignore[reportPrivateUsage] # source consistency - record_ids = first_keys is None or keys is None or first_keys == keys - if digest(first, record_ids=record_ids) != digest( - source, record_ids=record_ids - ): - return first_location, location - return None - - def require_consistent_sources( uses: Iterable[SourceUse], rebinding: Rebinding = (), ) -> None: - """Refuse schema differences and conflicting fixed rows at a shared address. + """Require one object per content hash and one schema and key per source ID. - Compare distinct objects only. A live source has no fixed rows to compare, - but does not prevent comparing two fixed sources that share its address. - Every pair of fixed sources is compared by ``_differing_fixed_rows`` (record ids - count only when their key columns are equal), so different rows are reported whatever - the order of the uses. Sources whose schemas and fixed rows agree but whose known - key columns differ are then refused too (``_key_columns_conflict``, ITL-1506). - For a bind, use the prospective sources alongside every unchanged binding. + Args: + uses: The graph's streams and where they are used. + rebinding: Prospective slot replacements to check before changing a binding. Raises: - InconsistentSourceError: Naming the sources and remedy for a conflict. + InconsistentSourceError: Naming both locations and how to resolve the conflict. """ + by_hash: dict[str, tuple[str, RootSource]] = {} by_id: dict[str, list[tuple[str, RootSource]]] = {} for location, source in root_source_uses(uses, rebinding): + content_hash = source.content_hash().to_string() + first_location, first = by_hash.setdefault(content_hash, (location, source)) + if first is not source: + reuse = "Build the source once and reuse the object" + if first.condition.equalities or source.condition.equalities: + reuse = "Call where() once and reuse the resulting source object" + raise InconsistentSourceError( + f"Source {source.source_id!r} has distinct source objects with one " + f"content hash in {first_location} and {location}. {reuse}, " + "or give each source its own source_id." + ) by_id.setdefault(source.source_id, []).append((location, source)) for source_id, group in by_id.items(): @@ -242,13 +130,18 @@ def require_consistent_sources( f"and {location}. Give the sources different source_id values." ) - differing = _differing_fixed_rows(group) - if differing is not None: - raise InconsistentSourceError( - f"Source {source_id!r} has different rows in {differing[0]} " - f"and {differing[1]}. Give the sources different source_id values." - ) - - message = _key_columns_conflict(source_id, group) - if message is not None: - raise InconsistentSourceError(message) + known_keys = [ + (location, keys) + for location, source in group + if (keys := source._resolved_key_columns) is not None # pyright: ignore[reportPrivateUsage] # source consistency + ] + if known_keys: + first_location, first_keys = known_keys[0] + for location, keys in known_keys[1:]: + if keys != first_keys: + raise InconsistentSourceError( + f"Source {source_id!r} has different key columns " + f"(record_id_columns) in {first_location} and {location}. " + "Give the sources different source_id values. ITL-1506 " + "tracks distinct readings in distinct named slots." + ) diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 374761105..422a45fd2 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -1434,9 +1434,8 @@ def run(self, *, load_only: bool = False) -> StreamView: Raises: SideEffectLogDataContextError: As for ``execute``. OrcapodDatabaseWriteError: If committing the invocation log fails. - InconsistentSourceError: If sources it reads share a source ID and - disagree (schema, fixed rows or key columns), as ``job.run()`` - refuses; nothing has run. + InconsistentSourceError: If distinct source objects share a content + hash, or sources with one ID differ in schema or key columns. """ import sys diff --git a/tests/test_core/data_tags/test_derived_source.py b/tests/test_core/data_tags/test_derived_source.py index 76a85fd7c..2ba5d0894 100644 --- a/tests/test_core/data_tags/test_derived_source.py +++ b/tests/test_core/data_tags/test_derived_source.py @@ -99,9 +99,10 @@ def _operator_job( ) -> PipelineJob: """A ``LOG`` join of the function node's output with itself filtered by ``unit``.""" job = PipelineJob(name=JOB, database=store) + source = _source() with job: - doubled = double.pod(_source(), label="double") - _ = Join()(doubled, _source().select_data_columns(["unit"]), label="joined") + doubled = double.pod(source, label="double") + _ = Join()(doubled, source.select_data_columns(["unit"]), label="joined") job.nodes["joined"].attach_databases( pipeline_database=store.at(JOB), cache_mode=CacheMode.LOG ) diff --git a/tests/test_core/sources/test_provisional_sources.py b/tests/test_core/sources/test_provisional_sources.py index 84c1bfc28..8c67b7eb0 100644 --- a/tests/test_core/sources/test_provisional_sources.py +++ b/tests/test_core/sources/test_provisional_sources.py @@ -227,9 +227,10 @@ def _ran_job() -> Any: from orcapod.operators import SelectDataColumns job = PipelineJob(name="derived", database=InMemoryArrowDatabase()) + origin = _origin() with job: - _total.pod(_origin(), label="total") - SelectDataColumns(["age", "weight"])(_origin(), label="picked") + _total.pod(origin, label="total") + SelectDataColumns(["age", "weight"])(origin, label="picked") job.run() return job diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index b69edfaf8..71d1ba6bf 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -23,7 +23,7 @@ from orcapod import PipelineJob, function_pod from orcapod.databases import DeltaTableDatabase -from orcapod.errors import RestrictedAggregationWarning +from orcapod.errors import InconsistentSourceError, RestrictedAggregationWarning from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.restrictions import restrictions_in_force from orcapod.core.sources.spiraldb_table_source import _checked_conditions @@ -1098,7 +1098,7 @@ def second(channel: int | None) -> int | None: events = _source(source_id="events", tag_only_columns=True) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: first.pod(events.where(subject_id="m1"), label="first") second.pod(events.where(subject_id="m2"), label="second") @@ -1120,7 +1120,7 @@ def second(amplitude: float | None) -> float | None: m1 = events.where(subject_id="m1").select_data_columns(["amplitude"]) m2 = events.where(subject_id="m2").select_data_columns(["amplitude"]) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: first.pod(m1, label="first") second.pod(m2, label="second") @@ -1152,7 +1152,7 @@ def first(amplitude: float | None) -> float | None: events = _source(source_id="events", tag_only_columns=True) outside = events.where(**prebuilt).select_data_columns(["amplitude"]) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: if prebuilt_first: first.pod(outside, label="first") @@ -1166,22 +1166,22 @@ def first(amplitude: float | None) -> float | None: def test_a_stream_with_the_hash_of_an_equal_captured_output_is_accepted( self, project, tmp_path, prebuilt_first ): - """The same restriction, its conditions in another order, is one stream.""" + """Prebuilt and captured projections can reuse one restricted source.""" @function_pod(output_keys="a") def first(amplitude: float | None) -> float | None: """Return ``amplitude``.""" return amplitude - events = _source(source_id="events", tag_only_columns=True) - outside = events.where(flag=True, subject_id="m1").select_data_columns( - ["amplitude"] + events = _source(source_id="events", tag_only_columns=True).where( + flag=True, subject_id="m1" ) + outside = events.select_data_columns(["amplitude"]) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) with job: if prebuilt_first: first.pod(outside, label="first") - events.where(subject_id="m1", flag=True).select_data_columns(["amplitude"]) + events.select_data_columns(["amplitude"]) if not prebuilt_first: first.pod(outside, label="first") @@ -1222,7 +1222,7 @@ def test_two_inputs_of_one_invocation_are_checked(self, project): """One operator over two differently restricted sources of one table.""" events = _source(source_id="events", tag_only_columns=True) job = PipelineJob(name="two") - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: events.where(subject_id="m1").semi_join( events.where(subject_id="m2"), label="both" @@ -1232,7 +1232,7 @@ def test_two_inputs_of_one_invocation_are_checked(self, project): def test_one_restriction_twice_in_one_job_is_accepted( self, project, tmp_path, restrict ): - """Two source objects with the same restriction (or none) are one source.""" + """Two branches can reuse one source with or without a restriction.""" @function_pod(output_keys="a") def first(amplitude: float | None) -> float | None: @@ -1244,16 +1244,13 @@ def second(channel: int | None) -> int | None: """Return ``channel``.""" return channel - def events(*conditions: tuple[str, object]) -> SpiralDBTableSource: - """Return the events source, with ``conditions`` in the order given.""" - source = _source(source_id="events", tag_only_columns=True) - return source.where(dict(conditions)) if restrict else source - + events = _source(source_id="events", tag_only_columns=True) + if restrict: + events = events.where(subject_id="m1", flag=True) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) with job: - # The same conditions given in another order are the same restriction. - first.pod(events(("subject_id", "m1"), ("flag", True)), label="first") - second.pod(events(("flag", True), ("subject_id", "m1")), label="second") + first.pod(events, label="first") + second.pod(events, label="second") job.run() expected = [3] if restrict else [1, 2, 3, 4, 5] @@ -1293,7 +1290,7 @@ def second(channel: int | None) -> int | None: return channel job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: first.pod(_source(source_id="events", limit=1), label="first") second.pod(_source(source_id="events", limit=2), label="second") @@ -1489,11 +1486,10 @@ def test_a_saved_config_of_the_earlier_form_loads(self, project): [(0.0, -0.0), (-0.0, 0.0), (math.nan, math.nan)], ids=["0.0 then -0.0", "-0.0 then 0.0", "NaN twice"], ) - def test_equal_float_conditions_are_one_restriction_in_a_pipeline( + def test_equal_float_conditions_still_require_one_source_object( self, project, tmp_path, values ): - """``0.0`` and ``-0.0``, or NaN twice, are one restriction (as Polars matches - them), so one table read with both in one pipeline is accepted.""" + """Equal conditions can belong to distinct source objects.""" @function_pod(output_keys="a") def first(amplitude: float | None) -> float | None: @@ -1506,10 +1502,16 @@ def second(channel: int | None) -> int | None: return channel events = _source(source_id="events", tag_only_columns=True) + first_read = events.where(amplitude=values[0]) + second_read = events.where(amplitude=values[1]) + assert first_read.condition == second_read.condition + assert first_read.content_hash() == second_read.content_hash() job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) with job: - first.pod(events.where(amplitude=values[0]), label="first") - second.pod(events.where(amplitude=values[1]), label="second") + first.pod(first_read, label="first") + with pytest.raises(InconsistentSourceError, match=r"Call where\(\) once"): + second.pod(second_read, label="second") + second.pod(first_read, label="second") summary = job.run() @@ -2048,7 +2050,7 @@ def test_a_proxy_and_a_source_restricted_two_ways_are_refused_at_capture( other = _events().where(subject_id="m2") first, second = (proxy, other) if order == "proxy first" else (other, proxy) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: first.select_data_columns(["amplitude"], label="a") second.select_data_columns(["channel"], label="b") @@ -2197,7 +2199,7 @@ def keep(amplitude: float | None) -> float | None: return amplitude job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: chains[first_chain](_events().where(subject_id="m1")) chains[second_chain](second()) @@ -2222,7 +2224,7 @@ def test_chains_built_before_the_job_over_two_restrictions_are_refused( m2 = built[chains[1]](_events().where(subject_id="m2")) first, second = (m1, m2) if order == "m1 first" else (m2, m1) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: first.semi_join(second, label="both") @@ -2233,9 +2235,10 @@ def test_one_restriction_through_two_chains_is_accepted( chains = self._chains() names = ["select", "drop"] if order == "select first" else ["drop", "select"] job = PipelineJob(name="one", database=DeltaTableDatabase(tmp_path / "s")) + events = _events().where(flag=True, subject_id="m1") with job: for name in names: - chains[name](_events().where(flag=True, subject_id="m1")) + chains[name](events) summary = job.run() assert summary.conditions == { "events": Condition.of(subject_id="m1", flag=True) @@ -2269,7 +2272,7 @@ def test_a_slot_rebound_between_invocations_is_refused_at_the_next( "drop": lambda s: s.drop_data_columns(["note"]), }[step] job = PipelineJob(name="live", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: MapData({"channel": "lane"})(slot) slot.bound_source = _events().where(subject_id="m2") @@ -2281,7 +2284,7 @@ def test_a_slot_rebound_after_the_last_invocation_is_refused_at_compile( m1 = _events().where(subject_id="m1") slot = self._slot(m1) job = PipelineJob(name="live", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: MapData({"channel": "lane"})(slot) m1.select_data_columns(["amplitude"]) @@ -2295,8 +2298,9 @@ def test_a_slot_rebound_to_an_equal_restriction_is_accepted( job = PipelineJob(name="live", database=DeltaTableDatabase(tmp_path / "s")) with job: MapData({"channel": "lane"})(slot) - slot.bound_source = _events().where(subject_id="m1") - m1.select_data_columns(["amplitude"]) + replacement = _events().where(subject_id="m1") + slot.bound_source = replacement + replacement.select_data_columns(["amplitude"]) assert job.run().conditions == {"events": Condition.of(subject_id="m1")} @@ -2356,7 +2360,9 @@ def test_a_bind_reading_a_source_two_ways_is_refused_before_anything_changes( other_db = DeltaTableDatabase(tmp_path / "other") for _ in range(2): - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): job.bind(sources={"events": stream}, database=other_db) assert job.database is before[0] assert slot.bound_source is before[1] @@ -2371,7 +2377,7 @@ def test_a_slot_rebound_directly_is_refused_when_the_run_starts( ) scans = len(fake_spiral_sdk.scan_log) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): if run == "job.run": job.run() elif run == "job.run_async": @@ -2386,9 +2392,9 @@ def test_two_tables_restricted_once_each_are_accepted( ): """Two sources, one restriction each: no conflict; the run reads only the rows both restrictions keep.""" - job = self._job(tmp_path, self._others().where(subject_id="m2")) - events = _events().where(subject_id="m2") others = self._others().where(subject_id="m2") + job = self._job(tmp_path, others) + events = _events().where(subject_id="m2") stream = ( events.semi_join(others) if order == "events first" @@ -2449,12 +2455,12 @@ def _bound(job: PipelineJob) -> tuple[Any, Any]: return job.nodes["events"].bound_source, job.nodes["pick"].bound_source @pytest.mark.parametrize("order", ["events first", "pick first"]) - def test_equivalent_restrictions_for_both_slots_are_accepted( + def test_one_restricted_object_for_both_slots_is_accepted( self, project, tmp_path, order ): job = self._job(tmp_path) events = _events().where(subject_id="m2", flag=True) - pick = self._pick(_events().where(flag=True).where(subject_id="m2")) + pick = self._pick(events) sources: dict[str, Any] = {"events": events, "pick": pick} if order == "pick first": sources = dict(reversed(sources.items())) @@ -2495,7 +2501,9 @@ def test_conflicting_restrictions_are_refused_and_nothing_changes( other = DeltaTableDatabase(tmp_path / "other") for _ in range(2): - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): job.bind(sources=sources, database=other) after = (job.database, *self._bound(job)) assert all(a is b for a, b in zip(after, before, strict=True)) @@ -2509,17 +2517,17 @@ def test_one_slot_changed_away_from_the_other_is_refused( m2 = _events().where(subject_id="m2") new = m2 if slot == "events" else self._pick(m2) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): job.bind(sources={slot: new}) after = self._bound(job) assert after[0] is before[0] and after[1] is before[1] @pytest.mark.parametrize("slot", ["events", "pick"]) - def test_one_slot_changed_to_an_equal_restriction_is_accepted( + def test_one_slot_rebound_to_the_same_restricted_source_is_accepted( self, project, tmp_path, slot ): job = self._job(tmp_path) - m1 = _events().where(subject_id="m1") + m1, _ = self._bound(job) new = m1 if slot == "events" else self._pick(m1) job.bind(sources={slot: new}) diff --git a/tests/test_pipeline/fixtures/itl_1469_main_shared_source.json b/tests/test_pipeline/fixtures/itl_1469_main_shared_source.json new file mode 100644 index 000000000..fc87518a5 --- /dev/null +++ b/tests/test_pipeline/fixtures/itl_1469_main_shared_source.json @@ -0,0 +1,310 @@ +{ + "orcapod_pipeline_job_version": "0.4.0", + "orcapod_version": "0.4.0rc8.dev23+ga40296cb5.d20261127", + "run": { + "run_id": null, + "status": "pending", + "unbound_sources": [], + "node_job_content_hashes": { + "result_b": "semantic_v1:4883ca3500eca6bfde3021cbb145483ddb180085bd756be99cadf05d1c5fbb62", + "result_a": "semantic_v1:0e509b410605f3c4b76310e3269afe91275f3d25fd7670447644077c2e51f90a" + } + }, + "pipeline": { + "orcapod_pipeline_version": "0.4.0", + "orcapod_version": "0.4.0rc8.dev23+ga40296cb5.d20261127", + "pipeline": { + "name": [ + "legacy_shared_source" + ] + }, + "nodes": { + "semantic_v1:cd7048c441163cf717c33b17636f39387d979ca491e0669317d2ee4d877c4cb2": { + "node_type": "source", + "label": "a", + "content_hash": "semantic_v1:cd7048c441163cf717c33b17636f39387d979ca491e0669317d2ee4d877c4cb2", + "pipeline_hash": "semantic_v1:21bd6a19a207bf8c14f0f39eb30c670608059cb59de15f5a1bfcc275b23caa44", + "output_schema": { + "tag": { + "t1": "large_string", + "t2": "large_string" + }, + "data": { + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "node_uri": [ + "source_node", + "a" + ], + "data_context_key": "std:v1:default", + "config": null, + "source_config": { + "source_type": "node", + "name": "a", + "tag_schema": { + "t1": "large_string", + "t2": "large_string" + }, + "data_schema": { + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "reconstructable": true + }, + "semantic_v1:e7b8e6eead280bf3de166e930850b9844b6d29416c75c8a08b0567edc2fd5072": { + "node_type": "source", + "label": "b", + "content_hash": "semantic_v1:e7b8e6eead280bf3de166e930850b9844b6d29416c75c8a08b0567edc2fd5072", + "pipeline_hash": "semantic_v1:21bd6a19a207bf8c14f0f39eb30c670608059cb59de15f5a1bfcc275b23caa44", + "output_schema": { + "tag": { + "t1": "large_string", + "t2": "large_string" + }, + "data": { + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "node_uri": [ + "source_node", + "b" + ], + "data_context_key": "std:v1:default", + "config": null, + "source_config": { + "source_type": "node", + "name": "b", + "tag_schema": { + "t1": "large_string", + "t2": "large_string" + }, + "data_schema": { + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "reconstructable": true + }, + "semantic_v1:35ebef3ad6fab56bcb5a830e63f05c96cd8614c3617f54db65daa4334acd81c7": { + "node_type": "function", + "label": "result_b", + "content_hash": "semantic_v1:35ebef3ad6fab56bcb5a830e63f05c96cd8614c3617f54db65daa4334acd81c7", + "pipeline_hash": "semantic_v1:6ba45e187c1d9f4c70471a461d00119370d652c9a19f084c996fef929b1cb272", + "output_schema": { + "tag": { + "t1": "large_string", + "t2": "large_string" + }, + "data": { + "out": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "node_uri": [ + "subtract", + "8ec7327fae9a46cdb6c57a16d8634c52ca3a594e50df2da4e5833143ad63618b", + "v0", + "python.function.v1" + ], + "data_context_key": "std:v1:default", + "config": null, + "function_config": { + "uri": [ + "subtract", + "8ec7327fae9a46cdb6c57a16d8634c52ca3a594e50df2da4e5833143ad63618b", + "v0", + "python.function.v1" + ], + "data_function": { + "data_function_type_id": "python.function.v1", + "uri": [ + "subtract", + "8ec7327fae9a46cdb6c57a16d8634c52ca3a594e50df2da4e5833143ad63618b", + "v0", + "python.function.v1" + ], + "config": { + "module_path": "__main__", + "callable_name": "subtract", + "version": "v0.0", + "input_data_schema": { + "x": "", + "y": "" + }, + "output_data_schema": { + "out": "" + }, + "output_keys": [ + "out" + ] + } + }, + "pod_config": null, + "ctx_arg_name": null + }, + "table_scope": "pipeline_hash", + "fall_through_tags": [] + }, + "semantic_v1:ed95f485c964d7d06671c14d6a0741ef9108338e5276873a830a83bc2fde0fee": { + "node_type": "function", + "label": "result_a", + "content_hash": "semantic_v1:ed95f485c964d7d06671c14d6a0741ef9108338e5276873a830a83bc2fde0fee", + "pipeline_hash": "semantic_v1:b1d774df931735c498e6ae6c33f270acf67a3f5c547127cf726114e58c0a295f", + "output_schema": { + "tag": { + "t1": "large_string", + "t2": "large_string" + }, + "data": { + "out": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "node_uri": [ + "add", + "8ec7327fae9a46cdb6c57a16d8634c52ca3a594e50df2da4e5833143ad63618b", + "v0", + "python.function.v1" + ], + "data_context_key": "std:v1:default", + "config": null, + "function_config": { + "uri": [ + "add", + "8ec7327fae9a46cdb6c57a16d8634c52ca3a594e50df2da4e5833143ad63618b", + "v0", + "python.function.v1" + ], + "data_function": { + "data_function_type_id": "python.function.v1", + "uri": [ + "add", + "8ec7327fae9a46cdb6c57a16d8634c52ca3a594e50df2da4e5833143ad63618b", + "v0", + "python.function.v1" + ], + "config": { + "module_path": "__main__", + "callable_name": "add", + "version": "v0.0", + "input_data_schema": { + "x": "", + "y": "" + }, + "output_data_schema": { + "out": "" + }, + "output_keys": [ + "out" + ] + } + }, + "pod_config": null, + "ctx_arg_name": null + }, + "table_scope": "pipeline_hash", + "fall_through_tags": [] + } + }, + "edges": [ + [ + "semantic_v1:cd7048c441163cf717c33b17636f39387d979ca491e0669317d2ee4d877c4cb2", + "semantic_v1:ed95f485c964d7d06671c14d6a0741ef9108338e5276873a830a83bc2fde0fee" + ], + [ + "semantic_v1:e7b8e6eead280bf3de166e930850b9844b6d29416c75c8a08b0567edc2fd5072", + "semantic_v1:35ebef3ad6fab56bcb5a830e63f05c96cd8614c3617f54db65daa4334acd81c7" + ] + ] + }, + "bindings": { + "sources": { + "a": { + "source_type": "csv", + "file_path": "shared.csv", + "tag_columns": [ + "t1", + "t2" + ], + "tag_only_columns": true, + "system_tag_columns": [], + "record_id_columns": null, + "source_name": "shared", + "source_name_given": true, + "source_version": 1, + "full_source_id": "csv_v1:shared", + "content_hash": "semantic_v1:7db9f47918267ecf78b37089217b1e009ddb5093b9a52463c174c1e032a033f4", + "pipeline_hash": "semantic_v1:21bd6a19a207bf8c14f0f39eb30c670608059cb59de15f5a1bfcc275b23caa44", + "tag_schema": { + "t1": "large_string", + "t2": "large_string" + }, + "data_schema": { + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "b": { + "source_type": "csv", + "file_path": "shared.csv", + "tag_columns": [ + "t1", + "t2" + ], + "tag_only_columns": true, + "system_tag_columns": [], + "record_id_columns": null, + "source_name": "shared", + "source_name_given": true, + "source_version": 1, + "full_source_id": "csv_v1:shared", + "content_hash": "semantic_v1:7db9f47918267ecf78b37089217b1e009ddb5093b9a52463c174c1e032a033f4", + "pipeline_hash": "semantic_v1:21bd6a19a207bf8c14f0f39eb30c670608059cb59de15f5a1bfcc275b23caa44", + "tag_schema": { + "t1": "large_string", + "t2": "large_string" + }, + "data_schema": { + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + } + }, + "database": null, + "result_database": null + } +} \ No newline at end of file diff --git a/tests/test_pipeline/test_job_node_rows_after_run.py b/tests/test_pipeline/test_job_node_rows_after_run.py index 04ba3867a..77d0dc739 100644 --- a/tests/test_pipeline/test_job_node_rows_after_run.py +++ b/tests/test_pipeline/test_job_node_rows_after_run.py @@ -86,10 +86,11 @@ def _source(data: list[dict[str, int]]) -> DictSource: def _build(data: list[dict[str, int]], db: Any) -> PipelineJob: """Return a job over ``db``: ``rowwise``, ``downstream`` of it, and ``grouped``.""" job = PipelineJob(name="itl1093", database=db) + source = _source(data) with job: - rowwise = inc.pod(_source(data), label="rowwise") + rowwise = inc.pod(source, label="rowwise") dbl.pod(rowwise, label="downstream") - total.pod(_source(data).group_by("g"), label="grouped") + total.pod(source.group_by("g"), label="grouped") return job diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index cc3fc9dbc..6274798e1 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -1,14 +1,11 @@ -"""Sources sharing an address must agree on any rows held in memory (ITL-1469).""" +"""Source registration and source ID conflicts (ITL-1469).""" from __future__ import annotations import itertools import json -from collections import Counter from pathlib import Path -import struct -import numpy as np import pyarrow as pa import pytest @@ -19,7 +16,6 @@ from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import ( InconsistentSourceError, - InputValidationError, SourceSlotNameCollisionError, ) from orcapod.operators import SemiJoin @@ -72,16 +68,6 @@ def with_copy(x: int, tag_value: str) -> int: return x + len(tag_value) -@function_pod(output_keys="out") -def with_nested(x: int, y: list[float | None] | None) -> int: - return x + len(y or []) - - -@function_pod(output_keys="out") -def with_array(x: list[np.ndarray]) -> int: # pyright: ignore[reportMissingTypeArgument] # the logical ndarray type is under test - return len(x) - - @function_pod(output_keys="out") def with_string(x: str) -> int: return len(x) @@ -104,27 +90,24 @@ def _refused( ) -> None: with graph: pod(first, label="fa") - with pytest.raises(InconsistentSourceError, match="different rows") as error: + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: pod(second, label="fb") for part in (first.source_id, "fa", "fb", "source_id"): assert part in str(error.value) assert "fb" not in graph.nodes -@pytest.mark.parametrize("graph", [Pipeline, PipelineJob]) -def test_issue_reproduction(graph: type[Pipeline] | type[PipelineJob]) -> None: - first, second = _dict(1), _dict(100) - assert first.content_hash() == second.content_hash() - _refused(first, second, graph("conflicts")) - - @pytest.mark.parametrize("kind", ["arrow", "dict", "frame"]) @pytest.mark.parametrize("role", ROLES) @pytest.mark.parametrize("reverse", [False, True]) @pytest.mark.parametrize( "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] ) -def test_fixed_types(kind: str, role: str, reverse: bool, orchestrator: type) -> None: +def test_in_memory_sources_register_by_object( + kind: str, role: str, reverse: bool, orchestrator: type +) -> None: def source(row: int, arrangement: Arrangement) -> RootSource: table = make_table(P, arrangement, rows=[row]) tag_only = True if role == PLAIN else [P.mixed_plain] if role == MIXED else [] @@ -150,8 +133,9 @@ def source(row: int, arrangement: Arrangement) -> RootSource: first, second = arrangements[::-1] if reverse else arrangements with PipelineJob(database=InMemoryArrowDatabase()) as job: with_pair.pod(source(0, first), label="fa") - with_pair.pod(source(0, second), label="same") - with pytest.raises(InconsistentSourceError, match="different rows"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + with_pair.pod(source(0, second), label="same") + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with_pair.pod(source(1, second), label="conflict") assert set(job.function_pods) == {"fa"} job.run(orchestrator=orchestrator()) @@ -162,7 +146,7 @@ def source(row: int, arrangement: Arrangement) -> RootSource: @pytest.mark.parametrize( "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] ) -def test_fixed_list_source(reverse: bool, orchestrator: type) -> None: +def test_list_sources_register_by_object(reverse: bool, orchestrator: type) -> None: def source(x: int, tag_order: tuple[str, ...]) -> ListSource: tags = {"t1": "a", "t2": "b"} return ListSource( @@ -175,32 +159,17 @@ def source(x: int, tag_order: tuple[str, ...]) -> ListSource: tags = ("t2", "t1") if reverse else ("t1", "t2") with PipelineJob(database=InMemoryArrowDatabase()) as job: increment.pod(source(1, tags), label="fa") - increment.pod(source(1, tags[::-1]), label="same") - with pytest.raises(InconsistentSourceError, match="different rows"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + increment.pod(source(1, tags[::-1]), label="same") + with pytest.raises(InconsistentSourceError, match="distinct source objects"): increment.pod(source(100, tags[::-1]), label="conflict") assert set(job.function_pods) == {"fa"} job.run(orchestrator=orchestrator()) assert job.fa.as_table()["out"].to_pylist() == [2] -@pytest.mark.parametrize("column", ["t1", "t2", "x", "y"]) -def test_all_tag_and_data_columns_are_checked(column: str) -> None: - row = {"t1": 1, "t2": 2, "x": 3, "y": 4} - layout = {"t2": 2, "y": 4, "t1": 1, "x": 3} - left = DictSource( - [row], tag_columns=["t1", "t2"], tag_only_columns=True, source_id="shared" - ) - right = DictSource( - [{**layout, column: 100}], - tag_columns=["t2", "t1"], - tag_only_columns=True, - source_id="shared", - ) - _refused(left, right, Pipeline("conflicts"), both.pod) - - -def test_fixed_sources_can_be_wrapped() -> None: - left, right = _dict(1), _dict(100) +def test_proxy_and_delegate_register_as_distinct_objects() -> None: + right = _dict(100) wrapper = SourceProxy( right.source_id, right.content_hash().to_string(), @@ -208,21 +177,23 @@ def test_fixed_sources_can_be_wrapped() -> None: *right.output_schema(), ) wrapper.bind(right) - _refused(left, wrapper, PipelineJob()) + assert wrapper.content_hash() == right.content_hash() + _refused(right, wrapper, PipelineJob()) @pytest.mark.parametrize("value", [1, 100]) def test_bound_proxy_uses_its_live_arrow_schema_for_collision_checks( value: int, ) -> None: - def source(x: int) -> ArrowTableSource: + def source(x: int, keys: str | None = None) -> ArrowTableSource: return ArrowTableSource( pa.table({"x": pa.array([x], type=pa.int32())}), infer_nullable=True, source_id="shared", + record_id_columns=keys, ) - first, delegate = source(1), source(value) + first, delegate = source(1), source(value, "x") proxy = SourceProxy( delegate.source_id, delegate.content_hash().to_string(), @@ -233,16 +204,10 @@ def source(x: int) -> ArrowTableSource: assert proxy.arrow_schemas[1].field("x").type == pa.int64() proxy.bind(delegate) - if value != 1: - _refused(first, proxy, PipelineJob()) - return - - with PipelineJob(database=InMemoryArrowDatabase()) as job: - increment.pod(first, label="fa") - increment.pod(proxy, label="fb") - assert set(job.function_pods) == {"fa"} - job.run() - assert job.fa.as_table()["out"].to_pylist() == [2] + assert first.content_hash() != proxy.content_hash() + message = _capture(first, proxy, increment.pod) + assert "different key columns" in message + assert "different schemas" not in message def test_implicit_projection_conflict_names_both_function_steps() -> None: @@ -310,36 +275,6 @@ def test_same_source_id_with_different_key_columns_is_refused_at_build( both.pod(second, label="fb") -@pytest.mark.parametrize("keyed", [False, True]) -def test_row_order_counts_only_for_positional_ids(keyed: bool) -> None: - rows = [{"k": "a", "t": 10, "x": 1, "y": 3}, {"k": "b", "t": 20, "x": 2, "y": 4}] - - def source(data: list[dict[str, str | int]], tags: list[str]) -> DictSource: - return DictSource( - data, - tag_columns=tags, - tag_only_columns=True, - record_id_columns=["k", "t"] if keyed else None, - source_id="shared", - ) - - first = source(rows, ["k", "t"]) - second = source(list(reversed(rows)), ["t", "k"]) - if keyed: - with PipelineJob() as job: - both.pod(first, label="fa") - both.pod(second, label="fb") - assert set(job.function_pods) == {"fa"} - _refused( - first, - source([rows[1], {**rows[0], "y": 100}], ["t", "k"]), - Pipeline("conflicts"), - both.pod, - ) - else: - _refused(first, second, Pipeline("conflicts"), both.pod) - - @pytest.mark.parametrize("reverse", [False, True]) def test_bind_refuses_same_rows_with_different_keys(reverse: bool) -> None: # Refused in any slots for now: distinct slots for distinct readings of one @@ -352,7 +287,7 @@ def test_bind_refuses_same_rows_with_different_keys(reverse: bool) -> None: with pytest.raises(InconsistentSourceError) as error: job.bind(sources={"left": pair[0], "right": pair[1]}) message = str(error.value) - assert "differ only in key columns" in message + assert "different key columns" in message assert "ITL-1506" in message assert "slot 'left'" in message and "slot 'right'" in message assert dict(job.sources) == before @@ -363,7 +298,7 @@ def test_bind_refuses_different_rows_with_different_keys(reverse: bool) -> None: positional = _dict(1) other = DictSource([{"x": 100}], record_id_columns="x", source_id="shared") pair = (other, positional) if reverse else (positional, other) - with pytest.raises(InconsistentSourceError, match="different rows"): + with pytest.raises(InconsistentSourceError, match="different key columns"): _job().bind(sources={"left": pair[0], "right": pair[1]}) @@ -379,69 +314,9 @@ def test_bind_refuses_live_sources_with_different_keys( with pytest.raises(InconsistentSourceError) as error: _job().bind(sources={"left": pair[0], "right": pair[1]}) message = str(error.value) - assert "differ only" not in message - assert "not compared" in message assert "ITL-1506" in message -def test_nulls_nan_signed_zero_and_nested_values() -> None: - nan = struct.unpack("d", struct.pack("Q", 0x7FF8000000000001))[0] - alternate_nan = struct.unpack("d", struct.pack("Q", 0x7FF8000000000002))[0] - layout = pa.schema( - [ - pa.field("x", pa.int64(), nullable=False), - pa.field("y", pa.list_(pa.float64())), - ] - ) - - def source(values: list[float | None]) -> ArrowTableSource: - table = pa.Table.from_pylist([{"x": 1, "y": values}], schema=layout) - return ArrowTableSource(table, source_id="shared") - - first, second = source([nan, -0.0, None]), source([alternate_nan, 0.0, None]) - with PipelineJob() as job: - with_nested.pod(first, label="fa") - with_nested.pod(second, label="fb") - assert set(job.function_pods) == {"fa"} - _refused(first, source([nan, -0.0, 1.0]), PipelineJob(), with_nested.pod) - - -def test_dictionary_columns_are_already_unsupported() -> None: - table = pa.table({"x": pa.array([1, 2]).dictionary_encode()}) - with pytest.raises(InputValidationError, match="dictionary"): - ArrowTableSource(table, source_id="shared") - - -def test_nested_logical_values_are_compared_as_encoded() -> None: - def source(value: int) -> DictSource: - return DictSource( - [{"x": [np.array([value], dtype=np.int64)]}], source_id="shared" - ) - - with Pipeline("conflicts") as pipeline: - with_array.pod(source(1), label="fa") - with_array.pod(source(1), label="fb") - assert set(pipeline.function_pods) == {"fa"} - _refused(source(1), source(100), Pipeline("conflicts"), with_array.pod) - - -def test_zero_rows_use_the_declared_schema() -> None: - def source(values: list[int]) -> ArrowTableSource: - return ArrowTableSource( - pa.Table.from_arrays( - [pa.array(values, type=pa.int64())], - schema=pa.schema([pa.field("x", pa.int64(), nullable=False)]), - ), - source_id="shared", - ) - - with PipelineJob() as job: - increment.pod(source([]), label="fa") - increment.pod(source([]), label="fb") - assert set(job.function_pods) == {"fa"} - _refused(source([]), source([1]), Pipeline("conflicts")) - - def _job() -> PipelineJob: with PipelineJob(database=InMemoryArrowDatabase()) as job: increment.pod(_dict(2, "left"), label="fa") @@ -460,7 +335,9 @@ def test_bind_checks_all_prospective_slots_atomically( job = PipelineJob.load(path) first, second = _dict(1), _dict(100) before = dict(job.sources) - with pytest.raises(InconsistentSourceError, match="different rows") as error: + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: job.bind(sources={"left": first, "right": second}) for part in (first.source_id, "left", "right", "source_id"): assert part in str(error.value) @@ -468,18 +345,19 @@ def test_bind_checks_all_prospective_slots_atomically( job.bind(sources={"left": first}) job.bind(sources={"left": second}) assert job.sources["left"] is second - with pytest.raises(InconsistentSourceError, match="different rows"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): job.bind(sources={"right": first}) job.bind(sources={"right": second}) assert job.sources["right"] is second - job.bind(sources={"left": _dict(100)}) + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + job.bind(sources={"left": _dict(100)}) def test_from_pipeline_checks_the_initial_bind() -> None: with Pipeline("conflicts") as graph: increment.pod(_dict(2, "left"), label="fa") increment.pod(_dict(3, "right"), label="fb") - with pytest.raises(InconsistentSourceError, match="different rows"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): PipelineJob.from_pipeline( graph, sources={"left": _dict(1), "right": _dict(100)} ) @@ -492,65 +370,29 @@ def test_run_checks_slots_changed_outside_job_bind(orchestrator: type) -> None: job = _job() job.nodes["left"].bound_source = _dict(1) job.nodes["right"].bound_source = _dict(100) - with pytest.raises(InconsistentSourceError, match="different rows"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): job.run(orchestrator=orchestrator()) assert not job.fa.as_table().num_rows assert not job.fb.as_table().num_rows -@pytest.mark.parametrize( - "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] -) -def test_run_rechecks_derived_rows_after_refresh(orchestrator: type) -> None: - def origin(x: int) -> DictSource: - return DictSource( - [{"t1": "a", "t2": "b", "x": x, "y": 2}], - tag_columns=["t1", "t2"], - tag_only_columns=True, - source_id="origin", - ) - - def derived(source: RootSource, name: str) -> DerivedSource: - return DerivedSource(source, tags_as_data={"t1": "tag_value"}, source_id=name) - - original = origin(1) - proxy = SourceProxy( - original.source_id, - original.content_hash().to_string(), - original.pipeline_hash().to_string(), - *original.output_schema(), - ) - proxy.bind(original) - first, second = derived(original, "shared"), derived(proxy, "shared") - with PipelineJob(database=InMemoryArrowDatabase()) as job: - with_copy.pod(derived(original, "left"), label="fa") - with_copy.pod(derived(original, "right"), label="fb") - - job.bind(sources={"left": first, "right": second}) - proxy.bind(origin(100)) - assert second.as_table()["x"].to_pylist() == [1] - with pytest.raises(InconsistentSourceError, match="different rows") as error: - job.run(orchestrator=orchestrator()) - assert "slot 'left'" in str(error.value) - assert "slot 'right'" in str(error.value) - assert second.as_table()["x"].to_pylist() == [100] - assert job.last_run is None - - def test_additive_recording_uses_the_current_binding() -> None: + original = _dict(1) with PipelineJob(database=InMemoryArrowDatabase()) as job: - increment.pod(_dict(1), label="fa") + increment.pod(original, label="fa") replacement = _dict(100) job.bind(sources={"shared": replacement}) with job: - with pytest.raises(InconsistentSourceError, match="different rows"): - increment.pod(_dict(2), label="conflict") + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + increment.pod(original, label="conflict") + increment_again.pod(replacement, label="replacement") consume_output.pod(job.fa, label="next") assert job.nodes["shared"].bound_source is replacement job.run() assert job.fa.as_table()["out"].to_pylist() == [101] + assert job.replacement.as_table()["out"].to_pylist() == [102] assert job.next.as_table()["next"].to_pylist() == [202] @@ -595,41 +437,26 @@ def source(kind: pa.DataType, name: str) -> ArrowTableSource: assert part in str(error.value) -def test_one_object_is_allowed_in_several_steps() -> None: +@pytest.mark.parametrize("graph_type", [Pipeline, PipelineJob]) +def test_one_object_is_allowed_in_several_steps( + graph_type: type[Pipeline] | type[PipelineJob], +) -> None: source = _dict(1) - with PipelineJob() as job: + with graph_type("reuse") as job: increment.pod(source, label="fa") increment_again.pod(source, label="fb") assert set(job.nodes) == {"shared", "fa", "fb"} -def test_dynamic_csv_and_cached_sources_are_allowed(tmp_path: Path) -> None: - first_path, second_path = tmp_path / "first.csv", tmp_path / "second.csv" - first_path.write_text("x\n1\n") - second_path.write_text("x\n100\n") - with PipelineJob() as job: - increment.pod(CSVSource(str(first_path), source_id="shared"), label="fa") - increment.pod(CSVSource(str(second_path), source_id="shared"), label="fb") - assert set(job.function_pods) == {"fa"} - - with PipelineJob() as job: - increment.pod(_dict(1).cached(InMemoryArrowDatabase()), label="fa") - increment.pod(_dict(100).cached(InMemoryArrowDatabase()), label="fb") - assert "fa" in job.nodes - - -def test_a_live_source_does_not_hide_two_conflicting_fixed_sources() -> None: - live = _dict(2).cached(InMemoryArrowDatabase()) - with PipelineJob(): - increment.pod(live, label="fa") - increment.pod(_dict(1), label="fb") - with pytest.raises(InconsistentSourceError, match="different rows") as error: - increment.pod(_dict(100), label="fc") - assert "step 'fb'" in str(error.value) - assert "step 'fc'" in str(error.value) +def test_cache_and_its_source_register_as_distinct_objects() -> None: + source = _dict(1) + cached = source.cached(InMemoryArrowDatabase()) + assert cached.content_hash() == source.content_hash() + _refused(source, cached, PipelineJob()) + _refused(cached, source.cached(InMemoryArrowDatabase()), PipelineJob()) -def test_issue_derived_job_sources_are_dynamic() -> None: +def test_stored_derived_sources_register_by_object() -> None: def derived(x: int) -> DerivedSource: with PipelineJob(database=InMemoryArrowDatabase()) as job: increment.pod(_dict(x), label="result") @@ -645,14 +472,9 @@ def derived(x: int) -> DerivedSource: def downstream(out: int) -> int: return out + 1 - with PipelineJob() as job: - downstream.pod(first, label="fa") - downstream.pod(second, label="fb") - assert "fa" in job.nodes + _refused(first, second, PipelineJob(), downstream.pod) -# ITL-1469 review: a source id names a dataset; key columns only name its rows. - _ROWS = [ {"t1": "a", "t2": "p", "x": 1, "y": 10}, {"t1": "b", "t2": "q", "x": 2, "y": 20}, @@ -689,7 +511,7 @@ def _capture(first: RootSource, second: RootSource, pod: _FunctionPodBase) -> st @pytest.mark.parametrize( "keys", [(["t1"], ["t2", "x"]), (None, ["t2", "t1"]), (["x", "y"], None)] ) -def test_fixed_same_rows_with_different_keys_differ_only_in_key_columns( +def test_capture_refuses_materialized_sources_with_different_key_columns( reverse: bool, keys: tuple[list[str] | None, list[str] | None] ) -> None: first = _keyed(_ROWS, keys[0]) @@ -699,76 +521,9 @@ def test_fixed_same_rows_with_different_keys_differ_only_in_key_columns( first, second = second, first assert first.content_hash() != second.content_hash() message = _capture(first, second, both.pod) - assert "differ only in key columns" in message - assert "ITL-1506" in message - assert "source_id=" in message - - -def test_fixed_same_rows_with_signed_zero_and_nan_differ_only_in_key_columns() -> None: - @function_pod(output_keys="out") - def with_float(x: int, y: float) -> float: - return x + y - - def source(ys: list[float], keys: list[str] | None) -> DictSource: - return DictSource( - [{"t": f"r{i}", "x": i, "y": y} for i, y in enumerate(ys)], - tag_columns="t", - tag_only_columns=True, - record_id_columns=keys, - source_id="shared", - ) - - nan = struct.unpack(">d", bytes.fromhex("7ff8000000000001"))[0] - first = source([0.0, float("nan"), 1.5], ["t"]) - second = source([-0.0, nan, 1.5], None) - assert "differ only in key columns" in _capture(first, second, with_float.pod) - - -@pytest.mark.parametrize("reverse", [False, True]) -def test_fixed_different_rows_with_different_keys_are_different_rows( - reverse: bool, -) -> None: - changed = [*_ROWS[:2], {**_ROWS[2], "y": 300}] - first, second = _keyed(_ROWS, ["t1"]), _keyed(changed, ["t2", "x"]) - if reverse: - first, second = second, first - _refused(first, second, Pipeline("conflicts"), both.pod) - - -def test_fixed_row_multiset_counts_duplicates_and_ignores_order() -> None: - def digest(rows: list[dict[str, str | int]]) -> bytes | None: - return _keyed(rows, None)._fixed_row_multiset # pyright: ignore[reportPrivateUsage] # testing the internal digest - - a, b = _ROWS[0], _ROWS[1] - assert digest([a, a, b]) == digest([a, b, a]) - assert digest([a, a, b]) != digest([a, b, b]) - assert digest([a, b]) != digest([a]) - - -@pytest.mark.parametrize("reverse", [False, True]) -def test_live_sources_with_different_keys_do_not_claim_only_key_columns( - tmp_path: Path, reverse: bool -) -> None: - first_path, second_path = tmp_path / "first.csv", tmp_path / "second.csv" - first_path.write_text("t1,t2,x,y\na,p,1,2\n") - second_path.write_text("t1,t2,x,y\nb,q,3,4\n") - sources = [ - CSVSource( - str(path), - source_id="shared", - tag_columns=["t1", "t2"], - tag_only_columns=True, - record_id_columns=keys, - ) - for path, keys in ((first_path, ["t1", "x"]), (second_path, ["t2", "y"])) - ] - first, second = sources[::-1] if reverse else sources - message = _capture(first, second, both.pod) - assert "differ only" not in message assert "different key columns" in message - assert "not compared" in message assert "ITL-1506" in message - assert "source_id=" in message + assert "source_id" in message @function_pod(output_keys="out") @@ -784,8 +539,7 @@ def _derived( ) -# Two copies, given in both orders; the conflict changes only the second copy (c2 -# copies t3 instead of t2: same type, other values). +# The second mapping changes the order. The third changes which column c2 copies. _COPIES = {"t1": "c1", "t2": "c2"} _COPIES_REVERSED = {"t2": "c2", "t1": "c1"} _SECOND_COPY_CHANGED = {"t1": "c1", "t3": "c2"} @@ -808,55 +562,10 @@ def test_derived_sources_over_live_origins_with_other_mapping_and_keys( second = _derived(origin, mapping, ["t3", "t1"]) assert first.arrow_schemas == second.arrow_schemas message = _capture(first, second, with_copies.pod) - assert "differ only" not in message - assert "not compared" in message + assert "different key columns" in message assert "ITL-1506" in message -@pytest.mark.parametrize("reverse", [False, True]) -def test_derived_sources_over_fixed_origins_compare_rows_without_record_ids( - reverse: bool, -) -> None: - origin = DictSource( - [ - {"t1": "a", "t2": "p", "t3": "u", "x": 1, "y": 10}, - {"t1": "b", "t2": "q", "t3": "v", "x": 2, "y": 20}, - ], - tag_columns=["t1", "t2", "t3"], - tag_only_columns=True, - source_id="origin", - ) - - def pair(mapping: dict[str, str]) -> tuple[DerivedSource, DerivedSource]: - first = _derived(origin, _COPIES, ["t1", "t2"]) - second = _derived(origin, mapping, ["t3", "t1"]) - return (second, first) if reverse else (first, second) - - # The mapping given in the other order copies the same values. - same = _capture(*pair(_COPIES_REVERSED), with_copies.pod) - assert "differ only in key columns" in same - # Only the second copy changed: the rows differ. - _refused(*pair(_SECOND_COPY_CHANGED), Pipeline("conflicts"), with_copies.pod) - - -def test_equal_keys_still_compare_record_ids() -> None: - # Equal key columns: today's comparison, record ids included, row order counting - # for positional ids. - _refused( - _keyed(_ROWS, None), - _keyed(list(reversed(_ROWS)), None), - Pipeline("conflicts"), - both.pod, - ) - with PipelineJob() as job: - both.pod(_keyed(_ROWS, ["t1"]), label="fa") - both.pod(_keyed(list(reversed(_ROWS)), ["t1"]), label="fb") - assert set(job.function_pods) == {"fa"} - - -# Re-review of b197756f. - - def test_unknown_key_columns_never_hide_a_conflict_between_known_ones() -> None: # An unbound proxy of the same id and schema has unknown key columns: it neither # causes nor suppresses a refusal between the sources whose keys are known. @@ -864,7 +573,7 @@ def test_unknown_key_columns_never_hide_a_conflict_between_known_ones() -> None: keyed = DictSource([{"x": 1}, {"x": 2}], record_id_columns="x", source_id="shared") proxy = SourceProxy( positional.source_id, - positional.content_hash().to_string(), + _dict(0, "other").content_hash().to_string(), positional.pipeline_hash().to_string(), *positional.output_schema(), ) @@ -874,41 +583,11 @@ def test_unknown_key_columns_never_hide_a_conflict_between_known_ones() -> None: ): with pytest.raises(InconsistentSourceError) as error: require_consistent_sources(uses) - # The proxy's rows were not compared, so the rows are not claimed equal. - message = str(error.value) - assert "different key columns" in message - assert "differ only" not in message - assert "not compared" in message - # Alone with either known source, the proxy causes nothing. + assert "different key columns" in str(error.value) require_consistent_sources([("slot 'p'", proxy), ("slot 'a'", positional)]) require_consistent_sources([("slot 'p'", proxy), ("slot 'b'", keyed)]) -def _three_slot_job() -> PipelineJob: - with PipelineJob(database=InMemoryArrowDatabase()) as job: - _ = increment.pod(_dict(2, "a"), label="fa") - _ = increment.pod(_dict(3, "b"), label="fb") - _ = increment.pod(_dict(4, "c"), label="fc") - return job - - -@pytest.mark.parametrize( - "order", list(itertools.permutations(["keyed", "forward", "backward"])) -) -def test_three_way_diagnosis_does_not_follow_slot_order(order: tuple[str, ...]) -> None: - sources = { - "keyed": DictSource( - [{"x": 1}, {"x": 2}], record_id_columns="x", source_id="shared" - ), - "forward": DictSource([{"x": 1}, {"x": 2}], source_id="shared"), - # Positional ids: another order is other rows than "forward". - "backward": DictSource([{"x": 2}, {"x": 1}], source_id="shared"), - } - job = _three_slot_job() - with pytest.raises(InconsistentSourceError, match="different rows"): - job.bind(sources=dict(zip("abc", (sources[name] for name in order)))) - - @function_pod(output_keys="out") def increment_matched(x: int) -> int: return x + 1 @@ -948,7 +627,7 @@ def _rebind_outside_bind(job: PipelineJob, right_keys: str | None, x: int) -> No @pytest.mark.parametrize("node", ["matched", "fm"]) @pytest.mark.parametrize( ("right_keys", "x", "message"), - [("k", 2, "differ only in key columns"), (None, 200, "different rows")], + [("k", 2, "different key columns"), (None, 200, "distinct source objects")], ) def test_node_run_checks_its_sources_like_job_run( node: str, right_keys: str | None, x: int, message: str @@ -963,110 +642,6 @@ def test_node_run_checks_its_sources_like_job_run( assert job.nodes[name].as_table().num_rows == 0 -def _count_digests(monkeypatch: pytest.MonkeyPatch) -> Counter[tuple[str, int]]: - """Count each kind of fixed-row digest by the source object that computes it.""" - calls: Counter[tuple[str, int]] = Counter() - exact = RootSource._digest_fixed_rows # pyright: ignore[reportPrivateUsage] # counted - multiset = RootSource._digest_fixed_row_multiset # pyright: ignore[reportPrivateUsage] # counted - - def counted_exact(self: RootSource) -> bytes: - calls["exact", id(self)] += 1 - return exact(self) - - def counted_multiset(self: RootSource) -> bytes: - calls["multiset", id(self)] += 1 - return multiset(self) - - monkeypatch.setattr(RootSource, "_digest_fixed_rows", counted_exact) - monkeypatch.setattr(RootSource, "_digest_fixed_row_multiset", counted_multiset) - return calls - - -def test_each_digest_is_computed_at_most_once_per_source_per_check( - monkeypatch: pytest.MonkeyPatch, -) -> None: - calls = _count_digests(monkeypatch) - rows = [{"x": 1}, {"x": 2}] - first = DictSource(rows, source_id="shared") - second = DictSource(rows, source_id="shared") - keyed = DictSource(rows, record_id_columns="x", source_id="shared") - uses = [("slot 'a'", first), ("slot 'b'", second), ("slot 'c'", keyed)] - for _ in range(2): - # Every check digests again (a held table can share memory with the - # caller's data), but each digest at most once per source. - calls.clear() - with pytest.raises(InconsistentSourceError, match="differ only in key"): - require_consistent_sources(uses) - # Equal keys need the exact digest, different keys the multiset digest. - assert calls == { - ("exact", id(first)): 1, - ("exact", id(second)): 1, - ("multiset", id(first)): 1, - ("multiset", id(second)): 1, - ("multiset", id(keyed)): 1, - } - - # Two sources whose key columns differ need only the multiset digest. - calls.clear() - pair = [ - ("slot 'a'", DictSource(rows, source_id="shared")), - ("slot 'b'", DictSource(rows, record_id_columns="x", source_id="shared")), - ] - with pytest.raises(InconsistentSourceError, match="differ only in key"): - require_consistent_sources(pair) - assert sorted(calls.values()) == [1, 1] - assert {kind for kind, _ in calls} == {"multiset"} - - -def test_a_proxy_and_its_source_are_digested_once_per_check( - monkeypatch: pytest.MonkeyPatch, -) -> None: - def derived() -> DerivedSource: - origin = DictSource( - [{"t": "a", "x": 1}, {"t": "b", "x": 2}], - tag_columns="t", - tag_only_columns=True, - source_id="origin", - ) - return DerivedSource( - origin, tags_as_data={"t": "tag_value"}, source_id="shared" - ) - - source, other = derived(), derived() - proxy = SourceProxy( - source.source_id, - source.content_hash().to_string(), - source.pipeline_hash().to_string(), - *source.output_schema(), - ) - proxy.bind(source) - calls = _count_digests(monkeypatch) - for uses in itertools.permutations( - [("slot 'p'", proxy), ("slot 'd'", source), ("slot 'o'", other)] - ): - calls.clear() - require_consistent_sources(uses) - assert calls == {("exact", id(source)): 1, ("exact", id(other)): 1} - - -def test_a_mutated_frame_is_compared_again_at_the_next_bind() -> None: - import pandas as pd - - def frame() -> pd.DataFrame: - return pd.DataFrame({"x": np.array([1, 2], dtype=np.int64)}) - - first_frame, second_frame = frame(), frame() - first = DataFrameSource(first_frame, source_id="shared") - second = DataFrameSource(second_frame, source_id="shared") - job = _job() - job.bind(sources={"left": first, "right": second}) - first_frame.iloc[0, 0] = 100 - if first.as_table()["x"].to_pylist() == [1, 2]: - pytest.skip("this pandas copies the frame; nothing is shared to mutate") - with pytest.raises(InconsistentSourceError, match="different rows"): - job.bind(sources={"left": first, "right": second}) - - def _arranged( arrangement: Arrangement, source_id: str, @@ -1100,10 +675,10 @@ def _arranged( @pytest.mark.parametrize( ("left_keys", "right_keys", "changed", "message"), [ - (["t1", "t2"], ["t2", "t1"], False, "differ only in key columns"), - (None, ["t2", "t1"], False, "differ only in key columns"), - (["t1", "t2"], ["t2", "t1"], True, "different rows"), - (None, None, True, "different rows"), + (["t1", "t2"], ["t2", "t1"], False, "different key columns"), + (None, ["t2", "t1"], False, "different key columns"), + (["t1", "t2"], ["t2", "t1"], True, "different key columns"), + (None, None, True, "distinct source objects"), ], ) @pytest.mark.parametrize( diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py new file mode 100644 index 000000000..a492c3b7e --- /dev/null +++ b/tests/test_pipeline/test_source_object_registration.py @@ -0,0 +1,286 @@ +"""A pipeline binds each source content hash to a single object (ITL-1469).""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from orcapod import Pipeline, PipelineJob, function_pod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import InconsistentSourceError +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.sources import CSVSource, DictSource + +Orchestrator = type[AsyncPipelineOrchestrator] | type[SyncPipelineOrchestrator] +ORCHESTRATORS = [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +ROWS = [{"t1": "a", "t2": "b", "x": 1, "y": 2}, {"t1": "c", "t2": "d", "x": 3, "y": 4}] + + +@function_pod(output_keys="out") +def total(x: int, y: int) -> int: + """Add the two data columns.""" + return x + y + + +@function_pod(output_keys="out") +def difference(x: int, y: int) -> int: + """Subtract the second data column from the first.""" + return x - y + + +@function_pod(output_keys="out") +def product(x: int, y: int) -> int: + """Multiply the two data columns.""" + return x * y + + +def _source( + tmp_path: Path, kind: str, name: str, *, reverse: bool = False, change: bool = False +) -> DictSource | CSVSource: + rows = [dict(row) for row in ROWS] + if change: + rows[-1]["y"] = 40 + columns = ["t1", "t2", "x", "y"] + tags = ["t1", "t2"] + if reverse: + columns.reverse() + tags.reverse() + if kind == "csv": + path = tmp_path / f"{name}-{reverse}.csv" + path.write_text( + ",".join(columns) + + "\n" + + "".join(",".join(str(row[col]) for col in columns) + "\n" for row in rows) + ) + return CSVSource( + str(path), source_id=name, tag_columns=tags, tag_only_columns=True + ) + return DictSource( + [{col: row[col] for col in columns} for row in rows], + source_id=name, + tag_columns=tags, + tag_only_columns=True, + ) + + +def _pair( + tmp_path: Path, kind: str, reverse: bool +) -> tuple[DictSource | CSVSource, DictSource | CSVSource]: + first = _source(tmp_path, kind, "shared") + second = _source(tmp_path, kind, "shared", reverse=True, change=kind != "equal") + assert first is not second + assert first.content_hash() == second.content_hash() + return (second, first) if reverse else (first, second) + + +def _job(tmp_path: Path, slots: tuple[str, ...] = ("a", "b")) -> PipelineJob: + with PipelineJob(database=InMemoryArrowDatabase()) as job: + for slot, compute in zip(slots, (total, difference, product)): + compute.pod(_source(tmp_path, "dict", slot), label=f"result_{slot}") + return job + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("kind", ["equal", "different", "csv"]) +@pytest.mark.parametrize("graph_type", [Pipeline, PipelineJob]) +def test_capture_refuses_two_objects_with_one_hash( + tmp_path: Path, + graph_type: type[Pipeline] | type[PipelineJob], + kind: str, + reverse: bool, +) -> None: + first, second = _pair(tmp_path, kind, reverse) + with graph_type("registration") as graph: + total.pod(first, label="first") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + total.pod(second, label="second") + for part in ("step 'first'", "step 'second'", "reuse", "source_id"): + assert part in str(error.value) + assert "second" not in graph.nodes + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("kind", ["equal", "different", "csv"]) +def test_bind_refuses_two_objects_with_one_hash( + tmp_path: Path, kind: str, reverse: bool +) -> None: + first, second = _pair(tmp_path, kind, reverse) + job = _job(tmp_path) + before = job.sources.copy() + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + job.bind(sources={"a": first, "b": second}) + assert "slot 'a'" in str(error.value) and "slot 'b'" in str(error.value) + assert job.sources == before + + job.bind(sources={"a": first, "b": first}) + assert job.sources["a"] is job.sources["b"] is first + job.bind(sources={"a": _source(tmp_path, kind, "replacement")}) + job.bind(sources={"b": second}) + assert job.sources["b"] is second + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("kind", ["equal", "different", "csv"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_run_refuses_two_objects_with_one_hash( + tmp_path: Path, kind: str, reverse: bool, orchestrator: Orchestrator +) -> None: + first, second = _pair(tmp_path, kind, reverse) + job = _job(tmp_path) + # Bypass bind to exercise the run-time check independently. + job.nodes["a"].bound_source = first + job.nodes["b"].bound_source = second + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + job.run(orchestrator=orchestrator()) + assert "slot 'a'" in str(error.value) and "slot 'b'" in str(error.value) + assert job.last_run is None + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("kind", ["equal", "different", "csv"]) +def test_load_refuses_different_configs_that_rebuild_to_one_hash( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, kind: str, reverse: bool +) -> None: + from orcapod.pipeline import serialization + + first, second = _pair(tmp_path, kind, reverse) + job = _job(tmp_path) + path = tmp_path / "job.json" + job.save(path) + saved = json.loads(path.read_text()) + saved["bindings"]["sources"] = {"a": first.to_config(), "b": second.to_config()} + if kind != "csv": + # In-memory sources have no persisted rows. Simulate their reconstruction + # from distinct configs without changing the saved-format support for them. + for name in ("a", "b"): + saved["bindings"]["sources"][name]["fixture_slot"] = name + restored = {"a": first, "b": second} + monkeypatch.setattr( + serialization, + "resolve_source_from_config", + lambda config: restored[config["fixture_slot"]], + ) + path.write_text(json.dumps(saved)) + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + PipelineJob.load(path) + assert "slot 'a'" in str(error.value) and "slot 'b'" in str(error.value) + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_load_refuses_one_source_id_with_different_key_columns( + tmp_path: Path, reverse: bool +) -> None: + csv = _source(tmp_path, "csv", "shared") + job = _job(tmp_path) + path = tmp_path / "job.json" + job.save(path) + saved = json.loads(path.read_text()) + first = {**csv.to_config(), "record_id_columns": ["t1", "x"]} + second = {**csv.to_config(), "record_id_columns": ["t2", "y"]} + configs = (second, first) if reverse else (first, second) + saved["bindings"]["sources"] = dict(zip(("a", "b"), configs, strict=True)) + path.write_text(json.dumps(saved)) + + with pytest.raises(InconsistentSourceError, match="different key columns") as error: + PipelineJob.load(path) + assert "slot 'a'" in str(error.value) and "slot 'b'" in str(error.value) + assert "ITL-1506" in str(error.value) + + +@pytest.mark.parametrize("slots", [("a", "b"), ("c", "b", "a")]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_load_reuses_one_object_for_identical_saved_configs( + tmp_path: Path, slots: tuple[str, ...], orchestrator: Orchestrator +) -> None: + job = _job(tmp_path, slots) + db = InMemoryArrowDatabase() + source = _source(tmp_path, "csv", "shared") + job.bind(database=db, sources=dict.fromkeys(slots, source)) + job.run(orchestrator=orchestrator()) + path = tmp_path / "job.json" + job.save(path) + saved = json.loads(path.read_text()) + configs = saved["bindings"]["sources"] + assert all(configs[name] == configs[slots[0]] for name in slots) + + loaded = PipelineJob.load(path, database=db) + shared = loaded.sources[slots[0]] + for name in slots: + assert loaded.sources[name] is shared + copied = tmp_path / "copied.json" + loaded.save(copied) + assert copied.read_bytes() == path.read_bytes() + + def rows(graph: PipelineJob, name: str) -> list[dict[str, Any]]: + return graph.nodes[name].as_table(columns={"sort_by_tags": True}).to_pylist() + + stored = { + table_path: db.get_all_records(table_path) + for table_path in db.list_table_paths() + } + loaded.run(orchestrator=orchestrator(), load_only=True) + for name in slots: + assert rows(loaded, name) == ROWS + assert rows(loaded, f"result_{name}") == rows(job, f"result_{name}") + assert { + table_path: db.get_all_records(table_path) + for table_path in db.list_table_paths() + } == stored + + replacement = _source(tmp_path, "csv", "replacement") + loaded.bind(sources={slots[0]: replacement}) + assert loaded.sources[slots[0]] is replacement + for name in slots[1:]: + assert loaded.sources[name] is shared + + +@pytest.mark.parametrize("reverse_keys", [False, True]) +def test_load_shares_repeated_configs_written_by_main( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, reverse_keys: bool +) -> None: + # origin/main (f55ed6d7) wrote a separate, identical config for each of two + # distinct CSVSource objects bound to different slots. + fixture = Path(__file__).with_name("fixtures") / "itl_1469_main_shared_source.json" + configs = json.loads(fixture.read_text())["bindings"]["sources"] + assert configs["a"] == configs["b"] + monkeypatch.chdir(tmp_path) + Path("shared.csv").write_text("t1,t2,x,y\na,b,1,2\nc,d,3,4\n") + path = fixture + if reverse_keys: + saved = json.loads(fixture.read_text()) + sources = saved["bindings"]["sources"] + sources["b"] = dict(reversed(sources["b"].items())) + path = tmp_path / "reordered.json" + path.write_text(json.dumps(saved)) + + job = PipelineJob.load(path) + assert job.sources["a"] is job.sources["b"] + assert job.nodes["a"].as_table().to_pylist() == ROWS + assert job.nodes["b"].as_table().to_pylist() == ROWS + + +def test_itl_1554_loading_shared_slots_feeding_the_same_pod(tmp_path: Path) -> None: + """Record the existing read-only DAG failure for this shared-source topology.""" + db = InMemoryArrowDatabase() + with PipelineJob(database=db) as job: + for slot in ("a", "b"): + total.pod(_source(tmp_path, "dict", slot), label=f"total_{slot}") + source = _source(tmp_path, "csv", "shared") + job.bind(sources={"a": source, "b": source}) + job.run() + path = tmp_path / "job.json" + job.save(path) + + with pytest.raises(NotImplementedError, match="StreamBase.identity_structure"): + PipelineJob.load(path, database=db) From 990d595e5d7d001d76232bf1237081545fe52987 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 16:12:07 -0800 Subject: [PATCH 21/42] fix(pipeline): preserve source registration across slot changes --- .zed/rules | 9 + CLAUDE.md | 9 + docs/concepts/sources.md | 24 +- src/orcapod/core/nodes/source_node.py | 44 ++- src/orcapod/pipeline/base.py | 84 +++--- src/orcapod/pipeline/graph.py | 1 + src/orcapod/pipeline/job.py | 191 +++++++----- src/orcapod/pipeline/restrictions.py | 5 +- src/orcapod/pipeline/source_consistency.py | 21 +- .../test_spiraldb_table_source_where.py | 15 +- .../test_pipeline/test_source_id_conflicts.py | 37 ++- .../test_source_object_registration.py | 284 +++++++++++++++++- 12 files changed, 570 insertions(+), 154 deletions(-) diff --git a/.zed/rules b/.zed/rules index 0131133c6..3dadd2933 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1510,6 +1510,15 @@ data. The rules: match its previous one (bind does not compare the two), but bind refuses, before replacing any binding, a bind after which two slots would read one source identity under different restrictions (below). A job run over a restricted source feeding GroupBy, Batch or MergeJoin issues one RestrictedAggregationWarning. + Each source content hash belongs to one source object per pipeline or job + (ITL-1469). Capture, compile, binding through either API, loading and running + check the sources the graph reads. A slot binding replaces its former source. + Pass the currently bound source when adding a step to a job. A capture of an + older source for the slot is refused while a different object is bound there + (ITL-1559 tracks whether a captured source should refer to the object or the slot). + Call where() once and reuse the resulting object. A source object conflict + raises InconsistentSourceError before the separate restriction check, which + can see restrictions beneath wrappers. A pipeline keeps one restriction (or none) per source identity (a restriction leaves the identity unchanged), so one table restricted two ways (or with and without a restriction) in one pipeline is refused (restrictions.require_one_restriction, over the sources the streams diff --git a/CLAUDE.md b/CLAUDE.md index 053e2539b..783f6c6d4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1558,6 +1558,15 @@ data. The rules: match its previous one (bind does not compare the two), but `bind` refuses, before replacing any binding, a bind after which two slots would read one source identity under different restrictions (below). A job run over a restricted source feeding `GroupBy`, `Batch` or `MergeJoin` issues one `RestrictedAggregationWarning`. + Each source content hash belongs to one source object per pipeline or job + (ITL-1469). Capture, compile, binding through either API, loading and running + check the sources the graph reads. A slot binding replaces its former source. + Pass the currently bound source when adding a step to a job. A capture of an + older source for the slot is refused while a different object is bound there + (ITL-1559 tracks whether a captured source should refer to the object or the slot). + Call where() once and reuse the resulting object. A source object conflict + raises InconsistentSourceError before the separate restriction check, which + can see restrictions beneath wrappers. A pipeline keeps one restriction (or none) per source identity (a restriction leaves the identity unchanged), so one table restricted two ways (or with and without a restriction) in one pipeline is refused (`restrictions.require_one_restriction`, over the sources the streams diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index a276e8531..f02a4a20a 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -79,16 +79,30 @@ record id names a row within its source and never holds the source id. A job nam slot by the source's name (`job.bind(sources={"units": ...})`). Each source content hash is registered to one Python object per pipeline or job. -Build the source once and reuse that object wherever you read it, or give each -source its own `source_id`. Two distinct objects with the same content hash raise +Build the source once and reuse that object wherever you read it. For sources +whose hash includes their `source_id`, each source can instead have its own ID. +Two distinct objects with the same content hash raise `InconsistentSourceError` even when their rows agree, including sources that read rows later. Capture, binding, loading and execution all check for conflicts. Rebinding replaces a slot's source. On load, slots with identical saved source configurations share one reconstructed object. -The source object can be a `SourceProxy`, a `CachedSource` or a `DerivedSource`. -Reuse the wrapper itself wherever you use that source. A wrapper and another source -with the same content hash cannot both be registered in the same pipeline. +When adding a step to a job after rebinding a slot, pass the source object currently +bound there. Capturing an older object while that slot holds a different object +raises `InconsistentSourceError`. To use the older object again, bind it to the slot +first. ITL-1559 tracks whether a captured source should refer to the object or to the +slot. + +The same rule applies to wrappers. Each of these pairs raises +`InconsistentSourceError` when the objects share one content hash. + +| Sources used together | How to share the source | +| --- | --- | +| A source and a `CachedSource` over it | Build the cache once and use it in both places. | +| Two caches over one source, or a cache and its inner cache | Choose one cache object and reuse it. | +| Two calls to `node.as_source()` on one node | Call `as_source()` once and reuse the result. | +| Two `DerivedSource(tags_as_data=...)` objects with the same hash | Build one derived source and reuse it. | +| A source or its cache paired with a `SourceProxy` restored for it | Choose one source object and reuse it. | ITL-1553 tracks accepting distinct objects that represent the same source. ITL-1531 tracks sources that read their rows later. diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b6b8bc0f6..913a9c4c2 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -13,6 +13,7 @@ import functools import json import logging +import weakref from abc import ABC, abstractmethod from collections.abc import AsyncIterator, Collection, Iterator, Mapping, Sequence from datetime import datetime @@ -65,6 +66,7 @@ ) if TYPE_CHECKING: + from orcapod.pipeline.job import PipelineJob from orcapod.types.explanation import Explanation from orcapod.channels import WritableChannel from orcapod.protocols.core_protocols import StreamProtocol @@ -1630,6 +1632,7 @@ def __init__( ) self._bound_source: StreamProtocol | None = None self._declared_form: _DeclaredForm | None = None + self._binding_owner: weakref.ReferenceType[PipelineJob] | None = None if bound_source is not None: # Checks the source and, for a narrower one, records how its rows become # rows of the declared schema (ITL-1112), as the setter does, but does not @@ -1655,12 +1658,15 @@ def run(self, *, load_only: bool = False) -> StreamView: load_only: Accepted for every job node; a source reads its rows either way. Raises: + InconsistentSourceError: If the bound stream reads conflicting sources. UnboundSourceError: When no concrete source is bound. ValueError: If ``load_only`` and the bound stream computes or delivers when read (``node_run.refuse_unloadable_inputs``). """ from orcapod.pipeline.node_run import check_sources, refuse_unloadable_inputs + from orcapod.pipeline.source_consistency import require_consistent_sources + require_consistent_sources([(f"node {self.label!r}", self)]) _ = check_sources([self]) if load_only: refuse_unloadable_inputs(self) @@ -1675,33 +1681,55 @@ def bound_source(self) -> StreamProtocol | None: def bound_source(self, value: StreamProtocol | None) -> None: """Bind *value* as the concrete source and invalidate both hash caches. - A source is checked against the slot's declared schema first (``validate``), so - one that does not fit is refused before anything changes. A narrower source - (``x: int`` for a slot declaring ``x: int | None``) is accepted, and the node - gives its rows as rows of the declared schema (ITL-1112). ``None`` unbinds. + A source must fit the slot's declared schema before the binding changes. + A narrower source (``x: int`` for a slot declaring ``x: int | None``) is + accepted, and the node gives its rows as rows of the declared schema + (ITL-1112). ``None`` unbinds. + In a job, assignment uses the binding checks of ``PipelineJob.bind()``. Binding stamps the slot as modified, so every job node fed by it is stale and reads empty until it runs again (ITL-1095). Raises: + InconsistentSourceError: If the replacement introduces conflicting sources. SourceSpecMismatchError: If *value* does not fit the declared schema. """ - self._bind(value) - self._update_modified_time() + owner = self._binding_owner() if self._binding_owner is not None else None + if owner is None: + self._bind(value) + self._update_modified_time() + else: + owner._replace_source_binding(self, value) # pyright: ignore[reportPrivateUsage] # the setter uses the job's binding transaction + + def _set_binding_owner(self, owner: PipelineJob | None) -> None: + """Route changes to a job while this is one of its active slots.""" + self._binding_owner = weakref.ref(owner) if owner is not None else None def _bound_stream(self) -> StreamProtocol | None: """The concrete stream bound to this slot, or ``None``.""" return self._bound_source def _bind(self, value: StreamProtocol | None) -> None: - """Check *value* and bind it, invalidating both hash caches. + """Check and install a binding without a job-wide transaction. The binding the setter and ``__init__`` share. Only the setter stamps the slot as modified (ITL-1095): a node built with its source is not a rebinding. Raises: + InconsistentSourceError: If the bound stream reads conflicting sources. SourceSpecMismatchError: If *value* does not fit the declared schema. """ - form = None if value is None else self._declared_form_for(value) + from orcapod.pipeline.source_consistency import require_consistent_sources + + form = None + if value is not None: + require_consistent_sources([(f"slot {self.name!r}", value)]) + form = self._declared_form_for(value) + self._apply_binding(value, form) + + def _apply_binding( + self, value: StreamProtocol | None, form: _DeclaredForm | None + ) -> None: + """Install a validated binding and invalidate its cached hashes.""" self._bound_source = value self._declared_form = form self._invalidate_content_hash_cache() diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 5cf61fad6..d1c5875fa 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -4,7 +4,7 @@ import logging from abc import ABC, abstractmethod -from collections.abc import Hashable, Iterator +from collections.abc import Hashable, Iterator, Mapping from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar @@ -133,9 +133,8 @@ def __init__( # --- Additive recording state (never cleared) ----------------- # Maps content-hash-string → PodInvocation for each recorded invocation. self._invocation_lut: dict[str, PodInvocation] = {} - # Keep the original input objects for validation even when a live source - # and a fixed source share one address and their invocations coalesce. - self._recorded_source_uses: dict[int, SourceUse] = {} + # Ordered graph keys chosen at capture, which stay fixed across rebindings. + self._invocation_input_keys: dict[str, tuple[str, ...]] = {} # Maps content-hash-string → raw stream for each unregistered upstream. self._source_streams: dict[str, Any] = {} # Topology graph — vertices and edges are content-hash strings. @@ -351,55 +350,58 @@ def _record_invocation(self, invocation: PodInvocation) -> None: key = invocation.content_hash().to_string() inputs = tuple(invocation.input_streams) - upstreams = [ - (upstream, upstream.content_hash().to_string()) for upstream in inputs - ] + input_keys = tuple(self._capture_input_key(upstream) for upstream in inputs) # Checked before anything is recorded, so a refused invocation leaves the # graph as it was. A restriction does not change a source's identity, so the # pipeline keeps one restriction (or none) per source identity, whatever # streams lead to it: every source this invocation reads is checked with # every source the pipeline's streams read now (nothing is remembered: a # slot rebound since the last invocation changes what they read). - require_consistent_sources(self._source_uses(invocation)) - require_one_restriction([*self._held_streams(), *inputs]) - self._remember_invocation(key, invocation) + uses = tuple(self._source_uses(invocation)) + require_consistent_sources(uses) + require_one_restriction(stream for _, stream in uses) + self._remember_invocation(key, invocation, input_keys) self._hash_graph.add_node(key) - for upstream, upstream_hash in upstreams: + for upstream, upstream_hash in zip(inputs, input_keys, strict=True): self._hash_graph.add_edge(upstream_hash, key) if upstream_hash not in self._source_streams: self._source_streams[upstream_hash] = upstream - def _remember_invocation(self, key: str, invocation: PodInvocation) -> None: + def _capture_input_key(self, stream: cp.StreamProtocol) -> str: + """Return the topology key for a new use of this stream.""" + return stream.content_hash().to_string() + + def _remember_invocation( + self, key: str, invocation: PodInvocation, input_keys: tuple[str, ...] + ) -> None: """Keep the smallest explicit label when identical invocations share a node.""" - for location, stream in invocation_source_uses(invocation): - self._recorded_source_uses[id(stream)] = (location, stream) previous = self._invocation_lut.get(key) if previous is not None and previous.label is not None: if invocation.label is None or previous.label < invocation.label: return self._invocation_lut[key] = invocation + self._invocation_input_keys[key] = input_keys - def _held_streams(self) -> list[Any]: - """Every stream the pipeline holds: its leaves and every recorded input.""" - return [ - *self._source_streams.values(), - *( - stream - for invocation in self._invocation_lut.values() - for stream in invocation.input_streams - ), - ] + def _recorded_uses( + self, bound_leaves: Mapping[str, cp.StreamProtocol] + ) -> Iterator[SourceUse]: + """Use the live binding when a recorded input was routed to a replaced slot.""" + # Prefer the labelled endpoint of a chain over an implicit projection. + for key, invocation in reversed(self._invocation_lut.items()): + for (location, stream), input_key in zip( + invocation_source_uses(invocation), + self._invocation_input_keys[key], + strict=True, + ): + yield location, bound_leaves.get(input_key, stream) + for key, stream in self._source_streams.items(): + yield f"source {stream.label!r}", bound_leaves.get(key, stream) def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse]: - """Inputs before hash deduplication, with their original step names.""" - # Prefer the labelled endpoint of a chain over an implicit projection. - for invocation in reversed(self._invocation_lut.values()): - yield from invocation_source_uses(invocation) - yield from self._recorded_source_uses.values() + """Held inputs and, when supplied, the candidate's inputs before deduplication.""" + yield from self._recorded_uses({}) if extra is not None: yield from invocation_source_uses(extra) - for stream in self._source_streams.values(): - yield f"source {stream.label!r}", stream def _source_node_from_recording(self, key: str) -> Any: """Create the source node for a recorded leaf.""" @@ -475,7 +477,7 @@ def reset(self) -> None: """No-op — all recording state is additive and persists across with-blocks. Note: - ``_invocation_lut``, ``_recorded_source_uses``, ``_source_streams``, and ``_hash_graph`` + ``_invocation_lut``, ``_source_streams``, and ``_hash_graph`` intentionally accumulate across ``with`` blocks. ``_persistent_node_map``, ``_node_lut``, ``_upstreams``, and ``_graph_edges`` are compiled artifacts overwritten by each @@ -537,8 +539,9 @@ def compile(self) -> None: # Checked again here, from what the streams read now: a slot rebound after # the last invocation would otherwise connect a branch recorded over one # restriction to another (ITL-1218). - require_consistent_sources(self._source_uses()) - require_one_restriction(self._held_streams()) + uses = tuple(self._source_uses()) + require_consistent_sources(uses) + require_one_restriction(stream for _, stream in uses) source_node_cls = self.source_node_class @@ -604,9 +607,7 @@ def compile(self) -> None: if key not in self._invocation_lut: continue # vertex with no invocation (e.g. pure source hash) inv = self._invocation_lut[key] - upstream_nodes = [ - node_map[up.content_hash().to_string()] for up in inv.input_streams - ] + upstream_nodes = [node_map[up] for up in self._invocation_input_keys[key]] if isinstance(inv, FunctionInvocation): node_map[key] = self.function_node_class( function_pod=inv.pod, @@ -838,10 +839,13 @@ def from_invocations( instance._source_streams = dict(graph.source_streams) for inv in graph.invocations: key = inv.content_hash().to_string() - instance._remember_invocation(key, inv) + input_keys = tuple( + instance._capture_input_key(up) for up in inv.input_streams + ) + instance._remember_invocation(key, inv, input_keys) instance._hash_graph.add_node(key) - for upstream in inv.input_streams: - instance._hash_graph.add_edge(upstream.content_hash().to_string(), key) + for input_key in input_keys: + instance._hash_graph.add_edge(input_key, key) # Also add source hashes as isolated nodes (no incoming edges) for h in graph.source_streams: if h not in instance._hash_graph: diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index baec82ecf..58e211ccd 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -690,6 +690,7 @@ def _clone_for_execution(self) -> "Pipeline": # Shared read-only structural state (recording + compiled) clone._name = self._name clone._invocation_lut = self._invocation_lut + clone._invocation_input_keys = self._invocation_input_keys clone._source_streams = self._source_streams clone._node_lut = self._node_lut clone._upstreams = self._upstreams diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 0a7aaac3d..7e2fcb41c 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -6,7 +6,7 @@ import enum import logging import sys -from collections.abc import Iterator +from collections.abc import Iterator, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast @@ -20,6 +20,7 @@ from orcapod.side_effects import SideEffectJobNode, SideEffectNode from orcapod.core.tracker import AutoRegisteringContextBasedTracker from orcapod.errors import ( + InconsistentSourceError, OrcapodDatabaseError, OrcapodDatabaseReadError, OrcapodDatabaseWriteError, @@ -57,10 +58,13 @@ if TYPE_CHECKING: from pathlib import Path + from orcapod.core.nodes.source_node import _DeclaredForm # pyright: ignore[reportPrivateUsage] # shared binding transaction + from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.execution_context import ExecutionContext from orcapod.pipeline.graph import Pipeline from orcapod.pipeline.pod_invocation import PodInvocation + from orcapod.pipeline.restrictions import Rebinding from orcapod.pipeline.source_consistency import SourceUse from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.protocols.database_protocols import ArrowDatabaseProtocol @@ -194,12 +198,8 @@ def __init__( self._auto_compile = auto_compile # name → bound concrete source (user-facing API: job.sources). self._sources: dict[str, cp.StreamProtocol] = {} - # hash → bound concrete source, keyed by the same hash as - # _persistent_node_map. Used by bind() for O(1) lookup by content - # hash; avoids name collisions when multiple concrete sources share - # the same class name (e.g. two ArrowTableSource objects). - self._sources_by_hash: dict[str, cp.StreamProtocol] = {} self._rebound_source_keys: set[str] = set() + self._captured_slot_keys: dict[str, str] = {} self._has_run: bool = False # True only while the last run started has finished and committed its writes: # what the database then holds for each node is what that run left (ITL-1043). @@ -234,7 +234,7 @@ def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse for key in self._rebound_source_keys if isinstance(slot := self._persistent_node_map.get(key), SourceJobNode) } - recorded = super()._source_uses() + recorded = self._recorded_uses(bound_leaves) if bound_leaves: yield from root_source_uses(recorded, bound_leaves=bound_leaves) else: @@ -242,6 +242,54 @@ def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse if extra is not None: yield from invocation_source_uses(extra) + def _capture_input_key(self, stream: cp.StreamProtocol) -> str: + """Route a newly captured use of a bound object to its existing slot.""" + stream_key = super()._capture_input_key(stream) + if isinstance(stream, SourceJobNode): + for key, node in self._persistent_node_map.items(): + if node is stream: + return key + if not self._rebound_source_keys: + return stream_key + slot_key = self._captured_slot_keys.get(stream_key, stream_key) + slot = self._persistent_node_map.get(slot_key) + # Stopgap (ITL-1559): refuse to route a new source object to a different + # one through the old hash. The follow-up will settle whether capture + # refers to the object or to the slot. + if isinstance(slot, SourceJobNode): + if ( + slot_key in self._rebound_source_keys + and slot.bound_source is not None + and slot.bound_source is not stream + ): + raise InconsistentSourceError( + f"Capture found distinct source objects for slot {slot.name!r}. " + "Pass the source bound there or bind the slot again with job.bind()." + ) + return slot_key + for key, slot in self._persistent_node_map.items(): + if ( + key in self._rebound_source_keys + and isinstance(slot, SourceJobNode) + and slot.bound_source is stream + ): + return key + return stream_key + + def _remember_invocation( + self, key: str, invocation: PodInvocation, input_keys: tuple[str, ...] + ) -> None: + """Remember the slot used by each newly captured replacement hash.""" + super()._remember_invocation(key, invocation, input_keys) + for stream, slot_key in zip(invocation.input_streams, input_keys, strict=True): + if slot_key not in self._rebound_source_keys: + continue + slot = self._persistent_node_map.get(slot_key) + if isinstance(slot, SourceJobNode) and slot.bound_source is stream: + stream_key = stream.content_hash().to_string() + if stream_key != slot_key: + self._captured_slot_keys[stream_key] = slot_key + def _source_node_from_recording(self, key: str) -> SourceJobNode: """Preserve an explicit binding when recompiling its slot.""" if key in self._rebound_source_keys: @@ -267,29 +315,21 @@ def compile(self) -> None: If ``_database`` is set, distributes databases to all function and operator job nodes. """ - # Preserve any sources already bound (e.g. from a prior bind() call). - pre_sources = dict(self._sources) - pre_sources_by_hash = dict(self._sources_by_hash) - + previous_slots = [ + node + for node in self._persistent_node_map.values() + if isinstance(node, SourceJobNode) + ] super().compile() - # Collect bound SourceJobNodes created during compilation. - # _sources is name-keyed (user-facing API via job.sources). - # _sources_by_hash is hash-keyed (internal use by bind()). - # Two concrete sources of the same class (e.g. two ArrowTableSource objects) - # would collide on name but have distinct hash keys. - compiled_by_name: dict[str, Any] = {} - compiled_by_hash: dict[str, Any] = {} - for h, n in self._persistent_node_map.items(): - if isinstance(n, SourceJobNode) and n.bound_source is not None: - compiled_by_name[n.name] = n.bound_source - compiled_by_hash[h] = n.bound_source - # Also index by schema-based hash (matches blueprint pipeline keys). - schema_hash = n.as_node().content_hash().to_string() - compiled_by_hash[schema_hash] = n.bound_source - # pre_sources / pre_sources_by_hash win over compiled (explicit bind() takes priority). - self._sources = {**compiled_by_name, **pre_sources} - self._sources_by_hash = {**compiled_by_hash, **pre_sources_by_hash} + for slot in previous_slots: + slot._set_binding_owner(None) # pyright: ignore[reportPrivateUsage] # the replaced slot no longer belongs to this job + self._sources = {} + for node in self._persistent_node_map.values(): + if isinstance(node, SourceJobNode): + node._set_binding_owner(self) # pyright: ignore[reportPrivateUsage] # setters participate in this job's binding transaction + if node.bound_source is not None: + self._sources[node.name] = node.bound_source # Invalidate the lazy compiled_pipeline cache. self._compiled_pipeline = None @@ -438,12 +478,8 @@ def from_pipeline( ) # Reconstruct via InvocationGraph (creates unbound SourceJobNodes). - # _compiled_pipeline is intentionally left as None here so the lazy - # property computes a schema-normalized blueprint via as_pipeline(). - # Setting it to the original pipeline would cause hash-key mismatches in - # _build_execution_graph(): the original pipeline may carry concrete - # (data-inclusive) hash keys in _upstreams, while _sources_by_hash is - # keyed by schema-based hashes derived from the unbound SourceJobNodes. + # Leave the compiled blueprint lazy so as_pipeline() builds it with + # the schema-based keys of the new job's slots. job = cls.from_invocations(pipeline.to_invocations(), name=pipeline._name) job._database = database # pyright: ignore[reportAttributeAccessIssue] # from_invocations is typed as the base class; the instance is a PipelineJob job._execution_context = execution_context @@ -547,18 +583,7 @@ def bind( for node in (self._persistent_node_map or {}).values() if isinstance(node, SourceJobNode) and node.name in to_bind ] - require_consistent_sources( - ( - (f"node {node.label!r}", node) - for node in self._persistent_node_map.values() - ), - rebinding, - ) - for node, source in rebinding: - node.validate(source) - refuse_restriction_conflicts( - (self._persistent_node_map or {}).values(), rebinding=rebinding - ) + prepared = self._prepare_source_bindings(rebinding) new_database = database if database is not None else self._database new_result_database = ( self._result_database @@ -575,26 +600,7 @@ def bind( if result_database_given: self._unresolved_result_database = None - if sources is not None: - # Update bound_source on SourceJobNodes and maintain both dicts. - for h, job_node in (self._persistent_node_map or {}).items(): - if isinstance(job_node, SourceJobNode) and job_node.name in sources: - job_node.bound_source = sources[job_node.name] - self._rebound_source_keys.add(h) - self._sources_by_hash[h] = sources[job_node.name] - # Also index by schema-based hash (matches blueprint pipeline keys). - schema_hash = job_node.as_node().content_hash().to_string() - self._sources_by_hash[schema_hash] = sources[job_node.name] - self._sources.update(sources) - # Every node predicts its schema again (ITL-1111). Since ITL-1112 a bind - # should never change a prediction: ``validate`` refuses a source of other - # column names or types, and the slot gives the declared schema, so this - # clear is expected to find nothing to change. It is kept so that a bind - # can never leave a stale prediction if a bound source's schema ever - # differs in a way the check does not see. - for job_node in (self._persistent_node_map or {}).values(): - if isinstance(job_node, StreamBase): - job_node._forget_output_schema() # pyright: ignore[reportPrivateUsage] # the job owns its nodes' bindings + self._apply_source_bindings(prepared) if execution_context is not None: self._execution_context = execution_context @@ -602,6 +608,56 @@ def bind( if database_changed and self._database is not None: self._distribute_databases() + def _replace_source_binding( + self, slot: SourceJobNode, source: cp.StreamProtocol | None + ) -> None: + """Apply a setter change through the same transaction as bind().""" + self._apply_source_bindings(self._prepare_source_bindings([(slot, source)])) + + def _prepare_source_bindings( + self, rebinding: Rebinding + ) -> list[tuple[SourceJobNode, cp.StreamProtocol | None, _DeclaredForm | None]]: + """Validate the prospective job and prepare each changed slot's row form.""" + nodes = self._persistent_node_map.values() + require_consistent_sources( + ((f"node {node.label!r}", node) for node in nodes), rebinding + ) + prepared = [ + ( + slot, + source, + slot._declared_form_for(source) if source is not None else None, # pyright: ignore[reportPrivateUsage] # validate the exact binding before committing it + ) + for slot, source in rebinding + ] + refuse_restriction_conflicts(nodes, rebinding=rebinding) + return prepared + + def _apply_source_bindings( + self, + prepared: Sequence[ + tuple[SourceJobNode, cp.StreamProtocol | None, _DeclaredForm | None] + ], + ) -> None: + """Commit validated slot replacements and invalidate dependent predictions.""" + if not prepared: + return + keys = {id(node): key for key, node in self._persistent_node_map.items()} + for slot, source, form in prepared: + slot._apply_binding(source, form) # pyright: ignore[reportPrivateUsage] # install the validated row form + slot._update_modified_time() # pyright: ignore[reportPrivateUsage] # the job owns the slot's binding + self._rebound_source_keys.add(keys[id(slot)]) + if source is None: + self._sources.pop(slot.name, None) + else: + self._sources[slot.name] = source + + # A binding preserves the declared schema. Clear predictions anyway so + # that each node reads the schema from its current inputs (ITL-1111). + for node in self._persistent_node_map.values(): + if isinstance(node, StreamBase): + node._forget_output_schema() # pyright: ignore[reportPrivateUsage] # the job owns its nodes' bindings + # ------------------------------------------------------------------ # _distribute_databases() # ------------------------------------------------------------------ @@ -2077,9 +2133,8 @@ def load( sjn = SourceJobNode._from_loaded_slot( # pyright: ignore[reportPrivateUsage] # the loader is the one caller bp_node, bound_source=sources.get(bp_node.name) ) + sjn._set_binding_owner(job) # pyright: ignore[reportPrivateUsage] # loading assigns the job's active slots job._persistent_node_map[node_hash] = sjn - if bp_node.name in sources: - job._sources_by_hash[node_hash] = sources[bp_node.name] elif isinstance(bp_node, _FunctionNode): descriptor = getattr(bp_node, "_descriptor", None) or {} diff --git a/src/orcapod/pipeline/restrictions.py b/src/orcapod/pipeline/restrictions.py index 3679d515f..598004959 100644 --- a/src/orcapod/pipeline/restrictions.py +++ b/src/orcapod/pipeline/restrictions.py @@ -42,10 +42,11 @@ (``source_name``), its condition and its limit.""" -Rebinding: TypeAlias = "Sequence[tuple[SourceJobNode, StreamProtocol]]" +Rebinding: TypeAlias = "Sequence[tuple[SourceJobNode, StreamProtocol | None]]" """The sources a bind is about to bind: ``(slot, source)`` pairs, one per slot of the job that the bind changes. A slot is matched by object identity, never by name: a -source being bound can itself be a slot of another job, of the same name.""" +source being bound can itself be a slot of another job, of the same name. +``None`` unbinds the slot.""" def source_name(source: RootSource) -> str: diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index 1dd1aabb7..b554b8a56 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -42,6 +42,9 @@ def root_source_uses( from orcapod.core.sources.base import RootSource replacements = {id(slot): source for slot, source in rebinding} + resolved_slots = ( + {id(slot) for slot in bound_leaves.values()} if bound_leaves else set() + ) visited: set[tuple[int, bool]] = set() pending = [ (location, stream, bool(bound_leaves)) @@ -53,7 +56,7 @@ def root_source_uses( if key in visited: continue visited.add(key) - if recorded and bound_leaves is not None: + if recorded and bound_leaves is not None and id(stream) not in resolved_slots: slot = bound_leaves.get(stream.content_hash().to_string()) if slot is not None: pending.append((location, slot, False)) @@ -63,7 +66,10 @@ def root_source_uses( elif isinstance(stream, SourceJobNode): bound = replacements.get(id(stream), stream.bound_source) if bound is not None: - pending.append((f"slot {stream.name!r}", bound, False)) + slot_use = f"slot {stream.name!r}" + if location != f"node {stream.label!r}": + slot_use = f"{location} via {slot_use}" + pending.append((slot_use, bound, False)) else: # Loaded nodes can have inputs that could not be reconstructed. upstreams = cast("tuple[StreamProtocol | None, ...]", stream.upstreams) @@ -102,6 +108,8 @@ def require_consistent_sources( Raises: InconsistentSourceError: Naming both locations and how to resolve the conflict. """ + from orcapod.core.sources.derived_source import DerivedSource + by_hash: dict[str, tuple[str, RootSource]] = {} by_id: dict[str, list[tuple[str, RootSource]]] = {} for location, source in root_source_uses(uses, rebinding): @@ -111,10 +119,15 @@ def require_consistent_sources( reuse = "Build the source once and reuse the object" if first.condition.equalities or source.condition.equalities: reuse = "Call where() once and reuse the resulting source object" + remedy = f"{reuse}, or give each source its own source_id." + if any( + isinstance(candidate, DerivedSource) and candidate._tags_as_data is None # pyright: ignore[reportPrivateUsage] # plain derived sources hash only the origin + for candidate in (first, source) + ): + remedy = f"{reuse}." raise InconsistentSourceError( f"Source {source.source_id!r} has distinct source objects with one " - f"content hash in {first_location} and {location}. {reuse}, " - "or give each source its own source_id." + f"content hash in {first_location} and {location}. {remedy}" ) by_id.setdefault(source.source_id, []).append((location, source)) diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index 71d1ba6bf..8fcfea27b 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -1706,14 +1706,13 @@ def test_binding_a_restricted_source_under_a_cache_is_refused( def test_a_slot_rebound_directly_is_refused_when_the_run_starts( self, project, tmp_path, mode, run ): - """A source set on the slot itself (no job to check it) is refused by the - run, sync or async, before any source is read or anything written.""" + """Invalid job state is refused at run time before any reads or writes.""" events = self._events() folder = tmp_path / "store" store = DeltaTableDatabase(folder) job = self._job(store, events) self._cache(job, "rename", mode, store) - job.nodes["events"].bound_source = events.where(subject_id="m1") + job.nodes["events"]._bind(events.where(subject_id="m1")) scans = len(fake_spiral_sdk.scan_log) with pytest.raises(ValueError, match="cannot cache a restricted read"): @@ -1888,8 +1887,8 @@ def test_async_execute_over_a_restricted_slot_is_refused( folder = tmp_path / "s" node = self._logged_node(DeltaTableDatabase(folder), mode) (slot,) = node.upstreams - slot.bound_source = _source(source_id="events", tag_only_columns=True).where( - subject_id="m1" + slot._bind( + _source(source_id="events", tag_only_columns=True).where(subject_id="m1") ) inputs, output = Channel(buffer_size=8), Channel(buffer_size=8) @@ -2119,7 +2118,7 @@ def test_nothing_changes_and_a_second_bind_behaves_alike( store = DeltaTableDatabase(tmp_path / "s") job = TestRestrictionThroughWrappers._cached_job(store, mode) node = job.nodes["rename"] - job.nodes["events"].bound_source = _events().where(subject_id="m1") + job.nodes["events"]._bind(_events().where(subject_id="m1")) before = (job.database, node._pipeline_database) # pyright: ignore[reportPrivateUsage] other = DeltaTableDatabase(tmp_path / "other") @@ -2372,8 +2371,8 @@ def test_a_slot_rebound_directly_is_refused_when_the_run_starts( self, project, other_table, tmp_path, run ): job = self._job(tmp_path, self._others().where(subject_id="m1")) - job.nodes["events"].bound_source = _events().semi_join( - self._others().where(subject_id="m2") + job.nodes["events"]._bind( + _events().semi_join(self._others().where(subject_id="m2")) ) scans = len(fake_spiral_sdk.scan_log) diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index 6274798e1..e14b18f06 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -94,7 +94,7 @@ def _refused( InconsistentSourceError, match="distinct source objects" ) as error: pod(second, label="fb") - for part in (first.source_id, "fa", "fb", "source_id"): + for part in (first.source_id, "fa", "fb", "reuse"): assert part in str(error.value) assert "fb" not in graph.nodes @@ -368,8 +368,8 @@ def test_from_pipeline_checks_the_initial_bind() -> None: ) def test_run_checks_slots_changed_outside_job_bind(orchestrator: type) -> None: job = _job() - job.nodes["left"].bound_source = _dict(1) - job.nodes["right"].bound_source = _dict(100) + job.nodes["left"]._bind(_dict(1)) + job.nodes["right"]._bind(_dict(100)) with pytest.raises(InconsistentSourceError, match="distinct source objects"): job.run(orchestrator=orchestrator()) assert not job.fa.as_table().num_rows @@ -609,18 +609,23 @@ def source(name: str) -> DictSource: def _rebind_outside_bind(job: PipelineJob, right_keys: str | None, x: int) -> None: - job.nodes["left"].bound_source = DictSource( - [{"k": "a", "x": 1}, {"k": "b", "x": 2}], - tag_columns="k", - tag_only_columns=True, - source_id="shared", + # Inject invalid job state to test the run-time checks. + job.nodes["left"]._bind( + DictSource( + [{"k": "a", "x": 1}, {"k": "b", "x": 2}], + tag_columns="k", + tag_only_columns=True, + source_id="shared", + ) ) - job.nodes["right"].bound_source = DictSource( - [{"k": "a", "x": 1}, {"k": "b", "x": x}], - tag_columns="k", - tag_only_columns=True, - record_id_columns=right_keys, - source_id="shared", + job.nodes["right"]._bind( + DictSource( + [{"k": "a", "x": 1}, {"k": "b", "x": x}], + tag_columns="k", + tag_only_columns=True, + record_id_columns=right_keys, + source_id="shared", + ) ) @@ -700,8 +705,8 @@ def test_node_run_checks_its_sources_on_several_columns( ) _ = with_pair.pod(matched, label="fm") # Rebound outside bind, so only the run-time checks can refuse. - job.nodes["left"].bound_source = _arranged(left, "shared", left_keys) - job.nodes["right"].bound_source = _arranged(right, "shared", right_keys, changed) + job.nodes["left"]._bind(_arranged(left, "shared", left_keys)) + job.nodes["right"]._bind(_arranged(right, "shared", right_keys, changed)) with pytest.raises(InconsistentSourceError, match=message): _ = job.run(orchestrator=orchestrator()) for node in ("m", "fm"): diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index a492c3b7e..6aa807b62 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -134,9 +134,9 @@ def test_run_refuses_two_objects_with_one_hash( ) -> None: first, second = _pair(tmp_path, kind, reverse) job = _job(tmp_path) - # Bypass bind to exercise the run-time check independently. - job.nodes["a"].bound_source = first - job.nodes["b"].bound_source = second + # Inject invalid job state to exercise the run-time check independently. + job.nodes["a"]._bind(first) + job.nodes["b"]._bind(second) with pytest.raises( InconsistentSourceError, match="distinct source objects" ) as error: @@ -284,3 +284,281 @@ def test_itl_1554_loading_shared_slots_feeding_the_same_pod(tmp_path: Path) -> N with pytest.raises(NotImplementedError, match="StreamBase.identity_structure"): PipelineJob.load(path, database=db) + + +@pytest.mark.parametrize("kind", ["equal", "different", "csv"]) +def test_slot_setter_refuses_duplicates_and_preserves_bindings( + tmp_path: Path, kind: str +) -> None: + first, second = _pair(tmp_path, kind, False) + job = _job(tmp_path) + job.nodes["a"].bound_source = first + original = job.nodes["b"].bound_source + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + job.nodes["b"].bound_source = second + assert "slot 'a'" in str(error.value) and "slot 'b'" in str(error.value) + assert job.nodes["b"].bound_source is original + assert job.sources["a"] is first + assert job.sources["b"] is original + job.compile() + assert job.nodes["a"].bound_source is first + assert job.nodes["b"].bound_source is original + + +def test_slot_setter_same_hash_replacement_survives_capture(tmp_path: Path) -> None: + first = _source(tmp_path, "dict", "a") + replacement = _source(tmp_path, "dict", "a", change=True) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + total.pod(first, label="first") + job.nodes["a"].bound_source = replacement + with job: + difference.pod(replacement, label="second") + assert job.sources["a"] is replacement + assert job.nodes["a"].bound_source is replacement + job.run() + assert sorted(job.first.as_table()["out"].to_pylist()) == [3, 43] + assert sorted(job.second.as_table()["out"].to_pylist()) == [-37, -1] + + +def test_slot_setter_can_unbind_and_recompile(tmp_path: Path) -> None: + job = _job(tmp_path) + job.nodes["a"].bound_source = None + assert "a" not in job.sources + job.compile() + assert job.nodes["a"].bound_source is None + assert job.unbound_sources == ["a"] + + +@pytest.mark.parametrize("binding", ["constructor", "from_stream", "setter"]) +@pytest.mark.filterwarnings("ignore::orcapod.errors.SemiJoinIgnoredColumnWarning") +def test_source_slot_refuses_composite_with_conflicting_roots( + tmp_path: Path, binding: str +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SemiJoin + + first, second = _pair(tmp_path, "different", False) + composite = SemiJoin()(first, second, label="matched") + slot = SourceJobNode.from_stream(first, name="standalone") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + if binding == "constructor": + SourceJobNode("standalone", bound_source=composite) + elif binding == "from_stream": + SourceJobNode.from_stream(composite, name="standalone") + else: + slot.bound_source = composite + for part in ("slot 'standalone'", "'matched' input 1", "'matched' input 2"): + assert part in str(error.value) + assert slot.bound_source is first + + +def test_coalesced_captures_release_duplicate_projections(tmp_path: Path) -> None: + import gc + from weakref import ref + + source = _source(tmp_path, "dict", "shared") + graph = Pipeline("retention") + + def capture_projection(): + projection = source.select_data_columns(["x", "y"]) + with graph: + _ = total.pod(projection, label="step") + return ref(projection) + + projections = [capture_projection() for _ in range(8)] + _ = gc.collect() + + assert "step" in graph.nodes + assert sum(projection_ref() is not None for projection_ref in projections) <= 2 + + +def test_capture_reports_both_uses_of_slots_with_the_same_name(tmp_path: Path) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + + first, second = _pair(tmp_path, "different", False) + left = SourceJobNode.from_stream(first, name="same") + right = SourceJobNode.from_stream(second, name="same") + with Pipeline("diagnostics"): + total.pod(left, label="first") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + difference.pod(right, label="second") + message = str(error.value) + assert "step 'first'" in message and "step 'second'" in message + + +def test_plain_derived_collision_only_suggests_reusing_the_object( + tmp_path: Path, +) -> None: + job = _job(tmp_path, ("a",)) + job.run() + first = job.result_a.as_source(source_id="left") + second = job.result_a.as_source(source_id="right") + assert first.content_hash() == second.content_hash() + assert first.source_id != second.source_id + + @function_pod(output_keys="answer") + def consume(out: int) -> int: + return out + + with Pipeline("diagnostics"): + consume.pod(first, label="first") + with pytest.raises(InconsistentSourceError, match="reuse the object") as error: + consume.pod(second, label="second") + assert "source_id" not in str(error.value) + + +def test_compile_refuses_schema_conflict_introduced_through_live_slot() -> None: + import pyarrow as pa + + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.sources import ArrowTableSource + + def source(name: str, kind: pa.DataType) -> ArrowTableSource: + return ArrowTableSource( + pa.table({"x": pa.array([1], type=kind), "y": [2]}), + source_id=name, + infer_nullable=True, + ) + + first = SourceJobNode.from_stream(source("shared", pa.int32()), name="same") + second = SourceJobNode.from_stream(source("other", pa.int64()), name="same") + with Pipeline("compile", auto_compile=False) as pipeline: + total.pod(first, label="first") + difference.pod(second, label="second") + second.bound_source = source("shared", pa.int64()) + with pytest.raises(InconsistentSourceError, match="different schemas") as error: + pipeline.compile() + assert "step 'first'" in str(error.value) and "step 'second'" in str(error.value) + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.SemiJoinIgnoredColumnWarning") +def test_source_slot_run_checks_roots_changed_after_binding(tmp_path: Path) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SemiJoin + + first, conflict = _pair(tmp_path, "different", False) + right = SourceJobNode.from_stream(_source(tmp_path, "dict", "other")) + composite = SemiJoin()(first, right, label="matched") + slot = SourceJobNode.from_stream(composite, name="standalone") + right.bound_source = conflict + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + slot.run() + + +@pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) +@pytest.mark.parametrize("bound_first", [False, True]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_capture_after_rebind_requires_the_current_source_object( + tmp_path: Path, setter: bool, bound_first: bool, orchestrator: Orchestrator +) -> None: + original = _source(tmp_path, "dict", "a") + same_original_hash = _source(tmp_path, "dict", "a", reverse=True, change=True) + replacement = _source(tmp_path, "dict", "b", change=True) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + total.pod(original, label="before") + if setter: + job.nodes["a"].bound_source = replacement + else: + job.bind(sources={"a": replacement}) + job.compile() + + with job: + if bound_first: + difference.pod(replacement, label="after") + for retired in (original, same_original_hash): + with pytest.raises(InconsistentSourceError, match="slot 'a'") as error: + product.pod(retired, label="refused") + assert "Pass the source bound there" in str(error.value) + assert "bind" in str(error.value) + if not bound_first: + difference.pod(replacement, label="after") + + assert set(job.sources) == {"a"} + assert set(job.nodes) == {"a", "before", "after"} + job.run(orchestrator=orchestrator()) + assert sorted(job.before.as_table()["out"].to_pylist()) == [3, 43] + assert sorted(job.after.as_table()["out"].to_pylist()) == [-37, -1] + + # Both steps still read the same slot if it is rebound again. + job.bind(sources={"a": original}) + job.compile() + with job: + with pytest.raises(InconsistentSourceError, match="slot 'a'"): + product.pod(replacement, label="also_refused") + job.run(orchestrator=orchestrator()) + assert sorted(job.before.as_table()["out"].to_pylist()) == [3, 7] + assert sorted(job.after.as_table()["out"].to_pylist()) == [-1, -1] + + +WRAPPER_PAIRS = [ + "source-cache", + "two-caches", + "nested-cache", + "two-as-source", + "two-tag-copies", + "source-proxy", + "cache-proxy", +] + + +@pytest.fixture(params=WRAPPER_PAIRS) +def wrapper_pair(tmp_path: Path, request: pytest.FixtureRequest): + from orcapod.core.sources.cached_source import CachedSource + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.databases import DeltaTableDatabase + from orcapod.sources import DerivedSource + + source = _source(tmp_path, "dict", "shared") + kind = request.param + if kind == "two-as-source": + job = _job(tmp_path, ("a",)) + job.run() + first = job.result_a.as_source() + return first, job.result_a.as_source(), first, "out" + if kind == "two-tag-copies": + first = DerivedSource( + source, tags_as_data={"t1": "tag_value"}, source_id="copied" + ) + second = DerivedSource( + source, tags_as_data={"t1": "tag_value"}, source_id="copied" + ) + return first, second, first, "x" + if kind in ("source-proxy", "cache-proxy"): + cache = source.cached(DeltaTableDatabase(tmp_path / "cache")) + proxy = CachedSource.from_config(cache.to_config()).cached_source + assert isinstance(proxy, SourceProxy) + proxy.bind(source) + return source if kind == "source-proxy" else cache, proxy, proxy, "x" + + cache = source.cached(InMemoryArrowDatabase()) + if kind == "source-cache": + return source, cache, cache, "x" + if kind == "two-caches": + return cache, source.cached(InMemoryArrowDatabase()), cache, "x" + return cache, cache.cached(InMemoryArrowDatabase()), cache, "x" + + +def test_wrapper_pairs_with_one_content_hash_are_refused(wrapper_pair) -> None: + first, second, _, column = wrapper_pair + assert first is not second + assert first.content_hash() == second.content_hash() + with Pipeline("wrapper_conflict") as graph: + first.map_data({column: "a"}, label="first") + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + second.map_data({column: "b"}, label="second") + assert "first" in graph.nodes + assert "second" not in graph.nodes + + +def test_one_wrapper_object_can_be_reused(wrapper_pair) -> None: + _, _, shared, column = wrapper_pair + with Pipeline("wrapper_reuse") as graph: + shared.map_data({column: "a"}, label="first") + shared.map_data({column: "b"}, label="second") + assert {"first", "second"} <= graph.nodes.keys() From 4830aca1dfb71c970edded27b946dde15508f333 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 16:28:13 -0800 Subject: [PATCH 22/42] fix(pipeline): validate captures against live source slots --- docs/concepts/sources.md | 17 +- src/orcapod/pipeline/job.py | 104 ++++++++-- src/orcapod/pipeline/source_consistency.py | 14 +- .../test_source_object_registration.py | 189 ++++++++++++++++++ 4 files changed, 295 insertions(+), 29 deletions(-) diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index f02a4a20a..6b1661804 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -88,10 +88,17 @@ Rebinding replaces a slot's source. On load, slots with identical saved source configurations share one reconstructed object. When adding a step to a job after rebinding a slot, pass the source object currently -bound there. Capturing an older object while that slot holds a different object -raises `InconsistentSourceError`. To use the older object again, bind it to the slot -first. ITL-1559 tracks whether a captured source should refer to the object or to the -slot. +bound there. This also applies to sources read through a stream built before +capture. A capture uses the slot that currently holds the supplied source object. +If the object has been replaced and is no longer bound in the job, capturing it +raises `InconsistentSourceError`. Bind it again to use it. ITL-1559 tracks whether a +captured source should refer to the object or to the slot. + +The temporary rule also refuses to reuse a recorded step when its recorded inputs +and the incoming stream point to different slots. This applies when you call the +same pod again and when a stream built before capture has the same hash as a recorded +step. Build a distinct step from the currently bound sources or restore the +recorded bindings. The same rule applies to wrappers. Each of these pairs raises `InconsistentSourceError` when the objects share one content hash. @@ -126,7 +133,7 @@ try: adjust.pod(second, label="second") except InconsistentSourceError as error: print(error) -# Source 'dict_v1:rates' has distinct source objects with one content hash in step 'first' and step 'second'. Build the source once and reuse the object, or give each source its own source_id. +# Source 'dict_v1:rates' has distinct source objects with one content hash in step 'first' and step 'second'. Build the source once and reuse the object. If the source ID contributes to the hash, give each source its own source_id. ``` A kind's version moves when a row read before a change of its implementation could read diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 7e2fcb41c..5d206433b 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -240,46 +240,52 @@ def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse else: yield from recorded if extra is not None: - yield from invocation_source_uses(extra) + candidate = tuple(invocation_source_uses(extra)) + if bound_leaves: + # A prebuilt stream may coalesce with a recorded invocation. + # Check its actual roots before the topology can redirect it. + for _, source in root_source_uses(candidate): + _ = self._capture_input_key(source) + yield from candidate def _capture_input_key(self, stream: cp.StreamProtocol) -> str: """Route a newly captured use of a bound object to its existing slot.""" - stream_key = super()._capture_input_key(stream) - if isinstance(stream, SourceJobNode): + if self._rebound_source_keys or isinstance(stream, SourceJobNode): for key, node in self._persistent_node_map.items(): if node is stream: return key + stream_key = super()._capture_input_key(stream) if not self._rebound_source_keys: return stream_key slot_key = self._captured_slot_keys.get(stream_key, stream_key) slot = self._persistent_node_map.get(slot_key) + if isinstance(slot, SourceJobNode) and slot.bound_source is stream: + return slot_key + for key, node in self._persistent_node_map.items(): + if isinstance(node, SourceJobNode) and node.bound_source is stream: + return key # Stopgap (ITL-1559): refuse to route a new source object to a different # one through the old hash. The follow-up will settle whether capture # refers to the object or to the slot. if isinstance(slot, SourceJobNode): - if ( - slot_key in self._rebound_source_keys - and slot.bound_source is not None - and slot.bound_source is not stream - ): + if slot_key in self._rebound_source_keys and slot.bound_source is not None: raise InconsistentSourceError( f"Capture found distinct source objects for slot {slot.name!r}. " "Pass the source bound there or bind the slot again with job.bind()." ) return slot_key - for key, slot in self._persistent_node_map.items(): - if ( - key in self._rebound_source_keys - and isinstance(slot, SourceJobNode) - and slot.bound_source is stream - ): - return key + if stream_key in self._invocation_lut: + inputs = stream.upstreams + input_keys = tuple(self._capture_input_key(upstream) for upstream in inputs) + self._refuse_reused_invocation(stream_key, inputs, input_keys) return stream_key def _remember_invocation( self, key: str, invocation: PodInvocation, input_keys: tuple[str, ...] ) -> None: """Remember the slot used by each newly captured replacement hash.""" + if self._rebound_source_keys: + self._refuse_reused_invocation(key, invocation.input_streams, input_keys) super()._remember_invocation(key, invocation, input_keys) for stream, slot_key in zip(invocation.input_streams, input_keys, strict=True): if slot_key not in self._rebound_source_keys: @@ -287,9 +293,70 @@ def _remember_invocation( slot = self._persistent_node_map.get(slot_key) if isinstance(slot, SourceJobNode) and slot.bound_source is stream: stream_key = stream.content_hash().to_string() - if stream_key != slot_key: + if ( + stream_key != slot_key + and stream_key not in self._persistent_node_map + ): self._captured_slot_keys[stream_key] = slot_key + def _refuse_reused_invocation( + self, + key: str, + inputs: tuple[cp.StreamProtocol, ...], + input_keys: tuple[str, ...], + ) -> None: + """Apply the ITL-1559 stopgap before reusing a step on different slots.""" + recorded_keys = self._invocation_input_keys.get(key) + if recorded_keys is None or recorded_keys == input_keys: + return + recorded = self._invocation_lut[key] + + def grouped_keys( + streams: tuple[cp.StreamProtocol, ...], keys: tuple[str, ...] + ) -> Any: + """Compare topology keys using the recorded pod's argument symmetry.""" + key_by_object = { + id(stream): name for stream, name in zip(streams, keys, strict=True) + } + + def resolve(group: cp.ArgumentGroup) -> Any: + if isinstance(group, tuple): + return tuple(resolve(member) for member in group) + if isinstance(group, frozenset): + return frozenset(resolve(member) for member in group) + return key_by_object[id(group)] + + return resolve(recorded.pod.argument_symmetry(streams)) + + if len(recorded_keys) == len(input_keys) and grouped_keys( + recorded.input_streams, recorded_keys + ) == grouped_keys(inputs, input_keys): + return + + raise InconsistentSourceError( + f"Cannot reuse a recorded step over {self._capture_slot_names(recorded_keys)} " + f"for inputs bound to {self._capture_slot_names(input_keys)} (ITL-1559). " + "Build a distinct step from the sources as currently bound, or bind back to " + "the recorded sources." + ) + + def _capture_slot_names(self, input_keys: tuple[str, ...]) -> str: + """Describe the source slots under the supplied recorded or candidate keys.""" + pending = list(input_keys) + visited: set[str] = set() + names: set[str] = set() + while pending: + key = pending.pop() + if key in visited: + continue + visited.add(key) + node = self._persistent_node_map.get(key) + if isinstance(node, SourceJobNode): + names.add(f"slot {node.name!r}") + elif key in self._invocation_input_keys: + pending.extend(self._invocation_input_keys[key]) + return ", ".join(sorted(names)) or "unrecorded inputs" + def _source_node_from_recording(self, key: str) -> SourceJobNode: """Preserve an explicit binding when recompiling its slot.""" if key in self._rebound_source_keys: @@ -324,12 +391,17 @@ def compile(self) -> None: for slot in previous_slots: slot._set_binding_owner(None) # pyright: ignore[reportPrivateUsage] # the replaced slot no longer belongs to this job + previous_sources = self._sources self._sources = {} for node in self._persistent_node_map.values(): if isinstance(node, SourceJobNode): node._set_binding_owner(self) # pyright: ignore[reportPrivateUsage] # setters participate in this job's binding transaction if node.bound_source is not None: self._sources[node.name] = node.bound_source + if self._loaded: + # Loaded jobs have no recorded invocations (ITL-1560). Preserve the + # bindings restored from the saved job when recompiling. + self._sources.update(previous_sources) # Invalidate the lazy compiled_pipeline cache. self._compiled_pipeline = None diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index b554b8a56..61b04766a 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -108,8 +108,6 @@ def require_consistent_sources( Raises: InconsistentSourceError: Naming both locations and how to resolve the conflict. """ - from orcapod.core.sources.derived_source import DerivedSource - by_hash: dict[str, tuple[str, RootSource]] = {} by_id: dict[str, list[tuple[str, RootSource]]] = {} for location, source in root_source_uses(uses, rebinding): @@ -119,12 +117,12 @@ def require_consistent_sources( reuse = "Build the source once and reuse the object" if first.condition.equalities or source.condition.equalities: reuse = "Call where() once and reuse the resulting source object" - remedy = f"{reuse}, or give each source its own source_id." - if any( - isinstance(candidate, DerivedSource) and candidate._tags_as_data is None # pyright: ignore[reportPrivateUsage] # plain derived sources hash only the origin - for candidate in (first, source) - ): - remedy = f"{reuse}." + remedy = f"{reuse}." + if first.source_id == source.source_id: + remedy += ( + " If the source ID contributes to the hash, give each source " + "its own source_id." + ) raise InconsistentSourceError( f"Source {source.source_id!r} has distinct source objects with one " f"content hash in {first_location} and {location}. {remedy}" diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index 6aa807b62..c3ddee0d5 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -66,6 +66,16 @@ def _source( ) +def _shifted_source(name: str, offset: int) -> DictSource: + """Build a fixture whose output values distinguish it from other slot bindings.""" + return DictSource( + [{**row, "x": int(row["x"]) + offset} for row in ROWS], + source_id=name, + tag_columns=["t1", "t2"], + tag_only_columns=True, + ) + + def _pair( tmp_path: Path, kind: str, reverse: bool ) -> tuple[DictSource | CSVSource, DictSource | CSVSource]: @@ -562,3 +572,182 @@ def test_one_wrapper_object_can_be_reused(wrapper_pair) -> None: shared.map_data({column: "a"}, label="first") shared.map_data({column: "b"}, label="second") assert {"first", "second"} <= graph.nodes.keys() + + +@function_pod(output_keys="out") +def increment(x: int) -> int: + """Increment the selected input.""" + return x + 1 + + +@function_pod(output_keys="doubled") +def double(out: int) -> int: + """Double the earlier output.""" + return out * 2 + + +@pytest.mark.parametrize("kind", ["select", "join", "function", "cache"]) +@pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +@pytest.mark.filterwarnings("ignore::orcapod.errors.SemiJoinIgnoredColumnWarning") +def test_prebuilt_stream_checks_for_a_retired_root_after_recompile( + tmp_path: Path, kind: str, setter: bool, orchestrator: Orchestrator +) -> None: + from orcapod.operators import SemiJoin + + original = _source(tmp_path, "dict", "a") + replacement = _shifted_source("b", 10) + peer = _source(tmp_path, "dict", "peer") + original_cache = original.cached(InMemoryArrowDatabase()) + consumer = double if kind == "function" else increment + + def build(prebuilt: bool = False): + if kind == "join": + return SemiJoin()(original, peer, label="joined") + if kind == "function": + return increment.pod(original, label="prepared") + source = ( + original + if kind == "select" + else ( + original.cached(InMemoryArrowDatabase()) if prebuilt else original_cache + ) + ) + return source.select_data_columns(["x"], label="selected") + + with PipelineJob(database=InMemoryArrowDatabase()) as job: + recorded = build() + consumer.pod(recorded, label="before") + if setter: + job.nodes["a"].bound_source = replacement + else: + job.bind(sources={"a": replacement}) + job.compile() + + prebuilt = build(prebuilt=True) + assert ( + prebuilt is not recorded and prebuilt.content_hash() == recorded.content_hash() + ) + with job: + with pytest.raises(InconsistentSourceError, match="slot 'a'") as error: + consumer.pod(prebuilt, label="refused") + assert "Pass the source bound there" in str(error.value) + job.run(orchestrator=orchestrator()) + assert "refused" not in job.nodes + column, expected = ( + ("doubled", [24, 28]) if kind == "function" else ("out", [12, 14]) + ) + assert sorted(job.before.as_table()[column].to_pylist()) == expected + + +@pytest.mark.parametrize( + "names", [("a", "b"), ("b", "a"), ("a", "b", "c"), ("c", "b", "a")] +) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_capture_uses_current_source_object_after_swapping_or_rotating_slots( + names: tuple[str, ...], orchestrator: Orchestrator +) -> None: + sources = { + name: _shifted_source(name, 10 * index) for index, name in enumerate(names) + } + with PipelineJob(database=InMemoryArrowDatabase()) as job: + for name, source in sources.items(): + total.pod(source, label=f"original_{name}") + rotated = names[1:] + names[:1] + job.bind( + sources={slot: sources[name] for slot, name in zip(names, rotated, strict=True)} + ) + job.compile() + with job: + for name, source in reversed(sources.items()): + difference.pod(source, label=f"added_{name}") + job.run(orchestrator=orchestrator()) + + assert set(job.sources) == set(names) + for index, name in enumerate(names): + before = job.nodes[f"original_{name}"] + after = job.nodes[f"added_{name}"] + assert sorted(after.as_table()["out"].to_pylist()) == [10 * index - 1] * 2 + offset = 10 * ((index + 1) % len(names)) + assert sorted(before.as_table()["out"].to_pylist()) == [offset + 3, offset + 7] + + +def test_cached_derived_collision_only_suggests_reusing_the_object( + tmp_path: Path, +) -> None: + job = _job(tmp_path, ("a",)) + job.run() + first = job.result_a.as_source(source_id="left").cached(InMemoryArrowDatabase()) + second = job.result_a.as_source(source_id="right").cached(InMemoryArrowDatabase()) + assert first.content_hash() == second.content_hash() + assert first.source_id != second.source_id + with Pipeline("diagnostics"): + first.map_data({"out": "first_out"}, label="first") + with pytest.raises(InconsistentSourceError, match="reuse the object") as error: + second.map_data({"out": "second_out"}, label="second") + assert "source_id" not in str(error.value) + + +@pytest.mark.parametrize("setter", [False, True]) +def test_recompiling_a_loaded_job_preserves_its_sources_mapping( + tmp_path: Path, setter: bool +) -> None: + original = _source(tmp_path, "csv", "a") + replacement = _source(tmp_path, "csv", "b", change=True) + db = InMemoryArrowDatabase() + with PipelineJob(database=db) as job: + total.pod(original, label="before") + job.bind(sources={"a": replacement}) + job.run() + path = tmp_path / "job.json" + job.save(path) + loaded = PipelineJob.load(path, database=db) + if setter: + loaded.nodes["a"].bound_source = original + before = loaded.sources + + loaded.compile() + + assert set(loaded.sources) == set(before) == {"a"} + assert loaded.sources["a"] is before["a"] + + +@pytest.mark.parametrize("prebuilt", [False, True], ids=["same-pod", "prebuilt"]) +@pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_capture_refuses_to_reuse_an_invocation_on_different_slots( + tmp_path: Path, prebuilt: bool, setter: bool, orchestrator: Orchestrator +) -> None: + first = _source(tmp_path, "dict", "a") + second = _shifted_source("b", 10) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + if prebuilt: + increment.pod(first.select_data_columns(["x"]), label="original_a") + else: + total.pod(first, label="original_a") + total.pod(second, label="original_b") + if setter: + job.nodes["a"].bound_source = second + job.nodes["b"].bound_source = first + else: + job.bind(sources={"a": second, "b": first}) + job.compile() + + outside = first.select_data_columns(["x"]) if prebuilt else first + with job: + with pytest.raises(InconsistentSourceError, match="ITL-1559") as error: + if prebuilt: + outside.map_data({"x": "selected"}, label="refused") + else: + total.pod(outside, label="refused") + assert "slot 'a'" in str(error.value) and "slot 'b'" in str(error.value) + assert "currently bound" in str(error.value) + assert "bind back" in str(error.value) + difference.pod(first, label="accepted") + + job.run(orchestrator=orchestrator()) + assert "refused" not in job.nodes + assert sorted(job.original_a.as_table()["out"].to_pylist()) == ( + [12, 14] if prebuilt else [13, 17] + ) + assert sorted(job.accepted.as_table()["out"].to_pylist()) == [-1, -1] From 9971756a68802a327c08b0856e658a46f54ec81a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 16:47:04 -0800 Subject: [PATCH 23/42] fix(pipeline): block capture until source bindings are restored --- .zed/rules | 9 +- CLAUDE.md | 9 +- docs/concepts/sources.md | 21 +- docs/reference/hashing.md | 3 +- src/orcapod/pipeline/base.py | 31 +-- src/orcapod/pipeline/job.py | 168 ++++---------- src/orcapod/pipeline/source_consistency.py | 34 +-- .../test_pipeline/test_source_id_conflicts.py | 20 +- .../test_source_object_registration.py | 206 ++++++++++++++---- 9 files changed, 251 insertions(+), 250 deletions(-) diff --git a/.zed/rules b/.zed/rules index 3dadd2933..903911627 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1513,9 +1513,12 @@ data. The rules: Each source content hash belongs to one source object per pipeline or job (ITL-1469). Capture, compile, binding through either API, loading and running check the sources the graph reads. A slot binding replaces its former source. - Pass the currently bound source when adding a step to a job. A capture of an - older source for the slot is refused while a different object is bound there - (ITL-1559 tracks whether a captured source should refer to the object or the slot). + A job accepts new steps only while every slot holds the exact source object + it held when that slot was first compiled. A slot originally compiled unbound + must be unbound. Rebinding or unbinding a slot blocks recording until all + original bindings are restored. InconsistentSourceError names the changed + slots. Restore the original bindings or build a new job. A job can compile + and run with its replacement bindings. ITL-1559 tracks capture after rebinding. Call where() once and reuse the resulting object. A source object conflict raises InconsistentSourceError before the separate restriction check, which can see restrictions beneath wrappers. diff --git a/CLAUDE.md b/CLAUDE.md index 783f6c6d4..e3cdc7d96 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1561,9 +1561,12 @@ data. The rules: Each source content hash belongs to one source object per pipeline or job (ITL-1469). Capture, compile, binding through either API, loading and running check the sources the graph reads. A slot binding replaces its former source. - Pass the currently bound source when adding a step to a job. A capture of an - older source for the slot is refused while a different object is bound there - (ITL-1559 tracks whether a captured source should refer to the object or the slot). + A job accepts new steps only while every slot holds the exact source object + it held when that slot was first compiled. A slot originally compiled unbound + must be unbound. Rebinding or unbinding a slot blocks recording until all + original bindings are restored. InconsistentSourceError names the changed + slots. Restore the original bindings or build a new job. A job can compile + and run with its replacement bindings. ITL-1559 tracks capture after rebinding. Call where() once and reuse the resulting object. A source object conflict raises InconsistentSourceError before the separate restriction check, which can see restrictions beneath wrappers. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 6b1661804..8c29a02dc 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -87,18 +87,15 @@ rows later. Capture, binding, loading and execution all check for conflicts. Rebinding replaces a slot's source. On load, slots with identical saved source configurations share one reconstructed object. -When adding a step to a job after rebinding a slot, pass the source object currently -bound there. This also applies to sources read through a stream built before -capture. A capture uses the slot that currently holds the supplied source object. -If the object has been replaced and is no longer bound in the job, capturing it -raises `InconsistentSourceError`. Bind it again to use it. ITL-1559 tracks whether a -captured source should refer to the object or to the slot. - -The temporary rule also refuses to reuse a recorded step when its recorded inputs -and the incoming stream point to different slots. This applies when you call the -same pod again and when a stream built before capture has the same hash as a recorded -step. Build a distinct step from the currently bound sources or restore the -recorded bindings. +A job accepts new steps only while every slot holds the exact source object +it held when that slot was first compiled. A slot originally compiled unbound +must be unbound. Rebinding or unbinding a slot blocks recording until all +original bindings are restored. InconsistentSourceError names the changed +slots. Restore the original bindings or build a new job. A job can compile +and run with its replacement bindings. ITL-1559 tracks capture after rebinding. + +Capturing into a loaded job or recompiling it can lose its restored graph +(ITL-1560). Recompilation preserves the loaded job's public `sources` mapping. The same rule applies to wrappers. Each of these pairs raises `InconsistentSourceError` when the objects share one content hash. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 3d6c8132e..25c189491 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -394,7 +394,8 @@ A record id is the row identifier (rule 8), built from row positions or key valu |---|---| | observer events (`node_hash`) | `core/nodes/function_node.py:FunctionJobNode.execute`, `core/nodes/function_node.py:FunctionJobNode.async_execute`, `core/nodes/function_node.py:FunctionJobNode._execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_cache_only`, `core/nodes/operator_node.py:OperatorJobNode.execute`, `core/nodes/operator_node.py:OperatorJobNode.async_execute`, `core/nodes/source_node.py:SourceNodeBase.execute`, `core/nodes/source_node.py:SourceNodeBase.async_execute` | | hooks (`pod_hash`) | `core/function_pod.py:_FunctionPodBase._build_post_run_payload` | -| in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase._record_invocation`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | +| in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase._record_invocation`, `pipeline/base.py:AbstractPipelineBase._record_invocation..`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations..`, `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | +| in-memory source registration keys | `pipeline/source_consistency.py:require_consistent_sources` | | in-memory topological sort of compiled and restored nodes, using the pipeline hash to order ready invocations | `pipeline/base.py:AbstractPipelineBase._ordered_node_map..order_key` | | 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__` | diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index d1c5875fa..a18a3933d 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -4,7 +4,7 @@ import logging from abc import ABC, abstractmethod -from collections.abc import Hashable, Iterator, Mapping +from collections.abc import Hashable, Iterator from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar @@ -350,7 +350,7 @@ def _record_invocation(self, invocation: PodInvocation) -> None: key = invocation.content_hash().to_string() inputs = tuple(invocation.input_streams) - input_keys = tuple(self._capture_input_key(upstream) for upstream in inputs) + input_keys = tuple(upstream.content_hash().to_string() for upstream in inputs) # Checked before anything is recorded, so a refused invocation leaves the # graph as it was. A restriction does not change a source's identity, so the # pipeline keeps one restriction (or none) per source identity, whatever @@ -367,10 +367,6 @@ def _record_invocation(self, invocation: PodInvocation) -> None: if upstream_hash not in self._source_streams: self._source_streams[upstream_hash] = upstream - def _capture_input_key(self, stream: cp.StreamProtocol) -> str: - """Return the topology key for a new use of this stream.""" - return stream.content_hash().to_string() - def _remember_invocation( self, key: str, invocation: PodInvocation, input_keys: tuple[str, ...] ) -> None: @@ -382,26 +378,15 @@ def _remember_invocation( self._invocation_lut[key] = invocation self._invocation_input_keys[key] = input_keys - def _recorded_uses( - self, bound_leaves: Mapping[str, cp.StreamProtocol] - ) -> Iterator[SourceUse]: - """Use the live binding when a recorded input was routed to a replaced slot.""" - # Prefer the labelled endpoint of a chain over an implicit projection. - for key, invocation in reversed(self._invocation_lut.items()): - for (location, stream), input_key in zip( - invocation_source_uses(invocation), - self._invocation_input_keys[key], - strict=True, - ): - yield location, bound_leaves.get(input_key, stream) - for key, stream in self._source_streams.items(): - yield f"source {stream.label!r}", bound_leaves.get(key, stream) - def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse]: """Held inputs and, when supplied, the candidate's inputs before deduplication.""" - yield from self._recorded_uses({}) + # Prefer the labelled endpoint of a chain over an implicit projection. + for invocation in reversed(self._invocation_lut.values()): + yield from invocation_source_uses(invocation) if extra is not None: yield from invocation_source_uses(extra) + for stream in self._source_streams.values(): + yield f"source {stream.label!r}", stream def _source_node_from_recording(self, key: str) -> Any: """Create the source node for a recorded leaf.""" @@ -840,7 +825,7 @@ def from_invocations( for inv in graph.invocations: key = inv.content_hash().to_string() input_keys = tuple( - instance._capture_input_key(up) for up in inv.input_streams + up.content_hash().to_string() for up in inv.input_streams ) instance._remember_invocation(key, inv, input_keys) instance._hash_graph.add_node(key) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 5d206433b..664a73874 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -48,7 +48,6 @@ from orcapod.pipeline.source_consistency import ( invocation_source_uses, require_consistent_sources, - root_source_uses, ) from orcapod.protocols import core_protocols as cp from orcapod.databases.utils import as_table_committing @@ -199,7 +198,7 @@ def __init__( # name → bound concrete source (user-facing API: job.sources). self._sources: dict[str, cp.StreamProtocol] = {} self._rebound_source_keys: set[str] = set() - self._captured_slot_keys: dict[str, str] = {} + self._sources_as_captured: dict[str, cp.StreamProtocol | None] = {} self._has_run: bool = False # True only while the last run started has finished and committed its writes: # what the database then holds for each node is what that run left (ITL-1043). @@ -227,135 +226,46 @@ def __exit__(self, exc_type=None, exc_value=None, traceback=None) -> None: if exc_type is None and self._auto_compile: self.compile() - def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse]: - """Use current bindings for history and check new inputs as supplied.""" - bound_leaves = { - key: slot - for key in self._rebound_source_keys - if isinstance(slot := self._persistent_node_map.get(key), SourceJobNode) - } - recorded = self._recorded_uses(bound_leaves) - if bound_leaves: - yield from root_source_uses(recorded, bound_leaves=bound_leaves) - else: - yield from recorded - if extra is not None: - candidate = tuple(invocation_source_uses(extra)) - if bound_leaves: - # A prebuilt stream may coalesce with a recorded invocation. - # Check its actual roots before the topology can redirect it. - for _, source in root_source_uses(candidate): - _ = self._capture_input_key(source) - yield from candidate - - def _capture_input_key(self, stream: cp.StreamProtocol) -> str: - """Route a newly captured use of a bound object to its existing slot.""" - if self._rebound_source_keys or isinstance(stream, SourceJobNode): - for key, node in self._persistent_node_map.items(): - if node is stream: - return key - stream_key = super()._capture_input_key(stream) - if not self._rebound_source_keys: - return stream_key - slot_key = self._captured_slot_keys.get(stream_key, stream_key) - slot = self._persistent_node_map.get(slot_key) - if isinstance(slot, SourceJobNode) and slot.bound_source is stream: - return slot_key - for key, node in self._persistent_node_map.items(): - if isinstance(node, SourceJobNode) and node.bound_source is stream: - return key - # Stopgap (ITL-1559): refuse to route a new source object to a different - # one through the old hash. The follow-up will settle whether capture - # refers to the object or to the slot. - if isinstance(slot, SourceJobNode): - if slot_key in self._rebound_source_keys and slot.bound_source is not None: - raise InconsistentSourceError( - f"Capture found distinct source objects for slot {slot.name!r}. " - "Pass the source bound there or bind the slot again with job.bind()." - ) - return slot_key - if stream_key in self._invocation_lut: - inputs = stream.upstreams - input_keys = tuple(self._capture_input_key(upstream) for upstream in inputs) - self._refuse_reused_invocation(stream_key, inputs, input_keys) - return stream_key - - def _remember_invocation( - self, key: str, invocation: PodInvocation, input_keys: tuple[str, ...] - ) -> None: - """Remember the slot used by each newly captured replacement hash.""" - if self._rebound_source_keys: - self._refuse_reused_invocation(key, invocation.input_streams, input_keys) - super()._remember_invocation(key, invocation, input_keys) - for stream, slot_key in zip(invocation.input_streams, input_keys, strict=True): - if slot_key not in self._rebound_source_keys: - continue - slot = self._persistent_node_map.get(slot_key) - if isinstance(slot, SourceJobNode) and slot.bound_source is stream: - stream_key = stream.content_hash().to_string() - if ( - stream_key != slot_key - and stream_key not in self._persistent_node_map - ): - self._captured_slot_keys[stream_key] = slot_key - - def _refuse_reused_invocation( - self, - key: str, - inputs: tuple[cp.StreamProtocol, ...], - input_keys: tuple[str, ...], - ) -> None: - """Apply the ITL-1559 stopgap before reusing a step on different slots.""" - recorded_keys = self._invocation_input_keys.get(key) - if recorded_keys is None or recorded_keys == input_keys: - return - recorded = self._invocation_lut[key] - - def grouped_keys( - streams: tuple[cp.StreamProtocol, ...], keys: tuple[str, ...] - ) -> Any: - """Compare topology keys using the recorded pod's argument symmetry.""" - key_by_object = { - id(stream): name for stream, name in zip(streams, keys, strict=True) + def _record_invocation(self, invocation: PodInvocation) -> None: + """Record a step only while every compiled slot has its original binding.""" + # ITL-1559: refuse additive capture until the relationship between captured + # objects and slots is defined. Check at recording so a bind inside an + # open capture context cannot bypass the rule. + changed = sorted( + { + node.name + for key, node in self._persistent_node_map.items() + if isinstance(node, SourceJobNode) + and key in self._sources_as_captured + and node.bound_source is not self._sources_as_captured[key] } - - def resolve(group: cp.ArgumentGroup) -> Any: - if isinstance(group, tuple): - return tuple(resolve(member) for member in group) - if isinstance(group, frozenset): - return frozenset(resolve(member) for member in group) - return key_by_object[id(group)] - - return resolve(recorded.pod.argument_symmetry(streams)) - - if len(recorded_keys) == len(input_keys) and grouped_keys( - recorded.input_streams, recorded_keys - ) == grouped_keys(inputs, input_keys): - return - - raise InconsistentSourceError( - f"Cannot reuse a recorded step over {self._capture_slot_names(recorded_keys)} " - f"for inputs bound to {self._capture_slot_names(input_keys)} (ITL-1559). " - "Build a distinct step from the sources as currently bound, or bind back to " - "the recorded sources." ) + if changed: + names = ", ".join(repr(name) for name in changed) + raise InconsistentSourceError( + f"Cannot record a step because these job slots are not as captured: " + f"{names}. Bind them back to their original objects or build a new " + "job (ITL-1559)." + ) + super()._record_invocation(invocation) - def _capture_slot_names(self, input_keys: tuple[str, ...]) -> str: - """Describe the source slots under the supplied recorded or candidate keys.""" - pending = list(input_keys) - visited: set[str] = set() - names: set[str] = set() - while pending: - key = pending.pop() - if key in visited: + def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse]: + """Validate actual graph leaves after a binding replaces a captured input.""" + if not self._rebound_source_keys: + yield from super()._source_uses(extra) + return + # A recorded operator's Python stream still holds its old upstreams. + # Compilation connects its recorded keys to the job's actual leaves. + for key, stream in self._source_streams.items(): + if key in self._invocation_lut: continue - visited.add(key) - node = self._persistent_node_map.get(key) - if isinstance(node, SourceJobNode): - names.add(f"slot {node.name!r}") - elif key in self._invocation_input_keys: - pending.extend(self._invocation_input_keys[key]) - return ", ".join(sorted(names)) or "unrecorded inputs" + slot = self._persistent_node_map.get(key) + if key in self._rebound_source_keys and isinstance(slot, SourceJobNode): + yield f"node {slot.label!r}", slot + else: + yield f"source {stream.label!r}", stream + if extra is not None: + yield from invocation_source_uses(extra) def _source_node_from_recording(self, key: str) -> SourceJobNode: """Preserve an explicit binding when recompiling its slot.""" @@ -393,8 +303,10 @@ def compile(self) -> None: slot._set_binding_owner(None) # pyright: ignore[reportPrivateUsage] # the replaced slot no longer belongs to this job previous_sources = self._sources self._sources = {} - for node in self._persistent_node_map.values(): + for key, node in self._persistent_node_map.items(): if isinstance(node, SourceJobNode): + if not self._loaded: + self._sources_as_captured.setdefault(key, node.bound_source) node._set_binding_owner(self) # pyright: ignore[reportPrivateUsage] # setters participate in this job's binding transaction if node.bound_source is not None: self._sources[node.name] = node.bound_source diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index 61b04766a..167152ab3 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -2,14 +2,13 @@ from __future__ import annotations -from collections.abc import Iterable, Mapping +from collections.abc import Iterable from typing import TYPE_CHECKING, cast from orcapod.errors import InconsistentSourceError from orcapod.utils.schema_utils import arrow_schema_identity if TYPE_CHECKING: - from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources.base import RootSource from orcapod.pipeline.pod_invocation import PodInvocation from orcapod.pipeline.restrictions import Rebinding @@ -34,33 +33,20 @@ def invocation_source_uses(invocation: PodInvocation) -> Iterable[SourceUse]: def root_source_uses( uses: Iterable[SourceUse], rebinding: Rebinding = (), - *, - bound_leaves: Mapping[str, SourceJobNode] | None = None, ) -> Iterable[tuple[str, RootSource]]: - """Walk to each source object, using live bindings for replaced graph leaves.""" + """Walk to each source object, using prospective bindings for replaced slots.""" from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources.base import RootSource replacements = {id(slot): source for slot, source in rebinding} - resolved_slots = ( - {id(slot) for slot in bound_leaves.values()} if bound_leaves else set() - ) - visited: set[tuple[int, bool]] = set() - pending = [ - (location, stream, bool(bound_leaves)) - for location, stream in reversed(list(uses)) - ] + visited: set[int] = set() + pending = list(uses) + pending.reverse() while pending: - location, stream, recorded = pending.pop() - key = (id(stream), recorded) - if key in visited: + location, stream = pending.pop() + if id(stream) in visited: continue - visited.add(key) - if recorded and bound_leaves is not None and id(stream) not in resolved_slots: - slot = bound_leaves.get(stream.content_hash().to_string()) - if slot is not None: - pending.append((location, slot, False)) - continue + visited.add(id(stream)) if isinstance(stream, RootSource): yield location, stream elif isinstance(stream, SourceJobNode): @@ -69,7 +55,7 @@ def root_source_uses( slot_use = f"slot {stream.name!r}" if location != f"node {stream.label!r}": slot_use = f"{location} via {slot_use}" - pending.append((slot_use, bound, False)) + pending.append((slot_use, bound)) else: # Loaded nodes can have inputs that could not be reconstructed. upstreams = cast("tuple[StreamProtocol | None, ...]", stream.upstreams) @@ -79,7 +65,7 @@ def root_source_uses( upstream_location = location if len(upstreams) > 1: upstream_location += f", {stream.label!r} input {index + 1}" - pending.append((upstream_location, upstream, recorded)) + pending.append((upstream_location, upstream)) def _comparison_schema(source: RootSource) -> tuple[ContentHash, ContentHash]: diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index e14b18f06..f3c489d19 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -376,7 +376,7 @@ def test_run_checks_slots_changed_outside_job_bind(orchestrator: type) -> None: assert not job.fb.as_table().num_rows -def test_additive_recording_uses_the_current_binding() -> None: +def test_additive_recording_resumes_when_original_binding_is_restored() -> None: original = _dict(1) with PipelineJob(database=InMemoryArrowDatabase()) as job: increment.pod(original, label="fa") @@ -384,16 +384,18 @@ def test_additive_recording_uses_the_current_binding() -> None: replacement = _dict(100) job.bind(sources={"shared": replacement}) with job: - with pytest.raises(InconsistentSourceError, match="distinct source objects"): - increment.pod(original, label="conflict") - increment_again.pod(replacement, label="replacement") - consume_output.pod(job.fa, label="next") - - assert job.nodes["shared"].bound_source is replacement + with pytest.raises(InconsistentSourceError, match="not as captured"): + consume_output.pod(job.fa, label="conflict") job.run() assert job.fa.as_table()["out"].to_pylist() == [101] - assert job.replacement.as_table()["out"].to_pylist() == [102] - assert job.next.as_table()["next"].to_pylist() == [202] + + job.bind(sources={"shared": original}) + with job: + consume_output.pod(job.fa, label="next") + job.run() + assert "conflict" not in job.nodes + assert job.fa.as_table()["out"].to_pylist() == [2] + assert job.next.as_table()["next"].to_pylist() == [4] def test_load_checks_schema_of_reconstructed_sources(tmp_path: Path) -> None: diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index c3ddee0d5..8f35a23d3 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -12,6 +12,7 @@ from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import InconsistentSourceError from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.protocols.core_protocols import StreamProtocol from orcapod.sources import CSVSource, DictSource Orchestrator = type[AsyncPipelineOrchestrator] | type[SyncPipelineOrchestrator] @@ -93,6 +94,14 @@ def _job(tmp_path: Path, slots: tuple[str, ...] = ("a", "b")) -> PipelineJob: return job +def _rebind(job: PipelineJob, sources: dict[str, StreamProtocol], setter: bool) -> None: + if setter: + for name, source in sources.items(): + job.nodes[name].bound_source = source + else: + job.bind(sources=sources) + + @pytest.mark.parametrize("reverse", [False, True]) @pytest.mark.parametrize("kind", ["equal", "different", "csv"]) @pytest.mark.parametrize("graph_type", [Pipeline, PipelineJob]) @@ -317,19 +326,22 @@ def test_slot_setter_refuses_duplicates_and_preserves_bindings( assert job.nodes["b"].bound_source is original -def test_slot_setter_same_hash_replacement_survives_capture(tmp_path: Path) -> None: +def test_slot_setter_same_hash_replacement_blocks_capture_but_runs( + tmp_path: Path, +) -> None: first = _source(tmp_path, "dict", "a") replacement = _source(tmp_path, "dict", "a", change=True) with PipelineJob(database=InMemoryArrowDatabase()) as job: total.pod(first, label="first") job.nodes["a"].bound_source = replacement with job: - difference.pod(replacement, label="second") + with pytest.raises(InconsistentSourceError, match="not as captured"): + difference.pod(replacement, label="second") + assert "second" not in job.nodes assert job.sources["a"] is replacement assert job.nodes["a"].bound_source is replacement job.run() assert sorted(job.first.as_table()["out"].to_pylist()) == [3, 43] - assert sorted(job.second.as_table()["out"].to_pylist()) == [-37, -1] def test_slot_setter_can_unbind_and_recompile(tmp_path: Path) -> None: @@ -462,46 +474,36 @@ def test_source_slot_run_checks_roots_changed_after_binding(tmp_path: Path) -> N @pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) -@pytest.mark.parametrize("bound_first", [False, True]) @pytest.mark.parametrize("orchestrator", ORCHESTRATORS) -def test_capture_after_rebind_requires_the_current_source_object( - tmp_path: Path, setter: bool, bound_first: bool, orchestrator: Orchestrator +def test_binding_back_the_captured_object_restores_capture_and_rows( + tmp_path: Path, setter: bool, orchestrator: Orchestrator ) -> None: original = _source(tmp_path, "dict", "a") - same_original_hash = _source(tmp_path, "dict", "a", reverse=True, change=True) + another_object = _source(tmp_path, "dict", "a", reverse=True, change=True) replacement = _source(tmp_path, "dict", "b", change=True) with PipelineJob(database=InMemoryArrowDatabase()) as job: total.pod(original, label="before") - if setter: - job.nodes["a"].bound_source = replacement - else: - job.bind(sources={"a": replacement}) - job.compile() + # Bind inside an open capture context so the check must run when recording. with job: - if bound_first: - difference.pod(replacement, label="after") - for retired in (original, same_original_hash): - with pytest.raises(InconsistentSourceError, match="slot 'a'") as error: - product.pod(retired, label="refused") - assert "Pass the source bound there" in str(error.value) - assert "bind" in str(error.value) - if not bound_first: - difference.pod(replacement, label="after") - - assert set(job.sources) == {"a"} - assert set(job.nodes) == {"a", "before", "after"} + _rebind(job, {"a": replacement}, setter) + for candidate in (replacement, original, another_object): + with pytest.raises( + InconsistentSourceError, match="not as captured" + ) as error: + difference.pod(candidate, label="refused") + assert "'a'" in str(error.value) + assert "ITL-1559" in str(error.value) + assert "Bind" in str(error.value) and "new job" in str(error.value) job.run(orchestrator=orchestrator()) assert sorted(job.before.as_table()["out"].to_pylist()) == [3, 43] - assert sorted(job.after.as_table()["out"].to_pylist()) == [-37, -1] - # Both steps still read the same slot if it is rebound again. - job.bind(sources={"a": original}) + _rebind(job, {"a": original}, setter) job.compile() with job: - with pytest.raises(InconsistentSourceError, match="slot 'a'"): - product.pod(replacement, label="also_refused") + difference.pod(original, label="after") job.run(orchestrator=orchestrator()) + assert set(job.nodes) == {"a", "before", "after"} assert sorted(job.before.as_table()["out"].to_pylist()) == [3, 7] assert sorted(job.after.as_table()["out"].to_pylist()) == [-1, -1] @@ -590,7 +592,7 @@ def double(out: int) -> int: @pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) @pytest.mark.parametrize("orchestrator", ORCHESTRATORS) @pytest.mark.filterwarnings("ignore::orcapod.errors.SemiJoinIgnoredColumnWarning") -def test_prebuilt_stream_checks_for_a_retired_root_after_recompile( +def test_rebound_job_refuses_prebuilt_streams_after_recompile( tmp_path: Path, kind: str, setter: bool, orchestrator: Orchestrator ) -> None: from orcapod.operators import SemiJoin @@ -629,9 +631,9 @@ def build(prebuilt: bool = False): prebuilt is not recorded and prebuilt.content_hash() == recorded.content_hash() ) with job: - with pytest.raises(InconsistentSourceError, match="slot 'a'") as error: + with pytest.raises(InconsistentSourceError, match="not as captured") as error: consumer.pod(prebuilt, label="refused") - assert "Pass the source bound there" in str(error.value) + assert "'a'" in str(error.value) job.run(orchestrator=orchestrator()) assert "refused" not in job.nodes column, expected = ( @@ -643,9 +645,10 @@ def build(prebuilt: bool = False): @pytest.mark.parametrize( "names", [("a", "b"), ("b", "a"), ("a", "b", "c"), ("c", "b", "a")] ) +@pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) @pytest.mark.parametrize("orchestrator", ORCHESTRATORS) -def test_capture_uses_current_source_object_after_swapping_or_rotating_slots( - names: tuple[str, ...], orchestrator: Orchestrator +def test_swapping_or_rotating_slots_blocks_capture_but_preserves_rows( + names: tuple[str, ...], setter: bool, orchestrator: Orchestrator ) -> None: sources = { name: _shifted_source(name, 10 * index) for index, name in enumerate(names) @@ -654,23 +657,42 @@ def test_capture_uses_current_source_object_after_swapping_or_rotating_slots( for name, source in sources.items(): total.pod(source, label=f"original_{name}") rotated = names[1:] + names[:1] - job.bind( - sources={slot: sources[name] for slot, name in zip(names, rotated, strict=True)} + _rebind( + job, + {slot: sources[name] for slot, name in zip(names, rotated, strict=True)}, + setter, ) job.compile() with job: - for name, source in reversed(sources.items()): - difference.pod(source, label=f"added_{name}") + for source in reversed(sources.values()): + with pytest.raises( + InconsistentSourceError, match="not as captured" + ) as error: + difference.pod(source, label="added") + assert all(repr(name) in str(error.value) for name in names) job.run(orchestrator=orchestrator()) + assert "added" not in job.nodes assert set(job.sources) == set(names) for index, name in enumerate(names): before = job.nodes[f"original_{name}"] - after = job.nodes[f"added_{name}"] - assert sorted(after.as_table()["out"].to_pylist()) == [10 * index - 1] * 2 offset = 10 * ((index + 1) % len(names)) assert sorted(before.as_table()["out"].to_pylist()) == [offset + 3, offset + 7] + restored, *still_changed = names + _rebind(job, {restored: sources[restored]}, setter) + with job: + with pytest.raises(InconsistentSourceError, match="not as captured") as error: + difference.pod(sources[restored], label="added") + assert repr(restored) not in str(error.value) + assert all(repr(name) in str(error.value) for name in still_changed) + + _rebind(job, {name: sources[name] for name in still_changed}, setter) + with job: + difference.pod(sources[restored], label="added") + job.run(orchestrator=orchestrator()) + assert sorted(job.added.as_table()["out"].to_pylist()) == [-1, -1] + def test_cached_derived_collision_only_suggests_reusing_the_object( tmp_path: Path, @@ -715,7 +737,7 @@ def test_recompiling_a_loaded_job_preserves_its_sources_mapping( @pytest.mark.parametrize("prebuilt", [False, True], ids=["same-pod", "prebuilt"]) @pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) @pytest.mark.parametrize("orchestrator", ORCHESTRATORS) -def test_capture_refuses_to_reuse_an_invocation_on_different_slots( +def test_rebound_job_refuses_same_pod_or_prebuilt_recapture( tmp_path: Path, prebuilt: bool, setter: bool, orchestrator: Orchestrator ) -> None: first = _source(tmp_path, "dict", "a") @@ -735,19 +757,109 @@ def test_capture_refuses_to_reuse_an_invocation_on_different_slots( outside = first.select_data_columns(["x"]) if prebuilt else first with job: - with pytest.raises(InconsistentSourceError, match="ITL-1559") as error: + with pytest.raises(InconsistentSourceError, match="not as captured") as error: if prebuilt: outside.map_data({"x": "selected"}, label="refused") else: total.pod(outside, label="refused") - assert "slot 'a'" in str(error.value) and "slot 'b'" in str(error.value) - assert "currently bound" in str(error.value) - assert "bind back" in str(error.value) - difference.pod(first, label="accepted") + assert "'a'" in str(error.value) and "'b'" in str(error.value) job.run(orchestrator=orchestrator()) assert "refused" not in job.nodes assert sorted(job.original_a.as_table()["out"].to_pylist()) == ( [12, 14] if prebuilt else [13, 17] ) - assert sorted(job.accepted.as_table()["out"].to_pylist()) == [-1, -1] + + +@pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_unbound_slot_blocks_prebuilt_capture_and_later_binding_still_runs( + setter: bool, orchestrator: Orchestrator +) -> None: + original, replacement, later = ( + _shifted_source(name, offset) + for name, offset in (("a", 0), ("b", 10), ("c", 20)) + ) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + recorded = increment.pod(original, label="before") + _rebind(job, {"a": replacement}, setter) + job.nodes["a"].bound_source = None + job.compile() + + prebuilt = increment.pod(original) + assert prebuilt.content_hash() == recorded.content_hash() + with job: + with pytest.raises(InconsistentSourceError, match="not as captured") as error: + double.pod(prebuilt, label="refused") + assert "'a'" in str(error.value) + _rebind(job, {"a": later}, setter) + job.compile() + job.run(orchestrator=orchestrator()) + assert "refused" not in job.nodes + assert sorted(job.before.as_table()["out"].to_pylist()) == [22, 24] + + +@pytest.mark.parametrize("use_slot", [False, True], ids=["composite", "slot"]) +@pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_current_composite_binding_blocks_capture_but_preserves_rows( + use_slot: bool, setter: bool, orchestrator: Orchestrator +) -> None: + first, second, replacement = ( + _shifted_source(name, offset) + for name, offset in (("a", 0), ("b", 10), ("c", 20)) + ) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + total.pod(first, label="first") + difference.pod(second, label="second") + composite = first.select_data_columns(["x", "y"]) + _rebind(job, {"a": replacement, "b": composite}, setter) + job.compile() + + assert job.sources["b"] is composite + with job: + with pytest.raises(InconsistentSourceError, match="not as captured") as error: + product.pod(job.nodes["b"] if use_slot else composite, label="refused") + assert "'a'" in str(error.value) and "'b'" in str(error.value) + job.run(orchestrator=orchestrator()) + assert "refused" not in job.nodes + assert sorted(job.first.as_table()["out"].to_pylist()) == [23, 27] + assert sorted(job.second.as_table()["out"].to_pylist()) == [-1, -1] + + +@pytest.mark.parametrize( + "wrapped_slot", [False, True], ids=["prebuilt", "source-job-node"] +) +@pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) +def test_capture_uses_the_binding_of_the_first_compiled_slot( + wrapped_slot: bool, setter: bool +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + + source = _shifted_source("a", 0) + original = source.select_data_columns(["x", "y"]) + recorded = ( + SourceJobNode.from_stream(original, name="slot") if wrapped_slot else original + ) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + total.pod(recorded, label="before") + (name,) = job.sources + assert job.sources[name] is original + + replacement = source.select_data_columns(["x", "y"]) + assert ( + replacement is not original + and replacement.content_hash() == original.content_hash() + ) + _rebind(job, {name: replacement}, setter) + job.compile() + with job: + with pytest.raises(InconsistentSourceError, match="not as captured") as error: + difference.pod(replacement, label="refused") + assert repr(name) in str(error.value) + + _rebind(job, {name: original}, setter) + with job: + difference.pod(original, label="after") + job.run() + assert sorted(job.after.as_table()["out"].to_pylist()) == [-1, -1] From 244f5b6c52992b5787aadd00446c3ead2512d223 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 16:59:28 -0800 Subject: [PATCH 24/42] fix(pipeline): make slot capture stable and atomic --- changelog.d/ITL-1469.md | 3 + docs/concepts/sources.md | 4 + docs/reference/hashing.md | 2 +- src/orcapod/core/tracker.py | 38 +++++++-- src/orcapod/pipeline/base.py | 25 ++++-- src/orcapod/pipeline/job.py | 23 ++++- .../protocols/core_protocols/trackers.py | 22 ++++- .../test_spiraldb_table_source_where.py | 44 +++++----- .../test_source_object_registration.py | 84 ++++++++++++++++++- 9 files changed, 199 insertions(+), 46 deletions(-) diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index f22dce42a..0bcddbc70 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -7,6 +7,9 @@ object across slots with identical source configurations. - Sources with the same source ID must agree on their Arrow schema and key columns, including when they occupy different slots. +- Capturing another job's source slot or a standalone slot keeps the source + object held at capture time. A capture refused by any active pipeline or job + leaves all their graphs unchanged. ### Known limitations diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 8c29a02dc..b219ffed9 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -94,6 +94,10 @@ original bindings are restored. InconsistentSourceError names the changed slots. Restore the original bindings or build a new job. A job can compile and run with its replacement bindings. ITL-1559 tracks capture after rebinding. +When a job captures another job's source slot or a standalone source slot, it +takes the source object bound to that slot at capture time. Later changes to the +supplying slot leave the receiving job's binding alone. + Capturing into a loaded job or recompiling it can lose its restored graph (ITL-1560). Recompilation preserves the loaded job's public `sources` mapping. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 25c189491..6c119ff9e 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -394,7 +394,7 @@ A record id is the row identifier (rule 8), built from row positions or key valu |---|---| | observer events (`node_hash`) | `core/nodes/function_node.py:FunctionJobNode.execute`, `core/nodes/function_node.py:FunctionJobNode.async_execute`, `core/nodes/function_node.py:FunctionJobNode._execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_cache_only`, `core/nodes/operator_node.py:OperatorJobNode.execute`, `core/nodes/operator_node.py:OperatorJobNode.async_execute`, `core/nodes/source_node.py:SourceNodeBase.execute`, `core/nodes/source_node.py:SourceNodeBase.async_execute` | | hooks (`pod_hash`) | `core/function_pod.py:_FunctionPodBase._build_post_run_payload` | -| in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase._record_invocation`, `pipeline/base.py:AbstractPipelineBase._record_invocation..`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations..`, `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | +| in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase.prepare_invocation`, `pipeline/base.py:AbstractPipelineBase.prepare_invocation..`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations..`, `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | | in-memory source registration keys | `pipeline/source_consistency.py:require_consistent_sources` | | in-memory topological sort of compiled and restored nodes, using the pipeline hash to order ready invocations | `pipeline/base.py:AbstractPipelineBase._ordered_node_map..order_key` | | 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..` | diff --git a/src/orcapod/core/tracker.py b/src/orcapod/core/tracker.py index 16ecb1803..677587854 100644 --- a/src/orcapod/core/tracker.py +++ b/src/orcapod/core/tracker.py @@ -1,12 +1,16 @@ from __future__ import annotations from abc import ABC, abstractmethod -from collections.abc import Generator +from collections.abc import Callable, Generator from contextlib import contextmanager -from typing import Any +from functools import partial +from typing import TYPE_CHECKING, Any from orcapod.protocols import core_protocols as cp +if TYPE_CHECKING: + from orcapod.pipeline.pod_invocation import PodInvocation + class BasicTrackerManager: def __init__(self) -> None: @@ -35,13 +39,14 @@ def get_active_trackers(self) -> list[cp.TrackerProtocol]: def record_operator_pod_invocation( self, - pod: cp.PodProtocol, + pod: cp.OperatorPodProtocol, upstreams: tuple[cp.StreamProtocol, ...] = (), label: str | None = None, ) -> None: """Record the invocation of a pod in the tracker.""" - for tracker in self.get_active_trackers(): - tracker.record_operator_pod_invocation(pod, upstreams, label=label) + from orcapod.pipeline.pod_invocation import OperatorInvocation + + self._record(partial(OperatorInvocation, pod, upstreams, label)) def record_function_pod_invocation( self, @@ -50,8 +55,9 @@ def record_function_pod_invocation( label: str | None = None, ) -> None: """Record the invocation of a data function to the tracker.""" - for tracker in self.get_active_trackers(): - tracker.record_function_pod_invocation(pod, input_stream, label=label) + from orcapod.pipeline.pod_invocation import FunctionInvocation + + self._record(partial(FunctionInvocation, pod, (input_stream,), label)) def record_side_effect_pod_invocation( self, @@ -60,8 +66,19 @@ def record_side_effect_pod_invocation( label: str | None = None, ) -> None: """Record a side-effect pod invocation in all active trackers.""" - for tracker in self.get_active_trackers(): - tracker.record_side_effect_pod_invocation(pod, input_stream, label=label) + from orcapod.pipeline.pod_invocation import SideEffectInvocation + + self._record(partial(SideEffectInvocation, pod, (input_stream,), label)) + + def _record(self, make_invocation: Callable[[], PodInvocation]) -> None: + """Prepare every active tracker's recording before committing in order.""" + trackers = self.get_active_trackers() + if not trackers: + return + invocation = make_invocation() + recordings = [tracker.prepare_invocation(invocation) for tracker in trackers] + for record in recordings: + record() @contextmanager def no_tracking(self) -> Generator[None, Any, None]: @@ -90,6 +107,9 @@ def set_active(self, active: bool = True) -> None: def is_active(self) -> bool: return self._active + @abstractmethod + def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: ... + @abstractmethod def record_operator_pod_invocation( self, diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index a18a3933d..24b769227 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -4,7 +4,7 @@ import logging from abc import ABC, abstractmethod -from collections.abc import Hashable, Iterator +from collections.abc import Callable, Hashable, Iterator from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar @@ -319,7 +319,10 @@ def record_side_effect_pod_invocation( ) def _record_invocation(self, invocation: PodInvocation) -> None: - """Store *invocation* and update the topology graph. + self.prepare_invocation(invocation)() + + def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: + """Validate *invocation* and prepare to update the topology graph. Non-source nodes in ``_persistent_node_map`` are keyed by the corresponding ``PodInvocation.content_hash()`` string. For @@ -340,6 +343,9 @@ def _record_invocation(self, invocation: PodInvocation) -> None: Args: invocation: The pod invocation to record. + Returns: + A callback that records the validated invocation. + Raises: ValueError: If the invocation reads a source under another restriction than the pipeline's streams read it under now, or two of its inputs @@ -360,12 +366,15 @@ def _record_invocation(self, invocation: PodInvocation) -> None: uses = tuple(self._source_uses(invocation)) require_consistent_sources(uses) require_one_restriction(stream for _, stream in uses) - self._remember_invocation(key, invocation, input_keys) - self._hash_graph.add_node(key) - for upstream, upstream_hash in zip(inputs, input_keys, strict=True): - self._hash_graph.add_edge(upstream_hash, key) - if upstream_hash not in self._source_streams: - self._source_streams[upstream_hash] = upstream + + def record() -> None: + self._remember_invocation(key, invocation, input_keys) + self._hash_graph.add_node(key) + for upstream, upstream_hash in zip(inputs, input_keys, strict=True): + self._hash_graph.add_edge(upstream_hash, key) + self._source_streams.setdefault(upstream_hash, upstream) + + return record def _remember_invocation( self, key: str, invocation: PodInvocation, input_keys: tuple[str, ...] diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 664a73874..468dd25ec 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -6,7 +6,7 @@ import enum import logging import sys -from collections.abc import Iterator, Sequence +from collections.abc import Callable, Iterator, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast @@ -226,8 +226,8 @@ def __exit__(self, exc_type=None, exc_value=None, traceback=None) -> None: if exc_type is None and self._auto_compile: self.compile() - def _record_invocation(self, invocation: PodInvocation) -> None: - """Record a step only while every compiled slot has its original binding.""" + def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: + """Prepare a step only while every compiled slot has its original binding.""" # ITL-1559: refuse additive capture until the relationship between captured # objects and slots is defined. Check at recording so a bind inside an # open capture context cannot bypass the rule. @@ -247,7 +247,22 @@ def _record_invocation(self, invocation: PodInvocation) -> None: f"{names}. Bind them back to their original objects or build a new " "job (ITL-1559)." ) - super()._record_invocation(invocation) + if any( + isinstance(stream, SourceJobNode) for stream in invocation.input_streams + ): + # Each job owns its slots. Keep the binding at capture, even if the + # supplying slot changes before this job first compiles. + invocation = type(invocation)( + pod=invocation.pod, + input_streams=tuple( + SourceJobNode.from_stream(stream) + if isinstance(stream, SourceJobNode) + else stream + for stream in invocation.input_streams + ), + label=invocation.label, + ) + return super().prepare_invocation(invocation) def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse]: """Validate actual graph leaves after a binding replaces a captured input.""" diff --git a/src/orcapod/protocols/core_protocols/trackers.py b/src/orcapod/protocols/core_protocols/trackers.py index 614dd87e5..a1f36b65e 100644 --- a/src/orcapod/protocols/core_protocols/trackers.py +++ b/src/orcapod/protocols/core_protocols/trackers.py @@ -1,11 +1,17 @@ +from __future__ import annotations + +from collections.abc import Callable from contextlib import AbstractContextManager -from typing import Protocol, runtime_checkable +from typing import TYPE_CHECKING, Protocol, runtime_checkable from orcapod.protocols.core_protocols.function_pod import FunctionPodProtocol from orcapod.protocols.core_protocols.operator_pod import OperatorPodProtocol from orcapod.protocols.core_protocols.side_effect_pod import SideEffectPodProtocol from orcapod.protocols.core_protocols.streams import StreamProtocol +if TYPE_CHECKING: + from orcapod.pipeline.pod_invocation import PodInvocation + @runtime_checkable class TrackerProtocol(Protocol): @@ -50,6 +56,20 @@ def is_active(self) -> bool: """ ... + def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: + """Validate an invocation without recording it. + + All checks that can refuse an invocation belong here. The manager calls + the returned callbacks only after every active tracker has accepted. + + Args: + invocation: The pod and inputs to record. + + Returns: + A callback that records the validated invocation. + """ + ... + def record_operator_pod_invocation( self, pod: OperatorPodProtocol, diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index 8fcfea27b..7a2fef702 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -2245,12 +2245,7 @@ def test_one_restriction_through_two_chains_is_accepted( class TestRestrictionsCheckedLive: - """The one-restriction rule reads what each stream reads now (CodeRabbit, PR 435). - - A slot rebound during the capture changes what the streams recorded from it read, - so nothing is kept from an earlier check: every invocation checks every stream - the pipeline holds with its own inputs, and compilation checks them again. - """ + """Restriction checks use the binding captured by the receiving job.""" @staticmethod def _slot(source: Any) -> Any: @@ -2259,11 +2254,9 @@ def _slot(source: Any) -> Any: return SourceJobNode.from_stream(source) @pytest.mark.parametrize("step", ["select", "drop"]) - def test_a_slot_rebound_between_invocations_is_refused_at_the_next( + def test_a_foreign_slot_rebound_between_invocations_keeps_its_captured_source( self, project, tmp_path, step ): - """A projection from a slot bound to m1, the slot rebound to m2, then a - projection from the m1 source: compiled, both would read m2's rows.""" m1 = _events().where(subject_id="m1") slot = self._slot(m1) later = { @@ -2271,25 +2264,27 @@ def test_a_slot_rebound_between_invocations_is_refused_at_the_next( "drop": lambda s: s.drop_data_columns(["note"]), }[step] job = PipelineJob(name="live", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(InconsistentSourceError, match="distinct source objects"): - with job: - MapData({"channel": "lane"})(slot) - slot.bound_source = _events().where(subject_id="m2") - later(m1) + with job: + MapData({"channel": "lane"})(slot) + slot.bound_source = _events().where(subject_id="m2") + later(m1) + assert job.sources["events"] is m1 + assert job.run().conditions == {"events": Condition.of(subject_id="m1")} - def test_a_slot_rebound_after_the_last_invocation_is_refused_at_compile( + def test_a_foreign_slot_rebound_before_compile_keeps_its_captured_source( self, project, tmp_path ): m1 = _events().where(subject_id="m1") slot = self._slot(m1) job = PipelineJob(name="live", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(InconsistentSourceError, match="distinct source objects"): - with job: - MapData({"channel": "lane"})(slot) - m1.select_data_columns(["amplitude"]) - slot.bound_source = _events().where(subject_id="m2") + with job: + MapData({"channel": "lane"})(slot) + m1.select_data_columns(["amplitude"]) + slot.bound_source = _events().where(subject_id="m2") + assert job.sources["events"] is m1 + assert job.run().conditions == {"events": Condition.of(subject_id="m1")} - def test_a_slot_rebound_to_an_equal_restriction_is_accepted( + def test_an_equal_restriction_on_a_rebound_foreign_slot_conflicts_with_the_capture( self, project, tmp_path ): m1 = _events().where(subject_id="m1") @@ -2299,7 +2294,12 @@ def test_a_slot_rebound_to_an_equal_restriction_is_accepted( MapData({"channel": "lane"})(slot) replacement = _events().where(subject_id="m1") slot.bound_source = replacement - replacement.select_data_columns(["amplitude"]) + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): + replacement.select_data_columns(["amplitude"]) + m1.select_data_columns(["amplitude"]) + assert job.sources["events"] is m1 assert job.run().conditions == {"events": Condition.of(subject_id="m1")} diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index 8f35a23d3..cba1cee8a 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -8,11 +8,12 @@ import pytest -from orcapod import Pipeline, PipelineJob, function_pod +from orcapod import Pipeline, PipelineJob, function_pod, side_effect_pod from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import InconsistentSourceError from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.side_effects import SideEffectPod from orcapod.sources import CSVSource, DictSource Orchestrator = type[AsyncPipelineOrchestrator] | type[SyncPipelineOrchestrator] @@ -863,3 +864,84 @@ def test_capture_uses_the_binding_of_the_first_compiled_slot( difference.pod(original, label="after") job.run() assert sorted(job.after.as_table()["out"].to_pylist()) == [-1, -1] + + +@pytest.mark.parametrize("foreign_origin", ["standalone", "job_bind", "job_setter"]) +@pytest.mark.parametrize("compile_mode", ["first", "implicit", "explicit"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_foreign_slot_binding_is_captured_by_value( + foreign_origin: str, compile_mode: str, orchestrator: Orchestrator +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + + original = _shifted_source("a", 0) + replacement = _shifted_source("b", 10) + upstream_job = None + if foreign_origin == "standalone": + foreign_slot = SourceJobNode.from_stream(original, name="a") + else: + with PipelineJob(database=InMemoryArrowDatabase()) as upstream_job: + total.pod(original, label="upstream") + foreign_slot = upstream_job.nodes["a"] + assert isinstance(foreign_slot, SourceJobNode) + + with PipelineJob( + database=InMemoryArrowDatabase(), auto_compile=compile_mode != "first" + ) as job: + total.pod(foreign_slot, label="before") + + if foreign_origin == "job_bind": + assert upstream_job is not None + upstream_job.bind(sources={"a": replacement}) + else: + foreign_slot.bound_source = replacement + assert foreign_slot.bound_source is replacement + + if compile_mode == "implicit": + with job: + difference.pod(original, label="after") + else: + job.compile() + + job.run(orchestrator=orchestrator()) + assert job.sources["a"] is original + assert sorted(job.before.as_table()["out"].to_pylist()) == [3, 7] + if compile_mode == "implicit": + assert sorted(job.after.as_table()["out"].to_pylist()) == [-1, -1] + + +@pytest.mark.parametrize( + "blocked_index,count", [(0, 2), (1, 2), (0, 3), (1, 3), (2, 3)] +) +@pytest.mark.parametrize("capture", ["function", "operator", "side_effect"]) +def test_nested_capture_refusal_leaves_every_job_unchanged( + blocked_index: int, count: int, capture: str +) -> None: + from contextlib import ExitStack + + def deliver(x: int, ctx: Any) -> None: + raise AssertionError("A refused side effect must never run") + + original = _shifted_source("a", 0) + replacement = _shifted_source("b", 10) + jobs = [PipelineJob(database=InMemoryArrowDatabase()) for _ in range(count)] + for job in jobs: + with job: + total.pod(original, label="before") + jobs[blocked_index].bind(sources={"a": replacement}) + + with ExitStack() as contexts: + for job in jobs: + contexts.enter_context(job) + with pytest.raises(InconsistentSourceError, match="not as captured"): + if capture == "function": + difference.pod(original, label="refused") + elif capture == "operator": + original.map_data({"x": "renamed"}, label="refused") + else: + tap = side_effect_pod(deliver) + assert isinstance(tap, SideEffectPod) + tap.process(original, label="refused") + + for job in jobs: + assert "refused" not in job.nodes From 103183485f3ff61c8270b4c6c6e2ec51622a7b2b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 17:40:38 -0800 Subject: [PATCH 25/42] fix(pipeline): refuse foreign bindable source slots --- .zed/rules | 5 + CLAUDE.md | 5 + changelog.d/ITL-1469.md | 9 +- docs/concepts/pipeline-job.md | 8 + docs/concepts/sources.md | 8 +- src/orcapod/pipeline/base.py | 18 +- src/orcapod/pipeline/job.py | 44 ++-- src/orcapod/pipeline/restrictions.py | 16 +- .../protocols/core_protocols/trackers.py | 5 +- .../test_spiraldb_table_source_where.py | 32 +-- .../test_source_object_registration.py | 219 ++++++++++++++---- 11 files changed, 271 insertions(+), 98 deletions(-) diff --git a/.zed/rules b/.zed/rules index 903911627..f4e2312ba 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1519,6 +1519,11 @@ data. The rules: original bindings are restored. InconsistentSourceError names the changed slots. Restore the original bindings or build a new job. A job can compile and run with its replacement bindings. ITL-1559 tracks capture after rebinding. + As a stopgap pending ITL-1559, a job refuses another job's or a standalone + SourceJobNode, including through prebuilt streams. Its bound_source can change + even if currently unbound. Pass the source itself, or use node.as_source() + for another job's stored results. The job's own slots are allowed with their + original bindings. A schema-only SourceNode declares a new unbound slot. Call where() once and reuse the resulting object. A source object conflict raises InconsistentSourceError before the separate restriction check, which can see restrictions beneath wrappers. diff --git a/CLAUDE.md b/CLAUDE.md index e3cdc7d96..5dfaa3ce4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1567,6 +1567,11 @@ data. The rules: original bindings are restored. InconsistentSourceError names the changed slots. Restore the original bindings or build a new job. A job can compile and run with its replacement bindings. ITL-1559 tracks capture after rebinding. + As a stopgap pending ITL-1559, a job refuses another job's or a standalone + SourceJobNode, including through prebuilt streams. Its bound_source can change + even if currently unbound. Pass the source itself, or use node.as_source() + for another job's stored results. The job's own slots are allowed with their + original bindings. A schema-only SourceNode declares a new unbound slot. Call where() once and reuse the resulting object. A source object conflict raises InconsistentSourceError before the separate restriction check, which can see restrictions beneath wrappers. diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index 0bcddbc70..35a07fc42 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -7,12 +7,15 @@ object across slots with identical source configurations. - Sources with the same source ID must agree on their Arrow schema and key columns, including when they occupy different slots. -- Capturing another job's source slot or a standalone slot keeps the source - object held at capture time. A capture refused by any active pipeline or job - leaves all their graphs unchanged. +- A capture refused by any active pipeline or job leaves all their graphs + unchanged. ### Known limitations - ITL-1506 tracks distinct readings of one dataset in distinct slots. ITL-1531 tracks sources that read their rows later. ITL-1553 tracks accepting distinct objects that represent the same source. +- As a stopgap pending ITL-1559, a job refuses foreign and standalone bindable + slots (`SourceJobNode`), including through streams built from them. Pass the + source itself, or use `node.as_source()` for another job's stored results. + Schema-only `SourceNode` declarations still create independent slots. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 41a19df1b..95fefebfa 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -103,6 +103,14 @@ Three more things a job node offers: the node has run in this process, to use as the input of another pipeline. - **`upstreams`** and **`label`** let you walk the pipeline backwards. +As a stopgap pending ITL-1559, a job cannot absorb steps from another job by +capturing compiled nodes or other streams that depend on the other job's +bindable source slots (`SourceJobNode`). The same restriction applies to +standalone `SourceJobNode` objects, even when unbound. Pass the source itself to +record a new chain, or use `node.as_source()` to read the stored results of an +earlier job. A job can use its own slots while their original bindings are in +place. A schema-only `SourceNode` declares an independent slot for each job. + ## The database Any Orcapod database can hold a job's results. Two are used most: diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index b219ffed9..a8a8ba923 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -94,9 +94,11 @@ original bindings are restored. InconsistentSourceError names the changed slots. Restore the original bindings or build a new job. A job can compile and run with its replacement bindings. ITL-1559 tracks capture after rebinding. -When a job captures another job's source slot or a standalone source slot, it -takes the source object bound to that slot at capture time. Later changes to the -supplying slot leave the receiving job's binding alone. +As a stopgap pending ITL-1559, a job refuses bindable source slots +(`SourceJobNode`) from another job or created standalone, including through a +stream built from one. Pass the source itself, or use `node.as_source()` to read +another job's stored results. A schema-only `SourceNode` declares a new unbound +slot for each job that captures it. Capturing into a loaded job or recompiling it can lose its restored graph (ITL-1560). Recompilation preserves the loaded job's public `sources` mapping. diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 24b769227..e46774f5d 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -4,8 +4,9 @@ import logging from abc import ABC, abstractmethod -from collections.abc import Callable, Hashable, Iterator +from collections.abc import Callable, Hashable, Iterable, Iterator from dataclasses import dataclass +from itertools import chain from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar from orcapod.core.nodes.function_node import FunctionNodeBase @@ -31,6 +32,7 @@ from orcapod.types.provenance import Highlight from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.pipeline.source_consistency import SourceUse + from orcapod.protocols.core_protocols import StreamProtocol else: nx = LazyModule("networkx") @@ -321,6 +323,9 @@ def record_side_effect_pod_invocation( def _record_invocation(self, invocation: PodInvocation) -> None: self.prepare_invocation(invocation)() + def _validate_capture_sources(self, streams: Iterable[StreamProtocol]) -> None: + """Check the streams of a new capture before recording it.""" + def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: """Validate *invocation* and prepare to update the topology graph. @@ -354,8 +359,9 @@ def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: """ from orcapod.pipeline.restrictions import require_one_restriction - key = invocation.content_hash().to_string() inputs = tuple(invocation.input_streams) + self._validate_capture_sources(inputs) + key = invocation.content_hash().to_string() input_keys = tuple(upstream.content_hash().to_string() for upstream in inputs) # Checked before anything is recorded, so a refused invocation leaves the # graph as it was. A restriction does not change a source's identity, so the @@ -825,6 +831,14 @@ def from_invocations( A compiled instance of ``cls``. """ instance = cls(name=name) + instance._validate_capture_sources( + chain( + graph.source_streams.values(), + chain.from_iterable( + invocation.input_streams for invocation in graph.invocations + ), + ) + ) require_consistent_sources( use for invocation in graph.invocations diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 468dd25ec..02eabcce7 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -6,7 +6,7 @@ import enum import logging import sys -from collections.abc import Callable, Iterator, Sequence +from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast @@ -37,6 +37,7 @@ refuse_restricted_operator_caches, refuse_restriction_conflicts, restrictions_in_force, + streams_beneath, warn_restricted_aggregation, ) from orcapod.pipeline.run_summary import ( @@ -226,8 +227,8 @@ def __exit__(self, exc_type=None, exc_value=None, traceback=None) -> None: if exc_type is None and self._auto_compile: self.compile() - def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: - """Prepare a step only while every compiled slot has its original binding.""" + def _validate_capture_sources(self, streams: Iterable[cp.StreamProtocol]) -> None: + """Require original bindings and refuse bindable slots outside this job.""" # ITL-1559: refuse additive capture until the relationship between captured # objects and slots is defined. Check at recording so a bind inside an # open capture context cannot bypass the rule. @@ -247,22 +248,27 @@ def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: f"{names}. Bind them back to their original objects or build a new " "job (ITL-1559)." ) - if any( - isinstance(stream, SourceJobNode) for stream in invocation.input_streams - ): - # Each job owns its slots. Keep the binding at capture, even if the - # supplying slot changes before this job first compiles. - invocation = type(invocation)( - pod=invocation.pod, - input_streams=tuple( - SourceJobNode.from_stream(stream) - if isinstance(stream, SourceJobNode) - else stream - for stream in invocation.input_streams - ), - label=invocation.label, - ) - return super().prepare_invocation(invocation) + # ITL-1559 stopgap: SourceJobNode has a mutable bound_source even when + # unbound. SourceNode only declares a name and schemas. + own_slots = { + id(node) + for node in self._persistent_node_map.values() + if isinstance(node, SourceJobNode) + } + visited: set[int] = set() + pending = list(streams) + while pending: + stream = pending.pop() + if id(stream) in visited: + continue + visited.add(id(stream)) + if isinstance(stream, SourceJobNode) and id(stream) not in own_slots: + raise InconsistentSourceError( + f"Capturing source slot {stream.name!r} from outside this job " + "is not supported yet (ITL-1559). Pass the source itself, or " + "use node.as_source() to read another job's stored results." + ) + pending.extend(streams_beneath(stream)) def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse]: """Validate actual graph leaves after a binding replaces a captured input.""" diff --git a/src/orcapod/pipeline/restrictions.py b/src/orcapod/pipeline/restrictions.py index 598004959..45935241f 100644 --- a/src/orcapod/pipeline/restrictions.py +++ b/src/orcapod/pipeline/restrictions.py @@ -107,10 +107,10 @@ def _inputs(stream: StreamProtocol) -> tuple[StreamProtocol, ...]: return tuple(upstream for upstream in upstreams if upstream is not None) -def _streams_beneath( +def streams_beneath( current: StreamProtocol, rebinding: Rebinding | None = None ) -> tuple[StreamProtocol, ...]: - """Return what ``current`` reads: the streams a restriction walk goes on to. + """Return the streams ``current`` reads when a graph walk goes upstream. A ``SourceJobNode`` reads its bound source (or, when it is one of the slots of ``rebinding``, the source a bind is about to bind there), a bound @@ -142,7 +142,7 @@ def restrictions_beneath( ) -> frozenset[tuple[str, Restriction]]: """Return the restrictions of every source the streams read, order-free. - Walks down to the root sources (``_streams_beneath``: through a slot's bound + Walks down to the root sources (``streams_beneath``: through a slot's bound source, a proxy's delegate and a cache's source); each restricted root gives ``(source name, restriction)``. Two results are equal when the same sources are restricted equally. @@ -166,7 +166,7 @@ def restrictions_beneath( restriction = restriction_of(current) if restriction is not None and isinstance(current, RootSource): found.add((source_name(current), restriction)) - pending.extend(_streams_beneath(current, rebinding)) + pending.extend(streams_beneath(current, rebinding)) return frozenset(found) @@ -187,7 +187,7 @@ def sources_read( """Return every root source the streams read, with its restriction. ``(content hash, source name, restriction or None)`` for each root source met by - ``_streams_beneath``, once per object. The content hash is the source's identity, + ``streams_beneath``, once per object. The content hash is the source's identity, which a restriction leaves unchanged, so it is the key of the one-restriction rule. ``rebinding``: the job's slots a bind is about to bind, with their sources. """ @@ -203,7 +203,7 @@ def sources_read( if any(current is seen for seen in visited): continue visited.append(current) - beneath = _streams_beneath(current, rebinding) + beneath = streams_beneath(current, rebinding) if ( isinstance(current, RootSource) and not isinstance(current, (CachedSource, SourceProxy)) @@ -466,10 +466,10 @@ def restrictions_in_force( elif (str(stream.label), entry) not in direct: direct.append((str(stream.label), entry)) if isinstance(stream, SourceJobNode): - pending.extend((inner, stream.name) for inner in _streams_beneath(stream)) + pending.extend((inner, stream.name) for inner in streams_beneath(stream)) else: # A slot bound to a stream over a source keeps its name down to it. - pending.extend((inner, slot) for inner in _streams_beneath(stream)) + pending.extend((inner, slot) for inner in streams_beneath(stream)) found = dict(slots) for label, entry in direct: if found.get(label) == entry: diff --git a/src/orcapod/protocols/core_protocols/trackers.py b/src/orcapod/protocols/core_protocols/trackers.py index a1f36b65e..0abd90b32 100644 --- a/src/orcapod/protocols/core_protocols/trackers.py +++ b/src/orcapod/protocols/core_protocols/trackers.py @@ -16,7 +16,10 @@ @runtime_checkable class TrackerProtocol(Protocol): """ - Records kernel invocations and stream creation for computational graph tracking. + Internal contract for recording invocations and stream creation. + + Every tracker implements ``prepare_invocation()`` so the manager can validate + a capture across all active trackers before any tracker records it. Trackers are responsible for maintaining the computational graph by recording relationships between kernels, streams, and invocations. They enable: diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index 7a2fef702..027091e42 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -2244,8 +2244,8 @@ def test_one_restriction_through_two_chains_is_accepted( } -class TestRestrictionsCheckedLive: - """Restriction checks use the binding captured by the receiving job.""" +class TestForeignRestrictedSlots: + """A job refuses foreign slots even when their sources are restricted.""" @staticmethod def _slot(source: Any) -> Any: @@ -2254,7 +2254,7 @@ def _slot(source: Any) -> Any: return SourceJobNode.from_stream(source) @pytest.mark.parametrize("step", ["select", "drop"]) - def test_a_foreign_slot_rebound_between_invocations_keeps_its_captured_source( + def test_a_foreign_slot_is_refused_before_its_restriction_changes( self, project, tmp_path, step ): m1 = _events().where(subject_id="m1") @@ -2265,39 +2265,38 @@ def test_a_foreign_slot_rebound_between_invocations_keeps_its_captured_source( }[step] job = PipelineJob(name="live", database=DeltaTableDatabase(tmp_path / "s")) with job: - MapData({"channel": "lane"})(slot) + with pytest.raises(InconsistentSourceError, match="not supported yet"): + MapData({"channel": "lane"})(slot) slot.bound_source = _events().where(subject_id="m2") later(m1) assert job.sources["events"] is m1 assert job.run().conditions == {"events": Condition.of(subject_id="m1")} - def test_a_foreign_slot_rebound_before_compile_keeps_its_captured_source( + def test_a_foreign_slot_does_not_replace_a_captured_restricted_source( self, project, tmp_path ): m1 = _events().where(subject_id="m1") slot = self._slot(m1) job = PipelineJob(name="live", database=DeltaTableDatabase(tmp_path / "s")) with job: - MapData({"channel": "lane"})(slot) m1.select_data_columns(["amplitude"]) + with pytest.raises(InconsistentSourceError, match="not supported yet"): + MapData({"channel": "lane"})(slot) slot.bound_source = _events().where(subject_id="m2") assert job.sources["events"] is m1 assert job.run().conditions == {"events": Condition.of(subject_id="m1")} - def test_an_equal_restriction_on_a_rebound_foreign_slot_conflicts_with_the_capture( + def test_a_foreign_slot_with_an_equal_restriction_is_refused( self, project, tmp_path ): m1 = _events().where(subject_id="m1") slot = self._slot(m1) job = PipelineJob(name="live", database=DeltaTableDatabase(tmp_path / "s")) with job: - MapData({"channel": "lane"})(slot) replacement = _events().where(subject_id="m1") slot.bound_source = replacement - with pytest.raises( - InconsistentSourceError, match="distinct source objects" - ): - replacement.select_data_columns(["amplitude"]) + with pytest.raises(InconsistentSourceError, match="not supported yet"): + MapData({"channel": "lane"})(slot) m1.select_data_columns(["amplitude"]) assert job.sources["events"] is m1 assert job.run().conditions == {"events": Condition.of(subject_id="m1")} @@ -2439,14 +2438,19 @@ def _pick(source: Any) -> Any: return source.select_data_columns(["amplitude", "flag"]) def _job(self, tmp_path: Path) -> PipelineJob: - from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.nodes.source_node import SourceJobNode, SourceNode m1 = _events().where(subject_id="m1") - pick = SourceJobNode.from_stream(self._pick(m1), name="pick") + selected = self._pick(m1) + borrowed = SourceJobNode.from_stream(selected, name="pick") + pick = SourceNode.from_stream(selected, name="pick") job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) with job: m1.map_data({"amplitude": "a"}, label="rename") + with pytest.raises(InconsistentSourceError, match="not supported yet"): + MapData({"amplitude": "b"})(borrowed) MapData({"amplitude": "b"})(pick) + job.bind(sources={"pick": selected}) return job @staticmethod diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index cba1cee8a..ad1a941b0 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -839,11 +839,12 @@ def test_capture_uses_the_binding_of_the_first_compiled_slot( source = _shifted_source("a", 0) original = source.select_data_columns(["x", "y"]) - recorded = ( - SourceJobNode.from_stream(original, name="slot") if wrapped_slot else original - ) with PipelineJob(database=InMemoryArrowDatabase()) as job: - total.pod(recorded, label="before") + if wrapped_slot: + foreign = SourceJobNode.from_stream(original, name="slot") + with pytest.raises(InconsistentSourceError, match="not supported yet"): + total.pod(foreign, label="borrowed") + total.pod(original, label="before") (name,) = job.sources assert job.sources[name] is original @@ -866,50 +867,6 @@ def test_capture_uses_the_binding_of_the_first_compiled_slot( assert sorted(job.after.as_table()["out"].to_pylist()) == [-1, -1] -@pytest.mark.parametrize("foreign_origin", ["standalone", "job_bind", "job_setter"]) -@pytest.mark.parametrize("compile_mode", ["first", "implicit", "explicit"]) -@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) -def test_foreign_slot_binding_is_captured_by_value( - foreign_origin: str, compile_mode: str, orchestrator: Orchestrator -) -> None: - from orcapod.core.nodes.source_node import SourceJobNode - - original = _shifted_source("a", 0) - replacement = _shifted_source("b", 10) - upstream_job = None - if foreign_origin == "standalone": - foreign_slot = SourceJobNode.from_stream(original, name="a") - else: - with PipelineJob(database=InMemoryArrowDatabase()) as upstream_job: - total.pod(original, label="upstream") - foreign_slot = upstream_job.nodes["a"] - assert isinstance(foreign_slot, SourceJobNode) - - with PipelineJob( - database=InMemoryArrowDatabase(), auto_compile=compile_mode != "first" - ) as job: - total.pod(foreign_slot, label="before") - - if foreign_origin == "job_bind": - assert upstream_job is not None - upstream_job.bind(sources={"a": replacement}) - else: - foreign_slot.bound_source = replacement - assert foreign_slot.bound_source is replacement - - if compile_mode == "implicit": - with job: - difference.pod(original, label="after") - else: - job.compile() - - job.run(orchestrator=orchestrator()) - assert job.sources["a"] is original - assert sorted(job.before.as_table()["out"].to_pylist()) == [3, 7] - if compile_mode == "implicit": - assert sorted(job.after.as_table()["out"].to_pylist()) == [-1, -1] - - @pytest.mark.parametrize( "blocked_index,count", [(0, 2), (1, 2), (0, 3), (1, 3), (2, 3)] ) @@ -945,3 +902,169 @@ def deliver(x: int, ctx: Any) -> None: for job in jobs: assert "refused" not in job.nodes + + +@pytest.mark.parametrize("foreign_origin", ["standalone", "other_job"]) +@pytest.mark.parametrize( + "form", ["direct", "hashed", "select", "function", "join", "invocations"] +) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_capture_refuses_foreign_source_slots( + foreign_origin: str, form: str, orchestrator: Orchestrator +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SelectDataColumns, SemiJoin + from orcapod.pipeline.base import InvocationGraph + from orcapod.pipeline.pod_invocation import FunctionInvocation + + source = _shifted_source("a", 0) + if foreign_origin == "standalone": + slot = SourceJobNode.from_stream(source, name="a") + else: + with PipelineJob(database=InMemoryArrowDatabase()) as upstream: + total.pod(source, label="upstream") + slot = upstream.nodes["a"] + assert isinstance(slot, SourceJobNode) + + original = _shifted_source("kept", 0) + with PipelineJob(database=InMemoryArrowDatabase()) as receiver: + total.pod(original, label="kept_result") + + @function_pod(output_keys="scaled") + def scale(out: int) -> int: + return out * 10 + + prebuilt = { + "select": lambda: SelectDataColumns(["x", "y"])(slot), + "function": lambda: total.pod(slot), + "join": lambda: SemiJoin()(slot, _shifted_source("other", 0)), + } + if form == "invocations": + graph = InvocationGraph( + invocations=(FunctionInvocation(total.pod, (slot,), "borrowed"),), + source_streams={slot.content_hash().to_string(): slot}, + ) + with pytest.raises(InconsistentSourceError, match="not supported yet") as error: + PipelineJob.from_invocations(graph) + elif form in prebuilt: + stream = prebuilt[form]() + with ( + receiver, + pytest.raises(InconsistentSourceError, match="not supported yet") as error, + ): + if form == "function": + scale.pod(stream, label="borrowed") + else: + total.pod(stream, label="borrowed") + else: + with ( + receiver, + pytest.raises(InconsistentSourceError, match="not supported yet") as error, + ): + mid = total.pod(slot, label="borrowed") + if form == "hashed": + _ = mid.content_hash() + slot.bound_source = _shifted_source("changed", 10) + scale.pod(mid, label="downstream") + + assert "'a'" in str(error.value) + assert "Pass the source itself" in str(error.value) + assert "as_source()" in str(error.value) + assert "ITL-1559" in str(error.value) + assert slot.bound_source is source + assert set(receiver.nodes) == {"kept", "kept_result"} + receiver.run(orchestrator=orchestrator()) + assert sorted(receiver.kept_result.as_table()["out"].to_pylist()) == [3, 7] + + +@pytest.mark.parametrize("owner_first", [True, False]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_foreign_slot_refusal_leaves_every_active_job_unchanged( + owner_first: bool, orchestrator: Orchestrator +) -> None: + source = _shifted_source("a", 0) + with PipelineJob(database=InMemoryArrowDatabase()) as owner: + total.pod(source, label="before") + with PipelineJob(database=InMemoryArrowDatabase()) as receiver: + total.pod(source, label="before") + contexts = (owner, receiver) if owner_first else (receiver, owner) + with contexts[0], contexts[1]: + with pytest.raises(InconsistentSourceError, match="not supported yet"): + product.pod(owner.nodes["a"], label="borrowed") + for job in contexts: + assert set(job.nodes) == {"a", "before"} + job.run(orchestrator=orchestrator()) + assert sorted(job.before.as_table()["out"].to_pylist()) == [3, 7] + + +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_capture_accepts_own_slots_and_another_jobs_stored_results( + orchestrator: Orchestrator, +) -> None: + source = _shifted_source("a", 0) + with PipelineJob(database=InMemoryArrowDatabase()) as upstream: + total.pod(source, label="before") + with upstream: + product.pod(upstream.nodes["a"], label="own_slot") + upstream.run(orchestrator=orchestrator()) + assert sorted(upstream.own_slot.as_table()["out"].to_pylist()) == [2, 12] + + @function_pod(output_keys="scaled") + def scale(out: int) -> int: + return out * 10 + + with PipelineJob(database=InMemoryArrowDatabase()) as receiver: + with pytest.raises(InconsistentSourceError, match="not supported yet"): + scale.pod(upstream.before, label="borrowed") + scale.pod(upstream.before.as_source(), label="stored") + assert "borrowed" not in receiver.nodes + receiver.run(orchestrator=orchestrator()) + assert sorted(receiver.stored.as_table()["scaled"].to_pylist()) == [30, 70] + + +@pytest.mark.parametrize("origin", ["standalone", "pipeline", "job_blueprint"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_schema_declaration_gives_each_job_its_own_binding( + origin: str, orchestrator: Orchestrator +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode, SourceNode + + original = _shifted_source("a", 0) + if origin == "pipeline": + with Pipeline("blueprint") as blueprint: + total.pod(original, label="result") + declaration = blueprint.nodes["a"] + elif origin == "job_blueprint": + with PipelineJob(database=InMemoryArrowDatabase()) as upstream: + total.pod(original, label="result") + declaration = upstream.as_pipeline().nodes["a"] + assert isinstance(upstream.nodes["a"], SourceJobNode) + assert upstream.nodes["a"].bound_source is original + else: + declaration = SourceNode.from_stream(original, name="a") + assert isinstance(declaration, SourceNode) + assert not hasattr(declaration, "bound_source") + + with PipelineJob(database=InMemoryArrowDatabase()) as first: + total.pod(declaration, label="result") + first_slot = first.nodes["a"] + assert isinstance(first_slot, SourceJobNode) + assert first_slot is not declaration + assert first_slot.bound_source is None + first.bind(sources={"a": original}) + + with PipelineJob(database=InMemoryArrowDatabase()) as second: + total.pod(declaration, label="result") + product.pod(declaration, label="reused") + second_slot = second.nodes["a"] + assert isinstance(second_slot, SourceJobNode) + assert second_slot is not first_slot + assert second_slot.bound_source is None + second_slot.bound_source = _shifted_source("b", 10) + + first.run(orchestrator=orchestrator()) + second.run(orchestrator=orchestrator()) + assert first_slot.bound_source is original + assert sorted(first.result.as_table()["out"].to_pylist()) == [3, 7] + assert sorted(second.result.as_table()["out"].to_pylist()) == [13, 17] + assert sorted(second.reused.as_table()["out"].to_pylist()) == [22, 52] From a31fd56bf9ff9b1bc5d2b93e3b67e0cce5b0c95f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 17:41:32 -0800 Subject: [PATCH 26/42] test(pipeline): cover explicit foreign slot registration --- .../test_source_object_registration.py | 27 ++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index ad1a941b0..957fdbf0e 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -906,12 +906,23 @@ def deliver(x: int, ctx: Any) -> None: @pytest.mark.parametrize("foreign_origin", ["standalone", "other_job"]) @pytest.mark.parametrize( - "form", ["direct", "hashed", "select", "function", "join", "invocations"] + "form", + [ + "direct", + "hashed", + "select", + "function", + "join", + "record", + "invocations", + "isolated", + ], ) @pytest.mark.parametrize("orchestrator", ORCHESTRATORS) def test_capture_refuses_foreign_source_slots( foreign_origin: str, form: str, orchestrator: Orchestrator ) -> None: + from orcapod.core.function_pod import FunctionPod from orcapod.core.nodes.source_node import SourceJobNode from orcapod.operators import SelectDataColumns, SemiJoin from orcapod.pipeline.base import InvocationGraph @@ -939,9 +950,19 @@ def scale(out: int) -> int: "function": lambda: total.pod(slot), "join": lambda: SemiJoin()(slot, _shifted_source("other", 0)), } - if form == "invocations": + pod = total.pod + assert isinstance(pod, FunctionPod) + if form == "record": + with pytest.raises(InconsistentSourceError, match="not supported yet") as error: + receiver.record_function_pod_invocation(pod, slot, label="borrowed") + elif form in {"invocations", "isolated"}: + invocations = ( + (FunctionInvocation(pod, (slot,), "borrowed"),) + if form == "invocations" + else () + ) graph = InvocationGraph( - invocations=(FunctionInvocation(total.pod, (slot,), "borrowed"),), + invocations=invocations, source_streams={slot.content_hash().to_string(): slot}, ) with pytest.raises(InconsistentSourceError, match="not supported yet") as error: From 47257e556d69f91ec2d59f3827ca3f89368221a5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 18:07:36 -0800 Subject: [PATCH 27/42] fix(pipeline): follow live inputs through source wrappers --- .zed/rules | 8 +- CLAUDE.md | 8 +- docs/concepts/sources.md | 5 ++ src/orcapod/core/sources/base.py | 10 +++ src/orcapod/core/sources/cached_source.py | 12 ++- src/orcapod/core/sources/derived_source.py | 6 ++ src/orcapod/core/sources/source_proxy.py | 11 ++- src/orcapod/pipeline/restrictions.py | 37 +++----- src/orcapod/pipeline/source_consistency.py | 8 +- .../test_spiraldb_table_source_where.py | 24 ++++- .../test_source_object_registration.py | 90 +++++++++++++++++++ 11 files changed, 183 insertions(+), 36 deletions(-) diff --git a/.zed/rules b/.zed/rules index f4e2312ba..e4021bf8c 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1534,9 +1534,11 @@ data. The rules: what they read) at capture, at compile, by bind before it binds and at the start of every run (refuse_restriction_conflicts), whatever streams lead there: projections, operator chains, streams built before the capture. A bind's walk matches the job's own slots by object - (Rebinding), never by name. RunSummary keeps one condition and one limit per slot (ITL-1293). Every restriction walk goes through a slot's bound source, - a SourceProxy's delegate and a CachedSource's source (_streams_beneath); a - DerivedSource is a root. A CachedSource + (Rebinding), never by name. RunSummary keeps one condition and one limit per slot (ITL-1293). + Capture and restriction checks follow job bindings and the live_source_inputs + declared by wrappers. A wrapper over stored results ends this walk. Source + registration uses the wrapper itself and its content hash. + A CachedSource over a restricted source is refused at construction (a cache is kept under the table's identity; developer, November 18, 2026), and so is an operator job node that caches (LOG or REPLAY) over a restricted source (developer, November 19, 2026: its cache is kept under the diff --git a/CLAUDE.md b/CLAUDE.md index 5dfaa3ce4..220a3466a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1582,9 +1582,11 @@ data. The rules: what they read) at capture, at compile, by `bind` before it binds and at the start of every run (`refuse_restriction_conflicts`), whatever streams lead there: projections, operator chains, streams built before the capture. A bind's walk matches the job's own slots by object - (`Rebinding`), never by name. `RunSummary` keeps one condition and one limit per slot (ITL-1293). Every restriction walk goes through a slot's bound source, - a `SourceProxy`'s delegate and a `CachedSource`'s source (`_streams_beneath`); a - `DerivedSource` is a root. A `CachedSource` + (`Rebinding`), never by name. `RunSummary` keeps one condition and one limit per slot (ITL-1293). + Capture and restriction checks follow job bindings and the live_source_inputs + declared by wrappers. A wrapper over stored results ends this walk. Source + registration uses the wrapper itself and its content hash. + A `CachedSource` over a restricted source is refused at construction (a cache is kept under the table's identity; developer, November 18, 2026), and so is an operator job node that caches (`LOG` or `REPLAY`) over a restricted source (developer, November 19, 2026: its cache is kept under the diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index a8a8ba923..6118704ee 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -100,6 +100,11 @@ stream built from one. Pass the source itself, or use `node.as_source()` to read another job's stored results. A schema-only `SourceNode` declares a new unbound slot for each job that captures it. +The capture and restriction checks follow wrappers that can read live inputs. +This includes tag-copy `DerivedSource` over a live source. A `DerivedSource` +over a job node reads stored results, so the checks stop there. Source object +registration uses the wrapper itself and its content hash. + Capturing into a loaded job or recompiling it can lose its restored graph (ITL-1560). Recompilation preserves the loaded job's public `sources` mapping. diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 881256c2e..88a0e8e6b 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -513,6 +513,16 @@ def upstreams(self) -> tuple[StreamProtocol, ...]: """Sources have no upstream dependencies.""" return () + @property + def live_source_inputs(self) -> tuple[StreamProtocol, ...] | None: + """Identify the inputs read live through this source. + + Wrappers that can read another stream live override this property. They + return an empty tuple when disconnected. A source that supplies its + own rows or reads stored results returns ``None``, ending the walk. + """ + return None + # ------------------------------------------------------------------------- # Stream delegation defaults # ------------------------------------------------------------------------- diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 77d4ed579..c2ac17f6c 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -41,7 +41,12 @@ report_rows_of_other_data_contexts, with_data_context, ) -from orcapod.protocols.core_protocols import DataProtocol, SourceProtocol, TagProtocol +from orcapod.protocols.core_protocols import ( + DataProtocol, + SourceProtocol, + StreamProtocol, + TagProtocol, +) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.system_constants import SOURCE_DB_SCHEMA_VERSION, constants from orcapod.types import ColumnConfig, Schema @@ -353,6 +358,11 @@ def cached_source(self) -> SourceProtocol: """The source this cache reads and keeps the rows of.""" return self._source + @property + def live_source_inputs(self) -> tuple[StreamProtocol, ...]: + """A cache can read its wrapped source live.""" + return (self._source,) + def _live_records(self) -> pa.Table: """Read the wrapped source's rows, each with its record hash in front. diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1c4a57228..24dd7a37f 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -42,6 +42,7 @@ if TYPE_CHECKING: from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.protocols.core_protocols import StreamProtocol def validate_tags_as_data( @@ -470,6 +471,11 @@ def _data_tags(self) -> tuple[str, ...]: """ return stream_data_tags(self._origin) + @property + def live_source_inputs(self) -> tuple[StreamProtocol, ...] | None: + """Tag copies over a source read it live. Job nodes give stored results.""" + return (self._origin,) if isinstance(self._origin, RootSource) else None + def _origin_records(self) -> "pa.Table | None": """Return the origin's rows, or ``None`` when a job node has none stored. diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 271c07ecc..50961f369 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -35,7 +35,11 @@ import pyarrow as pa - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import ( + DataProtocol, + StreamProtocol, + TagProtocol, + ) class SourceProxy(RootSource): @@ -95,6 +99,11 @@ def delegate(self) -> SourceProtocol | None: """The bound live source, or ``None`` if no source has been bound.""" return self._delegate + @property + def live_source_inputs(self) -> tuple[StreamProtocol, ...]: + """A bound proxy reads its delegate live.""" + return () if self._delegate is None else (self._delegate,) + @property @override def _resolved_key_columns(self) -> tuple[str, ...] | None: diff --git a/src/orcapod/pipeline/restrictions.py b/src/orcapod/pipeline/restrictions.py index 45935241f..ae3de57b1 100644 --- a/src/orcapod/pipeline/restrictions.py +++ b/src/orcapod/pipeline/restrictions.py @@ -6,8 +6,7 @@ This module holds every rule that reads them: - the walk from streams down to the sources they read (``restrictions_beneath``, - ``sources_read``), through a slot's bound source, a proxy's delegate and a cache's - source; + ``sources_read``), through a slot's bound source and a wrapper's live inputs; - the refusals: one source read under two restrictions in one pipeline (``require_one_restriction``), an operator node that caches over a restricted source (``refuse_restricted_operator_cache``), a ``CachedSource`` over one @@ -112,16 +111,12 @@ def streams_beneath( ) -> tuple[StreamProtocol, ...]: """Return the streams ``current`` reads when a graph walk goes upstream. - A ``SourceJobNode`` reads its bound source (or, when it is one of the slots of - ``rebinding``, the source a bind is about to bind there), a bound - ``SourceProxy`` its delegate, a ``CachedSource`` the source it caches; any other - stream its ``upstreams``. A ``DerivedSource`` is a root: it reads the rows stored - for its origin, never its origin's sources, so the walk ends there, as at every - other root source. + A job slot reads its bound source, with prospective bindings taking precedence. + Sources declare their live inputs themselves. Other streams read their + graph upstreams. """ from orcapod.core.nodes.source_node import SourceJobNode - from orcapod.core.sources.cached_source import CachedSource - from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.core.sources.base import RootSource if isinstance(current, SourceJobNode): bound = current.bound_source @@ -129,10 +124,8 @@ def streams_beneath( if slot is current: bound = source return () if bound is None else (bound,) - if isinstance(current, SourceProxy): - return () if current.delegate is None else (current.delegate,) - if isinstance(current, CachedSource): - return (current.cached_source,) + if isinstance(current, RootSource): + return current.live_source_inputs or () return _inputs(current) @@ -142,8 +135,8 @@ def restrictions_beneath( ) -> frozenset[tuple[str, Restriction]]: """Return the restrictions of every source the streams read, order-free. - Walks down to the root sources (``streams_beneath``: through a slot's bound - source, a proxy's delegate and a cache's source); each restricted root gives + Walks down to the root sources (through job bindings and live wrappers); + each restricted root gives ``(source name, restriction)``. Two results are equal when the same sources are restricted equally. @@ -192,8 +185,6 @@ def sources_read( rule. ``rebinding``: the job's slots a bind is about to bind, with their sources. """ from orcapod.core.sources.base import RootSource - from orcapod.core.sources.cached_source import CachedSource - from orcapod.core.sources.source_proxy import SourceProxy found: list[tuple[str, str, Restriction | None]] = [] visited: list[StreamProtocol] = [] @@ -203,12 +194,7 @@ def sources_read( if any(current is seen for seen in visited): continue visited.append(current) - beneath = streams_beneath(current, rebinding) - if ( - isinstance(current, RootSource) - and not isinstance(current, (CachedSource, SourceProxy)) - and not beneath - ): + if isinstance(current, RootSource) and current.live_source_inputs is None: found.append( ( current.content_hash().to_string(), @@ -216,7 +202,8 @@ def sources_read( restriction_of(current), ) ) - pending.extend(beneath) + else: + pending.extend(streams_beneath(current, rebinding)) return found diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index 167152ab3..b4cf85703 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -34,7 +34,13 @@ def root_source_uses( uses: Iterable[SourceUse], rebinding: Rebinding = (), ) -> Iterable[tuple[str, RootSource]]: - """Walk to each source object, using prospective bindings for replaced slots.""" + """Walk to the source objects registered by the graph. + + A ``RootSource`` supplies the registered object and ends this walk even if it + reads live inputs. Registering those inputs too would make a cache conflict + with the source whose hash it preserves. Capture safety and restrictions + instead follow live reads through sources. + """ from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources.base import RootSource diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index 027091e42..648f51f90 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -1985,8 +1985,8 @@ class TestRestrictionThroughWrappers: CodeRabbit (PR 435): a proxy bound to a restricted source has no condition of its own and binds by identity, which a restriction leaves unchanged, so the walks must look through it. Wrappers checked: ``SourceJobNode`` (bound source), - ``SourceProxy`` (delegate), ``CachedSource`` (cached source); a ``DerivedSource`` - is a root (it reads stored rows, not its origin's sources). + ``SourceProxy`` (delegate), ``CachedSource`` (cached source), and + ``DerivedSource`` when it reads a source live. """ @staticmethod @@ -1996,6 +1996,26 @@ def _bound_proxy(restriction: str) -> Any: proxy.bind(restricted) return proxy + def test_live_derived_sources_expose_their_origins_restrictions( + self, project, tmp_path + ): + from orcapod.sources import DerivedSource + + def derive(subject: str) -> DerivedSource: + return DerivedSource( + _events().where(subject_id=subject), + tags_as_data={"subject_id": "copied"}, + source_id=f"copy_{subject}", + ) + + first, second = derive("m1"), derive("m2") + with PipelineJob(database=DeltaTableDatabase(tmp_path / "store")) as job: + first.map_data({"amplitude": "renamed"}, label="first") + with pytest.raises(ValueError, match="two different restrictions"): + second.map_data({"amplitude": "renamed"}, label="second") + + assert job.run().conditions == {"copy_m1": Condition.of(subject_id="m1")} + @staticmethod def _cached_job(store: DeltaTableDatabase, mode: CacheMode) -> PipelineJob: job = PipelineJob(name="events", database=store) diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index 957fdbf0e..6675e4b8a 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -1089,3 +1089,93 @@ def test_schema_declaration_gives_each_job_its_own_binding( assert sorted(first.result.as_table()["out"].to_pylist()) == [3, 7] assert sorted(second.result.as_table()["out"].to_pylist()) == [13, 17] assert sorted(second.reused.as_table()["out"].to_pylist()) == [22, 52] + + +@pytest.mark.parametrize("wrapper", ["cache", "proxy"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_live_derived_source_refuses_a_wrapped_foreign_slot( + wrapper: str, orchestrator: Orchestrator +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.sources.cached_source import CachedSource + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.protocols.core_protocols import SourceProtocol + from orcapod.protocols.database_protocols import DatabaseRegistryProtocol + from orcapod.sources import DerivedSource + from orcapod.types import Condition + + class SourceSlot(SourceJobNode): + @property + def source_id(self) -> str: + source = self.bound_source + assert isinstance(source, DictSource) + return source.source_id + + @property + def condition(self) -> Condition: + return Condition() + + @property + def row_limit(self) -> int | None: + return None + + def to_config( + self, db_registry: DatabaseRegistryProtocol | None = None + ) -> dict[str, Any]: + source = self.bound_source + assert isinstance(source, DictSource) + return source.to_config(db_registry) + + @classmethod + def from_config( + cls, + config: dict[str, Any], + db_registry: DatabaseRegistryProtocol | None = None, + ) -> SourceProtocol: + raise NotImplementedError + + source = _shifted_source("original", 0) + foreign = SourceSlot.from_stream(source, name="foreign") + assert isinstance(foreign, SourceProtocol) + if wrapper == "cache": + origin = CachedSource(foreign, InMemoryArrowDatabase()) + else: + proxy = SourceProxy( + foreign.source_id, + foreign.content_hash().to_string(), + foreign.pipeline_hash().to_string(), + *foreign.output_schema(), + ) + proxy.bind(foreign) + origin = proxy + derived = DerivedSource(origin, tags_as_data={"t1": "copied"}, source_id="tag_copy") + + with PipelineJob(database=InMemoryArrowDatabase()) as receiver: + total.pod(source, label="kept") + with receiver: + with pytest.raises(InconsistentSourceError, match="foreign.*not supported yet"): + total.pod(derived, label="borrowed") + + assert isinstance(foreign, SourceSlot) + foreign.bound_source = _shifted_source("original", 10) + receiver.run(orchestrator=orchestrator()) + assert sorted(receiver.kept.as_table()["out"].to_pylist()) == [3, 7] + assert set(receiver.nodes) == {"original", "kept"} + + +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_live_derived_source_and_its_source_are_both_capturable( + orchestrator: Orchestrator, +) -> None: + from orcapod.sources import DerivedSource + + original = _shifted_source("a", 0) + derived = DerivedSource( + original, tags_as_data={"t1": "copied"}, source_id="tag_copy" + ) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + total.pod(original, label="original") + product.pod(derived, label="derived") + job.run(orchestrator=orchestrator()) + assert sorted(job.original.as_table()["out"].to_pylist()) == [3, 7] + assert sorted(job.derived.as_table()["out"].to_pylist()) == [2, 12] From 3857c772a2ea70405d586a8ed4a2053661715f05 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 19:13:51 -0800 Subject: [PATCH 28/42] test(spiraldb): expect source registration to reject distinct windows --- tests/test_core/sources/test_spiraldb_table_source_ranges.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_core/sources/test_spiraldb_table_source_ranges.py b/tests/test_core/sources/test_spiraldb_table_source_ranges.py index c47f0a0eb..3a5297636 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_ranges.py +++ b/tests/test_core/sources/test_spiraldb_table_source_ranges.py @@ -25,7 +25,7 @@ from orcapod import PipelineJob, function_pod from orcapod.databases import DeltaTableDatabase -from orcapod.errors import SourceTooLargeError +from orcapod.errors import InconsistentSourceError, SourceTooLargeError from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.sources import SpiralDBTableSource from orcapod.types import Condition, col @@ -749,7 +749,7 @@ def same(n: int | None) -> int | None: return n job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: same.pod( events.where(col("unit") < 2).select_data_columns(["n"]), label="a" From 2e721c86299ff16a58839f8b32936a07c0039b50 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 20:22:19 -0800 Subject: [PATCH 29/42] fix(pipeline): address source registration review findings --- .zed/rules | 2 + CLAUDE.md | 2 + changelog.d/ITL-1469.md | 10 ++- docs/concepts/pipeline-job.md | 7 +- docs/concepts/sources.md | 4 + src/orcapod/core/function_pod.py | 4 +- .../core/operators/static_output_pod.py | 2 +- src/orcapod/core/streams/base.py | 17 +++- src/orcapod/pipeline/job.py | 46 ++++++---- src/orcapod/pipeline/source_consistency.py | 31 +++++-- src/orcapod/side_effects.py | 2 +- .../test_spiraldb_table_source_ranges.py | 17 ++-- .../test_spiraldb_table_source_where.py | 89 +++++++++++++------ .../test_pipeline/test_source_id_conflicts.py | 36 ++++++++ .../test_source_object_registration.py | 61 +++++++++++-- 15 files changed, 255 insertions(+), 75 deletions(-) diff --git a/.zed/rules b/.zed/rules index cac93d9e4..566fac2f2 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1613,6 +1613,8 @@ data. The rules: even if currently unbound. Pass the source itself, or use node.as_source() for another job's stored results. The job's own slots are allowed with their original bindings. A schema-only SourceNode declares a new unbound slot. + The ITL-1559 stopgap also refuses prebuilt streams over the job's own slots. + Build the step inside the job from the slot, or pass the source itself. Call where() once and reuse the resulting object. A source object conflict raises InconsistentSourceError before the separate restriction check, which can see restrictions beneath wrappers. diff --git a/CLAUDE.md b/CLAUDE.md index 6f13eb53b..bae07801c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1662,6 +1662,8 @@ data. The rules: even if currently unbound. Pass the source itself, or use node.as_source() for another job's stored results. The job's own slots are allowed with their original bindings. A schema-only SourceNode declares a new unbound slot. + The ITL-1559 stopgap also refuses prebuilt streams over the job's own slots. + Build the step inside the job from the slot, or pass the source itself. Call where() once and reuse the resulting object. A source object conflict raises InconsistentSourceError before the separate restriction check, which can see restrictions beneath wrappers. diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index 35a07fc42..68c5bae7d 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -2,9 +2,10 @@ - A pipeline or job accepts one source object per content hash. Capture, binding, loading and execution reject distinct objects with the same hash, even if - their rows agree. Build a source once and reuse it, or give each source its own - source ID. Rebinding replaces a slot's source, and loading shares one rebuilt - object across slots with identical source configurations. + their rows agree. Build a source once and reuse it. Distinct IDs separate + sources only when the ID contributes to the content hash. Rebinding replaces + a slot's source, and loading shares one rebuilt object across slots with + identical source configurations. - Sources with the same source ID must agree on their Arrow schema and key columns, including when they occupy different slots. - A capture refused by any active pipeline or job leaves all their graphs @@ -19,3 +20,6 @@ slots (`SourceJobNode`), including through streams built from them. Pass the source itself, or use `node.as_source()` for another job's stored results. Schema-only `SourceNode` declarations still create independent slots. +- The ITL-1559 stopgap also refuses prebuilt streams over the receiving job's + own slots. Build the step inside the job from its slot, or pass the source + itself. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index ed06aa108..3b687d646 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -116,8 +116,11 @@ capturing compiled nodes or other streams that depend on the other job's bindable source slots (`SourceJobNode`). The same restriction applies to standalone `SourceJobNode` objects, even when unbound. Pass the source itself to record a new chain, or use `node.as_source()` to read the stored results of an -earlier job. A job can use its own slots while their original bindings are in -place. A schema-only `SourceNode` declares an independent slot for each job. +earlier job. A job can pass its own slots directly into new steps while their +original bindings are in place. The ITL-1559 stopgap refuses streams built +outside the job over one of its own slots. Build the step from the slot inside +the job, or pass the source itself. A schema-only `SourceNode` declares an +independent slot for each job. ## The database diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 31e879edb..f73ec9479 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -100,6 +100,10 @@ stream built from one. Pass the source itself, or use `node.as_source()` to read another job's stored results. A schema-only `SourceNode` declares a new unbound slot for each job that captures it. +The ITL-1559 stopgap also refuses a prebuilt stream over the receiving job's +own slot. Pass that slot directly into a step inside the job, or pass the +source itself. + The capture and restriction checks follow wrappers that can read live inputs. This includes tag-copy `DerivedSource` over a live source. A `DerivedSource` over a job node reads stored results, so the checks stop there. Source object diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 34b10d550..c2e4e7ea7 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -985,7 +985,7 @@ def process( input_stream=input_stream, label=label, ) - return output_stream + return output_stream._mark_recorded(self.tracker_manager) def __call__( self, @@ -2198,7 +2198,7 @@ def process( ) return FunctionPodStream( function_pod=self, input_stream=input_stream, label=label - ) + )._mark_recorded(self.tracker_manager) def process_data( self, diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index cae6813fe..3c1534d7c 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -328,7 +328,7 @@ def process( upstreams=streams, label=label, ) - return output_stream + return output_stream._mark_recorded(self.tracker_manager) def to_config(self) -> dict[str, Any]: """Serialize this operator to a JSON-compatible config dict. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 9f8b731f7..7812c7b25 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -17,7 +17,8 @@ from contextlib import contextmanager from contextvars import ContextVar from datetime import datetime -from typing import TYPE_CHECKING, Any, cast +from typing import TYPE_CHECKING, Any, Self, cast +from weakref import ReferenceType, ref import pandas as pd import polars as pl @@ -45,6 +46,7 @@ from orcapod.utils import arrow_utils if TYPE_CHECKING: + from orcapod.protocols.core_protocols import TrackerManagerProtocol, TrackerProtocol from orcapod.types.explanation import Explanation # TODO: consider using this instead of making copy of dicts @@ -751,6 +753,19 @@ def _rename_map( class StreamBase(TraceableBase): + _recording_trackers: tuple[ReferenceType[TrackerProtocol], ...] = () + + def _mark_recorded(self, manager: TrackerManagerProtocol) -> Self: + """Remember which trackers accepted the invocation that made this stream.""" + self._recording_trackers = tuple( + ref(tracker) for tracker in manager.get_active_trackers() + ) + return self + + def _was_recorded_by(self, tracker: TrackerProtocol) -> bool: + """Check recording provenance without comparing stream hashes.""" + return any(recording() is tracker for recording in self._recording_trackers) + @property @abstractmethod def producer(self) -> PodProtocol | None: ... diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 8131af6b9..efb15a6e3 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -231,7 +231,7 @@ def __exit__(self, exc_type=None, exc_value=None, traceback=None) -> None: self.compile() def _validate_capture_sources(self, streams: Iterable[cp.StreamProtocol]) -> None: - """Require original bindings and refuse bindable slots outside this job.""" + """Require original bindings and refuse captures that can detach a slot.""" # ITL-1559: refuse additive capture until the relationship between captured # objects and slots is defined. Check at recording so a bind inside an # open capture context cannot bypass the rule. @@ -253,25 +253,35 @@ def _validate_capture_sources(self, streams: Iterable[cp.StreamProtocol]) -> Non ) # ITL-1559 stopgap: SourceJobNode has a mutable bound_source even when # unbound. SourceNode only declares a name and schemas. - own_slots = { - id(node) - for node in self._persistent_node_map.values() - if isinstance(node, SourceJobNode) - } - visited: set[int] = set() - pending = list(streams) + # A prebuilt stream can retain an own slot after compile replaces it. + # Only recorded steps are rewired to their job's current slots. + own_nodes = {id(node) for node in self._persistent_node_map.values()} + visited: set[tuple[int, bool]] = set() + pending = [(stream, False) for stream in streams] while pending: - stream = pending.pop() - if id(stream) in visited: + stream, prebuilt = pending.pop() + key = id(stream), prebuilt + if key in visited: continue - visited.add(id(stream)) - if isinstance(stream, SourceJobNode) and id(stream) not in own_slots: - raise InconsistentSourceError( - f"Capturing source slot {stream.name!r} from outside this job " - "is not supported yet (ITL-1559). Pass the source itself, or " - "use node.as_source() to read another job's stored results." - ) - pending.extend(streams_beneath(stream)) + visited.add(key) + if isinstance(stream, SourceJobNode): + if id(stream) not in own_nodes: + raise InconsistentSourceError( + f"Capturing source slot {stream.name!r} from outside this job " + "is not supported yet (ITL-1559). Pass the source itself, or " + "use node.as_source() to read another job's stored results." + ) + if prebuilt: + raise InconsistentSourceError( + f"Capturing a prebuilt stream over source slot {stream.name!r} " + "is not supported yet (ITL-1559). Build the step inside the " + "job from its slot, or pass the source itself." + ) + elif id(stream) not in own_nodes and not ( + isinstance(stream, StreamBase) and stream._was_recorded_by(self) + ): + prebuilt = True + pending.extend((upstream, prebuilt) for upstream in streams_beneath(stream)) def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse]: """Validate actual graph leaves after a binding replaces a captured input.""" diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index b4cf85703..4f0dd0924 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -75,16 +75,33 @@ def root_source_uses( def _comparison_schema(source: RootSource) -> tuple[ContentHash, ContentHash]: - """Use the live proxy schema for the comparison, even after an unbound read.""" + """Compare a bound proxy's live schema through schema-preserving caches.""" + from orcapod.core.sources.cached_source import CachedSource from orcapod.core.sources.source_proxy import SourceProxy from orcapod.core.streams.base import typed_arrow_schemas - if isinstance(source, SourceProxy) and source.is_bound: - # The cached schema can describe the unbound proxy's Python types. - schemas = typed_arrow_schemas(source, own=False) - else: - schemas = source.arrow_schemas - return arrow_schema_identity(*schemas, source.data_context) + current: StreamProtocol = source + visited: set[int] = set() + saw_bound_proxy = False + while id(current) not in visited: + visited.add(id(current)) + if isinstance(current, CachedSource): + current = current.cached_source + elif ( + isinstance(current, SourceProxy) + and (delegate := current.delegate) is not None + ): + saw_bound_proxy = True + current = delegate + else: + if saw_bound_proxy: + # Cache and proxy schemas may still describe the unbound proxy. + # Keep the delegate's schema, including any tag copies it adds. + return arrow_schema_identity( + *typed_arrow_schemas(current), source.data_context + ) + break + return arrow_schema_identity(*source.arrow_schemas, source.data_context) def require_consistent_sources( diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 00790b7e8..c99a711eb 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -716,7 +716,7 @@ def process( side_effect_pod=self, input_stream=input_stream, label=label, - ) + )._mark_recorded(self.tracker_manager) def __call__( self, *streams: StreamProtocol, label: str | None = None diff --git a/tests/test_core/sources/test_spiraldb_table_source_ranges.py b/tests/test_core/sources/test_spiraldb_table_source_ranges.py index 3a5297636..d5d8871da 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_ranges.py +++ b/tests/test_core/sources/test_spiraldb_table_source_ranges.py @@ -749,14 +749,15 @@ def same(n: int | None) -> int | None: return n job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(InconsistentSourceError, match="distinct source objects"): - with job: - same.pod( - events.where(col("unit") < 2).select_data_columns(["n"]), label="a" - ) - same.pod( - events.where(col("unit") >= 2).select_data_columns(["n"]), label="b" - ) + with job: + same.pod( + events.where(col("unit") < 2).select_data_columns(["n"]), label="a" + ) + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): + events.where(col("unit") >= 2).select_data_columns(["n"], label="b") + assert {"a", "b"} & job.nodes.keys() == {"a"} def test_a_saved_job_keeps_the_window_in_canonical_order(self, project, tmp_path): store = tmp_path / "store" diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index 0bf5b8d85..700bcc9d1 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -1098,10 +1098,13 @@ def second(channel: int | None) -> int | None: events = _source(source_id="events", tag_only_columns=True) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(InconsistentSourceError, match="distinct source objects"): - with job: - first.pod(events.where(subject_id="m1"), label="first") + with job: + first.pod(events.where(subject_id="m1"), label="first") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): second.pod(events.where(subject_id="m2"), label="second") + assert {"first", "second"} & job.nodes.keys() == {"first"} def test_streams_built_before_the_capture_are_checked_too(self, project, tmp_path): """Streams over differently restricted sources, built outside, are refused.""" @@ -1120,10 +1123,13 @@ def second(amplitude: float | None) -> float | None: m1 = events.where(subject_id="m1").select_data_columns(["amplitude"]) m2 = events.where(subject_id="m2").select_data_columns(["amplitude"]) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(InconsistentSourceError, match="distinct source objects"): - with job: - first.pod(m1, label="first") + with job: + first.pod(m1, label="first") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): second.pod(m2, label="second") + assert {"first", "second"} & job.nodes.keys() == {"first"} @pytest.mark.parametrize( "captured, prebuilt", @@ -1152,13 +1158,26 @@ def first(amplitude: float | None) -> float | None: events = _source(source_id="events", tag_only_columns=True) outside = events.where(**prebuilt).select_data_columns(["amplitude"]) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(InconsistentSourceError, match="distinct source objects"): - with job: - if prebuilt_first: - first.pod(outside, label="first") - events.where(**captured).select_data_columns(["amplitude"]) - if not prebuilt_first: + with job: + if prebuilt_first: + first.pod(outside, label="first") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): + events.where(**captured).select_data_columns( + ["amplitude"], label="selected" + ) + else: + events.where(**captured).select_data_columns( + ["amplitude"], label="selected" + ) + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): first.pod(outside, label="first") + assert {"first", "selected"} & job.nodes.keys() == { + "first" if prebuilt_first else "selected" + } @pytest.mark.parametrize( "prebuilt_first", [False, True], ids=["captured first", "prebuilt first"] @@ -1222,11 +1241,14 @@ def test_two_inputs_of_one_invocation_are_checked(self, project): """One operator over two differently restricted sources of one table.""" events = _source(source_id="events", tag_only_columns=True) job = PipelineJob(name="two") - with pytest.raises(InconsistentSourceError, match="distinct source objects"): - with job: + with job: + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): events.where(subject_id="m1").semi_join( events.where(subject_id="m2"), label="both" ) + assert not job.nodes @pytest.mark.parametrize("restrict", [False, True]) def test_one_restriction_twice_in_one_job_is_accepted( @@ -1290,10 +1312,13 @@ def second(channel: int | None) -> int | None: return channel job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(InconsistentSourceError, match="distinct source objects"): - with job: - first.pod(_source(source_id="events", limit=1), label="first") + with job: + first.pod(_source(source_id="events", limit=1), label="first") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): second.pod(_source(source_id="events", limit=2), label="second") + assert {"first", "second"} & job.nodes.keys() == {"first"} def test_node_run_reports_the_restriction(self, project, tmp_path): """A node's own ``run()`` reports the restriction in the same shape.""" @@ -2083,11 +2108,16 @@ def test_a_proxy_and_a_source_restricted_two_ways_are_refused_at_capture( proxy = self._bound_proxy("a condition") # subject_id='m1' other = _events().where(subject_id="m2") first, second = (proxy, other) if order == "proxy first" else (other, proxy) - job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(InconsistentSourceError, match="distinct source objects"): - with job: - first.select_data_columns(["amplitude"], label="a") + job = PipelineJob( + name="two", database=DeltaTableDatabase(tmp_path / "s"), auto_compile=False + ) + with job: + first.select_data_columns(["amplitude"], label="a") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): second.select_data_columns(["channel"], label="b") + assert {inv.label for inv in job._invocation_lut.values()} == {"a"} def test_a_cache_over_a_proxy_bound_later_refuses_to_read(self, project, tmp_path): proxy = _proxy_for(_events()) @@ -2233,10 +2263,14 @@ def keep(amplitude: float | None) -> float | None: return amplitude job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(InconsistentSourceError, match="distinct source objects"): - with job: - chains[first_chain](_events().where(subject_id="m1")) + with job: + chains[first_chain](_events().where(subject_id="m1")) + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): chains[second_chain](second()) + assert "events" in job.nodes + assert len(job.nodes) == (3 if first_chain == "map then select" else 2) @pytest.mark.parametrize("order", ["m1 first", "m2 first"]) @pytest.mark.parametrize( @@ -2258,9 +2292,12 @@ def test_chains_built_before_the_job_over_two_restrictions_are_refused( m2 = built[chains[1]](_events().where(subject_id="m2")) first, second = (m1, m2) if order == "m1 first" else (m2, m1) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(InconsistentSourceError, match="distinct source objects"): - with job: + with job: + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): first.semi_join(second, label="both") + assert not job.nodes @pytest.mark.parametrize("order", ["select first", "drop first"]) def test_one_restriction_through_two_chains_is_accepted( diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index f3c489d19..42949bb06 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -210,6 +210,42 @@ def source(x: int, keys: str | None = None) -> ArrowTableSource: assert "different schemas" not in message +@pytest.mark.parametrize("reverse", [False, True]) +def test_cached_bound_proxy_uses_the_live_derived_schema(reverse: bool) -> None: + origin = ArrowTableSource( + pa.table({"t1": ["a"], "t2": ["b"], "x": pa.array([1], type=pa.int32())}), + tag_columns=["t1", "t2"], + tag_only_columns=True, + infer_nullable=True, + source_id="origin", + ) + first = DerivedSource(origin, tags_as_data={"t1": "copy"}, source_id="shared") + second = DerivedSource(origin, tags_as_data={"t2": "copy"}, source_id="shared") + assert first.content_hash() != second.content_hash() + proxy = SourceProxy( + first.source_id, + first.content_hash().to_string(), + first.pipeline_hash().to_string(), + *first.output_schema(), + ) + cached = proxy.cached(InMemoryArrowDatabase()) + assert cached.arrow_schemas[1].field("x").type == pa.int64() + proxy.bind(first) + assert first.arrow_schemas[1] == second.arrow_schemas[1] + assert first.arrow_schemas[1].field("x").type == pa.int32() + + # Prebuilt projections get their own slots, so the two sources are compared + # without also colliding on a direct slot name. + projected = { + "left": cached.map_data({"x": "left_x"}), + "right": second.map_data({"x": "right_x"}), + } + with Pipeline("comparison") as pipeline: + for label in ("right", "left") if reverse else ("left", "right"): + projected[label].map_data({f"{label}_x": "out"}, label=label) + assert {"left", "right"} <= pipeline.nodes.keys() + + def test_implicit_projection_conflict_names_both_function_steps() -> None: first = DictSource([{"x": 1, "y": 2}], source_id="shared") second = DictSource([{"x": 100, "y": 2}], source_id="shared") diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index 6675e4b8a..8a608957a 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -952,6 +952,7 @@ def scale(out: int) -> int: } pod = total.pod assert isinstance(pod, FunctionPod) + expected_binding = source if form == "record": with pytest.raises(InconsistentSourceError, match="not supported yet") as error: receiver.record_function_pod_invocation(pod, slot, label="borrowed") @@ -967,6 +968,16 @@ def scale(out: int) -> int: ) with pytest.raises(InconsistentSourceError, match="not supported yet") as error: PipelineJob.from_invocations(graph) + elif form == "hashed": + mid = total.pod(slot, label="borrowed") + _ = mid.content_hash() + expected_binding = _shifted_source("changed", 10) + slot.bound_source = expected_binding + with ( + receiver, + pytest.raises(InconsistentSourceError, match="not supported yet") as error, + ): + scale.pod(mid, label="downstream") elif form in prebuilt: stream = prebuilt[form]() with ( @@ -982,17 +993,13 @@ def scale(out: int) -> int: receiver, pytest.raises(InconsistentSourceError, match="not supported yet") as error, ): - mid = total.pod(slot, label="borrowed") - if form == "hashed": - _ = mid.content_hash() - slot.bound_source = _shifted_source("changed", 10) - scale.pod(mid, label="downstream") + total.pod(slot, label="borrowed") assert "'a'" in str(error.value) assert "Pass the source itself" in str(error.value) assert "as_source()" in str(error.value) assert "ITL-1559" in str(error.value) - assert slot.bound_source is source + assert slot.bound_source is expected_binding assert set(receiver.nodes) == {"kept", "kept_result"} receiver.run(orchestrator=orchestrator()) assert sorted(receiver.kept_result.as_table()["out"].to_pylist()) == [3, 7] @@ -1179,3 +1186,45 @@ def test_live_derived_source_and_its_source_are_both_capturable( job.run(orchestrator=orchestrator()) assert sorted(job.original.as_table()["out"].to_pylist()) == [3, 7] assert sorted(job.derived.as_table()["out"].to_pylist()) == [2, 12] + + +@pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_prebuilt_stream_over_own_slot_is_refused_before_rebinding( + setter: bool, orchestrator: Orchestrator +) -> None: + from orcapod.operators import SelectDataColumns + + source = _shifted_source("a", 0) + replacement = _shifted_source("b", 10) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + total.pod(source, label="direct") + + slot = job.nodes["a"] + prebuilt = SelectDataColumns(["x", "y"])(slot) + with Pipeline("also_tracking") as outer, job: + with pytest.raises( + InconsistentSourceError, match="'a'.*not supported yet" + ) as error: + total.pod(prebuilt, label="rejected") + assert "ITL-1559" in str(error.value) + assert "inside the job" in str(error.value) + + assert not outer.nodes + assert set(job.nodes) == {"a", "direct"} + slot = job.nodes["a"] + prebuilt_twin = SelectDataColumns(["x", "y"])(slot) + with job: + difference.pod(slot, label="own_slot") + recorded = SelectDataColumns(["x", "y"])(slot) + total.pod(recorded, label="inside") + assert prebuilt_twin.content_hash() == recorded.content_hash() + with pytest.raises(InconsistentSourceError, match="'a'.*not supported yet"): + total.pod(prebuilt_twin, label="rejected_twin") + assert {"rejected", "rejected_twin"}.isdisjoint(job.nodes) + + _rebind(job, {"a": replacement}, setter) + job.run(orchestrator=orchestrator()) + assert sorted(job.direct.as_table()["out"].to_pylist()) == [13, 17] + assert sorted(job.inside.as_table()["out"].to_pylist()) == [13, 17] + assert sorted(job.own_slot.as_table()["out"].to_pylist()) == [9, 9] From e8f38d14864be4aeed50a73010166b7db2f7b185 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 23:51:43 -0800 Subject: [PATCH 30/42] fix(pipeline): reject cyclic source slot bindings --- src/orcapod/core/nodes/source_node.py | 29 ++++++++++-- src/orcapod/errors.py | 6 +-- src/orcapod/pipeline/job.py | 6 ++- tests/test_core/nodes/test_source_node.py | 44 +++++++++++++++++++ .../test_source_object_registration.py | 29 +++++++++++- 5 files changed, 106 insertions(+), 8 deletions(-) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 913a9c4c2..ae138367e 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1584,6 +1584,8 @@ class SourceJobNode(ProvenanceMethods, SourceNodeBase): data_context: Optional data context override. Raises: + SourceSpecMismatchError: If *bound_source* does not fit the slot or would + create a cycle of bound slots. ValueError: If both *tag_schema* and *data_schema* are omitted and *bound_source* is ``None``. """ @@ -1691,7 +1693,8 @@ def bound_source(self, value: StreamProtocol | None) -> None: Raises: InconsistentSourceError: If the replacement introduces conflicting sources. - SourceSpecMismatchError: If *value* does not fit the declared schema. + SourceSpecMismatchError: If *value* does not fit the declared schema or + would create a cycle of bound slots. """ owner = self._binding_owner() if self._binding_owner is not None else None if owner is None: @@ -1708,6 +1711,23 @@ def _bound_stream(self) -> StreamProtocol | None: """The concrete stream bound to this slot, or ``None``.""" return self._bound_source + def _require_acyclic_binding( + self, + source: StreamProtocol | None, + replacements: Mapping[int, StreamProtocol | None] | None = None, + ) -> None: + """Reject a cycle through bound slots, accounting for pending replacements.""" + seen = {id(self)} + while isinstance(source, SourceJobNode): + slot_id = id(source) + if slot_id in seen: + raise SourceSpecMismatchError( + f"Cannot bind source slot {self.name!r}: the binding creates a slot cycle." + ) + seen.add(slot_id) + bound = source.bound_source + source = bound if replacements is None else replacements.get(slot_id, bound) + def _bind(self, value: StreamProtocol | None) -> None: """Check and install a binding without a job-wide transaction. @@ -1716,12 +1736,14 @@ def _bind(self, value: StreamProtocol | None) -> None: Raises: InconsistentSourceError: If the bound stream reads conflicting sources. - SourceSpecMismatchError: If *value* does not fit the declared schema. + SourceSpecMismatchError: If *value* does not fit the declared schema or + would create a cycle of bound slots. """ from orcapod.pipeline.source_consistency import require_consistent_sources form = None if value is not None: + self._require_acyclic_binding(value) require_consistent_sources([(f"slot {self.name!r}", value)]) form = self._declared_form_for(value) self._apply_binding(value, form) @@ -2237,7 +2259,8 @@ def _from_loaded_slot( bound_source: The source rebuilt from the saved config, if any. Raises: - SourceSpecMismatchError: If *bound_source* does not fit the slot. + SourceSpecMismatchError: If *bound_source* does not fit the slot or would + create a cycle of bound slots. """ node = cls( name=slot.name, diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index a6bd41974..14e5393d9 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -546,13 +546,13 @@ class UnboundSourceError(RuntimeError): class SourceSpecMismatchError(InputValidationError, ValueError): - """Raised when a concrete source's schema differs from a source slot's declared schema. + """Raised when a source does not fit its slot or its binding would create a cycle. A source fits a slot when its tag and data columns have the slot's names, roles and Python types (ITL-1112): those are what every downstream pipeline hash, and so every stored path, is built from. The message names the slot and the column, and for a type - difference both types. Raised by ``PipelineJob.bind(sources=...)`` and by assigning a - source node's ``bound_source``, before anything is bound. + difference both types. If a binding would create a cycle through bound slots, the + message names the target slot. Raised before the binding is installed. """ diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index efb15a6e3..23938799e 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -554,7 +554,8 @@ def bind( hash, or sources with one ID differ in schema or key columns (ITL-1506). The job is left as it was. SourceSpecMismatchError: If any source's columns differ from its slot's - declared names, roles or types. + declared names, roles or types, or the bindings would create a cycle + of bound slots. ValueError: If a source key has no matching ``SourceJobNode`` slot, or an operator node that caches (``LOG`` or ``REPLAY``) would read a restricted source, one this bind binds or one already bound @@ -638,6 +639,9 @@ def _prepare_source_bindings( self, rebinding: Rebinding ) -> list[tuple[SourceJobNode, cp.StreamProtocol | None, _DeclaredForm | None]]: """Validate the prospective job and prepare each changed slot's row form.""" + replacements = {id(slot): source for slot, source in rebinding} + for slot, source in rebinding: + slot._require_acyclic_binding(source, replacements) # pyright: ignore[reportPrivateUsage] # validate the proposed slot chain before committing it nodes = self._persistent_node_map.values() require_consistent_sources( ((f"node {node.label!r}", node) for node in nodes), rebinding diff --git a/tests/test_core/nodes/test_source_node.py b/tests/test_core/nodes/test_source_node.py index c88734df7..c571cb14c 100644 --- a/tests/test_core/nodes/test_source_node.py +++ b/tests/test_core/nodes/test_source_node.py @@ -252,6 +252,50 @@ def test_bound_source_property_updates_in_place(self, tag_schema, data_schema): job_node.bound_source = src assert job_node.bound_source is src + @pytest.mark.parametrize( + "length", [1, 2, 3], ids=["direct", "two_slots", "three_slots"] + ) + def test_slot_binding_refuses_cycles(self, tag_schema, data_schema, length): + from orcapod.core.sources.dict_source import DictSource + + source = DictSource( + data=[{"id": 1, "value": 1.0}], tag_columns=["id"], tag_only_columns=True + ) + target = SourceJobNode( + name="target", + tag_schema=tag_schema, + data_schema=data_schema, + bound_source=source, + ) + upstream = target + for index in range(length - 1): + upstream = SourceJobNode(name=f"upstream_{index}", bound_source=upstream) + previous_modified = target.last_modified, upstream.last_modified + + with pytest.raises(SourceSpecMismatchError, match=r"slot 'target'.*cycle"): + target.bound_source = upstream + + assert target.bound_source is source + assert (target.last_modified, upstream.last_modified) == previous_modified + + def test_slot_binding_accepts_acyclic_chain(self, tag_schema, data_schema): + from orcapod.core.sources.dict_source import DictSource + + source = DictSource( + data=[{"id": 1, "value": 1.0}], tag_columns=["id"], tag_only_columns=True + ) + leaf = SourceJobNode(name="slot", bound_source=source) + middle = SourceJobNode(name="slot", bound_source=leaf) + target = SourceJobNode( + name="slot", tag_schema=tag_schema, data_schema=data_schema + ) + target.bound_source = middle + + assert target.bound_source is middle + assert target.as_table().equals(source.as_table()) + target.bound_source = None + assert target.bound_source is None + def test_bound_source_setter_clears_content_hash_cache( self, tag_schema, data_schema ): diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index 8a608957a..ca2973981 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -10,7 +10,7 @@ from orcapod import Pipeline, PipelineJob, function_pod, side_effect_pod from orcapod.databases import InMemoryArrowDatabase -from orcapod.errors import InconsistentSourceError +from orcapod.errors import InconsistentSourceError, SourceSpecMismatchError from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.protocols.core_protocols import StreamProtocol from orcapod.side_effects import SideEffectPod @@ -354,6 +354,33 @@ def test_slot_setter_can_unbind_and_recompile(tmp_path: Path) -> None: assert job.unbound_sources == ["a"] +@pytest.mark.parametrize("setter", [False, True], ids=["batch_bind", "owned_setter"]) +def test_job_binding_refuses_slot_cycles_atomically( + tmp_path: Path, setter: bool +) -> None: + job = _job(tmp_path) + slot_a, slot_b = job.nodes["a"], job.nodes["b"] + original_a, original_b = slot_a.bound_source, slot_b.bound_source + previous_modified = slot_a.last_modified, slot_b.last_modified + original_database = job.database + + with pytest.raises(SourceSpecMismatchError, match=r"slot 'a'.*cycle"): + if setter: + slot_a.bound_source = slot_a + else: + job.bind( + sources={"a": slot_b, "b": slot_a}, + database=InMemoryArrowDatabase(), + ) + + assert slot_a.bound_source is original_a + assert slot_b.bound_source is original_b + assert job.sources["a"] is original_a + assert job.sources["b"] is original_b + assert (slot_a.last_modified, slot_b.last_modified) == previous_modified + assert job.database is original_database + + @pytest.mark.parametrize("binding", ["constructor", "from_stream", "setter"]) @pytest.mark.filterwarnings("ignore::orcapod.errors.SemiJoinIgnoredColumnWarning") def test_source_slot_refuses_composite_with_conflicting_roots( From 8b7d1d91f38ab7ce861af1078e770cebf508bf44 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 23:53:52 -0800 Subject: [PATCH 31/42] test(pipeline): type the slot cycle regressions --- tests/test_core/nodes/test_source_node.py | 8 ++++++-- tests/test_pipeline/test_source_object_registration.py | 7 +++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/tests/test_core/nodes/test_source_node.py b/tests/test_core/nodes/test_source_node.py index c571cb14c..eef3942da 100644 --- a/tests/test_core/nodes/test_source_node.py +++ b/tests/test_core/nodes/test_source_node.py @@ -255,7 +255,9 @@ def test_bound_source_property_updates_in_place(self, tag_schema, data_schema): @pytest.mark.parametrize( "length", [1, 2, 3], ids=["direct", "two_slots", "three_slots"] ) - def test_slot_binding_refuses_cycles(self, tag_schema, data_schema, length): + def test_slot_binding_refuses_cycles( + self, tag_schema: Schema, data_schema: Schema, length: int + ) -> None: from orcapod.core.sources.dict_source import DictSource source = DictSource( @@ -278,7 +280,9 @@ def test_slot_binding_refuses_cycles(self, tag_schema, data_schema, length): assert target.bound_source is source assert (target.last_modified, upstream.last_modified) == previous_modified - def test_slot_binding_accepts_acyclic_chain(self, tag_schema, data_schema): + def test_slot_binding_accepts_acyclic_chain( + self, tag_schema: Schema, data_schema: Schema + ) -> None: from orcapod.core.sources.dict_source import DictSource source = DictSource( diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index ca2973981..93767c6ba 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -4,7 +4,7 @@ import json from pathlib import Path -from typing import Any +from typing import Any, cast import pytest @@ -358,8 +358,11 @@ def test_slot_setter_can_unbind_and_recompile(tmp_path: Path) -> None: def test_job_binding_refuses_slot_cycles_atomically( tmp_path: Path, setter: bool ) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + job = _job(tmp_path) - slot_a, slot_b = job.nodes["a"], job.nodes["b"] + slot_a = cast(SourceJobNode, job.nodes["a"]) + slot_b = cast(SourceJobNode, job.nodes["b"]) original_a, original_b = slot_a.bound_source, slot_b.bound_source previous_modified = slot_a.last_modified, slot_b.last_modified original_database = job.database From 13ad734a7fb042f56f6d3e2e5afb2d57a6bdbf39 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 00:42:20 -0800 Subject: [PATCH 32/42] fix(pipeline): compare live derived schemas and clarify source conflicts --- changelog.d/ITL-1469.md | 3 +- docs/concepts/identity.md | 11 ++- src/orcapod/core/sources/derived_source.py | 16 +++- src/orcapod/pipeline/base.py | 17 ++-- src/orcapod/pipeline/job.py | 2 +- src/orcapod/pipeline/source_consistency.py | 73 +++++++++------ .../test_pipeline/test_source_id_conflicts.py | 88 +++++++++++++++++++ 7 files changed, 166 insertions(+), 44 deletions(-) diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index 68c5bae7d..27c40e2ab 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -7,7 +7,8 @@ a slot's source, and loading shares one rebuilt object across slots with identical source configurations. - Sources with the same source ID must agree on their Arrow schema and key - columns, including when they occupy different slots. + columns, including when they occupy different slots. For tag-copy sources + over a bound proxy, registration uses the live Arrow types. - A capture refused by any active pipeline or job leaves all their graphs unchanged. diff --git a/docs/concepts/identity.md b/docs/concepts/identity.md index 82ac38ac7..d4dfabdb3 100644 --- a/docs/concepts/identity.md +++ b/docs/concepts/identity.md @@ -13,7 +13,7 @@ The content hash captures schema, topology, and the **identity of the sources** pipeline. It is computed recursively: each element's content hash depends on its own identity plus the content hashes of all its upstream elements, all the way back to the sources. -A source's identity is its schema, its `source_id` and its key columns (the +Most sources use their schema, `source_id` and key columns in their identity (the `record_id_columns` that name its rows, or none when rows are named by position). What the `source_id` is depends on how the source was created: @@ -24,9 +24,12 @@ A source's identity is its schema, its `source_id` and its key columns (the path for `CSVSource`, the table folder's path or URI for `DeltaTableSource`), not from the rows. - If you pass `source_id` yourself, you are naming the source. The kind is part of the - canonical ID. Two sources with the same ID, schema and key columns have the same - content hash even when their rows differ. A pipeline or job registers one source - object per content hash at capture, binding, loading and execution. + canonical ID. For sources whose identity uses only the ID, schema and key columns, + matching those fields gives the same content hash even when the rows differ. + `DerivedSource(tags_as_data=...)` also hashes the tag-copy mapping. A derived source + without tag copies takes its identity from the producing node's content hash. + A pipeline or job registers one source object per content hash at capture, binding, + loading and execution. See [source consistency](sources.md#source-ids-name-the-kind-that-reads-the-data). Two sources that differ only in their key columns name the same rows differently, so they diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 4bd337d39..9681a87ec 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -577,7 +577,21 @@ def _compute_arrow_schemas(self) -> "tuple[pa.Schema, pa.Schema]": the origin stores rows. Rows read later must have these types (``_origin_records``). """ - table = self._empty_origin_table() + return self._arrow_schemas_from_origin_table(self._empty_origin_table()) + + def _arrow_schemas_from_origin( + self, tags: pa.Schema, data: pa.Schema + ) -> tuple[pa.Schema, pa.Schema]: + """Apply the tag copies to a live origin's schema for source registration.""" + fields = {field.name: field for field in (*tags, *data)} + return self._arrow_schemas_from_origin_table( + pa.schema(fields.values()).empty_table() + ) + + def _arrow_schemas_from_origin_table( + self, table: pa.Table + ) -> tuple[pa.Schema, pa.Schema]: + """Project the derived tag and data schemas from an origin's empty table.""" for tag, name in (self._tags_as_data or {}).items(): table = table.append_column( table.schema.field(tag).with_name(name), table.column(tag) diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index e46774f5d..f8dd9ccac 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -70,7 +70,7 @@ def _refuse_sources_sharing_a_slot_name( described = ( ", ".join(repr(i) for i in ids) if len(ids) > 1 - else f"{ids[0]!r} ({len(sources)} sources with other key columns or rows)" + else f"{ids[0]!r} ({len(sources)} distinct content hashes)" ) raise SourceSlotNameCollisionError( f"{len(sources)} different sources would take the slot name {slot_name!r}: " @@ -396,10 +396,11 @@ def _remember_invocation( def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse]: """Held inputs and, when supplied, the candidate's inputs before deduplication.""" # Prefer the labelled endpoint of a chain over an implicit projection. - for invocation in reversed(self._invocation_lut.values()): - yield from invocation_source_uses(invocation) - if extra is not None: - yield from invocation_source_uses(extra) + invocations = chain( + reversed(self._invocation_lut.values()), + (extra,) if extra is not None else (), + ) + yield from invocation_source_uses(invocations) for stream in self._source_streams.values(): yield f"source {stream.label!r}", stream @@ -839,11 +840,7 @@ def from_invocations( ), ) ) - require_consistent_sources( - use - for invocation in graph.invocations - for use in invocation_source_uses(invocation) - ) + require_consistent_sources(invocation_source_uses(graph.invocations)) instance._source_streams = dict(graph.source_streams) for inv in graph.invocations: key = inv.content_hash().to_string() diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 23938799e..e3f0e3f79 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -299,7 +299,7 @@ def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse else: yield f"source {stream.label!r}", stream if extra is not None: - yield from invocation_source_uses(extra) + yield from invocation_source_uses((extra,)) def _source_node_from_recording(self, key: str) -> SourceJobNode: """Preserve an explicit binding when recompiling its slot.""" diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index 4f0dd0924..aa2d522d0 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -2,6 +2,7 @@ from __future__ import annotations +from collections import Counter from collections.abc import Iterable from typing import TYPE_CHECKING, cast @@ -9,6 +10,8 @@ from orcapod.utils.schema_utils import arrow_schema_identity if TYPE_CHECKING: + import pyarrow as pa + from orcapod.core.sources.base import RootSource from orcapod.pipeline.pod_invocation import PodInvocation from orcapod.pipeline.restrictions import Rebinding @@ -18,16 +21,28 @@ SourceUse = tuple[str, "StreamProtocol"] -def invocation_source_uses(invocation: PodInvocation) -> Iterable[SourceUse]: - """Name the input streams of a recorded step for diagnostics.""" - label = invocation.label or getattr( - invocation.pod, "label", type(invocation.pod).__name__ - ) - for index, stream in enumerate(invocation.input_streams, 1): - name = f"step {label!r}" - if len(invocation.input_streams) > 1: - name += f" input {index}" - yield name, stream +def invocation_source_uses(invocations: Iterable[PodInvocation]) -> Iterable[SourceUse]: + """Name each invocation's inputs, numbering occurrences of repeated labels.""" + labelled = [ + ( + invocation.label + or getattr(invocation.pod, "label", type(invocation.pod).__name__), + invocation, + ) + for invocation in invocations + ] + counts = Counter(label for label, _ in labelled) + occurrences: Counter[str] = Counter() + for label, invocation in labelled: + step = f"step {label!r}" + if counts[label] > 1: + occurrences[label] += 1 + step += f" (occurrence {occurrences[label]})" + for index, stream in enumerate(invocation.input_streams, 1): + name = step + if len(invocation.input_streams) > 1: + name += f" input {index}" + yield name, stream def root_source_uses( @@ -75,33 +90,37 @@ def root_source_uses( def _comparison_schema(source: RootSource) -> tuple[ContentHash, ContentHash]: - """Compare a bound proxy's live schema through schema-preserving caches.""" + """Use a bound proxy's live Arrow types without changing source identity.""" from orcapod.core.sources.cached_source import CachedSource + from orcapod.core.sources.derived_source import DerivedSource from orcapod.core.sources.source_proxy import SourceProxy from orcapod.core.streams.base import typed_arrow_schemas - current: StreamProtocol = source visited: set[int] = set() - saw_bound_proxy = False - while id(current) not in visited: + + def live_schemas( + current: StreamProtocol, from_proxy: bool = False + ) -> tuple[pa.Schema, pa.Schema] | None: + if id(current) in visited: + return None visited.add(id(current)) if isinstance(current, CachedSource): - current = current.cached_source - elif ( + return live_schemas(current.cached_source, from_proxy=from_proxy) + if ( isinstance(current, SourceProxy) and (delegate := current.delegate) is not None ): - saw_bound_proxy = True - current = delegate - else: - if saw_bound_proxy: - # Cache and proxy schemas may still describe the unbound proxy. - # Keep the delegate's schema, including any tag copies it adds. - return arrow_schema_identity( - *typed_arrow_schemas(current), source.data_context - ) - break - return arrow_schema_identity(*source.arrow_schemas, source.data_context) + return live_schemas(delegate, from_proxy=True) + if isinstance(current, DerivedSource) and ( + inputs := current.live_source_inputs + ): + origin_schemas = live_schemas(inputs[0]) + if origin_schemas is not None: + return current._arrow_schemas_from_origin(*origin_schemas) # pyright: ignore[reportPrivateUsage] # source consistency + return typed_arrow_schemas(current) if from_proxy else None + + schemas = live_schemas(source) or source.arrow_schemas + return arrow_schema_identity(*schemas, source.data_context) def require_consistent_sources( diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index 42949bb06..97df9f528 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -246,6 +246,94 @@ def test_cached_bound_proxy_uses_the_live_derived_schema(reverse: bool) -> None: assert {"left", "right"} <= pipeline.nodes.keys() +@pytest.mark.parametrize("cached_origin", [False, True]) +@pytest.mark.parametrize("same_arrow_type", [False, True]) +def test_tag_copy_uses_live_arrow_schema_after_proxy_binding( + cached_origin: bool, same_arrow_type: bool +) -> None: + def origin(arrow_type: pa.DataType) -> ArrowTableSource: + return ArrowTableSource( + pa.table( + { + "t1": pa.array([1], type=arrow_type), + "t2": pa.array([2], type=arrow_type), + "x": pa.array([3], type=arrow_type), + "y": [4], + } + ), + tag_columns=["t1", "t2"], + tag_only_columns=True, + infer_nullable=True, + source_id="origin", + ) + + live = origin(pa.int32()) + proxy = SourceProxy( + live.source_id, + live.content_hash().to_string(), + live.pipeline_hash().to_string(), + *live.output_schema(), + ) + wrapped = proxy.cached(InMemoryArrowDatabase()) if cached_origin else proxy + first = DerivedSource(wrapped, tags_as_data={"t1": "copy"}, source_id="shared") + assert first.arrow_schemas[1].field("x").type == pa.int64() + captured_hash = first.content_hash() + proxy.bind(live) + + second = DerivedSource( + origin(pa.int32() if same_arrow_type else pa.int64()), + tags_as_data={"t2": "copy"}, + source_id="shared", + ) + assert first.content_hash() != second.content_hash() + # Prebuilt projections separate the slot names so the guard compares the sources. + left = first.map_data({"x": "left_x"}) + right = second.map_data({"x": "right_x"}) + with Pipeline("comparison") as pipeline: + left.map_data({"left_x": "out"}, label="left") + if same_arrow_type: + right.map_data({"right_x": "out"}, label="right") + else: + with pytest.raises(InconsistentSourceError, match="different schemas"): + right.map_data({"right_x": "out"}, label="right") + assert "left" in pipeline.nodes + assert ("right" in pipeline.nodes) == same_arrow_type + assert first.content_hash() == captured_hash + assert first.arrow_schemas[1].field("x").type == pa.int64() + + +@pytest.mark.parametrize("label", [None, "repeated"]) +def test_capture_distinguishes_repeated_step_labels(label: str | None) -> None: + name = label or "increment" + with Pipeline("repeated-steps") as pipeline: + increment.pod(_dict(1), label=label) + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + increment.pod(_dict(2), label=label) + assert f"step {name!r} (occurrence 1)" in str(error.value) + assert f"step {name!r} (occurrence 2)" in str(error.value) + assert name in pipeline.nodes + + +@pytest.mark.parametrize("graph_type", [Pipeline, PipelineJob]) +def test_same_slot_name_describes_distinct_derived_sources_with_equal_rows( + graph_type: type[Pipeline] | type[PipelineJob], +) -> None: + origin = DictSource( + [{"t1": "a", "t2": "a", "x": 1, "y": 2}], + tag_columns=["t1", "t2"], + tag_only_columns=True, + ) + first = DerivedSource(origin, tags_as_data={"t1": "copy"}, source_id="shared") + second = DerivedSource(origin, tags_as_data={"t2": "copy"}, source_id="shared") + assert first.as_table().equals(second.as_table()) + with pytest.raises(SourceSlotNameCollisionError, match="2 distinct content hashes"): + with graph_type("collision"): + first.map_data({"x": "left_x"}, label="left") + second.map_data({"x": "right_x"}, label="right") + + def test_implicit_projection_conflict_names_both_function_steps() -> None: first = DictSource([{"x": 1, "y": 2}], source_id="shared") second = DictSource([{"x": 100, "y": 2}], source_id="shared") From d3b98cee4246537ff17c36bd33a0dbd548ea04eb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 02:21:38 -0800 Subject: [PATCH 33/42] fix(pipeline): refuse bindings that depend on source slots --- changelog.d/ITL-1469.md | 4 + docs/concepts/sources.md | 5 + src/orcapod/core/nodes/source_node.py | 38 ++--- src/orcapod/core/sources/derived_source.py | 10 +- src/orcapod/errors.py | 6 +- src/orcapod/pipeline/job.py | 37 +++-- src/orcapod/pipeline/source_consistency.py | 24 ++- tests/test_core/nodes/test_source_node.py | 32 ++-- .../test_source_object_registration.py | 137 +++++++++++++++++- 9 files changed, 230 insertions(+), 63 deletions(-) diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index 27c40e2ab..3acbbdc43 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -24,3 +24,7 @@ - The ITL-1559 stopgap also refuses prebuilt streams over the receiving job's own slots. Build the step inside the job from its slot, or pass the source itself. +- Binding a slot to a source or stream that depends on any bindable slot raises + `SourceSpecMismatchError` (ITL-1559). A refused batch leaves all bindings + intact. Pass the underlying source, or use `node.as_source()` for stored + results. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index f73ec9479..8ebdae8c1 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -104,6 +104,11 @@ The ITL-1559 stopgap also refuses a prebuilt stream over the receiving job's own slot. Pass that slot directly into a step inside the job, or pass the source itself. +Binding a source slot to a source or stream that depends on any bindable slot +raises `SourceSpecMismatchError` (ITL-1559). Pass the underlying source or +use `node.as_source()` to read stored results. If a batch contains a refused +binding, every existing binding stays in place. + The capture and restriction checks follow wrappers that can read live inputs. This includes tag-copy `DerivedSource` over a live source. A `DerivedSource` over a job node reads stored results, so the checks stop there. Source object diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index ae138367e..83a7be915 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1584,8 +1584,8 @@ class SourceJobNode(ProvenanceMethods, SourceNodeBase): data_context: Optional data context override. Raises: - SourceSpecMismatchError: If *bound_source* does not fit the slot or would - create a cycle of bound slots. + SourceSpecMismatchError: If *bound_source* does not fit the slot or depends + on a bindable source slot (ITL-1559). ValueError: If both *tag_schema* and *data_schema* are omitted and *bound_source* is ``None``. """ @@ -1599,6 +1599,9 @@ def __init__( data_context: str | contexts.DataContext | None = None, arrow_schemas: "tuple[pa.Schema, pa.Schema] | None" = None, ) -> None: + from orcapod.pipeline.source_consistency import require_slot_free_binding + + require_slot_free_binding(name, bound_source) if tag_schema is None or data_schema is None: if bound_source is None: raise ValueError( @@ -1694,10 +1697,13 @@ def bound_source(self, value: StreamProtocol | None) -> None: Raises: InconsistentSourceError: If the replacement introduces conflicting sources. SourceSpecMismatchError: If *value* does not fit the declared schema or - would create a cycle of bound slots. + depends on a bindable source slot (ITL-1559). """ + from orcapod.pipeline.source_consistency import require_slot_free_binding + owner = self._binding_owner() if self._binding_owner is not None else None if owner is None: + require_slot_free_binding(self.name, value) self._bind(value) self._update_modified_time() else: @@ -1711,39 +1717,20 @@ def _bound_stream(self) -> StreamProtocol | None: """The concrete stream bound to this slot, or ``None``.""" return self._bound_source - def _require_acyclic_binding( - self, - source: StreamProtocol | None, - replacements: Mapping[int, StreamProtocol | None] | None = None, - ) -> None: - """Reject a cycle through bound slots, accounting for pending replacements.""" - seen = {id(self)} - while isinstance(source, SourceJobNode): - slot_id = id(source) - if slot_id in seen: - raise SourceSpecMismatchError( - f"Cannot bind source slot {self.name!r}: the binding creates a slot cycle." - ) - seen.add(slot_id) - bound = source.bound_source - source = bound if replacements is None else replacements.get(slot_id, bound) - def _bind(self, value: StreamProtocol | None) -> None: - """Check and install a binding without a job-wide transaction. + """Check and install a binding once its independence from slots is checked. The binding the setter and ``__init__`` share. Only the setter stamps the slot as modified (ITL-1095): a node built with its source is not a rebinding. Raises: InconsistentSourceError: If the bound stream reads conflicting sources. - SourceSpecMismatchError: If *value* does not fit the declared schema or - would create a cycle of bound slots. + SourceSpecMismatchError: If *value* does not fit the declared schema. """ from orcapod.pipeline.source_consistency import require_consistent_sources form = None if value is not None: - self._require_acyclic_binding(value) require_consistent_sources([(f"slot {self.name!r}", value)]) form = self._declared_form_for(value) self._apply_binding(value, form) @@ -2259,8 +2246,7 @@ def _from_loaded_slot( bound_source: The source rebuilt from the saved config, if any. Raises: - SourceSpecMismatchError: If *bound_source* does not fit the slot or would - create a cycle of bound slots. + SourceSpecMismatchError: If *bound_source* does not fit the slot. """ node = cls( name=slot.name, diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 9681a87ec..600bcc82b 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -474,8 +474,14 @@ def _data_tags(self) -> tuple[str, ...]: @property def live_source_inputs(self) -> tuple[StreamProtocol, ...] | None: - """Tag copies over a source read it live. Job nodes give stored results.""" - return (self._origin,) if isinstance(self._origin, RootSource) else None + """Expose live origins while treating stored-result job nodes as leaves.""" + from orcapod.core.nodes.source_node import SourceJobNode + + return ( + (self._origin,) + if isinstance(self._origin, (RootSource, SourceJobNode)) + else None + ) def _origin_records(self) -> "pa.Table | None": """Return the origin's rows, or ``None`` when a job node has none stored. diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 849522256..d1c9e77c3 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -612,13 +612,13 @@ class UnboundSourceError(RuntimeError): class SourceSpecMismatchError(InputValidationError, ValueError): - """Raised when a source does not fit its slot or its binding would create a cycle. + """Raised when a source does not fit its slot or depends on a bindable slot. A source fits a slot when its tag and data columns have the slot's names, roles and Python types (ITL-1112): those are what every downstream pipeline hash, and so every stored path, is built from. The message names the slot and the column, and for a type - difference both types. If a binding would create a cycle through bound slots, the - message names the target slot. Raised before the binding is installed. + difference both types. For a slot-dependent source, the message names both slots + (ITL-1559). Raised before the binding is installed. """ diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index e3f0e3f79..cf2d9c5d5 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -49,6 +49,7 @@ from orcapod.pipeline.source_consistency import ( invocation_source_uses, require_consistent_sources, + require_slot_free_binding, ) from orcapod.protocols import core_protocols as cp from orcapod.databases.utils import as_table_committing @@ -554,8 +555,8 @@ def bind( hash, or sources with one ID differ in schema or key columns (ITL-1506). The job is left as it was. SourceSpecMismatchError: If any source's columns differ from its slot's - declared names, roles or types, or the bindings would create a cycle - of bound slots. + declared names, roles or types, or the source depends on a bindable + source slot (ITL-1559). ValueError: If a source key has no matching ``SourceJobNode`` slot, or an operator node that caches (``LOG`` or ``REPLAY``) would read a restricted source, one this bind binds or one already bound @@ -639,9 +640,8 @@ def _prepare_source_bindings( self, rebinding: Rebinding ) -> list[tuple[SourceJobNode, cp.StreamProtocol | None, _DeclaredForm | None]]: """Validate the prospective job and prepare each changed slot's row form.""" - replacements = {id(slot): source for slot, source in rebinding} for slot, source in rebinding: - slot._require_acyclic_binding(source, replacements) # pyright: ignore[reportPrivateUsage] # validate the proposed slot chain before committing it + require_slot_free_binding(slot.name, source) nodes = self._persistent_node_map.values() require_consistent_sources( ((f"node {node.label!r}", node) for node in nodes), rebinding @@ -1885,6 +1885,8 @@ def load( InconsistentSourceError: If distinct reconstructed source objects share a content hash, or sources with one ID differ in schema or key columns (ITL-1506). + SourceSpecMismatchError: If a reconstructed source depends on a bindable + source slot (ITL-1559). ValueError: If the file's format version is not the one this Orcapod writes (an earlier format is refused, never migrated), or if it was saved before the database key was renamed (``bindings.store`` @@ -1992,6 +1994,7 @@ def load( check_saved_source_config(src_config) except ValueError as exc: raise ValueError(f"{path}: source {spec_name!r}: {exc}") from exc + failure: Exception | None = None try: # Slots written with the same complete config share one rebuild. config_key = _json.dumps(src_config, sort_keys=True) @@ -2000,13 +2003,23 @@ def load( src_config ) source = sources_by_config[config_key] - if source is not None: - # A rebuilt source its slot refuses (a file whose column types - # changed) is one that could not be rebuilt (ITL-1112). + except Exception as exc: + failure = exc + else: + if source is None: + continue + require_slot_free_binding(spec_name, source) + try: + # A rebuilt source whose column types changed is treated as + # one that could not be rebuilt (ITL-1112). if spec_name in slots: slots[spec_name].validate(source) + except Exception as exc: + failure = exc + else: sources[spec_name] = source - except NotImplementedError: + + if isinstance(failure, NotImplementedError): # In-memory sources (DictSource, ListSource, ArrowTableSource, # DataFrameSource) are not saved with the job, by design. logger.info( @@ -2019,12 +2032,12 @@ def load( spec_name, spec_name, ) - except Warning: + elif isinstance(failure, Warning): # A warning turned into an error (a ProvisionalHashWarning under an # error filter) is the caller's request: it propagates, never read as a # source that could not be rebuilt (ITL-1331). - raise - except Exception as exc: + raise failure + elif failure is not None: logger.warning( "Could not reconstruct source %r (%s) from its saved config: %s. " "Stored function-node results are still readable from the database. " @@ -2033,7 +2046,7 @@ def load( spec_name, saved_source_kind(src_config), # Its type, never its text (ITL-1391). - type(exc).__name__, + type(failure).__name__, spec_name, spec_name, ) diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index aa2d522d0..1bba8369d 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -6,7 +6,7 @@ from collections.abc import Iterable from typing import TYPE_CHECKING, cast -from orcapod.errors import InconsistentSourceError +from orcapod.errors import InconsistentSourceError, SourceSpecMismatchError from orcapod.utils.schema_utils import arrow_schema_identity if TYPE_CHECKING: @@ -21,6 +21,28 @@ SourceUse = tuple[str, "StreamProtocol"] +def require_slot_free_binding(name: str, source: StreamProtocol | None) -> None: + """Report a proposed binding that reads a bindable job slot.""" + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.pipeline.restrictions import streams_beneath + + # TODO(ITL-1559): live slot references can create cycles or retain an old + # slot after recompilation. Stored-result sources end the live-input walk. + pending = [] if source is None else [source] + visited: set[int] = set() + while pending: + stream = pending.pop() + if id(stream) in visited: + continue + visited.add(id(stream)) + if isinstance(stream, SourceJobNode): + raise SourceSpecMismatchError( + f"Binding source slot {name!r} to a source that depends on source " + f"slot {stream.name!r} is not supported yet (ITL-1559)." + ) + pending.extend(streams_beneath(stream)) + + def invocation_source_uses(invocations: Iterable[PodInvocation]) -> Iterable[SourceUse]: """Name each invocation's inputs, numbering occurrences of repeated labels.""" labelled = [ diff --git a/tests/test_core/nodes/test_source_node.py b/tests/test_core/nodes/test_source_node.py index eef3942da..10a02e025 100644 --- a/tests/test_core/nodes/test_source_node.py +++ b/tests/test_core/nodes/test_source_node.py @@ -8,6 +8,7 @@ from orcapod.core.nodes.source_node import SourceJobNode from orcapod.errors import SourceSpecMismatchError, UnboundSourceError +from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import ColumnConfig, Schema @@ -253,12 +254,13 @@ def test_bound_source_property_updates_in_place(self, tag_schema, data_schema): assert job_node.bound_source is src @pytest.mark.parametrize( - "length", [1, 2, 3], ids=["direct", "two_slots", "three_slots"] + "length", [1, 2, 3], ids=["direct", "one_projection", "two_projections"] ) def test_slot_binding_refuses_cycles( self, tag_schema: Schema, data_schema: Schema, length: int ) -> None: from orcapod.core.sources.dict_source import DictSource + from orcapod.operators import SelectDataColumns source = DictSource( data=[{"id": 1, "value": 1.0}], tag_columns=["id"], tag_only_columns=True @@ -269,33 +271,37 @@ def test_slot_binding_refuses_cycles( data_schema=data_schema, bound_source=source, ) - upstream = target - for index in range(length - 1): - upstream = SourceJobNode(name=f"upstream_{index}", bound_source=upstream) - previous_modified = target.last_modified, upstream.last_modified + upstream: StreamProtocol = target + for _ in range(length - 1): + upstream = SelectDataColumns(["value"])(upstream) + previous_modified = target.last_modified - with pytest.raises(SourceSpecMismatchError, match=r"slot 'target'.*cycle"): + with pytest.raises( + SourceSpecMismatchError, match=r"slot 'target'.*slot 'target'.*ITL-1559" + ): target.bound_source = upstream assert target.bound_source is source - assert (target.last_modified, upstream.last_modified) == previous_modified + assert target.last_modified == previous_modified + assert target.as_table().equals(source.as_table()) - def test_slot_binding_accepts_acyclic_chain( - self, tag_schema: Schema, data_schema: Schema + @pytest.mark.parametrize("cached", [False, True]) + def test_slot_binding_accepts_slot_free_source_and_unbinding( + self, tag_schema: Schema, data_schema: Schema, cached: bool ) -> None: from orcapod.core.sources.dict_source import DictSource + from orcapod.databases import InMemoryArrowDatabase source = DictSource( data=[{"id": 1, "value": 1.0}], tag_columns=["id"], tag_only_columns=True ) - leaf = SourceJobNode(name="slot", bound_source=source) - middle = SourceJobNode(name="slot", bound_source=leaf) + binding = source.cached(InMemoryArrowDatabase()) if cached else source target = SourceJobNode( name="slot", tag_schema=tag_schema, data_schema=data_schema ) - target.bound_source = middle + target.bound_source = binding - assert target.bound_source is middle + assert target.bound_source is binding assert target.as_table().equals(source.as_table()) target.bound_source = None assert target.bound_source is None diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index 93767c6ba..03215d2e3 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -12,7 +12,7 @@ from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import InconsistentSourceError, SourceSpecMismatchError from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator -from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.protocols.core_protocols import SourceProtocol, StreamProtocol from orcapod.side_effects import SideEffectPod from orcapod.sources import CSVSource, DictSource @@ -367,7 +367,10 @@ def test_job_binding_refuses_slot_cycles_atomically( previous_modified = slot_a.last_modified, slot_b.last_modified original_database = job.database - with pytest.raises(SourceSpecMismatchError, match=r"slot 'a'.*cycle"): + dependency = "a" if setter else "b" + with pytest.raises( + SourceSpecMismatchError, match=rf"slot 'a'.*slot '{dependency}'.*ITL-1559" + ): if setter: slot_a.bound_source = slot_a else: @@ -384,6 +387,123 @@ def test_job_binding_refuses_slot_cycles_atomically( assert job.database is original_database +@pytest.mark.parametrize("path", ["standalone_setter", "owned_setter", "batch_bind"]) +def test_binding_refuses_projection_over_the_receiving_slot( + tmp_path: Path, path: str +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SelectDataColumns + + job = _job(tmp_path) + original = job.sources["a"] + slot = ( + SourceJobNode("a", bound_source=original) + if path == "standalone_setter" + else cast(SourceJobNode, job.nodes["a"]) + ) + view = SelectDataColumns(["x", "y"])(slot) + before = job.sources + + with pytest.raises( + SourceSpecMismatchError, + match=r"slot 'a'.*slot 'a'.*not supported yet.*ITL-1559", + ): + if path == "batch_bind": + job.bind(sources={"b": _shifted_source("replacement", 10), "a": view}) + else: + slot.bound_source = view + + assert slot.bound_source is original + assert job.sources == before + assert slot.run().table.to_pylist() == ROWS + assert job.nodes["b"].bound_source is before["b"] + + +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +@pytest.mark.parametrize("kind", ["direct", "projection", "join", "cached", "derived"]) +def test_bind_refuses_other_slots_atomically_and_recompile_preserves_rows( + tmp_path: Path, kind: str, orchestrator: Orchestrator +) -> None: + from orcapod.operators import Join, SelectDataColumns + from orcapod.core.nodes.function_node import FunctionJobNode + from orcapod.sources import CachedSource, DerivedSource + + job = _job(tmp_path, ("a", "b", "c")) + slot_b, slot_c = job.nodes["b"], job.nodes["c"] + candidate: StreamProtocol = slot_b + if kind == "projection": + candidate = SelectDataColumns(["x", "y"])(slot_b) + elif kind == "join": + candidate = Join()( + SelectDataColumns(["x"])(slot_b), SelectDataColumns(["y"])(slot_c) + ) + elif kind == "cached": + candidate = CachedSource( + cast(SourceProtocol, slot_b), cache_database=InMemoryArrowDatabase() + ) + elif kind == "derived": + candidate = DerivedSource( + cast(FunctionJobNode, slot_b), + source_id="from_slot", + tags_as_data={"t1": "t"}, + ) + + before = job.sources + with pytest.raises( + SourceSpecMismatchError, + match=r"slot 'a'.*slot '[bc]'.*not supported yet.*ITL-1559", + ): + job.bind(sources={"c": _shifted_source("replacement", 10), "a": candidate}) + + for name, source in before.items(): + assert job.sources[name] is job.nodes[name].bound_source is source + assert job.nodes[name].as_table().to_pylist() == ROWS + job.compile() + assert all( + job.nodes[name].bound_source is source for name, source in before.items() + ) + job.run(orchestrator=orchestrator()) + assert sorted(job.nodes["result_a"].as_table()["out"].to_pylist()) == [3, 7] + assert sorted(job.nodes["result_b"].as_table()["out"].to_pylist()) == [-1, -1] + assert sorted(job.nodes["result_c"].as_table()["out"].to_pylist()) == [2, 12] + + +@pytest.mark.parametrize("bound", [False, True]) +@pytest.mark.parametrize("path", ["constructor", "from_pipeline", "load"]) +def test_initial_bind_refuses_a_foreign_slot( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, bound: bool, path: str +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.pipeline import serialization + + other = _job(tmp_path) + foreign = cast(SourceJobNode, other.nodes["b"]) + if not bound: + foreign.bound_source = None + old_binding = foreign.bound_source + job = _job(tmp_path) + match = r"slot 'a'.*slot 'b'.*not supported yet.*ITL-1559" + + if path == "constructor": + with pytest.raises(SourceSpecMismatchError, match=match): + SourceJobNode("a", bound_source=foreign) + elif path == "from_pipeline": + pipeline = job.as_pipeline() + with pytest.raises(SourceSpecMismatchError, match=match): + PipelineJob.from_pipeline(pipeline, sources={"a": foreign}) + else: + job_path = tmp_path / "job.json" + job.save(job_path) + monkeypatch.setattr( + serialization, "resolve_source_from_config", lambda _config: foreign + ) + with pytest.raises(SourceSpecMismatchError, match=match): + PipelineJob.load(job_path) + + assert foreign.bound_source is old_binding + assert job.nodes["a"].as_table().to_pylist() == ROWS + + @pytest.mark.parametrize("binding", ["constructor", "from_stream", "setter"]) @pytest.mark.filterwarnings("ignore::orcapod.errors.SemiJoinIgnoredColumnWarning") def test_source_slot_refuses_composite_with_conflicting_roots( @@ -491,15 +611,18 @@ def source(name: str, kind: pa.DataType) -> ArrowTableSource: @pytest.mark.filterwarnings("ignore::orcapod.errors.SemiJoinIgnoredColumnWarning") -def test_source_slot_run_checks_roots_changed_after_binding(tmp_path: Path) -> None: +def test_source_slot_run_checks_roots_changed_after_binding( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: from orcapod.core.nodes.source_node import SourceJobNode from orcapod.operators import SemiJoin first, conflict = _pair(tmp_path, "different", False) - right = SourceJobNode.from_stream(_source(tmp_path, "dict", "other")) + right = _source(tmp_path, "dict", "other") composite = SemiJoin()(first, right, label="matched") slot = SourceJobNode.from_stream(composite, name="standalone") - right.bound_source = conflict + # Simulate a rewired composite; its original binding uses only plain sources. + monkeypatch.setattr(composite, "_upstreams", (first, conflict)) with pytest.raises(InconsistentSourceError, match="distinct source objects"): slot.run() @@ -1071,11 +1194,13 @@ def test_capture_accepts_own_slots_and_another_jobs_stored_results( def scale(out: int) -> int: return out * 10 + stored_source = upstream.before.as_source() with PipelineJob(database=InMemoryArrowDatabase()) as receiver: with pytest.raises(InconsistentSourceError, match="not supported yet"): scale.pod(upstream.before, label="borrowed") - scale.pod(upstream.before.as_source(), label="stored") + scale.pod(stored_source, label="stored") assert "borrowed" not in receiver.nodes + receiver.bind(sources={stored_source.source_name: stored_source}) receiver.run(orchestrator=orchestrator()) assert sorted(receiver.stored.as_table()["scaled"].to_pylist()) == [30, 70] From 50efa4d9afcef8bec3f8d5612ca1a89a260782f5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 02:22:44 -0800 Subject: [PATCH 34/42] test(pipeline): exercise restriction refusal with a concrete source --- .../test_spiraldb_table_source_where.py | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index 700bcc9d1..d6de06ffc 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -2194,30 +2194,24 @@ def test_nothing_changes_and_a_second_bind_behaves_alike( assert after[0] is before[0] and after[1] is before[1] @pytest.mark.parametrize("mode", _CACHING, ids=lambda m: m.name) - @pytest.mark.parametrize("inner_name", ["events", "inner"]) @pytest.mark.parametrize("with_database", [True, False], ids=["db", "no-db"]) - def test_a_slot_over_a_restricted_slot_is_refused_before_anything_changes( - self, project, tmp_path, mode, inner_name, with_database + def test_binding_a_restricted_source_is_refused_before_anything_changes( + self, project, tmp_path, mode, with_database ): - """A source to bind that is itself a slot (of another job) bound to a - restricted source: its restriction is read, whatever its name. Only the - job's own slots take the source being bound (CodeRabbit, PR 435).""" - from orcapod.core.nodes.source_node import SourceJobNode - + """Refuse a cache over a prospective restricted binding (PR 435).""" store = DeltaTableDatabase(tmp_path / "s") job = TestRestrictionThroughWrappers._cached_job(store, mode) node, slot = job.nodes["rename"], job.nodes["events"] - inner = SourceJobNode.from_stream(_events(), name=inner_name) - inner.bound_source = _events().where(subject_id="m1") + restricted = _events().where(subject_id="m1") before = (job.database, node._pipeline_database, slot.bound_source) # pyright: ignore[reportPrivateUsage] other = DeltaTableDatabase(tmp_path / "other") for _ in range(2): with pytest.raises(ValueError, match="cannot cache a restricted read"): if with_database: - job.bind(sources={"events": inner}, database=other) + job.bind(sources={"events": restricted}, database=other) else: - job.bind(sources={"events": inner}) + job.bind(sources={"events": restricted}) after = (job.database, node._pipeline_database, slot.bound_source) # pyright: ignore[reportPrivateUsage] assert all(a is b for a, b in zip(after, before, strict=True)) From d18b20ddc1f34e51d65e3b032703d975a5a72a22 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 03:03:53 -0800 Subject: [PATCH 35/42] fix(pipeline): revalidate source slot bindings before runs --- .zed/rules | 4 + CLAUDE.md | 4 + changelog.d/ITL-1469.md | 3 + docs/concepts/pipeline-job.md | 18 ++ docs/concepts/sources.md | 6 +- src/orcapod/core/nodes/function_node.py | 12 +- src/orcapod/core/nodes/operator_node.py | 8 +- src/orcapod/core/nodes/source_node.py | 42 ++++- src/orcapod/core/nodes/staleness.py | 22 ++- src/orcapod/core/sources/source_proxy.py | 17 +- src/orcapod/errors.py | 14 +- src/orcapod/pipeline/job.py | 16 +- src/orcapod/pipeline/node_run.py | 18 +- src/orcapod/pipeline/source_consistency.py | 75 ++++++-- src/orcapod/side_effects.py | 2 + .../test_source_object_registration.py | 168 ++++++++++++++++++ 16 files changed, 387 insertions(+), 42 deletions(-) diff --git a/.zed/rules b/.zed/rules index c7ede4026..32ea06421 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1620,6 +1620,10 @@ data. The rules: original bindings. A schema-only SourceNode declares a new unbound slot. The ITL-1559 stopgap also refuses prebuilt streams over the job's own slots. Build the step inside the job from the slot, or pass the source itself. + A slot binding must be independent of every bindable slot, including through + live wrappers. Binding and run preparation (both job and node, including + load-only) report a dependency as SourceSpecMismatchError. Pass the underlying + source or use a non-slot node's as_source() for stored results. Call where() once and reuse the resulting object. A source object conflict raises InconsistentSourceError before the separate restriction check, which can see restrictions beneath wrappers. diff --git a/CLAUDE.md b/CLAUDE.md index 91b00c3d1..9532b9446 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1669,6 +1669,10 @@ data. The rules: original bindings. A schema-only SourceNode declares a new unbound slot. The ITL-1559 stopgap also refuses prebuilt streams over the job's own slots. Build the step inside the job from the slot, or pass the source itself. + A slot binding must be independent of every bindable slot, including through + live wrappers. Binding and run preparation (both job and node, including + load-only) report a dependency as SourceSpecMismatchError. Pass the underlying + source or use a non-slot node's as_source() for stored results. Call where() once and reuse the resulting object. A source object conflict raises InconsistentSourceError before the separate restriction check, which can see restrictions beneath wrappers. diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index 3acbbdc43..796f0e463 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -11,6 +11,9 @@ over a bound proxy, registration uses the live Arrow types. - A capture refused by any active pipeline or job leaves all their graphs unchanged. +- Job and node runs recheck that bound sources do not depend on source slots. + If a live input changes after binding and introduces a slot dependency, + execution raises `SourceSpecMismatchError` before reading sources. ### Known limitations diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 3b687d646..08a912e7b 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -382,6 +382,24 @@ tag_schema=Schema({...}), data_schema=Schema({...}))`) means one Arrow type per zones, declare the slot with Arrow schemas (`tag_schema=pa.schema([...])`). Binding a source never changes a node's schema or where its results are stored. +A binding must also be independent of every bindable source slot, including +slots reached through operators or source wrappers. As a stopgap pending +ITL-1559, the job checks this when binding and again before each run, including +a load-only run. This check also applies to a direct node run. Pass the +underlying source, or use a non-slot node's `as_source()` to read stored results. + +```python +from orcapod.errors import SourceSpecMismatchError +from orcapod.operators import SelectDataColumns + +projection = SelectDataColumns(["weight", "height"])(job_b.nodes["mice"]) +try: + job_a.bind(sources={"mice": projection}) +except SourceSpecMismatchError as error: + print(error) +# Binding source slot 'mice' to a source that depends on source slot 'mice' is not supported yet (ITL-1559). Pass the underlying source, or use a non-slot node's as_source() to read stored results. +``` + A job made without sources has **unbound** slots. It can still be run: nodes that depend on an unbound source are skipped, and `job.unbound_sources` lists what is missing. Bind later with `job.bind(...)`: diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index e993a63e4..7bb9c5ddf 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -106,8 +106,10 @@ source itself. Binding a source slot to a source or stream that depends on any bindable slot raises `SourceSpecMismatchError` (ITL-1559). Pass the underlying source or -use `node.as_source()` to read stored results. If a batch contains a refused -binding, every existing binding stays in place. +use a non-slot node's `as_source()` to read stored results. If a batch contains +a refused binding, every existing binding stays in place. Job and node runs +recheck the binding before reading sources, including for load-only runs, +because an operator or wrapper can change its inputs after binding. The capture and restriction checks follow wrappers that can read live inputs. This includes tag-copy `DerivedSource` over a live source. A `DerivedSource` diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index e7e890a89..453847887 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -331,8 +331,8 @@ def run_job_node( ) -> None: """Run a job node as its ``run()`` does (developer, November 13, 2026; ITL-1095). - Source registrations are checked as in ``job.run()`` before reading new data. Every - source feeding the node is first checked for new data (``check_sources``, + Source bindings and registrations are checked as in ``job.run()``. Every + source feeding the node is then checked for new data (``check_sources``, ITL-1102). Nothing runs when the node then holds a current run (``holds_current_run``). Otherwise a node that depends on job nodes runs with them (``run_with_dependencies``) and one built over streams outside a job runs alone @@ -355,8 +355,12 @@ def run_job_node( ) from orcapod.pipeline.restrictions import refuse_restriction_conflicts from orcapod.pipeline.run_summary import warn_row_failures - from orcapod.pipeline.source_consistency import require_consistent_sources + from orcapod.pipeline.source_consistency import ( + require_consistent_sources, + require_run_source_bindings, + ) + require_run_source_bindings([node]) require_consistent_sources([(f"node {node.label!r}", node)]) # A source read under two restrictions, or a caching operator over a restricted # source, is refused before any source is checked and before anything is @@ -4348,6 +4352,8 @@ def run(self, *, load_only: bool = False) -> StreamView: (``CACHE_ONLY``): read its stored rows with ``as_source()``. InconsistentSourceError: If distinct source objects share a content hash, or sources with one ID differ in schema or key columns. + SourceSpecMismatchError: If a bound source now depends on a bindable slot + or the live inputs contain a cycle (ITL-1559). """ from orcapod.pipeline.serialization import LoadStatus diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 6a5eeb5c6..55668dba5 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1953,6 +1953,8 @@ def run(self, *, load_only: bool = False) -> StreamView: ``REPLAY``) over a restricted source (ITL-1218); nothing has run. InconsistentSourceError: If distinct source objects share a content hash, or sources with one ID differ in schema or key columns. + SourceSpecMismatchError: If a bound source now depends on a bindable slot + or the live inputs contain a cycle (ITL-1559). """ from orcapod.pipeline.node_run import ( check_sources, @@ -1962,10 +1964,14 @@ def run(self, *, load_only: bool = False) -> StreamView: ) from orcapod.pipeline.restrictions import refuse_restriction_conflicts from orcapod.pipeline.run_summary import warn_row_failures - from orcapod.pipeline.source_consistency import require_consistent_sources + from orcapod.pipeline.source_consistency import ( + require_consistent_sources, + require_run_source_bindings, + ) if self._loaded and not load_only: raise self._cannot_compute_error() + require_run_source_bindings([self]) require_consistent_sources([(f"node {self.label!r}", self)]) # A source read under two restrictions, or a caching operator over a restricted # source, is refused before any source is checked and before anything is diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 83a7be915..31c5cc373 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1599,9 +1599,13 @@ def __init__( data_context: str | contexts.DataContext | None = None, arrow_schemas: "tuple[pa.Schema, pa.Schema] | None" = None, ) -> None: - from orcapod.pipeline.source_consistency import require_slot_free_binding + from orcapod.pipeline.source_consistency import ( + slot_dependency, + slot_dependency_error, + ) - require_slot_free_binding(name, bound_source) + if (dependency := slot_dependency(bound_source)) is not None: + raise slot_dependency_error(name, dependency) if tag_schema is None or data_schema is None: if bound_source is None: raise ValueError( @@ -1664,13 +1668,19 @@ def run(self, *, load_only: bool = False) -> StreamView: Raises: InconsistentSourceError: If the bound stream reads conflicting sources. + SourceSpecMismatchError: If the bound stream now depends on a source slot + or its live inputs contain a cycle (ITL-1559). UnboundSourceError: When no concrete source is bound. ValueError: If ``load_only`` and the bound stream computes or delivers when read (``node_run.refuse_unloadable_inputs``). """ from orcapod.pipeline.node_run import check_sources, refuse_unloadable_inputs - from orcapod.pipeline.source_consistency import require_consistent_sources + from orcapod.pipeline.source_consistency import ( + require_consistent_sources, + require_run_source_bindings, + ) + require_run_source_bindings([self]) require_consistent_sources([(f"node {self.label!r}", self)]) _ = check_sources([self]) if load_only: @@ -1699,11 +1709,15 @@ def bound_source(self, value: StreamProtocol | None) -> None: SourceSpecMismatchError: If *value* does not fit the declared schema or depends on a bindable source slot (ITL-1559). """ - from orcapod.pipeline.source_consistency import require_slot_free_binding + from orcapod.pipeline.source_consistency import ( + slot_dependency, + slot_dependency_error, + ) owner = self._binding_owner() if self._binding_owner is not None else None if owner is None: - require_slot_free_binding(self.name, value) + if (dependency := slot_dependency(value)) is not None: + raise slot_dependency_error(self.name, dependency) self._bind(value) self._update_modified_time() else: @@ -1757,9 +1771,16 @@ def last_modified(self) -> datetime | None: data change (one built over data held in memory) is not re-read: build a new source object and bind it, or clear the dependent nodes. """ + from orcapod.pipeline.source_consistency import ( + slot_dependency, + slot_dependency_error, + ) + own = self._modified_time if self._bound_source is None: return own + if (dependency := slot_dependency(self._bound_source)) is not None: + raise slot_dependency_error(self.name, dependency) bound = self._bound_source.last_modified if bound is None or own is None: return bound @@ -2178,6 +2199,9 @@ def from_stream( Returns: A ``SourceJobNode`` configured according to the case above. + + Raises: + SourceSpecMismatchError: If the stream to be bound depends on a source slot. """ match stream: case SourceJobNode(): @@ -2206,6 +2230,14 @@ def from_stream( return node case _: # Case 3: concrete stream — bound SJN. + from orcapod.pipeline.source_consistency import ( + slot_dependency, + slot_dependency_error, + ) + + # Schema and source-name inference can consult the live inputs. + if (dependency := slot_dependency(stream)) is not None: + raise slot_dependency_error(name, dependency) # Slot name priority: # 1. explicit *name* parameter # 2. stream.source_name for RootSource (its id without the kind part) diff --git a/src/orcapod/core/nodes/staleness.py b/src/orcapod/core/nodes/staleness.py index b7a140a61..3a12199e8 100644 --- a/src/orcapod/core/nodes/staleness.py +++ b/src/orcapod/core/nodes/staleness.py @@ -11,6 +11,8 @@ from collections.abc import Iterable from typing import Any +from orcapod.errors import live_input_cycle_error + class RunHoldingNode: """Mixin of the job nodes that hold the rows of their current run. @@ -93,25 +95,30 @@ def _job_upstreams(node: Any) -> list[RunHoldingNode]: return [upstream for upstream in upstreams if isinstance(upstream, RunHoldingNode)] -def _stale(node: RunHoldingNode, memo: dict[int, bool]) -> bool: +def _stale(node: RunHoldingNode, memo: dict[int, bool | None]) -> bool: """Whether ``node`` is stale; ``memo`` keeps each node's answer for one traversal.""" key = id(node) if key not in memo: + memo[key] = None # on the active path, answer still pending memo[key] = node._own_staleness() or any( # pyright: ignore[reportPrivateUsage] # the mixin's own helper _stale(upstream, memo) for upstream in _job_upstreams(node) ) - return memo[key] + result = memo[key] + if result is None: + raise live_input_cycle_error() + return result def _current( node: RunHoldingNode, load_only: bool, - memo: dict[int, bool], - stale_memo: dict[int, bool], + memo: dict[int, bool | None], + stale_memo: dict[int, bool | None], ) -> bool: """Whether ``node`` holds a current run; memoized for one traversal.""" key = id(node) if key not in memo: + memo[key] = None # on the active path, answer still pending memo[key] = ( node._holds_run(load_only=load_only) # pyright: ignore[reportPrivateUsage] # the mixin's own hook and not _stale(node, stale_memo) @@ -120,7 +127,10 @@ def _current( for upstream in _job_upstreams(node) ) ) - return memo[key] + result = memo[key] + if result is None: + raise live_input_cycle_error() + return result def upstream_job_node_stale(upstreams: Iterable[Any]) -> bool: @@ -135,7 +145,7 @@ def upstream_job_node_stale(upstreams: Iterable[Any]) -> bool: Returns: ``True`` if any upstream ``RunHoldingNode`` is stale. """ - memo: dict[int, bool] = {} + memo: dict[int, bool | None] = {} return any( isinstance(upstream, RunHoldingNode) and _stale(upstream, memo) for upstream in upstreams diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 50961f369..c72518e59 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -10,6 +10,7 @@ from __future__ import annotations +from contextvars import ContextVar from datetime import datetime from typing import TYPE_CHECKING, Any @@ -22,6 +23,7 @@ StreamView, head_of, ) +from orcapod.errors import live_input_cycle_error from orcapod.types import ColumnConfig from orcapod.core.streams.base import ( check_head_size, @@ -42,6 +44,11 @@ ) +_modification_path: ContextVar[frozenset[int]] = ContextVar( + "source_proxy_modification_path", default=frozenset() +) + + class SourceProxy(RootSource): """A proxy source that preserves identity and optionally delegates. @@ -191,7 +198,15 @@ def last_modified(self) -> datetime | None: own = self._modified_time if self._delegate is None: return own - bound = self._delegate.last_modified + path = _modification_path.get() + key = id(self) + if key in path: + raise live_input_cycle_error() + token = _modification_path.set(path | {key}) + try: + bound = self._delegate.last_modified + finally: + _modification_path.reset(token) if bound is None or own is None: return bound return max(own, bound) diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index e3174a001..ea3759b8f 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -612,16 +612,24 @@ class UnboundSourceError(RuntimeError): class SourceSpecMismatchError(InputValidationError, ValueError): - """Raised when a source does not fit its slot or depends on a bindable slot. + """Raised for an incompatible source binding or a cycle in live inputs. A source fits a slot when its tag and data columns have the slot's names, roles and Python types (ITL-1112): those are what every downstream pipeline hash, and so every stored path, is built from. The message names the slot and the column, and for a type - difference both types. For a slot-dependent source, the message names both slots - (ITL-1559). Raised before the binding is installed. + difference both types. For a slot-dependent source, the message names the + dependency and any known receiving slot (ITL-1559). The error is raised before + installing an invalid binding or running with one. """ +def live_input_cycle_error() -> SourceSpecMismatchError: + """Report a cycle found while following live inputs.""" + return SourceSpecMismatchError( + "A cycle in the live input graph is not supported (ITL-1559)." + ) + + class InconsistentSourceError(ValueError): """Raised when sources conflict in a pipeline or job. diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index cf2d9c5d5..3cd1cd2dd 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -49,7 +49,9 @@ from orcapod.pipeline.source_consistency import ( invocation_source_uses, require_consistent_sources, - require_slot_free_binding, + require_run_source_bindings, + slot_dependency, + slot_dependency_error, ) from orcapod.protocols import core_protocols as cp from orcapod.databases.utils import as_table_committing @@ -641,7 +643,8 @@ def _prepare_source_bindings( ) -> list[tuple[SourceJobNode, cp.StreamProtocol | None, _DeclaredForm | None]]: """Validate the prospective job and prepare each changed slot's row form.""" for slot, source in rebinding: - require_slot_free_binding(slot.name, source) + if (dependency := slot_dependency(source)) is not None: + raise slot_dependency_error(slot.name, dependency) nodes = self._persistent_node_map.values() require_consistent_sources( ((f"node {node.label!r}", node) for node in nodes), rebinding @@ -1172,6 +1175,8 @@ def run( ``job.nodes``. Raises: + SourceSpecMismatchError: If a bound source now depends on a bindable slot + or the live inputs contain a cycle (ITL-1559). ValueError: If no database is set, or ``commit_every_rows`` is not a positive integer smaller than the database's ``batch_size``. RuntimeError: If no pipeline has been compiled, or the job was built @@ -1264,6 +1269,7 @@ async def run_async( Raises: TypeError: If ``orchestrator`` is not an ``AsyncPipelineOrchestrator``; run a ``SyncPipelineOrchestrator`` with ``job.run``. + SourceSpecMismatchError: As for ``run``. ValueError: As for ``run``. RuntimeError: As for ``run``. OrcapodDatabaseWriteError: As for ``run``. @@ -1351,6 +1357,9 @@ def _prepare_run( "computation, create a fresh PipelineJob from the original pipeline " "definition." ) + # Live inputs can change in place after a binding has been checked. + require_run_source_bindings(self._persistent_node_map.values()) + # Until this run finishes, what the database holds for a node is not certain. self._last_run_finished = False @@ -2008,7 +2017,8 @@ def load( else: if source is None: continue - require_slot_free_binding(spec_name, source) + if (dependency := slot_dependency(source)) is not None: + raise slot_dependency_error(spec_name, dependency) try: # A rebuilt source whose column types changed is treated as # one that could not be rebuilt (ITL-1112). diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index b1799c170..a18f23049 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -18,7 +18,11 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any -from orcapod.errors import OrcapodDatabaseError, OrcapodDatabaseWriteError +from orcapod.errors import ( + OrcapodDatabaseError, + OrcapodDatabaseWriteError, + live_input_cycle_error, +) from orcapod.pipeline.run_summary import ( RunCountingObserver, RunSummary, @@ -425,23 +429,29 @@ def run_with_dependencies( from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator graph: OrcaDAG[Any] = OrcaDAG() - seen: list[Any] = [] + active: set[int] = set() + seen: set[int] = set() outside: list[Any] = [] def visit(node: Any) -> None: """Add ``node`` and what it depends on, up to the sources of the job.""" - if any(node is other for other in seen): + key = id(node) + if key in active: + raise live_input_cycle_error() + if key in seen: return - seen.append(node) + seen.add(key) graph.add_node(node) if isinstance(node, SourceJobNode): return if not _is_job_node(node): outside.append(node) return + active.add(key) for upstream in node.upstreams: visit(upstream) graph.add_edge(upstream, node) + active.remove(key) visit(target) plan = plan_run(graph, load_only=load_only, outside=outside) diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index 1bba8369d..99a593229 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -6,12 +6,17 @@ from collections.abc import Iterable from typing import TYPE_CHECKING, cast -from orcapod.errors import InconsistentSourceError, SourceSpecMismatchError +from orcapod.errors import ( + InconsistentSourceError, + SourceSpecMismatchError, + live_input_cycle_error, +) from orcapod.utils.schema_utils import arrow_schema_identity if TYPE_CHECKING: import pyarrow as pa + from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources.base import RootSource from orcapod.pipeline.pod_invocation import PodInvocation from orcapod.pipeline.restrictions import Rebinding @@ -21,26 +26,68 @@ SourceUse = tuple[str, "StreamProtocol"] -def require_slot_free_binding(name: str, source: StreamProtocol | None) -> None: - """Report a proposed binding that reads a bindable job slot.""" +def slot_dependency_error( + name: str | None, dependency: SourceJobNode +) -> SourceSpecMismatchError: + """Name the slots involved in an unsupported binding and how to replace it.""" + target = "a source slot" if name is None else f"source slot {name!r}" + return SourceSpecMismatchError( + f"Binding {target} to a source that depends on source slot " + f"{dependency.name!r} is not supported yet (ITL-1559). " + + "Pass the underlying source, or use a non-slot node's as_source() to read stored results." + ) + + +def _streams_to_slots(streams: Iterable[StreamProtocol]) -> Iterable[StreamProtocol]: + """Walk live inputs up to source slots and reject cycles by object identity.""" from orcapod.core.nodes.source_node import SourceJobNode from orcapod.pipeline.restrictions import streams_beneath - # TODO(ITL-1559): live slot references can create cycles or retain an old - # slot after recompilation. Stored-result sources end the live-input walk. - pending = [] if source is None else [source] + pending = [(stream, False) for stream in streams] + pending.reverse() + active: set[int] = set() visited: set[int] = set() while pending: - stream = pending.pop() - if id(stream) in visited: + stream, leaving = pending.pop() + key = id(stream) + if leaving: + active.remove(key) + visited.add(key) continue - visited.add(id(stream)) - if isinstance(stream, SourceJobNode): - raise SourceSpecMismatchError( - f"Binding source slot {name!r} to a source that depends on source " - f"slot {stream.name!r} is not supported yet (ITL-1559)." + if key in active: + raise live_input_cycle_error() + if key in visited: + continue + yield stream + active.add(key) + pending.append((stream, True)) + if not isinstance(stream, SourceJobNode): + pending.extend( + (upstream, False) for upstream in reversed(streams_beneath(stream)) ) - pending.extend(streams_beneath(stream)) + + +def slot_dependency(source: StreamProtocol | None) -> SourceJobNode | None: + """Find a bindable slot a source would read, if any.""" + from orcapod.core.nodes.source_node import SourceJobNode + + # TODO(ITL-1559): live slot references can create cycles or retain an old + # slot after recompilation. Stored-result sources end the live-input walk. + if source is not None: + for stream in _streams_to_slots((source,)): + if isinstance(stream, SourceJobNode): + return stream + return None + + +def require_run_source_bindings(streams: Iterable[StreamProtocol]) -> None: + """Recheck live slot bindings before a run checks sources or reads rows.""" + from orcapod.core.nodes.source_node import SourceJobNode + + for stream in _streams_to_slots(streams): + if isinstance(stream, SourceJobNode): + if (dependency := slot_dependency(stream.bound_source)) is not None: + raise slot_dependency_error(stream.name, dependency) def invocation_source_uses(invocations: Iterable[PodInvocation]) -> Iterable[SourceUse]: diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index c99a711eb..2ecfbfeb8 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -1424,6 +1424,8 @@ def run(self, *, load_only: bool = False) -> StreamView: OrcapodDatabaseWriteError: If committing the invocation log fails. InconsistentSourceError: If distinct source objects share a content hash, or sources with one ID differ in schema or key columns. + SourceSpecMismatchError: If a bound source now depends on a bindable slot + or the live inputs contain a cycle (ITL-1559). """ import sys diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index 03215d2e3..32b2fe38c 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio import json from pathlib import Path from typing import Any, cast @@ -419,6 +420,173 @@ def test_binding_refuses_projection_over_the_receiving_slot( assert job.nodes["b"].bound_source is before["b"] +@pytest.mark.parametrize("load_only", [False, True]) +@pytest.mark.parametrize( + "entry", ["sync", "async_orchestrator", "run_async", "slot", "node"] +) +def test_run_refuses_slot_cycle_created_by_upstream_replacement( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, entry: str, load_only: bool +) -> None: + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SelectDataColumns + + job = _job(tmp_path) + slot = cast(SourceJobNode, job.nodes["a"]) + source = job.sources["a"] + projection = OperatorJobNode(SelectDataColumns(["x", "y"]), [source]) + job.bind(sources={"a": projection}) + _ = projection.run() + assert slot.run().table.to_pylist() == ROWS + projection.upstreams = (slot,) + + def unexpected_check() -> bool: + pytest.fail("A source was checked before the invalid binding was refused") + + monkeypatch.setattr(job.sources["b"], "check_for_new_data", unexpected_check) + with pytest.raises(SourceSpecMismatchError, match=r"slot 'a'.*slot 'a'.*ITL-1559"): + if entry == "run_async": + _ = asyncio.run(job.run_async(load_only=load_only)) + elif entry == "slot": + _ = slot.run(load_only=load_only) + elif entry == "node": + _ = job.nodes["result_a"].run(load_only=load_only) + else: + orch = ( + AsyncPipelineOrchestrator + if entry == "async_orchestrator" + else SyncPipelineOrchestrator + ) + _ = job.run(orchestrator=orch(), load_only=load_only) + + projection.upstreams = (source,) + assert slot.bound_source is projection + assert slot.run().table.to_pylist() == ROWS + + +def test_standalone_slot_run_refuses_cycle_created_by_upstream_replacement() -> None: + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SelectDataColumns + + source = _shifted_source("ordinary", 10) + projection = OperatorJobNode(SelectDataColumns(["x", "y"]), [source]) + slot = SourceJobNode("standalone", bound_source=projection) + _ = projection.run() + projection.upstreams = (slot,) + with pytest.raises( + SourceSpecMismatchError, match=r"slot 'standalone'.*slot 'standalone'.*ITL-1559" + ): + _ = slot.run() + + +@pytest.mark.parametrize("warm", [False, True]) +def test_run_refuses_foreign_slot_introduced_by_proxy_rebind( + tmp_path: Path, warm: bool +) -> None: + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.sources import CachedSource, DerivedSource + + foreign = _job(tmp_path).nodes["b"] + ordinary = DerivedSource( + _shifted_source("ordinary", 10), source_id="copy", tags_as_data={"t1": "copy"} + ) + candidate = DerivedSource( + CachedSource( + cast(SourceProtocol, foreign), cache_database=InMemoryArrowDatabase() + ), + source_id="copy", + tags_as_data={"t1": "copy"}, + ) + proxy = SourceProxy( + ordinary.source_id, + ordinary.content_hash().to_string(), + ordinary.pipeline_hash().to_string(), + *ordinary.output_schema(), + ) + proxy.bind(ordinary) + outer = DerivedSource(proxy, source_id="outer", tags_as_data={"t2": "other"}) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + _ = total.pod(outer, label="result") + if warm: + _ = job.run() + + proxy.bind(candidate) + for run in (job.nodes["outer"].run, job.nodes["result"].run, job.run): + with pytest.raises( + SourceSpecMismatchError, match=r"slot 'outer'.*slot 'b'.*ITL-1559" + ): + _ = run() + + +@pytest.mark.parametrize("target", ["proxy", "slot"]) +def test_last_modified_and_run_refuse_cycle_through_proxy_delegate(target: str) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.sources import DerivedSource + + source = _shifted_source("ordinary", 10) + proxy = SourceProxy( + source.source_id, + source.content_hash().to_string(), + source.pipeline_hash().to_string(), + *source.output_schema(), + ) + proxy.bind(source) + derived = DerivedSource(proxy, source_id="copy", tags_as_data={"t1": "copy"}) + slot = SourceJobNode("a", bound_source=derived) + proxy.bind(proxy) + + with pytest.raises(SourceSpecMismatchError, match="cycle.*ITL-1559"): + _ = (proxy if target == "proxy" else slot).last_modified + with pytest.raises(SourceSpecMismatchError, match="cycle.*ITL-1559"): + _ = slot.run(load_only=True) + proxy.bind(source) + assert slot.last_modified is not None + + +def test_staleness_refuses_cycle_of_job_operators() -> None: + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.operators import SelectDataColumns + + source = _shifted_source("ordinary", 10) + projection = OperatorJobNode(SelectDataColumns(["x", "y"]), [source]) + _ = projection.run() + projection.upstreams = (projection,) + with pytest.raises(SourceSpecMismatchError, match="cycle.*ITL-1559"): + _ = projection.is_stale + with pytest.raises(SourceSpecMismatchError, match="cycle.*ITL-1559"): + _ = projection.run() + projection.upstreams = (source,) + assert not projection.is_stale + + +@pytest.mark.parametrize("name", [None, "a"]) +@pytest.mark.parametrize("wrapper", ["cache", "projection"]) +def test_from_stream_refuses_slot_dependency_before_inferring_name( + tmp_path: Path, name: str | None, wrapper: str +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SelectDataColumns + from orcapod.sources import CachedSource + + foreign = cast(SourceJobNode, _job(tmp_path).nodes["b"]) + candidate = ( + CachedSource( + cast(SourceProtocol, cast(object, foreign)), + cache_database=InMemoryArrowDatabase(), + ) + if wrapper == "cache" + else SelectDataColumns(["x", "y"])(foreign) + ) + target = r"slot 'a'" if name else r"a source slot" + with pytest.raises( + SourceSpecMismatchError, + match=rf"{target}.*slot 'b'.*ITL-1559.*Pass the underlying source.*as_source\(\)", + ): + _ = SourceJobNode.from_stream(candidate, name=name) + + @pytest.mark.parametrize("orchestrator", ORCHESTRATORS) @pytest.mark.parametrize("kind", ["direct", "projection", "join", "cached", "derived"]) def test_bind_refuses_other_slots_atomically_and_recompile_preserves_rows( From 7c3f14857b375612a88474cb6b9b62aa8e8ca49f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:01:34 -0800 Subject: [PATCH 36/42] fix(pipeline): validate live bindings before direct reads --- .zed/rules | 6 +- CLAUDE.md | 6 +- changelog.d/ITL-1469.md | 6 +- docs/concepts/pipeline-job.md | 5 +- docs/concepts/sources.md | 6 +- src/orcapod/core/nodes/function_node.py | 4 +- src/orcapod/core/nodes/operator_node.py | 24 +++-- src/orcapod/core/nodes/source_node.py | 102 +++++++++--------- src/orcapod/core/sources/derived_source.py | 16 ++- src/orcapod/errors.py | 8 +- src/orcapod/pipeline/job.py | 4 +- src/orcapod/pipeline/source_consistency.py | 55 ++++++---- .../test_source_object_registration.py | 89 +++++++++++++-- 13 files changed, 216 insertions(+), 115 deletions(-) diff --git a/.zed/rules b/.zed/rules index 25f7f8024..4b08f5a2e 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1630,9 +1630,9 @@ data. The rules: The ITL-1559 stopgap also refuses prebuilt streams over the job's own slots. Build the step inside the job from the slot, or pass the source itself. A slot binding must be independent of every bindable slot, including through - live wrappers. Binding and run preparation (both job and node, including - load-only) report a dependency as SourceSpecMismatchError. Pass the underlying - source or use a non-slot node's as_source() for stored results. + live wrappers (ITL-1559). Binding, direct reads, and both job and node runs + (including load-only) report a dependency as SourceSpecMismatchError. Pass + the underlying source or use a non-slot node's as_source() for stored results. Call where() once and reuse the resulting object. A source object conflict raises InconsistentSourceError before the separate restriction check, which can see restrictions beneath wrappers. diff --git a/CLAUDE.md b/CLAUDE.md index de7ca353b..85ed07112 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1679,9 +1679,9 @@ data. The rules: The ITL-1559 stopgap also refuses prebuilt streams over the job's own slots. Build the step inside the job from the slot, or pass the source itself. A slot binding must be independent of every bindable slot, including through - live wrappers. Binding and run preparation (both job and node, including - load-only) report a dependency as SourceSpecMismatchError. Pass the underlying - source or use a non-slot node's as_source() for stored results. + live wrappers (ITL-1559). Binding, direct reads, and both job and node runs + (including load-only) report a dependency as SourceSpecMismatchError. Pass + the underlying source or use a non-slot node's as_source() for stored results. Call where() once and reuse the resulting object. A source object conflict raises InconsistentSourceError before the separate restriction check, which can see restrictions beneath wrappers. diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index 796f0e463..86e33deed 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -11,9 +11,9 @@ over a bound proxy, registration uses the live Arrow types. - A capture refused by any active pipeline or job leaves all their graphs unchanged. -- Job and node runs recheck that bound sources do not depend on source slots. - If a live input changes after binding and introduces a slot dependency, - execution raises `SourceSpecMismatchError` before reading sources. +- Direct reads and job and node runs recheck that bound sources are independent + of source slots. If an operator or wrapper introduces a slot dependency + after binding, they raise `SourceSpecMismatchError` before reading sources. ### Known limitations diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 52375ca34..70618124c 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -385,8 +385,9 @@ never changes a node's schema or where its results are stored. A binding must also be independent of every bindable source slot, including slots reached through operators or source wrappers. As a stopgap pending -ITL-1559, the job checks this when binding and again before each run, including -a load-only run. This check also applies to a direct node run. Pass the +ITL-1559, Orcapod checks this when binding, when reading the slot directly and +before each job or node run, including a load-only run. This also protects the +schema and hash lookups needed to construct an `as_source()` result. Pass the underlying source, or use a non-slot node's `as_source()` to read stored results. ```python diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index bdc66ac25..64c7e03c1 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -107,9 +107,9 @@ source itself. Binding a source slot to a source or stream that depends on any bindable slot raises `SourceSpecMismatchError` (ITL-1559). Pass the underlying source or use a non-slot node's `as_source()` to read stored results. If a batch contains -a refused binding, every existing binding stays in place. Job and node runs -recheck the binding before reading sources, including for load-only runs, -because an operator or wrapper can change its inputs after binding. +a refused binding, every existing binding stays in place. Direct slot reads +and job and node runs, including load-only runs, recheck the binding because +an operator or wrapper can change its inputs after binding. The capture and restriction checks follow wrappers that can read live inputs. This includes tag-copy `DerivedSource` over a live source. A `DerivedSource` diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 453847887..c90bf5206 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -357,10 +357,10 @@ def run_job_node( from orcapod.pipeline.run_summary import warn_row_failures from orcapod.pipeline.source_consistency import ( require_consistent_sources, - require_run_source_bindings, + require_live_source_bindings, ) - require_run_source_bindings([node]) + require_live_source_bindings([node]) require_consistent_sources([(f"node {node.label!r}", node)]) # A source read under two restrictions, or a caching operator over a restricted # source, is refused before any source is checked and before anything is diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 55668dba5..1663d8033 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1966,12 +1966,12 @@ def run(self, *, load_only: bool = False) -> StreamView: from orcapod.pipeline.run_summary import warn_row_failures from orcapod.pipeline.source_consistency import ( require_consistent_sources, - require_run_source_bindings, + require_live_source_bindings, ) if self._loaded and not load_only: raise self._cannot_compute_error() - require_run_source_bindings([self]) + require_live_source_bindings([self]) require_consistent_sources([(f"node {self.label!r}", self)]) # A source read under two restrictions, or a caching operator over a restricted # source, is refused before any source is checked and before anything is @@ -2074,6 +2074,9 @@ def _current_output(self) -> StreamProtocol | None: operator changed since). Before a run in this process it holds none, whatever its cache mode and database hold (ITL-1095). """ + from orcapod.pipeline.source_consistency import require_live_source_bindings + + require_live_source_bindings((self,)) if self._cached_output_stream is None or self.is_stale: return None return self._cached_output_stream @@ -2157,16 +2160,15 @@ def head( """ check_head_size(n) config = ColumnConfig.handle_config(columns, all_info=all_info) - if self._cached_output_stream is None: - return self._head_without_rows( - config, ViewStatus.NOT_COMPUTED, note=JOB_NODE_NOT_RUN_NOTE - ) - if self.is_stale: - # run() would recompute; the kept rows are not the current result. - return self._head_without_rows( - config, ViewStatus.NOT_COMPUTED, note=STALE_NOTE + current = self._current_output() + if current is None: + note = ( + JOB_NODE_NOT_RUN_NOTE + if self._cached_output_stream is None + else STALE_NOTE ) - head = head_of(self._cached_output_stream.head(n, columns=config), self) + return self._head_without_rows(config, ViewStatus.NOT_COMPUTED, note=note) + head = head_of(current.head(n, columns=config), self) if self._run_load_only: # Output of a load-only run: its input may lack rows (ITL-1095). return dataclasses.replace( diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 1591f5d59..aee117d2c 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -756,7 +756,7 @@ def content_hash(self, hasher=None) -> ContentHash: The saved value stands while no source is bound (ITL-1138); a bound source gives its own identity, as for any slot. """ - if self._saved_content_hash is not None and self._bound_stream() is None: + if self._bound_stream() is None and self._saved_content_hash is not None: return self._saved_content_hash return super().content_hash(hasher) @@ -1705,10 +1705,10 @@ def run(self, *, load_only: bool = False) -> StreamView: from orcapod.pipeline.node_run import check_sources, refuse_unloadable_inputs from orcapod.pipeline.source_consistency import ( require_consistent_sources, - require_run_source_bindings, + require_live_source_bindings, ) - require_run_source_bindings([self]) + require_live_source_bindings([self]) require_consistent_sources([(f"node {self.label!r}", self)]) _ = check_sources([self]) if load_only: @@ -1756,7 +1756,11 @@ def _set_binding_owner(self, owner: PipelineJob | None) -> None: self._binding_owner = weakref.ref(owner) if owner is not None else None def _bound_stream(self) -> StreamProtocol | None: - """The concrete stream bound to this slot, or ``None``.""" + """Resolve the live binding before reading it, even if its rows are cached.""" + from orcapod.pipeline.source_consistency import require_live_source_bindings + + if self._bound_source is not None: + require_live_source_bindings((self,)) return self._bound_source def _bind(self, value: StreamProtocol | None) -> None: @@ -1799,17 +1803,11 @@ def last_modified(self) -> datetime | None: data change (one built over data held in memory) is not re-read: build a new source object and bind it, or clear the dependent nodes. """ - from orcapod.pipeline.source_consistency import ( - slot_dependency, - slot_dependency_error, - ) - own = self._modified_time - if self._bound_source is None: + source = self._bound_stream() + if source is None: return own - if (dependency := slot_dependency(self._bound_source)) is not None: - raise slot_dependency_error(self.name, dependency) - bound = self._bound_source.last_modified + bound = source.last_modified if bound is None or own is None: return bound return max(own, bound) @@ -1924,8 +1922,9 @@ def identity_structure(self) -> Any: Bound source's identity structure when bound; schema-based identity (inherited from SourceNodeBase) when unbound. """ - if self._bound_source is not None: - return self._bound_source.identity_structure() + source = self._bound_stream() + if source is not None: + return source.identity_structure() return super().identity_structure() def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: @@ -1936,12 +1935,13 @@ def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: and an unbound slot answer with the slot's own keys: their description reports its types undeclared (``arrow_types_declared``). """ - if self._bound_source is None or self._declared_form is not None: + source = self._bound_stream() + if source is None or self._declared_form is not None: return self.keys() - table = typed_zero_row_input(self._bound_source) + table = typed_zero_row_input(source) if table is None: return self.keys() - return keys_of_rows(table, self._bound_source.keys()) + return keys_of_rows(table, source.keys()) def arrow_schema(self) -> pa.Schema: """The Arrow schema of the columns this stream passes between job nodes. @@ -1981,7 +1981,8 @@ def _rows_table( # without a bound source): its rows, as main iterated them (ITL-1347, the # one rule). return None - if self._bound_source is None: + source = self._bound_stream() + if source is None: raise UnboundSourceError( f"SourceJobNode '{self._name}' has no concrete source bound. " "Call job.bind(sources={'': source}) before running." @@ -1989,20 +1990,20 @@ def _rows_table( if self._declared_form is not None: return None if ( - not table_is_rows(self._bound_source) - or self._bound_source.data_context_key != self.data_context_key + not table_is_rows(source) + or source.data_context_key != self.data_context_key ): # Not a library source kind whose table is its rows (a side-effect or # function pod stream, an operator's result, a raw stream, a poller), or # one whose rows report another data context than the node's: its rows, # as main iterated them (the edge table is built in the node's context). return None - table = self._bound_source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + table = source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) if not system_tags_as_rows_give(table): # System tags the rows would type otherwise (a narrow integer, a # nullable field): the rows decide, as on main. return None - return table, keys_of_rows(table, self._bound_source.keys()) + return table, keys_of_rows(table, source.keys()) def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Delegate to concrete source, or raise if unbound. @@ -2010,14 +2011,15 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: Raises: UnboundSourceError: When no concrete source is attached. """ - if self._bound_source is None: + source = self._bound_stream() + if source is None: raise UnboundSourceError( f"SourceJobNode '{self._name}' has no concrete source bound. " "Call job.bind(sources={'': source}) before running." ) if self._declared_form is None: - return self._bound_source.iter_data() - return self._declared_rows(self._bound_source.iter_data(), self._declared_form) + return source.iter_data() + return self._declared_rows(source.iter_data(), self._declared_form) def _typed_zero_row_table(self) -> "pa.Table | None": """The bound source's zero-row table in the declared form; ``None`` if unknown. @@ -2027,9 +2029,10 @@ def _typed_zero_row_table(self) -> "pa.Table | None": table (ITL-1112, ITL-912). ``None`` when unbound or when the source cannot type its rows without rows. See ``typed_zero_row_table``. """ - if self._bound_source is None: + source = self._bound_stream() + if source is None: return self._declared_zero_row_table() - table = typed_zero_row_table(self._bound_source) + table = typed_zero_row_table(source) if table is None or self._declared_form is None: return table return self._declared_form.apply(table) @@ -2046,9 +2049,8 @@ def _display_name(self) -> str: def _schema_requires_io(self, config: ColumnConfig) -> bool: """Whether reading the schema with ``config`` would poll: as for the bound source.""" - return self._bound_source is not None and schema_requires_io( - self._bound_source, config - ) + source = self._bound_stream() + return source is not None and schema_requires_io(source, config) def head( self, @@ -2061,7 +2063,8 @@ def head( A narrower bound source's rows are shown as rows of the declared schema. """ - if self._bound_source is None: + source = self._bound_stream() + if source is None: check_head_size(n) return self._head_without_rows( ColumnConfig.handle_config(columns, all_info=all_info), @@ -2069,15 +2072,13 @@ def head( note="no source bound", ) if self._declared_form is None: - return head_of( - self._bound_source.head(n, columns=columns, all_info=all_info), self - ) + return head_of(source.head(n, columns=columns, all_info=all_info), self) # The source's own head, read with every column group the declared stream # needs; the declared stream then selects the asked-for groups and computes # the content hashes of the declared rows. Nothing is computed. config = ColumnConfig.handle_config(columns, all_info=all_info) view = head_of( - self._bound_source.head( + source.head( n, columns=ColumnConfig( meta=True, @@ -2089,9 +2090,9 @@ def head( ), self, ) - table = self._declared_stream( - self._bound_source, self._declared_form, view.table - ).as_table(columns=config) + table = self._declared_stream(source, self._declared_form, view.table).as_table( + columns=config + ) renames = self._declared_form.renames tag_columns = {renames.get(c, c) for c in view.tag_columns} return dataclasses.replace( @@ -2114,13 +2115,14 @@ async def async_iter_data( Raises: UnboundSourceError: When no concrete source is attached. """ - if self._bound_source is None: + source = self._bound_stream() + if source is None: raise UnboundSourceError( f"SourceJobNode '{self._name}' has no concrete source bound. " "Call job.bind(sources={'': source}) before running." ) form = self._declared_form - async for tag, data in self._bound_source.async_iter_data(): + async for tag, data in source.async_iter_data(): yield (tag, data) if form is None else self._declared_row(tag, data, form) def output_schema( @@ -2147,10 +2149,11 @@ def output_schema( Returns: Tuple of ``(tag_schema, data_schema)``. """ - if self._bound_source is None or self._declared_form is not None: + source = self._bound_stream() + if source is None or self._declared_form is not None: # Unbound, or bound to a narrower source given as the declared schema. return super().output_schema(columns=columns, all_info=all_info) - return self._bound_source.output_schema(columns=columns, all_info=all_info) + return source.output_schema(columns=columns, all_info=all_info) def as_table( self, @@ -2170,14 +2173,15 @@ def as_table( Raises: UnboundSourceError: When no concrete source is attached. """ - if self._bound_source is None: + source = self._bound_stream() + if source is None: raise UnboundSourceError( f"SourceJobNode '{self._name}' has no concrete source bound. " "Call job.bind(sources={'': source}) before calling as_table()." ) if self._declared_form is None: - return self._bound_source.as_table(columns=columns, all_info=all_info) - table = self._bound_source.as_table( + return source.as_table(columns=columns, all_info=all_info) + table = source.as_table( columns={ "meta": True, "source": True, @@ -2186,9 +2190,9 @@ def as_table( "sort_by_tags": False, } ) - return self._declared_stream( - self._bound_source, self._declared_form, table - ).as_table(columns=columns, all_info=all_info) + return self._declared_stream(source, self._declared_form, table).as_table( + columns=columns, all_info=all_info + ) @classmethod def from_stream( diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 600bcc82b..9003fc5fc 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -260,6 +260,9 @@ def __init__( record_id_columns: str | Collection[str] | None = None, **kwargs: Any, ) -> None: + from orcapod.core.nodes.staleness import RunHoldingNode + from orcapod.pipeline.source_consistency import require_live_source_bindings + key_columns = normalize_record_id_columns(record_id_columns) if tags_as_data is None: if isinstance(origin, RootSource): @@ -271,11 +274,16 @@ def __init__( raise ValueError( "record_id_columns is only used together with tags_as_data." ) - self._tags_as_data: dict[str, str] | None = None - else: + elif source_id is None: # No default source id (ITL-1313): refused before the origin is read. - if source_id is None: - raise self._missing_source_id() + raise self._missing_source_id() + + if isinstance(origin, RunHoldingNode): + # Constructing a stored-result source can inspect the live node's + # schema or hash. Once constructed, its live-input walk ends there. + require_live_source_bindings((origin,)) + self._tags_as_data: dict[str, str] | None = None + if tags_as_data is not None: # The mapping names a set of copies: they are placed in the order of their # new names, so the order it is given in changes nothing (ITL-1271). self._tags_as_data = dict( diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index ea3759b8f..dda5b2a65 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -619,14 +619,16 @@ class SourceSpecMismatchError(InputValidationError, ValueError): stored path, is built from. The message names the slot and the column, and for a type difference both types. For a slot-dependent source, the message names the dependency and any known receiving slot (ITL-1559). The error is raised before - installing an invalid binding or running with one. + installing, reading or running with an invalid binding. """ -def live_input_cycle_error() -> SourceSpecMismatchError: +def live_input_cycle_error(label: str | None = None) -> SourceSpecMismatchError: """Report a cycle found while following live inputs.""" + location = "" if label is None else f" at {label!r}" return SourceSpecMismatchError( - "A cycle in the live input graph is not supported (ITL-1559)." + f"A cycle in the live input graph{location} is not supported (ITL-1559). " + "Remove the circular input or replace it with an independent source." ) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 3cd1cd2dd..af4a0ae15 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -49,7 +49,7 @@ from orcapod.pipeline.source_consistency import ( invocation_source_uses, require_consistent_sources, - require_run_source_bindings, + require_live_source_bindings, slot_dependency, slot_dependency_error, ) @@ -1358,7 +1358,7 @@ def _prepare_run( "definition." ) # Live inputs can change in place after a binding has been checked. - require_run_source_bindings(self._persistent_node_map.values()) + require_live_source_bindings(self._persistent_node_map.values()) # Until this run finishes, what the database holds for a node is not certain. self._last_run_finished = False diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index 99a593229..5a0eedadc 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -38,33 +38,48 @@ def slot_dependency_error( ) -def _streams_to_slots(streams: Iterable[StreamProtocol]) -> Iterable[StreamProtocol]: - """Walk live inputs up to source slots and reject cycles by object identity.""" +def _walk_live_inputs( + streams: Iterable[StreamProtocol], *, stop_at_slots: bool = False +) -> Iterable[StreamProtocol]: + """Walk live inputs by identity, checking slot dependencies and active-path cycles. + + A prospective binding stops at its first slot. A read or run follows each + slot's binding and refuses a second slot anywhere in that binding. Track + the binding walk separately so a path entering a slot from its own bound + stream reports both slots, even if it then revisits the starting stream. + """ from orcapod.core.nodes.source_node import SourceJobNode from orcapod.pipeline.restrictions import streams_beneath - pending = [(stream, False) for stream in streams] + pending: list[tuple[StreamProtocol, SourceJobNode | None, bool]] = [ + (stream, None, False) for stream in streams + ] pending.reverse() - active: set[int] = set() - visited: set[int] = set() + active: set[tuple[int, bool]] = set() + visited: set[tuple[int, bool]] = set() while pending: - stream, leaving = pending.pop() - key = id(stream) + stream, binding, leaving = pending.pop() + key = (id(stream), binding is not None) if leaving: active.remove(key) visited.add(key) continue + if isinstance(stream, SourceJobNode) and binding is not None: + raise slot_dependency_error(binding.name, stream) if key in active: - raise live_input_cycle_error() + raise live_input_cycle_error(stream.label) if key in visited: continue yield stream + if isinstance(stream, SourceJobNode) and stop_at_slots: + continue active.add(key) - pending.append((stream, True)) - if not isinstance(stream, SourceJobNode): - pending.extend( - (upstream, False) for upstream in reversed(streams_beneath(stream)) - ) + pending.append((stream, binding, True)) + next_binding = stream if isinstance(stream, SourceJobNode) else binding + pending.extend( + (upstream, next_binding, False) + for upstream in reversed(streams_beneath(stream)) + ) def slot_dependency(source: StreamProtocol | None) -> SourceJobNode | None: @@ -74,20 +89,16 @@ def slot_dependency(source: StreamProtocol | None) -> SourceJobNode | None: # TODO(ITL-1559): live slot references can create cycles or retain an old # slot after recompilation. Stored-result sources end the live-input walk. if source is not None: - for stream in _streams_to_slots((source,)): + for stream in _walk_live_inputs((source,), stop_at_slots=True): if isinstance(stream, SourceJobNode): return stream return None -def require_run_source_bindings(streams: Iterable[StreamProtocol]) -> None: - """Recheck live slot bindings before a run checks sources or reads rows.""" - from orcapod.core.nodes.source_node import SourceJobNode - - for stream in _streams_to_slots(streams): - if isinstance(stream, SourceJobNode): - if (dependency := slot_dependency(stream.bound_source)) is not None: - raise slot_dependency_error(stream.name, dependency) +def require_live_source_bindings(streams: Iterable[StreamProtocol]) -> None: + """Check live inputs before resolving schemas or hashes, reading rows or running.""" + for _ in _walk_live_inputs(streams): + pass def invocation_source_uses(invocations: Iterable[PodInvocation]) -> Iterable[SourceUse]: diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index 32b2fe38c..0aa99955e 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -4,6 +4,7 @@ import asyncio import json +import re from pathlib import Path from typing import Any, cast @@ -480,9 +481,53 @@ def test_standalone_slot_run_refuses_cycle_created_by_upstream_replacement() -> _ = slot.run() +@pytest.mark.parametrize( + "entry", + ["table", "iteration", "async_iteration", "hash", "head", "preview", "as_source"], +) +def test_standalone_reads_refuse_slot_cycle_created_by_upstream_replacement( + entry: str, +) -> None: + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SelectDataColumns + + source = DictSource( + [{"t": "a", "x": 80}, {"t": "b", "x": 81}], + source_id="ordinary", + tag_columns=["t"], + tag_only_columns=True, + ) + projection = OperatorJobNode( + SelectDataColumns(["x"]), [source], pipeline_database=InMemoryArrowDatabase() + ) + slot = SourceJobNode("a", bound_source=projection) + projection.upstreams = (slot,) + + async def read_async() -> None: + _ = [row async for row in slot.async_iter_data()] + + message = r"slot 'a'.*slot 'a'.*ITL-1559.*Pass the underlying source" + if entry == "preview": + preview = slot._repr_html_() + assert re.search(message, preview) + return + reads = { + "table": slot.as_table, + "iteration": lambda: list(slot.iter_data()), + "async_iteration": lambda: asyncio.run(read_async()), + "hash": slot.content_hash, + "head": slot.head, + "as_source": projection.as_source, + } + with pytest.raises(SourceSpecMismatchError, match=message): + _ = reads[entry]() + + @pytest.mark.parametrize("warm", [False, True]) -def test_run_refuses_foreign_slot_introduced_by_proxy_rebind( - tmp_path: Path, warm: bool +@pytest.mark.parametrize("entry", ["run", "table", "iteration", "head", "preview"]) +def test_live_binding_refuses_foreign_slot_introduced_by_proxy_rebind( + tmp_path: Path, warm: bool, entry: str ) -> None: from orcapod.core.sources.source_proxy import SourceProxy from orcapod.sources import CachedSource, DerivedSource @@ -508,15 +553,43 @@ def test_run_refuses_foreign_slot_introduced_by_proxy_rebind( outer = DerivedSource(proxy, source_id="outer", tags_as_data={"t2": "other"}) with PipelineJob(database=InMemoryArrowDatabase()) as job: _ = total.pod(outer, label="result") + slot = job.nodes["outer"] if warm: - _ = job.run() + assert slot.as_table()["x"].to_pylist() == [11, 13] + if entry == "run": + _ = job.run() proxy.bind(candidate) - for run in (job.nodes["outer"].run, job.nodes["result"].run, job.run): - with pytest.raises( - SourceSpecMismatchError, match=r"slot 'outer'.*slot 'b'.*ITL-1559" - ): - _ = run() + message = r"slot 'outer'.*slot 'b'.*ITL-1559.*Pass the underlying source" + if entry == "preview": + assert re.search(message, slot._repr_html_()) + elif entry == "run": + for run in (slot.run, job.nodes["result"].run, job.run): + with pytest.raises(SourceSpecMismatchError, match=message): + _ = run() + else: + reads = { + "table": slot.as_table, + "iteration": lambda: list(slot.iter_data()), + "head": slot.head, + } + with pytest.raises(SourceSpecMismatchError, match=message): + _ = reads[entry]() + + +def test_operator_run_cycle_diagnostic_names_the_step_and_remedy() -> None: + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.operators import SelectDataColumns + + source = _shifted_source("ordinary", 10) + projection = OperatorJobNode(SelectDataColumns(["x"]), [source], label="project") + projection.upstreams = (projection,) + + with pytest.raises( + SourceSpecMismatchError, + match=r"cycle.*'project'.*ITL-1559.*Remove the circular input", + ): + _ = projection.run() @pytest.mark.parametrize("target", ["proxy", "slot"]) From f10f8117d8978052dfddccaa5c87465b921a5a74 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:28:36 -0800 Subject: [PATCH 37/42] =?UTF-8?q?fix(pipeline):=20refuse=20bindings=20to?= =?UTF-8?q?=20the=20job=E2=80=99s=20own=20nodes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Apply the ITL-1559 dependency rule to stored-result origins and validate cold function reads. Record the upstream reassignment limitation under ITL-1586. --- .zed/rules | 9 +- CLAUDE.md | 9 +- changelog.d/ITL-1469.md | 16 +- docs/concepts/pipeline-job.md | 13 +- src/orcapod/core/nodes/function_node.py | 7 +- src/orcapod/core/nodes/source_node.py | 26 ++- src/orcapod/core/nodes/staleness.py | 10 + src/orcapod/core/sources/derived_source.py | 5 + src/orcapod/pipeline/job.py | 30 ++- src/orcapod/pipeline/source_consistency.py | 104 ++++++---- .../test_source_object_registration.py | 183 ++++++++++++++++++ 11 files changed, 323 insertions(+), 89 deletions(-) diff --git a/.zed/rules b/.zed/rules index 4b08f5a2e..726794ab0 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1629,10 +1629,11 @@ data. The rules: original bindings. A schema-only SourceNode declares a new unbound slot. The ITL-1559 stopgap also refuses prebuilt streams over the job's own slots. Build the step inside the job from the slot, or pass the source itself. - A slot binding must be independent of every bindable slot, including through - live wrappers (ITL-1559). Binding, direct reads, and both job and node runs - (including load-only) report a dependency as SourceSpecMismatchError. Pass - the underlying source or use a non-slot node's as_source() for stored results. + A slot binding must be independent of every bindable slot and every node + of its own job, including through stored-result sources and other wrappers + (ITL-1559). Binding, direct reads, and both job and node runs (including + load-only) report a dependency as SourceSpecMismatchError. Pass the + underlying source or use another job's node.as_source() for stored results. Call where() once and reuse the resulting object. A source object conflict raises InconsistentSourceError before the separate restriction check, which can see restrictions beneath wrappers. diff --git a/CLAUDE.md b/CLAUDE.md index 85ed07112..b580ee084 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1678,10 +1678,11 @@ data. The rules: original bindings. A schema-only SourceNode declares a new unbound slot. The ITL-1559 stopgap also refuses prebuilt streams over the job's own slots. Build the step inside the job from the slot, or pass the source itself. - A slot binding must be independent of every bindable slot, including through - live wrappers (ITL-1559). Binding, direct reads, and both job and node runs - (including load-only) report a dependency as SourceSpecMismatchError. Pass - the underlying source or use a non-slot node's as_source() for stored results. + A slot binding must be independent of every bindable slot and every node + of its own job, including through stored-result sources and other wrappers + (ITL-1559). Binding, direct reads, and both job and node runs (including + load-only) report a dependency as SourceSpecMismatchError. Pass the + underlying source or use another job's node.as_source() for stored results. Call where() once and reuse the resulting object. A source object conflict raises InconsistentSourceError before the separate restriction check, which can see restrictions beneath wrappers. diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index 86e33deed..05a2c7b47 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -11,9 +11,9 @@ over a bound proxy, registration uses the live Arrow types. - A capture refused by any active pipeline or job leaves all their graphs unchanged. -- Direct reads and job and node runs recheck that bound sources are independent - of source slots. If an operator or wrapper introduces a slot dependency - after binding, they raise `SourceSpecMismatchError` before reading sources. +- Direct reads and job and node runs recheck source binding dependencies. + If an operator or wrapper introduces a forbidden dependency after binding, + they raise `SourceSpecMismatchError` before reading sources. ### Known limitations @@ -27,7 +27,9 @@ - The ITL-1559 stopgap also refuses prebuilt streams over the receiving job's own slots. Build the step inside the job from its slot, or pass the source itself. -- Binding a slot to a source or stream that depends on any bindable slot raises - `SourceSpecMismatchError` (ITL-1559). A refused batch leaves all bindings - intact. Pass the underlying source, or use `node.as_source()` for stored - results. +- Binding a slot to a source or stream that depends on any bindable slot or + any node of its own job raises `SourceSpecMismatchError` (ITL-1559). A + refused batch leaves all bindings intact. Pass the underlying source, or + use another job's `node.as_source()` for stored results. +- Reassigning an invocation's upstreams is unsupported after capture. + Rewiring an operator can leave stale rows in direct reads (ITL-1586). diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 70618124c..93bba7958 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -383,12 +383,13 @@ tag_schema=Schema({...}), data_schema=Schema({...}))`) means one Arrow type per zones, declare the slot with Arrow schemas (`tag_schema=pa.schema([...])`). Binding a source never changes a node's schema or where its results are stored. -A binding must also be independent of every bindable source slot, including -slots reached through operators or source wrappers. As a stopgap pending -ITL-1559, Orcapod checks this when binding, when reading the slot directly and -before each job or node run, including a load-only run. This also protects the -schema and hash lookups needed to construct an `as_source()` result. Pass the -underlying source, or use a non-slot node's `as_source()` to read stored results. +A binding must be independent of every bindable source slot and every node +of its own job, including dependencies reached through operators, +`node.as_source()`, or other source wrappers. As a stopgap pending ITL-1559, +Orcapod checks this when binding, when reading the slot directly, and before +each job or node run, including a load-only run. This also protects the schema +and hash lookups needed to construct an `as_source()` result. Pass the +underlying source, or use another job's `node.as_source()` to read stored results. ```python from orcapod.errors import SourceSpecMismatchError diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index c90bf5206..395d3bba1 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -4316,13 +4316,16 @@ def _prepare_held_read(self) -> None: RuntimeError: If ``load_status`` is UNAVAILABLE. """ from orcapod.pipeline.serialization import LoadStatus + from orcapod.pipeline.source_consistency import require_live_source_bindings status = self.load_status if status == LoadStatus.UNAVAILABLE: raise self._no_database_error() # A CACHE_ONLY node has no live input to be stale against. - if status != LoadStatus.CACHE_ONLY and self.is_stale: - self.clear_cache() + if status != LoadStatus.CACHE_ONLY: + require_live_source_bindings((self,)) + if self.is_stale: + self.clear_cache() def run(self, *, load_only: bool = False) -> StreamView: """Run the node as a job run would, and return a ``StreamView`` of its rows. diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index aee117d2c..279514c09 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1628,12 +1628,10 @@ def __init__( arrow_schemas: "tuple[pa.Schema, pa.Schema] | None" = None, ) -> None: from orcapod.pipeline.source_consistency import ( - slot_dependency, - slot_dependency_error, + require_independent_source_binding, ) - if (dependency := slot_dependency(bound_source)) is not None: - raise slot_dependency_error(name, dependency) + require_independent_source_binding(bound_source, name) if tag_schema is None or data_schema is None: if bound_source is None: raise ValueError( @@ -1735,17 +1733,15 @@ def bound_source(self, value: StreamProtocol | None) -> None: Raises: InconsistentSourceError: If the replacement introduces conflicting sources. SourceSpecMismatchError: If *value* does not fit the declared schema or - depends on a bindable source slot (ITL-1559). + depends on a bindable source slot or on this job's own node (ITL-1559). """ from orcapod.pipeline.source_consistency import ( - slot_dependency, - slot_dependency_error, + require_independent_source_binding, ) - owner = self._binding_owner() if self._binding_owner is not None else None + owner = self._get_binding_owner() if owner is None: - if (dependency := slot_dependency(value)) is not None: - raise slot_dependency_error(self.name, dependency) + require_independent_source_binding(value, self.name) self._bind(value) self._update_modified_time() else: @@ -1755,6 +1751,10 @@ def _set_binding_owner(self, owner: PipelineJob | None) -> None: """Route changes to a job while this is one of its active slots.""" self._binding_owner = weakref.ref(owner) if owner is not None else None + def _get_binding_owner(self) -> PipelineJob | None: + """Return the job that owns this active slot, if any.""" + return self._binding_owner() if self._binding_owner is not None else None + def _bound_stream(self) -> StreamProtocol | None: """Resolve the live binding before reading it, even if its rows are cached.""" from orcapod.pipeline.source_consistency import require_live_source_bindings @@ -2263,13 +2263,11 @@ def from_stream( case _: # Case 3: concrete stream — bound SJN. from orcapod.pipeline.source_consistency import ( - slot_dependency, - slot_dependency_error, + require_independent_source_binding, ) # Schema and source-name inference can consult the live inputs. - if (dependency := slot_dependency(stream)) is not None: - raise slot_dependency_error(name, dependency) + require_independent_source_binding(stream, name) # Slot name priority: # 1. explicit *name* parameter # 2. stream.source_name for RootSource (its id without the kind part) diff --git a/src/orcapod/core/nodes/staleness.py b/src/orcapod/core/nodes/staleness.py index 3a12199e8..dccc62c53 100644 --- a/src/orcapod/core/nodes/staleness.py +++ b/src/orcapod/core/nodes/staleness.py @@ -8,6 +8,7 @@ from __future__ import annotations +import weakref from collections.abc import Iterable from typing import Any @@ -24,6 +25,15 @@ class RunHoldingNode: # The summary of the node's last ``run()`` (with the nodes it ran first); a class # default so nodes rebuilt from a saved descriptor start without one. _last_run: Any = None + _pipeline_job: weakref.ReferenceType[object] | None = None + + def _set_pipeline_job(self, job: object) -> None: + """Keep a node's job provenance through recompilation without owning the job.""" + self._pipeline_job = weakref.ref(job) + + def _belongs_to_job(self, job: object) -> bool: + """Whether this node was compiled or loaded as part of this job.""" + return self._pipeline_job is not None and self._pipeline_job() is job @property def last_run(self) -> Any: diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 9003fc5fc..d21b3a4f5 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -491,6 +491,11 @@ def live_source_inputs(self) -> tuple[StreamProtocol, ...] | None: else None ) + @property + def stored_result_origin(self) -> StreamProtocol | None: + """Return the stored-result node whose live schema and keys this source uses.""" + return self._origin if self.live_source_inputs is None else None + def _origin_records(self) -> "pa.Table | None": """Return the origin's rows, or ``None`` when a job node has none stored. diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index af4a0ae15..278b51461 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -15,6 +15,8 @@ from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.nodes.source_node import SourceJobNode +from orcapod.core.nodes.staleness import RunHoldingNode +from orcapod.core.sources.base import RootSource from orcapod.core.sources.derived_source import DerivedSource from orcapod.core.streams.base import StreamBase from orcapod.side_effects import SideEffectJobNode, SideEffectNode @@ -49,9 +51,9 @@ from orcapod.pipeline.source_consistency import ( invocation_source_uses, require_consistent_sources, + require_independent_source_binding, require_live_source_bindings, - slot_dependency, - slot_dependency_error, + require_no_owned_node_dependency, ) from orcapod.protocols import core_protocols as cp from orcapod.databases.utils import as_table_committing @@ -267,6 +269,8 @@ def _validate_capture_sources(self, streams: Iterable[cp.StreamProtocol]) -> Non if key in visited: continue visited.add(key) + if isinstance(stream, DerivedSource): + require_no_owned_node_dependency(stream, stream.source_name, self) if isinstance(stream, SourceJobNode): if id(stream) not in own_nodes: raise InconsistentSourceError( @@ -306,11 +310,17 @@ def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse def _source_node_from_recording(self, key: str) -> SourceJobNode: """Preserve an explicit binding when recompiling its slot.""" + stream = self._source_streams[key] if key in self._rebound_source_keys: slot = self._persistent_node_map.get(key) if isinstance(slot, SourceJobNode): - return self.source_node_class.from_stream(slot) - return self.source_node_class.from_stream(self._source_streams[key]) + stream = slot + if isinstance(stream, SourceJobNode): + require_independent_source_binding(stream.bound_source, stream.name, self) + else: + name = stream.source_name if isinstance(stream, RootSource) else None + require_independent_source_binding(stream, name, self) + return self.source_node_class.from_stream(stream) def compile(self) -> None: """Compile recorded invocations into a frozen DAG of job nodes. @@ -341,6 +351,8 @@ def compile(self) -> None: previous_sources = self._sources self._sources = {} for key, node in self._persistent_node_map.items(): + if isinstance(node, RunHoldingNode): + node._set_pipeline_job(self) # pyright: ignore[reportPrivateUsage] # compiled node provenance if isinstance(node, SourceJobNode): if not self._loaded: self._sources_as_captured.setdefault(key, node.bound_source) @@ -558,7 +570,7 @@ def bind( (ITL-1506). The job is left as it was. SourceSpecMismatchError: If any source's columns differ from its slot's declared names, roles or types, or the source depends on a bindable - source slot (ITL-1559). + source slot or a node of this job (ITL-1559). ValueError: If a source key has no matching ``SourceJobNode`` slot, or an operator node that caches (``LOG`` or ``REPLAY``) would read a restricted source, one this bind binds or one already bound @@ -643,8 +655,7 @@ def _prepare_source_bindings( ) -> list[tuple[SourceJobNode, cp.StreamProtocol | None, _DeclaredForm | None]]: """Validate the prospective job and prepare each changed slot's row form.""" for slot, source in rebinding: - if (dependency := slot_dependency(source)) is not None: - raise slot_dependency_error(slot.name, dependency) + require_independent_source_binding(source, slot.name, self) nodes = self._persistent_node_map.values() require_consistent_sources( ((f"node {node.label!r}", node) for node in nodes), rebinding @@ -2017,8 +2028,7 @@ def load( else: if source is None: continue - if (dependency := slot_dependency(source)) is not None: - raise slot_dependency_error(spec_name, dependency) + require_independent_source_binding(source, spec_name) try: # A rebuilt source whose column types changed is treated as # one that could not be rebuilt (ITL-1112). @@ -2294,6 +2304,8 @@ def load( # Callers needing blueprint nodes for rendering use job.pipeline.dag. job_dag: OrcaDAG = OrcaDAG() for node in job._persistent_node_map.values(): + if isinstance(node, RunHoldingNode): + node._set_pipeline_job(job) # pyright: ignore[reportPrivateUsage] # restored node provenance job_dag.add_node(node) for u_hash, v_hash in job._graph_edges: u_node = job._persistent_node_map.get(u_hash) diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index 5a0eedadc..0a086ac99 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -16,8 +16,8 @@ if TYPE_CHECKING: import pyarrow as pa - from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources.base import RootSource + from orcapod.pipeline.job import PipelineJob from orcapod.pipeline.pod_invocation import PodInvocation from orcapod.pipeline.restrictions import Rebinding from orcapod.protocols.core_protocols import StreamProtocol @@ -26,79 +26,97 @@ SourceUse = tuple[str, "StreamProtocol"] -def slot_dependency_error( - name: str | None, dependency: SourceJobNode +def _binding_dependency_error( + name: str | None, dependency: StreamProtocol ) -> SourceSpecMismatchError: - """Name the slots involved in an unsupported binding and how to replace it.""" + """Name the dependency that makes a slot binding unsupported.""" + from orcapod.core.nodes.source_node import SourceJobNode + target = "a source slot" if name is None else f"source slot {name!r}" + if isinstance(dependency, SourceJobNode): + detail = f"source slot {dependency.name!r}" + remedy = "use a non-slot node's as_source() to read stored results" + else: + detail = f"node {dependency.label!r} of the same job" + remedy = "use another job's node.as_source() to read stored results" return SourceSpecMismatchError( - f"Binding {target} to a source that depends on source slot " - f"{dependency.name!r} is not supported yet (ITL-1559). " - + "Pass the underlying source, or use a non-slot node's as_source() to read stored results." + f"Binding {target} to a source that depends on {detail} " + f"is not supported yet (ITL-1559). Pass the underlying source, or {remedy}." ) -def _walk_live_inputs( - streams: Iterable[StreamProtocol], *, stop_at_slots: bool = False -) -> Iterable[StreamProtocol]: - """Walk live inputs by identity, checking slot dependencies and active-path cycles. +def require_no_owned_node_dependency( + stream: StreamProtocol, name: str | None, owner: PipelineJob +) -> None: + """Refuse a dependency on a node of the binding's own job.""" + from orcapod.core.nodes.staleness import RunHoldingNode + from orcapod.core.sources.derived_source import DerivedSource - A prospective binding stops at its first slot. A read or run follows each - slot's binding and refuses a second slot anywhere in that binding. Track - the binding walk separately so a path entering a slot from its own bound - stream reports both slots, even if it then revisits the starting stream. + dependency = ( + stream.stored_result_origin if isinstance(stream, DerivedSource) else stream + ) + if isinstance(dependency, RunHoldingNode) and dependency._belongs_to_job(owner): # pyright: ignore[reportPrivateUsage] # binding checks use node provenance + raise _binding_dependency_error(name, dependency) + + +def _require_live_inputs( + streams: Iterable[StreamProtocol], + binding: tuple[str | None, PipelineJob | None] | None = None, +) -> None: + """Validate live inputs by identity, with a separate walk inside each binding. + + A binding refuses any bindable slot and any node of its owner, including a + stored-result origin. Stored results from other jobs remain leaves. """ from orcapod.core.nodes.source_node import SourceJobNode from orcapod.pipeline.restrictions import streams_beneath - pending: list[tuple[StreamProtocol, SourceJobNode | None, bool]] = [ - (stream, None, False) for stream in streams - ] + pending = [(stream, binding, False) for stream in streams] pending.reverse() - active: set[tuple[int, bool]] = set() - visited: set[tuple[int, bool]] = set() + active: set[tuple[int, bool, int]] = set() + visited: set[tuple[int, bool, int]] = set() while pending: - stream, binding, leaving = pending.pop() - key = (id(stream), binding is not None) + stream, current_binding, leaving = pending.pop() + owner = current_binding[1] if current_binding is not None else None + key = (id(stream), current_binding is not None, id(owner)) if leaving: active.remove(key) visited.add(key) continue - if isinstance(stream, SourceJobNode) and binding is not None: - raise slot_dependency_error(binding.name, stream) - if key in active: - raise live_input_cycle_error(stream.label) if key in visited: continue - yield stream - if isinstance(stream, SourceJobNode) and stop_at_slots: - continue + if current_binding is not None: + name = current_binding[0] + if isinstance(stream, SourceJobNode): + raise _binding_dependency_error(name, stream) + if owner is not None: + require_no_owned_node_dependency(stream, name, owner) + if key in active: + raise live_input_cycle_error(stream.label) active.add(key) - pending.append((stream, binding, True)) - next_binding = stream if isinstance(stream, SourceJobNode) else binding + pending.append((stream, current_binding, True)) + next_binding = ( + (stream.name, stream._get_binding_owner()) # pyright: ignore[reportPrivateUsage] # validate the active slot in its owning job + if isinstance(stream, SourceJobNode) + else current_binding + ) pending.extend( (upstream, next_binding, False) for upstream in reversed(streams_beneath(stream)) ) -def slot_dependency(source: StreamProtocol | None) -> SourceJobNode | None: - """Find a bindable slot a source would read, if any.""" - from orcapod.core.nodes.source_node import SourceJobNode - - # TODO(ITL-1559): live slot references can create cycles or retain an old - # slot after recompilation. Stored-result sources end the live-input walk. +def require_independent_source_binding( + source: StreamProtocol | None, name: str | None, owner: PipelineJob | None = None +) -> None: + """Refuse a prospective binding before reading its schema, name or rows.""" if source is not None: - for stream in _walk_live_inputs((source,), stop_at_slots=True): - if isinstance(stream, SourceJobNode): - return stream - return None + _require_live_inputs((source,), (name, owner)) def require_live_source_bindings(streams: Iterable[StreamProtocol]) -> None: """Check live inputs before resolving schemas or hashes, reading rows or running.""" - for _ in _walk_live_inputs(streams): - pass + _require_live_inputs(streams) def invocation_source_uses(invocations: Iterable[PodInvocation]) -> Iterable[SourceUse]: diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index 0aa99955e..befa8c354 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -1624,3 +1624,186 @@ def test_prebuilt_stream_over_own_slot_is_refused_before_rebinding( assert sorted(job.direct.as_table()["out"].to_pylist()) == [13, 17] assert sorted(job.inside.as_table()["out"].to_pylist()) == [13, 17] assert sorted(job.own_slot.as_table()["out"].to_pylist()) == [9, 9] + + +@function_pod(output_keys=("x", "y")) +def same_columns(x: int, y: int) -> tuple[int, int]: + """Return both input columns so stored results fit the original slot.""" + return x, y + + +def _stored_result_job( + kind: str, offset: int = 0, *, copy: bool = False +) -> PipelineJob: + from orcapod.types import CacheMode + + from orcapod.sources import DerivedSource + + base = _shifted_source("a", offset) + source = ( + DerivedSource(base, source_id="a", tags_as_data={"t1": "copy"}) + if copy + else base + ) + database = InMemoryArrowDatabase() + with PipelineJob("stored", database=database) as job: + if kind == "operator": + _ = source.select_data_columns(["x", "y"], label="result") + else: + _ = same_columns.pod(source, label="result") + if kind == "operator": + job.nodes["result"].attach_databases( + pipeline_database=database.at("stored"), cache_mode=CacheMode.LOG + ) + _ = job.run() + return job + + +@pytest.mark.parametrize("kind", ["operator", "function"]) +@pytest.mark.parametrize("wrapped", [False, True]) +@pytest.mark.parametrize("route", ["batch", "setter", "recompiled"]) +def test_slot_binding_refuses_its_own_stored_results( + kind: str, wrapped: bool, route: str +) -> None: + job = _stored_result_job(kind) + stored = job.nodes["result"].as_source() + source = stored.cached(InMemoryArrowDatabase()) if wrapped else stored + if route == "recompiled": + job.compile() + original = job.sources["a"] + + with pytest.raises( + SourceSpecMismatchError, match=r"slot 'a'.*node 'result'.*ITL-1559" + ): + _rebind(job, {"a": source}, setter=route == "setter") + + assert job.nodes["a"].bound_source is original + assert job.sources["a"] is original + assert job.nodes["a"].as_table()["x"].to_pylist() == [1, 3] + + +def test_capture_refuses_its_own_stored_results() -> None: + job = _stored_result_job("operator") + stored = job.nodes["result"].as_source() + with job: + with pytest.raises( + SourceSpecMismatchError, match=r"slot .*node 'result'.*ITL-1559" + ): + _ = total.pod(stored, label="feedback") + + assert "feedback" not in job.nodes + + +@pytest.mark.parametrize( + "entry", ["sync", "async", "load_only", "slot", "node", "read"] +) +@pytest.mark.parametrize("kind", ["operator", "function"]) +def test_own_stored_results_introduced_by_proxy_rebind_are_refused( + entry: str, kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.sources import DerivedSource + + job = _stored_result_job(kind, copy=True) + foreign = _stored_result_job(kind, offset=10, copy=True) + foreign_results = foreign.nodes["result"].as_source() + own_results = job.nodes["result"].as_source() + proxy = SourceProxy( + foreign_results.source_id, + foreign_results.content_hash().to_string(), + foreign_results.pipeline_hash().to_string(), + *foreign_results.output_schema(), + ) + proxy.bind(foreign_results) + slot = job.nodes["a"] + result = job.nodes["result"] + wrapped = DerivedSource(proxy, source_id="bridged", tags_as_data={"t1": "copy"}) + job.bind(sources={"a": wrapped}) + _ = job.run() + assert sorted(result.as_table()["x"].to_pylist()) == [11, 13] + + proxy.bind(own_results) + + def unexpected_check() -> bool: + pytest.fail("A source was checked before the invalid binding was refused") + + monkeypatch.setattr(wrapped, "check_for_new_data", unexpected_check) + reads = { + "sync": job.run, + "async": lambda: asyncio.run(job.run_async()), + "load_only": lambda: job.run(load_only=True), + "slot": slot.run, + "node": result.run, + "read": slot.as_table, + } + with pytest.raises( + SourceSpecMismatchError, match=r"slot 'a'.*node 'result'.*ITL-1559" + ): + _ = reads[entry]() + + +@pytest.mark.parametrize("read", ["iter_data", "async_iter_data", "held_row_count"]) +def test_cold_function_held_reads_refuse_a_slot_cycle( + tmp_path: Path, read: str +) -> None: + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.operators import SelectDataColumns + + job = _job(tmp_path) + slot = job.nodes["a"] + function = job.nodes["result_a"] + projection = OperatorJobNode(SelectDataColumns(["x", "y"]), [job.sources["a"]]) + job.bind(sources={"a": projection}) + projection.upstreams = (slot,) + + async def read_async() -> None: + _ = [row async for row in function.async_iter_data()] + + with pytest.raises(SourceSpecMismatchError, match=r"slot 'a'.*slot 'a'.*ITL-1559"): + if read == "iter_data": + _ = list(function.iter_data()) + elif read == "async_iter_data": + asyncio.run(read_async()) + else: + _ = function.held_row_count() + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="Reassigning operator inputs can leave stale held rows on direct reads (ITL-1586).", +) +def test_rewired_operator_slot_does_not_read_stale_rows_from_same_hash_roots() -> None: + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SemiJoin + + first, other, conflict = ( + DictSource( + [{"t": tag, "x": value}], + source_id=name, + tag_columns=["t"], + tag_only_columns=True, + ) + for name, tag, value in [("same", "a", 1), ("other", "a", 2), ("same", "b", 3)] + ) + assert first.content_hash() == conflict.content_hash() + operator = OperatorJobNode( + SemiJoin(), + [first, other], + label="op", + pipeline_database=InMemoryArrowDatabase(), + ) + slot = SourceJobNode.from_stream(operator, name="slot") + _ = operator.run() + assert slot.as_table().to_pylist() == [{"t": "a", "x": 1}] + + operator.upstreams = (first, conflict) + for run in (slot.run, operator.run): + with pytest.raises(InconsistentSourceError, match=r"input 1.*input 2"): + _ = run() + try: + rows = slot.as_table().to_pylist() + except InconsistentSourceError: + return + assert rows == [] From 5ad69a9596dc5bdd941c691701d834117c70592c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:53:21 -0800 Subject: [PATCH 38/42] fix(pipeline): reject stored-result binding cycles across jobs --- .zed/rules | 3 + CLAUDE.md | 3 + changelog.d/ITL-1469.md | 2 + docs/concepts/pipeline-job.md | 3 + docs/concepts/sources.md | 21 ++- src/orcapod/core/nodes/function_node.py | 9 +- src/orcapod/core/nodes/source_node.py | 16 +- src/orcapod/core/nodes/staleness.py | 10 ++ src/orcapod/core/sources/derived_source.py | 15 +- src/orcapod/errors.py | 11 +- src/orcapod/pipeline/base.py | 9 +- src/orcapod/pipeline/job.py | 37 +++-- src/orcapod/pipeline/source_consistency.py | 129 ++++++++++------ .../operators/test_polars_filter_warning.py | 5 +- .../test_bind_narrower_source.py | 28 ++-- .../test_source_object_registration.py | 144 ++++++++++++++++++ 16 files changed, 346 insertions(+), 99 deletions(-) diff --git a/.zed/rules b/.zed/rules index 726794ab0..c02e143d6 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1634,6 +1634,9 @@ data. The rules: (ITL-1559). Binding, direct reads, and both job and node runs (including load-only) report a dependency as SourceSpecMismatchError. Pass the underlying source or use another job's node.as_source() for stored results. + A stored-result source still uses its origin's schema and keys. Binding checks + follow the origin's inputs through other jobs and refuse cycles, naming the + slots involved. A one-way stored-result binding stays supported. Call where() once and reuse the resulting object. A source object conflict raises InconsistentSourceError before the separate restriction check, which can see restrictions beneath wrappers. diff --git a/CLAUDE.md b/CLAUDE.md index b580ee084..be9064757 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1683,6 +1683,9 @@ data. The rules: (ITL-1559). Binding, direct reads, and both job and node runs (including load-only) report a dependency as SourceSpecMismatchError. Pass the underlying source or use another job's node.as_source() for stored results. + A stored-result source still uses its origin's schema and keys. Binding checks + follow the origin's inputs through other jobs and refuse cycles, naming the + slots involved. A one-way stored-result binding stays supported. Call where() once and reuse the resulting object. A source object conflict raises InconsistentSourceError before the separate restriction check, which can see restrictions beneath wrappers. diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index 05a2c7b47..43cb0c746 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -14,6 +14,8 @@ - Direct reads and job and node runs recheck source binding dependencies. If an operator or wrapper introduces a forbidden dependency after binding, they raise `SourceSpecMismatchError` before reading sources. +- Bindings to stored results reject cycles across jobs and name the slots + involved. Pipeline capture and compilation also reject circular wrapper inputs. ### Known limitations diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 93bba7958..fa0ea0339 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -390,6 +390,9 @@ Orcapod checks this when binding, when reading the slot directly, and before each job or node run, including a load-only run. This also protects the schema and hash lookups needed to construct an `as_source()` result. Pass the underlying source, or use another job's `node.as_source()` to read stored results. +The stored-result source still uses its origin's schema and keys, so Orcapod +checks the origin's inputs across jobs. If those inputs lead back to the receiving +slot, the binding is refused and the error names the slots in the cycle. ```python from orcapod.errors import SourceSpecMismatchError diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 64c7e03c1..c65ec4b01 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -104,17 +104,22 @@ The ITL-1559 stopgap also refuses a prebuilt stream over the receiving job's own slot. Pass that slot directly into a step inside the job, or pass the source itself. -Binding a source slot to a source or stream that depends on any bindable slot -raises `SourceSpecMismatchError` (ITL-1559). Pass the underlying source or -use a non-slot node's `as_source()` to read stored results. If a batch contains -a refused binding, every existing binding stays in place. Direct slot reads -and job and node runs, including load-only runs, recheck the binding because -an operator or wrapper can change its inputs after binding. +Binding through a live input to any bindable slot, or binding to a node of the +receiving job even through `as_source()`, raises `SourceSpecMismatchError` +(ITL-1559). Another job's `node.as_source()` can provide stored results, provided +its inputs do not lead back to the receiving slot through other bindings. The +error names the slots involved in such a cycle. Pass an independent underlying +source to break the cycle. A refused batch preserves all existing bindings. +Direct reads and job and node runs, including load-only runs, recheck the +binding because an operator or wrapper can change its inputs after binding. The capture and restriction checks follow wrappers that can read live inputs. This includes tag-copy `DerivedSource` over a live source. A `DerivedSource` -over a job node reads stored results, so the checks stop there. Source object -registration uses the wrapper itself and its content hash. +over a job node reads stored results. Capture checks for an origin from the +receiving job, and binding validation follows the origin's inputs because the +derived source still uses the node's live schema and keys. Restriction checks +stop at the wrapper, and source object registration uses the wrapper itself +and its content hash. Capturing into a loaded job or recompiling it can lose its restored graph (ITL-1560). Recompilation preserves the loaded job's public `sources` mapping. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 395d3bba1..93be1232d 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -4225,6 +4225,8 @@ def head( config, ViewStatus.UNAVAILABLE, note="no database attached" ) if self._run_entry_counts is None: + if status != LoadStatus.CACHE_ONLY: + self._require_live_bindings() return self._head_without_rows( config, ViewStatus.NOT_COMPUTED, note=JOB_NODE_NOT_RUN_NOTE ) @@ -4316,16 +4318,13 @@ def _prepare_held_read(self) -> None: RuntimeError: If ``load_status`` is UNAVAILABLE. """ from orcapod.pipeline.serialization import LoadStatus - from orcapod.pipeline.source_consistency import require_live_source_bindings status = self.load_status if status == LoadStatus.UNAVAILABLE: raise self._no_database_error() # A CACHE_ONLY node has no live input to be stale against. - if status != LoadStatus.CACHE_ONLY: - require_live_source_bindings((self,)) - if self.is_stale: - self.clear_cache() + if status != LoadStatus.CACHE_ONLY and self.is_stale: + self.clear_cache() def run(self, *, load_only: bool = False) -> StreamView: """Run the node as a job run would, and return a ``StreamView`` of its rows. diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 279514c09..aaaa972de 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1628,10 +1628,12 @@ def __init__( arrow_schemas: "tuple[pa.Schema, pa.Schema] | None" = None, ) -> None: from orcapod.pipeline.source_consistency import ( - require_independent_source_binding, + binding_dependency_error, + independent_source_dependency, ) - require_independent_source_binding(bound_source, name) + if (dependency := independent_source_dependency(bound_source)) is not None: + raise binding_dependency_error(dependency, name) if tag_schema is None or data_schema is None: if bound_source is None: raise ValueError( @@ -1736,12 +1738,12 @@ def bound_source(self, value: StreamProtocol | None) -> None: depends on a bindable source slot or on this job's own node (ITL-1559). """ from orcapod.pipeline.source_consistency import ( - require_independent_source_binding, + require_live_source_bindings, ) owner = self._get_binding_owner() if owner is None: - require_independent_source_binding(value, self.name) + require_live_source_bindings((self,), rebinding=((self, value),)) self._bind(value) self._update_modified_time() else: @@ -2263,11 +2265,13 @@ def from_stream( case _: # Case 3: concrete stream — bound SJN. from orcapod.pipeline.source_consistency import ( - require_independent_source_binding, + binding_dependency_error, + independent_source_dependency, ) # Schema and source-name inference can consult the live inputs. - require_independent_source_binding(stream, name) + if (dependency := independent_source_dependency(stream)) is not None: + raise binding_dependency_error(dependency, name) # Slot name priority: # 1. explicit *name* parameter # 2. stream.source_name for RootSource (its id without the kind part) diff --git a/src/orcapod/core/nodes/staleness.py b/src/orcapod/core/nodes/staleness.py index dccc62c53..9efe40a73 100644 --- a/src/orcapod/core/nodes/staleness.py +++ b/src/orcapod/core/nodes/staleness.py @@ -13,6 +13,10 @@ from typing import Any from orcapod.errors import live_input_cycle_error +from orcapod.utils.lazy_module import LazyModule + +# Source consistency identifies job nodes using this mixin. +_source_consistency = LazyModule("orcapod.pipeline.source_consistency") class RunHoldingNode: @@ -55,6 +59,7 @@ def is_stale(self) -> bool: stale (ITL-1095). A stale node reads empty until it runs again. Each node of the ancestry is checked once, however many paths lead to it. """ + self._require_live_bindings() return _stale(self, {}) def _own_staleness(self) -> bool: @@ -79,8 +84,13 @@ def holds_current_run(self, *, load_only: bool = False) -> bool: Returns: ``True`` if the node holds a current run for such a run. """ + self._require_live_bindings() return _current(self, load_only, {}, {}) + def _require_live_bindings(self) -> None: + """Validate the stream graph even when there are no held rows to check.""" + _source_consistency.require_live_source_bindings((self,)) + def _holds_run(self, *, load_only: bool) -> bool: """Whether the node holds the rows of a completed run good for such a run.""" raise NotImplementedError diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index d21b3a4f5..13ddd5cfe 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -280,7 +280,7 @@ def __init__( if isinstance(origin, RunHoldingNode): # Constructing a stored-result source can inspect the live node's - # schema or hash. Once constructed, its live-input walk ends there. + # schema or hash. require_live_source_bindings((origin,)) self._tags_as_data: dict[str, str] | None = None if tags_as_data is not None: @@ -328,6 +328,7 @@ def identity_structure(self) -> Any: Returns: The identity structure. """ + self._require_origin_bindings() self._note_provisional_identity_use() # a direct read is a use (ITL-1331) if self._tags_as_data is None: # Tied precisely to the specific node's data identity @@ -434,6 +435,7 @@ def output_schema( columns: ColumnConfig | dict[str, Any] | None = None, all_info: bool = False, ) -> tuple[Schema, Schema]: + self._require_origin_bindings() if self._tags_as_data is None: return self._origin.output_schema(columns=columns, all_info=all_info) return self._columns_stream(self._tags_as_data).output_schema( @@ -446,6 +448,7 @@ def keys( columns: ColumnConfig | dict[str, Any] | None = None, all_info: bool = False, ) -> tuple[tuple[str, ...], tuple[str, ...]]: + self._require_origin_bindings() if self._tags_as_data is None: return self._origin.keys(columns=columns, all_info=all_info) return self._columns_stream(self._tags_as_data).keys( @@ -496,6 +499,12 @@ def stored_result_origin(self) -> StreamProtocol | None: """Return the stored-result node whose live schema and keys this source uses.""" return self._origin if self.live_source_inputs is None else None + def _require_origin_bindings(self) -> None: + """Check the origin before obtaining even cached rows or metadata.""" + from orcapod.pipeline.source_consistency import require_live_source_bindings + + require_live_source_bindings((self,)) + def _origin_records(self) -> "pa.Table | None": """Return the origin's rows, or ``None`` when a job node has none stored. @@ -669,6 +678,7 @@ def _derive_from( def _get_stream(self) -> ArrowTableStream: # Every read of rows notes the provisional use, also of rows kept from an # earlier read (ITL-1331), as a provisional operator's stream does. + self._require_origin_bindings() self._note_provisional_identity_use() if self._tags_as_data is not None: if self._cached_stream is not None: @@ -719,6 +729,7 @@ def check_for_new_data(self) -> bool: ``True`` if the source's modified time moved: it holds new rows, or it holds none and its origin changed. """ + self._require_origin_bindings() if isinstance(self._origin, RootSource): _ = self._origin.check_for_new_data() seen = self._origin.last_modified @@ -753,6 +764,7 @@ def check_for_new_data(self) -> bool: def _schema_requires_io(self, config: ColumnConfig) -> bool: """Whether reading the schema with ``config`` would poll: as for the origin.""" + self._require_origin_bindings() return schema_requires_io(self._origin, config) def head( @@ -773,6 +785,7 @@ def head( its head (see ``StreamBase.head``). """ check_head_size(n) + self._require_origin_bindings() # A preview is a read of rows: it notes the provisional use (ITL-1331). self._note_provisional_identity_use() config = ColumnConfig.handle_config(columns, all_info=all_info) diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index dda5b2a65..81bc32bf9 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -623,9 +623,14 @@ class SourceSpecMismatchError(InputValidationError, ValueError): """ -def live_input_cycle_error(label: str | None = None) -> SourceSpecMismatchError: - """Report a cycle found while following live inputs.""" - location = "" if label is None else f" at {label!r}" +def live_input_cycle_error( + label: str | None = None, *, slots: tuple[str, ...] = () +) -> SourceSpecMismatchError: + """Report a cycle found while following live and stored-result inputs.""" + if slots: + location = " through source slots " + ", ".join(map(repr, slots)) + else: + location = "" if label is None else f" at {label!r}" return SourceSpecMismatchError( f"A cycle in the live input graph{location} is not supported (ITL-1559). " "Remove the circular input or replace it with an independent source." diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index f8dd9ccac..4e0d91875 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -21,6 +21,7 @@ from orcapod.pipeline.source_consistency import ( invocation_source_uses, require_consistent_sources, + require_live_source_bindings, ) from orcapod.side_effects import SideEffectNode from orcapod.protocols import core_protocols as cp @@ -361,6 +362,8 @@ def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: inputs = tuple(invocation.input_streams) self._validate_capture_sources(inputs) + uses = tuple(self._source_uses(invocation)) + require_live_source_bindings(stream for _, stream in uses) key = invocation.content_hash().to_string() input_keys = tuple(upstream.content_hash().to_string() for upstream in inputs) # Checked before anything is recorded, so a refused invocation leaves the @@ -369,7 +372,6 @@ def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: # streams lead to it: every source this invocation reads is checked with # every source the pipeline's streams read now (nothing is remembered: a # slot rebound since the last invocation changes what they read). - uses = tuple(self._source_uses(invocation)) require_consistent_sources(uses) require_one_restriction(stream for _, stream in uses) @@ -541,6 +543,7 @@ def compile(self) -> None: # the last invocation would otherwise connect a branch recorded over one # restriction to another (ITL-1218). uses = tuple(self._source_uses()) + require_live_source_bindings(stream for _, stream in uses) require_consistent_sources(uses) require_one_restriction(stream for _, stream in uses) @@ -832,7 +835,7 @@ def from_invocations( A compiled instance of ``cls``. """ instance = cls(name=name) - instance._validate_capture_sources( + inputs = tuple( chain( graph.source_streams.values(), chain.from_iterable( @@ -840,6 +843,8 @@ def from_invocations( ), ) ) + instance._validate_capture_sources(inputs) + require_live_source_bindings(inputs) require_consistent_sources(invocation_source_uses(graph.invocations)) instance._source_streams = dict(graph.source_streams) for inv in graph.invocations: diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 278b51461..3435d7c20 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -8,6 +8,7 @@ import sys from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass +from itertools import chain from typing import TYPE_CHECKING, Any, cast import orcapod @@ -49,11 +50,12 @@ warn_row_failures, ) from orcapod.pipeline.source_consistency import ( + binding_dependency_error, + independent_source_dependency, invocation_source_uses, + owned_node_dependency, require_consistent_sources, - require_independent_source_binding, require_live_source_bindings, - require_no_owned_node_dependency, ) from orcapod.protocols import core_protocols as cp from orcapod.databases.utils import as_table_committing @@ -269,8 +271,11 @@ def _validate_capture_sources(self, streams: Iterable[cp.StreamProtocol]) -> Non if key in visited: continue visited.add(key) - if isinstance(stream, DerivedSource): - require_no_owned_node_dependency(stream, stream.source_name, self) + if ( + isinstance(stream, DerivedSource) + and (dependency := owned_node_dependency(stream, self)) is not None + ): + raise binding_dependency_error(dependency, stream.source_name) if isinstance(stream, SourceJobNode): if id(stream) not in own_nodes: raise InconsistentSourceError( @@ -315,11 +320,14 @@ def _source_node_from_recording(self, key: str) -> SourceJobNode: slot = self._persistent_node_map.get(key) if isinstance(slot, SourceJobNode): stream = slot - if isinstance(stream, SourceJobNode): - require_independent_source_binding(stream.bound_source, stream.name, self) - else: - name = stream.source_name if isinstance(stream, RootSource) else None - require_independent_source_binding(stream, name, self) + source = stream.bound_source if isinstance(stream, SourceJobNode) else stream + if (dependency := independent_source_dependency(source, self)) is not None: + name = None + if isinstance(stream, SourceJobNode): + name = stream.name + elif isinstance(stream, RootSource): + name = stream.source_name + raise binding_dependency_error(dependency, name) return self.source_node_class.from_stream(stream) def compile(self) -> None: @@ -654,9 +662,13 @@ def _prepare_source_bindings( self, rebinding: Rebinding ) -> list[tuple[SourceJobNode, cp.StreamProtocol | None, _DeclaredForm | None]]: """Validate the prospective job and prepare each changed slot's row form.""" - for slot, source in rebinding: - require_independent_source_binding(source, slot.name, self) nodes = self._persistent_node_map.values() + # Walk the proposed bindings in input order so a refused batch names the + # same receiving slot as a single bind, then check the rest of the graph. + require_live_source_bindings( + chain((slot for slot, _ in rebinding), nodes), + rebinding=rebinding, + ) require_consistent_sources( ((f"node {node.label!r}", node) for node in nodes), rebinding ) @@ -2028,7 +2040,8 @@ def load( else: if source is None: continue - require_independent_source_binding(source, spec_name) + if (dependency := independent_source_dependency(source)) is not None: + raise binding_dependency_error(dependency, spec_name) try: # A rebuilt source whose column types changed is treated as # one that could not be rebuilt (ITL-1112). diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index 0a086ac99..220485396 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -4,6 +4,7 @@ from collections import Counter from collections.abc import Iterable +from dataclasses import dataclass from typing import TYPE_CHECKING, cast from orcapod.errors import ( @@ -16,6 +17,7 @@ if TYPE_CHECKING: import pyarrow as pa + from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources.base import RootSource from orcapod.pipeline.job import PipelineJob from orcapod.pipeline.pod_invocation import PodInvocation @@ -26,8 +28,8 @@ SourceUse = tuple[str, "StreamProtocol"] -def _binding_dependency_error( - name: str | None, dependency: StreamProtocol +def binding_dependency_error( + dependency: StreamProtocol, name: str | None = None ) -> SourceSpecMismatchError: """Name the dependency that makes a slot binding unsupported.""" from orcapod.core.nodes.source_node import SourceJobNode @@ -45,10 +47,10 @@ def _binding_dependency_error( ) -def require_no_owned_node_dependency( - stream: StreamProtocol, name: str | None, owner: PipelineJob -) -> None: - """Refuse a dependency on a node of the binding's own job.""" +def owned_node_dependency( + stream: StreamProtocol, owner: PipelineJob +) -> StreamProtocol | None: + """Return an own-job node read directly or through a stored-result source.""" from orcapod.core.nodes.staleness import RunHoldingNode from orcapod.core.sources.derived_source import DerivedSource @@ -56,67 +58,102 @@ def require_no_owned_node_dependency( stream.stored_result_origin if isinstance(stream, DerivedSource) else stream ) if isinstance(dependency, RunHoldingNode) and dependency._belongs_to_job(owner): # pyright: ignore[reportPrivateUsage] # binding checks use node provenance - raise _binding_dependency_error(name, dependency) + return dependency + return None + +@dataclass(frozen=True) +class _Binding: + """The policy for a slot's source, with an optional slot still being inferred.""" -def _require_live_inputs( + owner: PipelineJob | None + slot: SourceJobNode | None = None + + +def _binding_dependency( streams: Iterable[StreamProtocol], - binding: tuple[str | None, PipelineJob | None] | None = None, -) -> None: - """Validate live inputs by identity, with a separate walk inside each binding. + binding: _Binding | None = None, + rebinding: Rebinding = (), +) -> StreamProtocol | None: + """Walk live and stored-result dependencies before a read resolves them. - A binding refuses any bindable slot and any node of its owner, including a - stored-result origin. Stored results from other jobs remain leaves. + The path tracks identity across all wrappers and jobs. At a stored-result + origin the live-binding restriction ends, but the metadata dependency still + leads into the origin's inputs and any slots those inputs read. Completed + walks can be shared between paths with the same binding policy. """ from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.sources.derived_source import DerivedSource from orcapod.pipeline.restrictions import streams_beneath - pending = [(stream, binding, False) for stream in streams] - pending.reverse() - active: set[tuple[int, bool, int]] = set() + pending = [(stream, binding, False) for stream in reversed(tuple(streams))] + active: dict[int, StreamProtocol] = {} visited: set[tuple[int, bool, int]] = set() while pending: stream, current_binding, leaving = pending.pop() - owner = current_binding[1] if current_binding is not None else None - key = (id(stream), current_binding is not None, id(owner)) + identity = id(stream) + owner = current_binding.owner if current_binding is not None else None + key = (identity, current_binding is not None, id(owner)) if leaving: - active.remove(key) + del active[identity] visited.add(key) continue - if key in visited: - continue if current_binding is not None: - name = current_binding[0] + dependency = None if isinstance(stream, SourceJobNode): - raise _binding_dependency_error(name, stream) - if owner is not None: - require_no_owned_node_dependency(stream, name, owner) - if key in active: - raise live_input_cycle_error(stream.label) - active.add(key) + dependency = stream + elif owner is not None: + dependency = owned_node_dependency(stream, owner) + if dependency is not None: + if current_binding.slot is None: + return dependency + raise binding_dependency_error(dependency, current_binding.slot.name) + if identity in active: + cycle = list(active.values())[list(active).index(identity) :] + slots = [node for node in cycle if isinstance(node, SourceJobNode)] + if len(slots) == 1 and not any( + isinstance(node, DerivedSource) + and node.stored_result_origin is not None + for node in cycle + ): + raise binding_dependency_error(slots[0], slots[0].name) + raise live_input_cycle_error( + stream.label, slots=tuple(slot.name for slot in slots) + ) + if key in visited: + continue + active[identity] = stream pending.append((stream, current_binding, True)) - next_binding = ( - (stream.name, stream._get_binding_owner()) # pyright: ignore[reportPrivateUsage] # validate the active slot in its owning job - if isinstance(stream, SourceJobNode) - else current_binding - ) - pending.extend( - (upstream, next_binding, False) - for upstream in reversed(streams_beneath(stream)) - ) + if ( + isinstance(stream, DerivedSource) + and (origin := stream.stored_result_origin) is not None + ): + pending.append((origin, None, False)) + else: + if isinstance(stream, SourceJobNode): + slot_owner = stream._get_binding_owner() # pyright: ignore[reportPrivateUsage] # active slot's provenance + current_binding = _Binding(slot_owner, stream) + pending.extend( + (upstream, current_binding, False) + for upstream in reversed(streams_beneath(stream, rebinding)) + ) + return None -def require_independent_source_binding( - source: StreamProtocol | None, name: str | None, owner: PipelineJob | None = None -) -> None: - """Refuse a prospective binding before reading its schema, name or rows.""" - if source is not None: - _require_live_inputs((source,), (name, owner)) +def independent_source_dependency( + source: StreamProtocol | None, owner: PipelineJob | None = None +) -> StreamProtocol | None: + """Return a forbidden dependency before inferring or creating a source slot.""" + if source is None: + return None + return _binding_dependency((source,), _Binding(owner)) -def require_live_source_bindings(streams: Iterable[StreamProtocol]) -> None: - """Check live inputs before resolving schemas or hashes, reading rows or running.""" - _require_live_inputs(streams) +def require_live_source_bindings( + streams: Iterable[StreamProtocol], rebinding: Rebinding = () +) -> None: + """Check live bindings before resolving schemas or hashes, reading rows or running.""" + _binding_dependency(streams, rebinding=rebinding) def invocation_source_uses(invocations: Iterable[PodInvocation]) -> Iterable[SourceUse]: diff --git a/tests/test_core/operators/test_polars_filter_warning.py b/tests/test_core/operators/test_polars_filter_warning.py index 8e249807d..612d9f22d 100644 --- a/tests/test_core/operators/test_polars_filter_warning.py +++ b/tests/test_core/operators/test_polars_filter_warning.py @@ -201,11 +201,12 @@ def _saved_job(tmp_path: Path, *, rebuildable: bool) -> Path: [pl.col("depth") >= 10] if rebuildable else [[True, False, True]] ) job = PipelineJob(name="filtered", database=DeltaTableDatabase(tmp_path / "store")) + source = _source() with warnings.catch_warnings(): warnings.simplefilter("ignore", PolarsFilterWarning) with job: - _ = _source().polars_filter(*first, session="s1", label="first") - _ = _source().polars_filter(*second, unit=3, label="second") + _ = source.polars_filter(*first, session="s1", label="first") + _ = source.polars_filter(*second, unit=3, label="second") path = tmp_path / "job.json" job.save(path) return path diff --git a/tests/test_pipeline/test_bind_narrower_source.py b/tests/test_pipeline/test_bind_narrower_source.py index 8f555bc75..37733fb65 100644 --- a/tests/test_pipeline/test_bind_narrower_source.py +++ b/tests/test_pipeline/test_bind_narrower_source.py @@ -23,6 +23,8 @@ import orcapod from orcapod import PipelineJob, function_pod +from orcapod.core.function_pod import FunctionPod +from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.source_node import SourceJobNode, SourceNode from orcapod.core.operators import Join, MapData from orcapod.core.streams.arrow_table_stream import ArrowTableStream @@ -583,24 +585,22 @@ def _xw_job() -> PipelineJob: def test_meta_columns_of_a_narrower_stream_are_kept() -> None: """The ``__`` columns a job node's rows carry reach the rows of a narrower bind.""" - @function_pod(output_keys="x") def same(v: int) -> int: """Return ``v``.""" return v - origin = PipelineJob(name="origin", database=InMemoryArrowDatabase()) - with origin: - _ = same.pod( - DictSource( - [{"id": 0, "v": 1}], - tag_columns=["id"], - tag_only_columns=True, - source_id="o", - ), - label="same", - ) - _ = origin.run() - stream = origin.nodes["same"] + stream = FunctionJobNode( + FunctionPod.from_fn(same, output_keys="x"), + DictSource( + [{"id": 0, "v": 1}], + tag_columns=["id"], + tag_only_columns=True, + source_id="o", + ), + pipeline_database=InMemoryArrowDatabase(), + label="same", + ) + _ = stream.run() job = PipelineJob(name="j", database=InMemoryArrowDatabase()) with job: _ = MapData({"x": "y"})(_slot(int | None), label="renamed") diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index befa8c354..c6e3dadf6 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -1768,6 +1768,150 @@ async def read_async() -> None: _ = function.held_row_count() +def _feedback_job(name: str, *, copy: bool = False) -> PipelineJob: + """Build a cold function job whose results fit another job's slot.""" + from orcapod.sources import DerivedSource + + root = _shifted_source(name, 0) + source = ( + DerivedSource(root, source_id=name, tags_as_data={"t1": "copy"}) + if copy + else root + ) + with PipelineJob(name, database=InMemoryArrowDatabase()) as job: + _ = same_columns.pod(source, label="result") + return job + + +@pytest.mark.parametrize("setter", [False, True], ids=["batch", "setter"]) +@pytest.mark.parametrize("chain", [False, True], ids=["mutual", "three_jobs"]) +def test_stored_result_bindings_refuse_cross_job_feedback( + setter: bool, chain: bool +) -> None: + left, right = _feedback_job("left"), _feedback_job("right") + left_rows = left.nodes["result"].as_source() + right_rows = right.nodes["result"].as_source() + middle = _feedback_job("middle") if chain else None + if middle is None: + left.bind(sources={"left": right_rows}) + else: + middle_rows = middle.nodes["result"].as_source() + middle.bind(sources={"middle": right_rows}) + left.bind(sources={"left": middle_rows.cached(InMemoryArrowDatabase())}) + assert left.nodes["left"].as_table().num_rows == 0 + right_source = right.sources["right"] + + with pytest.raises(SourceSpecMismatchError, match="cycle.*ITL-1559") as error: + _rebind(right, {"right": left_rows}, setter=setter) + + assert "'left'" in str(error.value) and "'right'" in str(error.value) + if chain: + assert "'middle'" in str(error.value) + assert right.sources["right"] is right_source + assert right.nodes["right"].bound_source is right_source + assert left.nodes["left"].as_table().num_rows == 0 + + +@pytest.mark.parametrize( + "entry", + [ + "run", + "run_async", + "load_only", + "node_run", + "slot_table", + "node_table", + "derived_table", + "derived_head", + "node_head", + "staleness", + "current", + "preview", + ], +) +def test_reads_refuse_stored_result_feedback_introduced_by_proxy(entry: str) -> None: + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.sources import DerivedSource + + left, right, independent = ( + _feedback_job(name, copy=True) for name in ("left", "right", "left") + ) + result = left.nodes["result"] + left_rows = result.as_source() + independent_rows = independent.nodes["result"].as_source() + right_rows = right.nodes["result"].as_source() + proxy = SourceProxy( + independent_rows.source_id, + independent_rows.content_hash().to_string(), + independent_rows.pipeline_hash().to_string(), + *independent_rows.output_schema(), + ) + proxy.bind(independent_rows) + left.bind( + sources={ + "left": DerivedSource( + right_rows, source_id="read_right", tags_as_data={"t1": "copy"} + ) + } + ) + right.bind( + sources={ + "right": DerivedSource( + proxy, source_id="read_left", tags_as_data={"t1": "copy"} + ) + } + ) + proxy.bind(left_rows) + + if entry == "preview": + message = result._repr_html_() + else: + reads = { + "run": left.run, + "run_async": lambda: asyncio.run(left.run_async()), + "load_only": lambda: left.run(load_only=True), + "node_run": result.run, + "slot_table": left.nodes["left"].as_table, + "node_table": result.as_table, + "derived_table": left_rows.as_table, + "derived_head": left_rows.head, + "node_head": result.head, + "staleness": lambda: result.is_stale, + "current": result.holds_current_run, + } + with pytest.raises(SourceSpecMismatchError, match="cycle.*ITL-1559") as error: + _ = reads[entry]() + message = str(error.value) + assert "'left'" in message and "'right'" in message + assert "cycle" in message and "ITL-1559" in message + + +@pytest.mark.parametrize("cached", [False, True], ids=["delegate", "cache"]) +@pytest.mark.parametrize("late", [False, True], ids=["capture", "compile"]) +def test_pipeline_refuses_a_proxy_cycle(cached: bool, late: bool) -> None: + from orcapod.core.sources.source_proxy import SourceProxy + + source = _shifted_source("input", 0) + proxy = SourceProxy( + source.source_id, + source.content_hash().to_string(), + source.pipeline_hash().to_string(), + *source.output_schema(), + ) + circular = proxy.cached(InMemoryArrowDatabase()) if cached else proxy + graph = Pipeline("cycle") + if late: + with pytest.raises(SourceSpecMismatchError, match="cycle.*ITL-1559"), graph: + _ = total.pod(proxy, label="result") + proxy.bind(circular) + else: + proxy.bind(circular) + with graph: + with pytest.raises(SourceSpecMismatchError, match="cycle.*ITL-1559"): + _ = total.pod(proxy, label="result") + assert "result" not in graph.nodes + + @pytest.mark.xfail( strict=True, raises=AssertionError, From d9242d5407665b18b21b1d8ed05310daec4fa55b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 05:12:39 -0800 Subject: [PATCH 39/42] fix(pipeline): resolve staleness validator without a lazy wrapper --- src/orcapod/core/nodes/staleness.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/orcapod/core/nodes/staleness.py b/src/orcapod/core/nodes/staleness.py index 9efe40a73..d767f7f3b 100644 --- a/src/orcapod/core/nodes/staleness.py +++ b/src/orcapod/core/nodes/staleness.py @@ -8,15 +8,12 @@ from __future__ import annotations +import importlib import weakref from collections.abc import Iterable from typing import Any from orcapod.errors import live_input_cycle_error -from orcapod.utils.lazy_module import LazyModule - -# Source consistency identifies job nodes using this mixin. -_source_consistency = LazyModule("orcapod.pipeline.source_consistency") class RunHoldingNode: @@ -89,7 +86,12 @@ def holds_current_run(self, *, load_only: bool = False) -> bool: def _require_live_bindings(self) -> None: """Validate the stream graph even when there are no held rows to check.""" - _source_consistency.require_live_source_bindings((self,)) + # Source consistency sits above this mixin in the import graph and uses it + # to recognize job nodes. Resolve the module when the graph is checked. + source_consistency = importlib.import_module( + "orcapod.pipeline.source_consistency" + ) + source_consistency.require_live_source_bindings((self,)) def _holds_run(self, *, load_only: bool) -> bool: """Whether the node holds the rows of a completed run good for such a run.""" From 99cd83cbcd5d79b88ee8939b01c2837e12e6a8b8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 06:29:47 -0800 Subject: [PATCH 40/42] fix(pipeline): validate transitive bindings and restore tracker callbacks --- changelog.d/ITL-1469.md | 7 +- docs/concepts/pipeline-job.md | 6 +- docs/concepts/sources.md | 8 +- src/orcapod/core/tracker.py | 54 +++++++--- src/orcapod/pipeline/source_consistency.py | 32 +++++- .../protocols/core_protocols/trackers.py | 23 +---- src/orcapod/side_effects.py | 4 +- tests/test_core/test_tracker.py | 59 +++++++++++ .../test_source_object_registration.py | 98 +++++++++++++++++++ 9 files changed, 242 insertions(+), 49 deletions(-) diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index 43cb0c746..893421eed 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -10,12 +10,15 @@ columns, including when they occupy different slots. For tag-copy sources over a bound proxy, registration uses the live Arrow types. - A capture refused by any active pipeline or job leaves all their graphs - unchanged. + unchanged. Successful capture still calls each active tracker's recording + callback in registration order. - Direct reads and job and node runs recheck source binding dependencies. If an operator or wrapper introduces a forbidden dependency after binding, they raise `SourceSpecMismatchError` before reading sources. - Bindings to stored results reject cycles across jobs and name the slots - involved. Pipeline capture and compilation also reject circular wrapper inputs. + involved. They also reject acyclic dependencies on nodes of the receiving + job. Cold side-effect row reads recheck bindings. Pipeline capture and + compilation also reject circular wrapper inputs. ### Known limitations diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index fa0ea0339..5111c077a 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -391,8 +391,10 @@ each job or node run, including a load-only run. This also protects the schema and hash lookups needed to construct an `as_source()` result. Pass the underlying source, or use another job's `node.as_source()` to read stored results. The stored-result source still uses its origin's schema and keys, so Orcapod -checks the origin's inputs across jobs. If those inputs lead back to the receiving -slot, the binding is refused and the error names the slots in the cycle. +checks the origin's inputs across jobs. If those inputs reach another node in +the receiving job, the error names that node and the receiving slot. If those +inputs form a cycle, the error names the slots in the cycle. A side-effect node +also checks its bindings when read before its first run. ```python from orcapod.errors import SourceSpecMismatchError diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index c65ec4b01..f4a995561 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -106,10 +106,10 @@ source itself. Binding through a live input to any bindable slot, or binding to a node of the receiving job even through `as_source()`, raises `SourceSpecMismatchError` -(ITL-1559). Another job's `node.as_source()` can provide stored results, provided -its inputs do not lead back to the receiving slot through other bindings. The -error names the slots involved in such a cycle. Pass an independent underlying -source to break the cycle. A refused batch preserves all existing bindings. +(ITL-1559). Another job's `node.as_source()` can provide stored results when its +inputs are independent of the receiving job's nodes, including through other +jobs' bindings. The error names the dependency or the slots involved in a +cycle. A refused batch preserves all existing bindings. Direct reads and job and node runs, including load-only runs, recheck the binding because an operator or wrapper can change its inputs after binding. diff --git a/src/orcapod/core/tracker.py b/src/orcapod/core/tracker.py index 677587854..8fe5372d1 100644 --- a/src/orcapod/core/tracker.py +++ b/src/orcapod/core/tracker.py @@ -4,7 +4,7 @@ from collections.abc import Callable, Generator from contextlib import contextmanager from functools import partial -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable from orcapod.protocols import core_protocols as cp @@ -12,6 +12,13 @@ from orcapod.pipeline.pod_invocation import PodInvocation +@runtime_checkable +class _PreparesInvocation(Protocol): + """Optional validation before dispatching a capture to multiple trackers.""" + + def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: ... + + class BasicTrackerManager: def __init__(self) -> None: self._active_trackers: list[cp.TrackerProtocol] = [] @@ -46,7 +53,12 @@ def record_operator_pod_invocation( """Record the invocation of a pod in the tracker.""" from orcapod.pipeline.pod_invocation import OperatorInvocation - self._record(partial(OperatorInvocation, pod, upstreams, label)) + self._record( + partial(OperatorInvocation, pod, upstreams, label), + lambda tracker: tracker.record_operator_pod_invocation( + pod, upstreams, label=label + ), + ) def record_function_pod_invocation( self, @@ -57,7 +69,12 @@ def record_function_pod_invocation( """Record the invocation of a data function to the tracker.""" from orcapod.pipeline.pod_invocation import FunctionInvocation - self._record(partial(FunctionInvocation, pod, (input_stream,), label)) + self._record( + partial(FunctionInvocation, pod, (input_stream,), label), + lambda tracker: tracker.record_function_pod_invocation( + pod, input_stream, label=label + ), + ) def record_side_effect_pod_invocation( self, @@ -68,17 +85,27 @@ def record_side_effect_pod_invocation( """Record a side-effect pod invocation in all active trackers.""" from orcapod.pipeline.pod_invocation import SideEffectInvocation - self._record(partial(SideEffectInvocation, pod, (input_stream,), label)) + self._record( + partial(SideEffectInvocation, pod, (input_stream,), label), + lambda tracker: tracker.record_side_effect_pod_invocation( + pod, input_stream, label=label + ), + ) - def _record(self, make_invocation: Callable[[], PodInvocation]) -> None: - """Prepare every active tracker's recording before committing in order.""" + def _record( + self, + make_invocation: Callable[[], PodInvocation], + record: Callable[[cp.TrackerProtocol], None], + ) -> None: + """Preflight nested captures before dispatching the recording callbacks.""" trackers = self.get_active_trackers() - if not trackers: - return - invocation = make_invocation() - recordings = [tracker.prepare_invocation(invocation) for tracker in trackers] - for record in recordings: - record() + if len(trackers) > 1: + invocation = make_invocation() + for tracker in trackers: + if isinstance(tracker, _PreparesInvocation): + _ = tracker.prepare_invocation(invocation) + for tracker in trackers: + record(tracker) @contextmanager def no_tracking(self) -> Generator[None, Any, None]: @@ -107,9 +134,6 @@ def set_active(self, active: bool = True) -> None: def is_active(self) -> bool: return self._active - @abstractmethod - def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: ... - @abstractmethod def record_operator_pod_invocation( self, diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py index 220485396..ea5ac9be8 100644 --- a/src/orcapod/pipeline/source_consistency.py +++ b/src/orcapod/pipeline/source_consistency.py @@ -78,9 +78,10 @@ def _binding_dependency( """Walk live and stored-result dependencies before a read resolves them. The path tracks identity across all wrappers and jobs. At a stored-result - origin the live-binding restriction ends, but the metadata dependency still - leads into the origin's inputs and any slots those inputs read. Completed - walks can be shared between paths with the same binding policy. + origin the live-slot restriction ends. The metadata dependency still leads + into the origin's inputs and bound slots, where the receiving binding's + own-job restriction applies. Check that ancestry after the cycle walk so + cycles still report all their slots. """ from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources.derived_source import DerivedSource @@ -89,6 +90,7 @@ def _binding_dependency( pending = [(stream, binding, False) for stream in reversed(tuple(streams))] active: dict[int, StreamProtocol] = {} visited: set[tuple[int, bool, int]] = set() + stored_bindings: list[tuple[StreamProtocol, PipelineJob, SourceJobNode | None]] = [] while pending: stream, current_binding, leaving = pending.pop() identity = id(stream) @@ -128,6 +130,8 @@ def _binding_dependency( isinstance(stream, DerivedSource) and (origin := stream.stored_result_origin) is not None ): + if current_binding is not None and owner is not None: + stored_bindings.append((origin, owner, current_binding.slot)) pending.append((origin, None, False)) else: if isinstance(stream, SourceJobNode): @@ -137,6 +141,28 @@ def _binding_dependency( (upstream, current_binding, False) for upstream in reversed(streams_beneath(stream, rebinding)) ) + + checked_origins: set[tuple[int, int]] = set() + for origin, owner, slot in stored_bindings: + ancestry = [origin] + while ancestry: + stream = ancestry.pop() + origin_key = (id(stream), id(owner)) + if origin_key in checked_origins: + continue + checked_origins.add(origin_key) + dependency = owned_node_dependency(stream, owner) + if dependency is not None: + if slot is None: + return dependency + raise binding_dependency_error(dependency, slot.name) + if ( + isinstance(stream, DerivedSource) + and (stored_origin := stream.stored_result_origin) is not None + ): + ancestry.append(stored_origin) + else: + ancestry.extend(reversed(streams_beneath(stream, rebinding))) return None diff --git a/src/orcapod/protocols/core_protocols/trackers.py b/src/orcapod/protocols/core_protocols/trackers.py index 0abd90b32..a816ebfd5 100644 --- a/src/orcapod/protocols/core_protocols/trackers.py +++ b/src/orcapod/protocols/core_protocols/trackers.py @@ -1,26 +1,19 @@ from __future__ import annotations -from collections.abc import Callable from contextlib import AbstractContextManager -from typing import TYPE_CHECKING, Protocol, runtime_checkable +from typing import Protocol, runtime_checkable from orcapod.protocols.core_protocols.function_pod import FunctionPodProtocol from orcapod.protocols.core_protocols.operator_pod import OperatorPodProtocol from orcapod.protocols.core_protocols.side_effect_pod import SideEffectPodProtocol from orcapod.protocols.core_protocols.streams import StreamProtocol -if TYPE_CHECKING: - from orcapod.pipeline.pod_invocation import PodInvocation - @runtime_checkable class TrackerProtocol(Protocol): """ Internal contract for recording invocations and stream creation. - Every tracker implements ``prepare_invocation()`` so the manager can validate - a capture across all active trackers before any tracker records it. - Trackers are responsible for maintaining the computational graph by recording relationships between kernels, streams, and invocations. They enable: - Lineage tracking and data provenance @@ -59,20 +52,6 @@ def is_active(self) -> bool: """ ... - def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: - """Validate an invocation without recording it. - - All checks that can refuse an invocation belong here. The manager calls - the returned callbacks only after every active tracker has accepted. - - Args: - invocation: The pod and inputs to record. - - Returns: - A callback that records the validated invocation. - """ - ... - def record_operator_pod_invocation( self, pod: OperatorPodProtocol, diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 2ecfbfeb8..866298130 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -1320,7 +1320,9 @@ def _current_rows(self) -> list[tuple[TagProtocol, DataProtocol]] | None: Held rows go stale, and are dropped, when an upstream changed after the run: the judgement ``FunctionJobNode`` uses for the rows it holds. """ - if self._held_rows is not None and self.is_stale: + if self._held_rows is None: + self._require_live_bindings() + elif self.is_stale: self._held_rows = None return self._held_rows diff --git a/tests/test_core/test_tracker.py b/tests/test_core/test_tracker.py index 046239abb..c1bd0123d 100644 --- a/tests/test_core/test_tracker.py +++ b/tests/test_core/test_tracker.py @@ -19,6 +19,7 @@ import pyarrow as pa import pytest +from orcapod import side_effect_pod from orcapod.core.function_pod import FunctionPod, function_pod from orcapod.core.nodes import FunctionNode, OperatorNode, SourceNode from orcapod.core.nodes.source_node import SourceJobNode @@ -28,6 +29,9 @@ from orcapod.core.streams import ArrowTableStream from orcapod.core.tracker import BasicTrackerManager from orcapod.pipeline import Pipeline +from orcapod.protocols import core_protocols as cp +from orcapod.side_effects import SideEffectPod +from orcapod.sources import DictSource from orcapod.types import Schema # --------------------------------------------------------------------------- @@ -54,6 +58,61 @@ def _make_pipeline( ) +def test_capture_calls_existing_tracker_callbacks_in_registration_order() -> None: + callbacks: list[tuple[str, str | None]] = [] + + class RecordingPipeline(Pipeline): + def record_operator_pod_invocation( + self, + pod: cp.OperatorPodProtocol, + upstreams: tuple[cp.StreamProtocol, ...] = (), + label: str | None = None, + ) -> None: + callbacks.append((self.name[0], label)) + super().record_operator_pod_invocation(pod, upstreams, label=label) + + def record_function_pod_invocation( + self, + pod: cp.FunctionPodProtocol, + input_stream: cp.StreamProtocol, + label: str | None = None, + ) -> None: + callbacks.append((self.name[0], label)) + super().record_function_pod_invocation(pod, input_stream, label=label) + + def record_side_effect_pod_invocation( + self, + pod: cp.SideEffectPodProtocol, + input_stream: cp.StreamProtocol, + label: str | None = None, + ) -> None: + callbacks.append((self.name[0], label)) + super().record_side_effect_pod_invocation(pod, input_stream, label=label) + + @function_pod(output_keys="value") + def transform(x: int) -> int: + return x * 2 + + @side_effect_pod + def deliver(x: int) -> None: + pytest.fail("Capturing a side effect must never deliver") + + assert isinstance(deliver, SideEffectPod) + source = DictSource([{"x": 1}]) + with RecordingPipeline("first") as first, RecordingPipeline("second") as second: + _ = source.map_data({"x": "value"}, label="operator") + _ = transform.pod(source, label="function") + _ = deliver.process(source, label="side_effect") + + assert callbacks == [ + (name, label) + for label in ("operator", "function", "side_effect") + for name in ("first", "second") + ] + assert {"operator", "function", "side_effect"} <= first.nodes.keys() + assert first.nodes.keys() == second.nodes.keys() + + def _make_source_node(name: str = "test_spec") -> SourceNode: """SourceNode matching the schema of _make_stream().""" return SourceNode( diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index c6e3dadf6..1be76d953 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -1783,6 +1783,104 @@ def _feedback_job(name: str, *, copy: bool = False) -> PipelineJob: return job +def _independent_branches_job() -> PipelineJob: + with PipelineJob("branches", database=InMemoryArrowDatabase()) as job: + _ = same_columns.pod(_shifted_source("a", 0), label="left") + _ = same_columns.pod(_shifted_source("b", 10), label="right") + _ = job.nodes["left"].run() + return job + + +@pytest.mark.parametrize("setter", [False, True], ids=["batch", "setter"]) +def test_slot_binding_refuses_acyclic_stored_results_from_its_own_job( + setter: bool, +) -> None: + job = _independent_branches_job() + other = _feedback_job("other") + other.bind(sources={"other": job.nodes["left"].as_source()}) + _ = other.run() + original = job.sources["b"] + + with pytest.raises( + SourceSpecMismatchError, match=r"slot 'b'.*node 'left'.*ITL-1559" + ): + _rebind(job, {"b": other.nodes["result"].as_source()}, setter=setter) + + assert job.sources["b"] is original + assert job.nodes["b"].bound_source is original + + +@pytest.mark.parametrize("entry", ["run", "run_async", "load_only"]) +def test_run_refuses_acyclic_stored_results_after_other_job_rebinds( + entry: str, monkeypatch: pytest.MonkeyPatch +) -> None: + job = _independent_branches_job() + other = _feedback_job("other") + _ = other.run() + stored = other.nodes["result"].as_source() + job.bind(sources={"b": stored}) + other.bind(sources={"other": job.nodes["left"].as_source()}) + + def unexpected_check() -> bool: + pytest.fail("A source was checked before the invalid binding was refused") + + monkeypatch.setattr(stored, "check_for_new_data", unexpected_check) + with pytest.raises( + SourceSpecMismatchError, match=r"slot 'b'.*node 'left'.*ITL-1559" + ): + if entry == "run_async": + _ = asyncio.run(job.run_async()) + else: + _ = job.run(load_only=entry == "load_only") + + +@pytest.mark.parametrize("read", ["iter_data", "async_iter_data", "held_row_count"]) +def test_cold_side_effect_held_reads_refuse_rebound_stored_results( + tmp_path: Path, read: str +) -> None: + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.databases import DeltaTableDatabase + from orcapod.sources import CachedSource, DerivedSource + + @side_effect_pod + def deliver(x: int, y: int) -> None: + pytest.fail("Reading a side-effect node must never deliver") + + assert isinstance(deliver, SideEffectPod) + root = DerivedSource( + _shifted_source("a", 0), source_id="a", tags_as_data={"t1": "copy"} + ) + with PipelineJob("with_effect", database=InMemoryArrowDatabase()) as job: + _ = same_columns.pod(root, label="result") + _ = deliver.process(root, label="deliver") + foreign = _feedback_job("a", copy=True) + own_rows = job.nodes["result"].as_source() + foreign_rows = foreign.nodes["result"].as_source() + disk = foreign_rows.cached(DeltaTableDatabase(tmp_path / "cache")) + restored = CachedSource.from_config(disk.to_config()) + proxy = restored.cached_source + assert isinstance(proxy, SourceProxy) + proxy.bind(foreign_rows) + source = DerivedSource(proxy, source_id="outer", tags_as_data={"t1": "copy"}) + job.bind(sources={"a": source}) + node = job.nodes["deliver"] + assert node.held_row_count() == 0 + proxy.bind(own_rows) + + async def read_async() -> None: + _ = [row async for row in node.async_iter_data()] + + with pytest.raises( + SourceSpecMismatchError, match=r"slot 'a'.*node 'result'.*ITL-1559" + ): + if read == "iter_data": + _ = list(node.iter_data()) + elif read == "async_iter_data": + asyncio.run(read_async()) + else: + _ = node.held_row_count() + + @pytest.mark.parametrize("setter", [False, True], ids=["batch", "setter"]) @pytest.mark.parametrize("chain", [False, True], ids=["mutual", "three_jobs"]) def test_stored_result_bindings_refuse_cross_job_feedback( From 5e4c4952e022d83b629d10d3b73bf95a062ef821 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 07:37:42 -0800 Subject: [PATCH 41/42] fix(pipeline): validate stored-result captures before recording (ITL-1469) --- changelog.d/ITL-1469.md | 6 +- src/orcapod/core/streams/base.py | 14 ++-- src/orcapod/pipeline/job.py | 7 +- tests/test_core/test_tracker.py | 67 ++++++++++++++++++- .../test_source_object_registration.py | 49 ++++++++++++++ 5 files changed, 134 insertions(+), 9 deletions(-) diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index 893421eed..f366d9550 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -10,8 +10,10 @@ columns, including when they occupy different slots. For tag-copy sources over a bound proxy, registration uses the live Arrow types. - A capture refused by any active pipeline or job leaves all their graphs - unchanged. Successful capture still calls each active tracker's recording - callback in registration order. + unchanged, including when a stored result depends on the receiving job + through another job's bindings. Successful capture still calls each active + tracker's recording callback in registration order, including trackers that + do not support weak references. - Direct reads and job and node runs recheck source binding dependencies. If an operator or wrapper introduces a forbidden dependency after binding, they raise `SourceSpecMismatchError` before reading sources. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 7812c7b25..78d6ae944 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -756,10 +756,16 @@ class StreamBase(TraceableBase): _recording_trackers: tuple[ReferenceType[TrackerProtocol], ...] = () def _mark_recorded(self, manager: TrackerManagerProtocol) -> Self: - """Remember which trackers accepted the invocation that made this stream.""" - self._recording_trackers = tuple( - ref(tracker) for tracker in manager.get_active_trackers() - ) + """Remember recording provenance where a tracker supports weak references.""" + recordings: list[ReferenceType[TrackerProtocol]] = [] + for tracker in manager.get_active_trackers(): + try: + recordings.append(ref(tracker)) + except TypeError: + # Trackers implementing only the public protocol can use slots + # without weak-reference support. Their callbacks still run. + continue + self._recording_trackers = tuple(recordings) return self def _was_recorded_by(self, tracker: TrackerProtocol) -> bool: diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 3435d7c20..89e720170 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -53,7 +53,6 @@ binding_dependency_error, independent_source_dependency, invocation_source_uses, - owned_node_dependency, require_consistent_sources, require_live_source_bindings, ) @@ -273,8 +272,12 @@ def _validate_capture_sources(self, streams: Iterable[cp.StreamProtocol]) -> Non visited.add(key) if ( isinstance(stream, DerivedSource) - and (dependency := owned_node_dependency(stream, self)) is not None + and stream.stored_result_origin is not None + and (dependency := independent_source_dependency(stream, self)) + is not None ): + # The stored origin ends the live capture walk. Its metadata + # still follows bindings, which must be valid for the new slot. raise binding_dependency_error(dependency, stream.source_name) if isinstance(stream, SourceJobNode): if id(stream) not in own_nodes: diff --git a/tests/test_core/test_tracker.py b/tests/test_core/test_tracker.py index c1bd0123d..f0386c8a3 100644 --- a/tests/test_core/test_tracker.py +++ b/tests/test_core/test_tracker.py @@ -16,6 +16,8 @@ from __future__ import annotations +from dataclasses import dataclass, field + import pyarrow as pa import pytest @@ -27,7 +29,7 @@ from orcapod.core.data_function import PythonDataFunction from orcapod.core.sources.arrow_table_source import ArrowTableSource from orcapod.core.streams import ArrowTableStream -from orcapod.core.tracker import BasicTrackerManager +from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER, BasicTrackerManager from orcapod.pipeline import Pipeline from orcapod.protocols import core_protocols as cp from orcapod.side_effects import SideEffectPod @@ -113,6 +115,69 @@ def deliver(x: int) -> None: assert first.nodes.keys() == second.nodes.keys() +@pytest.mark.parametrize("kind", ["operator", "function", "side_effect"]) +def test_capture_accepts_trackers_without_weak_reference_support(kind: str) -> None: + @dataclass(slots=True) + class InvocationLog: + events: list[tuple[str, str | None]] = field(default_factory=list) + active: bool = True + + def set_active(self, active: bool = True) -> None: + self.active = active + + def is_active(self) -> bool: + return self.active + + def record_operator_pod_invocation( + self, + pod: cp.OperatorPodProtocol, + upstreams: tuple[cp.StreamProtocol, ...] = (), + label: str | None = None, + ) -> None: + self.events.append(("operator", label)) + + def record_function_pod_invocation( + self, + pod: cp.FunctionPodProtocol, + input_stream: cp.StreamProtocol, + label: str | None = None, + ) -> None: + self.events.append(("function", label)) + + def record_side_effect_pod_invocation( + self, + pod: cp.SideEffectPodProtocol, + input_stream: cp.StreamProtocol, + label: str | None = None, + ) -> None: + self.events.append(("side_effect", label)) + + @function_pod(output_keys="value") + def transform(x: int) -> int: + return x * 2 + + @side_effect_pod + def deliver(x: int) -> None: + pytest.fail("Capturing a side effect must never deliver") + + assert isinstance(deliver, SideEffectPod) + tracker = InvocationLog() + source = DictSource([{"x": 1}]) + DEFAULT_TRACKER_MANAGER.register_tracker(tracker) + try: + if kind == "operator": + stream = source.map_data({"x": "value"}, label="mapped") + elif kind == "function": + stream = transform.pod(source, label="mapped") + else: + stream = deliver.process(source, label="mapped") + finally: + DEFAULT_TRACKER_MANAGER.deregister_tracker(tracker) + + assert stream.label == "mapped" + assert tracker.events == [(kind, "mapped")] + + def _make_source_node(name: str = "test_spec") -> SourceNode: """SourceNode matching the schema of _make_stream().""" return SourceNode( diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index 1be76d953..1902b296c 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -1791,6 +1791,55 @@ def _independent_branches_job() -> PipelineJob: return job +@pytest.mark.parametrize( + "job_first", [False, True], ids=["pipeline-first", "job-first"] +) +@pytest.mark.parametrize("cached", [False, True], ids=["direct", "cached"]) +def test_transitive_stored_result_capture_leaves_active_graphs_unchanged( + job_first: bool, cached: bool +) -> None: + job = _independent_branches_job() + other = _feedback_job("other") + other.bind(sources={"other": job.nodes["left"].as_source()}) + _ = other.run() + stored = other.nodes["result"].as_source() + source = stored.cached(InMemoryArrowDatabase()) if cached else stored + with Pipeline("outer", auto_compile=False) as outer: + _ = total.pod(_shifted_source("outer", 0), label="kept") + outer.compile() + + def public_state(pipeline: Pipeline | PipelineJob) -> tuple[object, ...]: + """Snapshot public topology, compiled nodes and registered sources.""" + invocations = pipeline.to_invocations() + return ( + tuple(pipeline.graph.nodes), + tuple(pipeline.graph.edges), + {label: id(node) for label, node in pipeline.nodes.items()}, + tuple(invocations.source_streams), + tuple(invocation.label for invocation in invocations.invocations), + ) + + before = [public_state(pipeline) for pipeline in (job, other, outer)] + bindings = [ + {name: id(source) for name, source in j.sources.items()} for j in (job, other) + ] + first, second = (job, outer) if job_first else (outer, job) + with first, second: + with pytest.raises( + SourceSpecMismatchError, match=r"slot .*node 'left'.*ITL-1559" + ): + _ = total.pod(source, label="feedback") + assert [public_state(pipeline) for pipeline in (job, other, outer)] == before + assert [ + {name: id(source) for name, source in j.sources.items()} + for j in (job, other) + ] == bindings + + outer.compile() + assert set(outer.nodes) == {"outer", "kept"} + assert set(job.nodes) == {"a", "b", "left", "right"} + + @pytest.mark.parametrize("setter", [False, True], ids=["batch", "setter"]) def test_slot_binding_refuses_acyclic_stored_results_from_its_own_job( setter: bool, From b997704886a675ff6af6c57a482f25326df27fd0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 09:32:59 -0800 Subject: [PATCH 42/42] fix(pipeline): address source registration review findings --- changelog.d/ITL-1469.md | 8 +- docs/reference/hashing.md | 2 +- src/orcapod/core/nodes/operator_node.py | 6 +- src/orcapod/core/tracker.py | 11 ++- src/orcapod/errors.py | 4 +- src/orcapod/pipeline/base.py | 41 ++++++--- src/orcapod/pipeline/job.py | 6 +- tests/test_core/nodes/test_source_node.py | 2 + tests/test_core/test_tracker.py | 88 +++++++++++------- .../test_pipeline/test_source_id_conflicts.py | 89 +++++++++++++++++-- .../test_source_object_registration.py | 37 ++++++++ 11 files changed, 232 insertions(+), 62 deletions(-) diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md index f366d9550..34553da16 100644 --- a/changelog.d/ITL-1469.md +++ b/changelog.d/ITL-1469.md @@ -13,10 +13,14 @@ unchanged, including when a stored result depends on the receiving job through another job's bindings. Successful capture still calls each active tracker's recording callback in registration order, including trackers that - do not support weak references. + do not support weak references. Passive trackers still receive source-pod + notifications with no upstream streams. Deferred recording checks source + conflicts again when the callback is called. - Direct reads and job and node runs recheck source binding dependencies. If an operator or wrapper introduces a forbidden dependency after binding, - they raise `SourceSpecMismatchError` before reading sources. + they raise `SourceSpecMismatchError` before reading sources. If source + validation refuses a job run, saving the job retains the previous run's + expected row counts. - Bindings to stored results reject cycles across jobs and name the slots involved. They also reject acyclic dependencies on nodes of the receiving job. Cold side-effect row reads recheck bindings. Pipeline capture and diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 0d9813cda..a304b9603 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -398,7 +398,7 @@ A record id is the row identifier (rule 8), built from row positions or key valu |---|---| | observer events (`node_hash`) | `core/nodes/function_node.py:FunctionJobNode.execute`, `core/nodes/function_node.py:FunctionJobNode.async_execute`, `core/nodes/function_node.py:FunctionJobNode._execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_cache_only`, `core/nodes/operator_node.py:OperatorJobNode.execute`, `core/nodes/operator_node.py:OperatorJobNode.async_execute`, `core/nodes/source_node.py:SourceNodeBase.execute`, `core/nodes/source_node.py:SourceNodeBase.async_execute` | | hooks (`pod_hash`) | `core/function_pod.py:_FunctionPodBase._build_post_run_payload` | -| in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase.prepare_invocation`, `pipeline/base.py:AbstractPipelineBase.prepare_invocation..`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations..`, `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | +| in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase._validate_invocation`, `pipeline/base.py:AbstractPipelineBase._validate_invocation..`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations..`, `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | | in-memory source registration keys | `pipeline/source_consistency.py:require_consistent_sources` | | in-memory lookup keys for a validated operator input or input pair (ITL-1358) | `core/operators/index.py:Index.validate_unary_input`, `core/operators/index.py:Index.async_execute`, `core/operators/pick.py:Pick.validate_unary_input`, `core/operators/pick.py:Pick.async_execute`, `core/operators/semijoin.py:SemiJoin.validate_binary_inputs`, `core/operators/semijoin.py:SemiJoin.async_execute` | | in-memory topological sort of compiled and restored nodes, using the pipeline hash to order ready invocations | `pipeline/base.py:AbstractPipelineBase._ordered_node_map..order_key` | diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 1663d8033..46910c0d7 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -2076,8 +2076,10 @@ def _current_output(self) -> StreamProtocol | None: """ from orcapod.pipeline.source_consistency import require_live_source_bindings - require_live_source_bindings((self,)) - if self._cached_output_stream is None or self.is_stale: + if self._cached_output_stream is None: + require_live_source_bindings((self,)) + return None + if self.is_stale: return None return self._cached_output_stream diff --git a/src/orcapod/core/tracker.py b/src/orcapod/core/tracker.py index 8fe5372d1..8ebceb775 100644 --- a/src/orcapod/core/tracker.py +++ b/src/orcapod/core/tracker.py @@ -100,9 +100,14 @@ def _record( """Preflight nested captures before dispatching the recording callbacks.""" trackers = self.get_active_trackers() if len(trackers) > 1: - invocation = make_invocation() - for tracker in trackers: - if isinstance(tracker, _PreparesInvocation): + preparers = [ + tracker + for tracker in trackers + if isinstance(tracker, _PreparesInvocation) + ] + if preparers: + invocation = make_invocation() + for tracker in preparers: _ = tracker.prepare_invocation(invocation) for tracker in trackers: record(tracker) diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 81bc32bf9..87ccfa54b 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -645,8 +645,8 @@ class InconsistentSourceError(ValueError): (ITL-1506). Two different schemas competing for one input slot also raise this error. - Build a source once and reuse that object, or give each source its - own ``source_id``. + Build a source once and reuse that object. Distinct ``source_id`` values + give sources distinct hashes only when the ID contributes to the hash. """ diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 4e0d91875..b4134b9c4 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -6,6 +6,7 @@ from abc import ABC, abstractmethod from collections.abc import Callable, Hashable, Iterable, Iterator from dataclasses import dataclass +from functools import partial from itertools import chain from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar @@ -322,7 +323,15 @@ def record_side_effect_pod_invocation( ) def _record_invocation(self, invocation: PodInvocation) -> None: - self.prepare_invocation(invocation)() + """Validate the invocation and record it immediately.""" + key, input_keys = self._validate_invocation(invocation) + self._remember_invocation(key, invocation, input_keys) + self._hash_graph.add_node(key) + for upstream, upstream_hash in zip( + invocation.input_streams, input_keys, strict=True + ): + self._hash_graph.add_edge(upstream_hash, key) + self._source_streams.setdefault(upstream_hash, upstream) def _validate_capture_sources(self, streams: Iterable[StreamProtocol]) -> None: """Check the streams of a new capture before recording it.""" @@ -330,6 +339,25 @@ def _validate_capture_sources(self, streams: Iterable[StreamProtocol]) -> None: def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: """Validate *invocation* and prepare to update the topology graph. + The callback validates again against the graph as it stands when called. + + Args: + invocation: The pod invocation to record. + + Returns: + A callback that validates and records the invocation. + + Raises: + ValueError: If the invocation cannot be recorded in the current graph. + """ + self._validate_invocation(invocation) + return partial(self._record_invocation, invocation) + + def _validate_invocation( + self, invocation: PodInvocation + ) -> tuple[str, tuple[str, ...]]: + """Check whether a capture can be recorded and resolve its graph keys. + Non-source nodes in ``_persistent_node_map`` are keyed by the corresponding ``PodInvocation.content_hash()`` string. For ``PipelineJob`` (where ``source_node_class`` is ``SourceJobNode``), @@ -350,7 +378,7 @@ def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: invocation: The pod invocation to record. Returns: - A callback that records the validated invocation. + The invocation hash and the upstream stream hashes. Raises: ValueError: If the invocation reads a source under another restriction @@ -375,14 +403,7 @@ def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: require_consistent_sources(uses) require_one_restriction(stream for _, stream in uses) - def record() -> None: - self._remember_invocation(key, invocation, input_keys) - self._hash_graph.add_node(key) - for upstream, upstream_hash in zip(inputs, input_keys, strict=True): - self._hash_graph.add_edge(upstream_hash, key) - self._source_streams.setdefault(upstream_hash, upstream) - - return record + return key, input_keys def _remember_invocation( self, key: str, invocation: PodInvocation, input_keys: tuple[str, ...] diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 89e720170..d64b113dc 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1386,9 +1386,6 @@ def _prepare_run( # Live inputs can change in place after a binding has been checked. require_live_source_bindings(self._persistent_node_map.values()) - # Until this run finishes, what the database holds for a node is not certain. - self._last_run_finished = False - # The job's database, then a separate result database (ITL-1408): each one # that commits table by table. committing = [ @@ -1455,6 +1452,9 @@ def _prepare_run( (f"node {node.label!r}", node) for node in self._persistent_node_map.values() ) + # Once source preflight passes, stored row counts may change during the run. + self._last_run_finished = False + hash_dag: OrcaDAG[str] = OrcaDAG() for u, v in self._graph_edges: hash_dag.add_edge(u, v) diff --git a/tests/test_core/nodes/test_source_node.py b/tests/test_core/nodes/test_source_node.py index 10a02e025..f59312046 100644 --- a/tests/test_core/nodes/test_source_node.py +++ b/tests/test_core/nodes/test_source_node.py @@ -259,6 +259,7 @@ def test_bound_source_property_updates_in_place(self, tag_schema, data_schema): def test_slot_binding_refuses_cycles( self, tag_schema: Schema, data_schema: Schema, length: int ) -> None: + """Refuse a cycle and keep the previous binding and rows.""" from orcapod.core.sources.dict_source import DictSource from orcapod.operators import SelectDataColumns @@ -289,6 +290,7 @@ def test_slot_binding_refuses_cycles( def test_slot_binding_accepts_slot_free_source_and_unbinding( self, tag_schema: Schema, data_schema: Schema, cached: bool ) -> None: + """Bind and unbind an independent source, with or without a cache.""" from orcapod.core.sources.dict_source import DictSource from orcapod.databases import InMemoryArrowDatabase diff --git a/tests/test_core/test_tracker.py b/tests/test_core/test_tracker.py index f0386c8a3..1f7c4024b 100644 --- a/tests/test_core/test_tracker.py +++ b/tests/test_core/test_tracker.py @@ -115,42 +115,62 @@ def deliver(x: int) -> None: assert first.nodes.keys() == second.nodes.keys() -@pytest.mark.parametrize("kind", ["operator", "function", "side_effect"]) -def test_capture_accepts_trackers_without_weak_reference_support(kind: str) -> None: - @dataclass(slots=True) - class InvocationLog: - events: list[tuple[str, str | None]] = field(default_factory=list) - active: bool = True +@dataclass(slots=True, eq=False) +class InvocationLog: + """Record tracker notifications in arrival order.""" + + events: list[tuple[str, str | None]] = field(default_factory=list) + active: bool = True + + def set_active(self, active: bool = True) -> None: + """Set whether this tracker accepts notifications.""" + self.active = active + + def is_active(self) -> bool: + """Return whether this tracker accepts notifications.""" + return self.active + + def record_operator_pod_invocation( + self, + pod: cp.OperatorPodProtocol, + upstreams: tuple[cp.StreamProtocol, ...] = (), + label: str | None = None, + ) -> None: + """Log an operator notification.""" + self.events.append(("operator", label)) + + def record_function_pod_invocation( + self, + pod: cp.FunctionPodProtocol, + input_stream: cp.StreamProtocol, + label: str | None = None, + ) -> None: + """Log a function notification.""" + self.events.append(("function", label)) + + def record_side_effect_pod_invocation( + self, + pod: cp.SideEffectPodProtocol, + input_stream: cp.StreamProtocol, + label: str | None = None, + ) -> None: + """Log a side-effect notification.""" + self.events.append(("side_effect", label)) + + +def test_source_pod_notification_reaches_both_passive_trackers() -> None: + """Forward an empty-upstream notification to both protocol-only trackers.""" + manager = BasicTrackerManager() + first, second = InvocationLog(), InvocationLog() + manager.register_tracker(first) + manager.register_tracker(second) + manager.record_operator_pod_invocation(SelectTagColumns(["id"]), label="source") + assert first.events == second.events == [("operator", "source")] - def set_active(self, active: bool = True) -> None: - self.active = active - def is_active(self) -> bool: - return self.active - - def record_operator_pod_invocation( - self, - pod: cp.OperatorPodProtocol, - upstreams: tuple[cp.StreamProtocol, ...] = (), - label: str | None = None, - ) -> None: - self.events.append(("operator", label)) - - def record_function_pod_invocation( - self, - pod: cp.FunctionPodProtocol, - input_stream: cp.StreamProtocol, - label: str | None = None, - ) -> None: - self.events.append(("function", label)) - - def record_side_effect_pod_invocation( - self, - pod: cp.SideEffectPodProtocol, - input_stream: cp.StreamProtocol, - label: str | None = None, - ) -> None: - self.events.append(("side_effect", label)) +@pytest.mark.parametrize("kind", ["operator", "function", "side_effect"]) +def test_capture_accepts_trackers_without_weak_reference_support(kind: str) -> None: + """Record each invocation even when the tracker cannot be weakly referenced.""" @function_pod(output_keys="value") def transform(x: int) -> int: diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index 97df9f528..a745e03c9 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -18,8 +18,9 @@ InconsistentSourceError, SourceSlotNameCollisionError, ) -from orcapod.operators import SemiJoin +from orcapod.operators import MapData, SemiJoin from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.pipeline.pod_invocation import OperatorInvocation from orcapod.pipeline.source_consistency import require_consistent_sources from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.sources import ( @@ -302,6 +303,56 @@ def origin(arrow_type: pa.DataType) -> ArrowTableSource: assert first.arrow_schemas[1].field("x").type == pa.int64() +def test_refused_source_run_preserves_saved_expected_rows(tmp_path: Path) -> None: + """Keep the prior row counts when the source check refuses a new run.""" + + def source(kind: pa.DataType) -> ArrowTableSource: + """Build a tagged source whose columns all use the given Arrow type.""" + return ArrowTableSource( + pa.table({name: pa.array([1, 2], type=kind) for name in ("t1", "t2", "x")}), + tag_columns=["t1", "t2"], + tag_only_columns=True, + infer_nullable=True, + source_id="origin", + ) + + narrow = source(pa.int32()) + wide = source(pa.int64()) + proxy = SourceProxy( + narrow.source_id, + narrow.content_hash().to_string(), + narrow.pipeline_hash().to_string(), + *narrow.output_schema(), + ) + left = DerivedSource(proxy, tags_as_data={"t1": "copy"}, source_id="shared") + right = DerivedSource(narrow, tags_as_data={"t2": "copy"}, source_id="shared") + assert left.arrow_schemas[1].field("x").type == pa.int64() + proxy.bind(narrow) + + with PipelineJob(database=InMemoryArrowDatabase()) as job: + _ = increment.pod( + DerivedSource(wide, tags_as_data={"t1": "copy"}, source_id="slot_a"), + label="left", + ) + _ = increment_again.pod( + DerivedSource(narrow, tags_as_data={"t2": "copy"}, source_id="slot_b"), + label="right", + ) + job.bind(sources={"slot_a": left, "slot_b": right}) + _ = job.run() + path = tmp_path / "job.json" + job.save(path) + expected = json.loads(path.read_text())["run"]["expected_rows"] + assert expected["left"] == expected["right"] == 2 + + proxy.unbind() + with pytest.raises(InconsistentSourceError, match="different schemas"): + _ = job.run() + proxy.bind(narrow) + job.save(path) + assert json.loads(path.read_text())["run"].get("expected_rows") == expected + + @pytest.mark.parametrize("label", [None, "repeated"]) def test_capture_distinguishes_repeated_step_labels(label: str | None) -> None: name = label or "increment" @@ -541,7 +592,10 @@ def test_load_checks_schema_of_reconstructed_sources(tmp_path: Path) -> None: def test_schema_conflicts_at_capture_and_bind() -> None: + """Refuse different Arrow schemas during capture and during binding.""" + def source(kind: pa.DataType, name: str) -> ArrowTableSource: + """Build the named source with the given physical Arrow type.""" return ArrowTableSource( pa.table({"x": pa.array([1], type=kind)}), infer_nullable=True, @@ -549,10 +603,7 @@ def source(kind: pa.DataType, name: str) -> ArrowTableSource: ) first, second = source(pa.int32(), "shared"), source(pa.int64(), "shared") - with pytest.raises(InconsistentSourceError, match="different schemas"): - with Pipeline("conflicts"): - increment.pod(first, label="fa") - increment.pod(second, label="fb") + assert "different schemas" in _capture(first, second, increment.pod) with PipelineJob() as job: increment.pod(source(pa.int32(), "left"), label="fa") @@ -563,6 +614,34 @@ def source(kind: pa.DataType, name: str) -> ArrowTableSource: assert part in str(error.value) +def test_deferred_capture_refuses_new_source_conflict() -> None: + """Recheck the graph when a previously prepared invocation records.""" + + pipeline = Pipeline("deferred capture") + first = _dict(1) + second = _dict(2) + initial = MapData({"x": "initial"}) + other = MapData({"x": "other"}) + record_first = pipeline.prepare_invocation( + OperatorInvocation(initial, (first,), "first") + ) + record_conflicting = pipeline.prepare_invocation( + OperatorInvocation(other, (second,), "conflicting") + ) + record_shared = pipeline.prepare_invocation( + OperatorInvocation(other, (first,), "reused") + ) + record_first() + before = pipeline.graph.copy() + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + record_conflicting() + assert set(pipeline.graph.nodes) == set(before.nodes) + assert set(pipeline.graph.edges) == set(before.edges) + record_shared() + pipeline.compile() + assert set(pipeline.nodes) == {"first", "reused", "shared"} + + @pytest.mark.parametrize("graph_type", [Pipeline, PipelineJob]) def test_one_object_is_allowed_in_several_steps( graph_type: type[Pipeline] | type[PipelineJob], diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index 1902b296c..bdafae460 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -5,6 +5,7 @@ import asyncio import json import re +from collections.abc import Iterable from pathlib import Path from typing import Any, cast @@ -44,6 +45,7 @@ def product(x: int, y: int) -> int: def _source( tmp_path: Path, kind: str, name: str, *, reverse: bool = False, change: bool = False ) -> DictSource | CSVSource: + """Build the named source with optional changes to values and column order.""" rows = [dict(row) for row in ROWS] if change: rows[-1]["y"] = 40 @@ -83,6 +85,7 @@ def _shifted_source(name: str, offset: int) -> DictSource: def _pair( tmp_path: Path, kind: str, reverse: bool ) -> tuple[DictSource | CSVSource, DictSource | CSVSource]: + """Return distinct sources with the same content hash and optional row changes.""" first = _source(tmp_path, kind, "shared") second = _source(tmp_path, kind, "shared", reverse=True, change=kind != "equal") assert first is not second @@ -91,6 +94,7 @@ def _pair( def _job(tmp_path: Path, slots: tuple[str, ...] = ("a", "b")) -> PipelineJob: + """Compile independent slots with different sources and function identities.""" with PipelineJob(database=InMemoryArrowDatabase()) as job: for slot, compute in zip(slots, (total, difference, product)): compute.pod(_source(tmp_path, "dict", slot), label=f"result_{slot}") @@ -98,6 +102,7 @@ def _job(tmp_path: Path, slots: tuple[str, ...] = ("a", "b")) -> PipelineJob: def _rebind(job: PipelineJob, sources: dict[str, StreamProtocol], setter: bool) -> None: + """Rebind by independent setter calls or one atomic batch.""" if setter: for name, source in sources.items(): job.nodes[name].bound_source = source @@ -592,6 +597,34 @@ def test_operator_run_cycle_diagnostic_names_the_step_and_remedy() -> None: _ = projection.run() +def test_warm_operator_read_validates_live_bindings_once( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Avoid a second validation walk when staleness already checks the operator.""" + from orcapod.pipeline import source_consistency + + with PipelineJob(database=InMemoryArrowDatabase()) as job: + _ = _source(tmp_path, "dict", "rows").map_data({"x": "value"}, label="mapped") + _ = job.run() + mapped = job.nodes["mapped"] + validate = source_consistency.require_live_source_bindings + calls = 0 + + def count_validation(streams: Iterable[StreamProtocol]) -> None: + """Count validations starting at the compiled operator.""" + nonlocal calls + roots = tuple(streams) + if len(roots) == 1 and roots[0] is mapped: + calls += 1 + validate(roots) + + monkeypatch.setattr( + source_consistency, "require_live_source_bindings", count_validation + ) + assert mapped.held_row_count() == len(ROWS) + assert calls == 1 + + @pytest.mark.parametrize("target", ["proxy", "slot"]) def test_last_modified_and_run_refuse_cycle_through_proxy_delegate(target: str) -> None: from orcapod.core.nodes.source_node import SourceJobNode @@ -916,6 +949,7 @@ def test_binding_back_the_captured_object_restores_capture_and_rows( @pytest.fixture(params=WRAPPER_PAIRS) def wrapper_pair(tmp_path: Path, request: pytest.FixtureRequest): + """Return two same-hash wrappers, one reusable source, and its input column.""" from orcapod.core.sources.cached_source import CachedSource from orcapod.core.sources.source_proxy import SourceProxy from orcapod.databases import DeltaTableDatabase @@ -999,6 +1033,7 @@ def test_rebound_job_refuses_prebuilt_streams_after_recompile( consumer = double if kind == "function" else increment def build(prebuilt: bool = False): + """Build the selected stream over the same original source.""" if kind == "join": return SemiJoin()(original, peer, label="joined") if kind == "function": @@ -1635,6 +1670,7 @@ def same_columns(x: int, y: int) -> tuple[int, int]: def _stored_result_job( kind: str, offset: int = 0, *, copy: bool = False ) -> PipelineJob: + """Materialize an operator or function result with the input column names.""" from orcapod.types import CacheMode from orcapod.sources import DerivedSource @@ -1784,6 +1820,7 @@ def _feedback_job(name: str, *, copy: bool = False) -> PipelineJob: def _independent_branches_job() -> PipelineJob: + """Compile two distinct branches and materialize only the left result.""" with PipelineJob("branches", database=InMemoryArrowDatabase()) as job: _ = same_columns.pod(_shifted_source("a", 0), label="left") _ = same_columns.pod(_shifted_source("b", 10), label="right")