Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions changelog.d/ITL-1125.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
### Breaking changes and migration

- Assigning `upstreams` on a live operator or function node compares the current
and replacement inputs when every input has a declared schema available without
reading rows, polling, or computing a new pipeline hash. The setter requires the
same input count and the same multiset of tag and data schemas, including declared
system-tag names and types. It compares types and nullability by column name,
ignores input order and data meta columns, and leaves read-only blueprints and
inputs with unavailable schemas to the existing setter behavior. If any schema
read raises an exception, the setter treats the declaration as unavailable.
A source's system-tag declaration is unavailable if reading it would compute
its schema hash. An Arrow-backed stream's Python declaration is available once
its schema has been read with system tags. Assignment leaves Arrow conversion
to ordinary schema reads. Self-references are diagnosed when a job node runs.
Function nodes still require exactly one input. Build a new pipeline to change
known input schemas.

### Known limitations

- An Arrow width change is detected only if it changes `output_schema()`, for
example through a changed system-tag name. The setter uses declared schema types.
13 changes: 5 additions & 8 deletions docs/dev/design_issues/ITL-1111-GW1.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,9 @@ a polling source's answer changes once it has polled. The debug logs take `%s` a
a stream or logging at debug level is bounded too.
Call-count tests over 20 stages: `tests/test_pipeline/test_graph_walk_cost.py`.

Left as they are: assigning `SourceJobNode.bound_source` directly, or setting a node's
`upstreams`, clears no memo of the nodes downstream of it, which keep their schema (their
pipeline hashes are equally stale today; a strict xfail test records the `upstreams` case, and a
`bound_source` of another column type is refused, ITL-1112). The risk is bounded:
nothing in `src` calls the `upstreams` setter (the loaders build a node with `__new__` and set
`_input_streams` before any schema is asked; only tests call it), and after ITL-1112 a bind
cannot change a slot's schema. Cascading the clear (a registry of dependents, or a setter that
refuses an upstream of another schema) is for the developer to decide. And each join keeps both inputs' system-tag columns, so their number doubles per
Assigning `SourceJobNode.bound_source` directly or setting a node's `upstreams` clears no memo
of downstream nodes. A bind preserves the slot's schema (ITL-1112), and the `upstreams`
setter refuses a change to the multiset of input schemas when every schema is available
without reading rows (ITL-1125). Each join keeps both inputs'
system-tag columns, so their number doubles per
stage (2 ** (stages + 1)), which is the width of the output, not a walk.
26 changes: 26 additions & 0 deletions docs/dev/design_issues/ITL-1125-USC1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
## `src/orcapod/core/nodes/`

### USC1 — Rewiring a node could leave downstream schemas and pipeline hashes stale
**Status:** resolved
**Severity:** high
**Issue:** ITL-1125

Assigning an upstream with a different schema could change the rewired node's output
schema while downstream nodes kept their previous schema predictions and pipeline hashes.
A stale pipeline hash still names the table for the old schema.

**Fix:** When every input's `output_schema()` is available without reading or hashing
rows, running a zero-row derivation, polling, or computing a pipeline hash, the live
setters compare the old and new input counts and multisets of declared schema pairs.
They compare tag fields, including system tags, and data fields by name, type and
nullability. Data meta fields and input order do not enter the comparison. The setters
read existing schema predictions and keep any new predictions local to the check.
A source whose system-tag schema hash has not been computed is unavailable to the
comparison. Assigning an upstream leaves that computation to an explicit schema read.
Arrow-backed streams provide a Python declaration after a schema read with system
tags. The comparison does not run Arrow conversion. A node's own output declaration
describes its prior wiring, so a self-reference is left to the run's cycle diagnostic.
A refusal preserves the wiring. Unavailable declarations and read-only
blueprints retain the previous setter behavior, including function nodes' one-input
requirement. An exception during a schema read makes the declaration unavailable
to the setter. Arrow widths that produce identical declarations are outside this check.
4 changes: 4 additions & 0 deletions src/orcapod/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import orcapod.contexts as contexts
from orcapod.config import DEFAULT_CONFIG, OrcapodConfig
from orcapod.core.schema_read import require_schema_work_allowed
from orcapod.types import ContentHash

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -269,6 +270,9 @@ def pipeline_hash(self, hasher=None) -> ContentHash:
hasher = self.data_context.semantic_hasher
cache_key = hasher.hasher_id
if cache_key not in self._pipeline_hash_cache:
# Predictions can need a pipeline hash for system-tag names. A cold
# hash may compute content hashes while building a symmetric input set.
require_schema_work_allowed()
from orcapod.protocols.hashing_protocols import PipelineElementProtocol

def pipeline_resolver(obj: Any) -> ContentHash:
Expand Down
12 changes: 11 additions & 1 deletion src/orcapod/core/nodes/function_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@

from orcapod import contexts
from orcapod.core.nodes.provenance_methods import ProvenanceMethods
from orcapod.core.nodes.upstream_schema import require_same_upstream_schemas
from orcapod.core.schema_read import require_schema_work_allowed
from orcapod.core.function_pod import (
fall_through_tags,
function_input,
Expand Down Expand Up @@ -561,7 +563,14 @@ def upstreams(self) -> tuple[StreamProtocol, ...]:

@upstreams.setter
def upstreams(self, value: tuple[StreamProtocol, ...]) -> None:
if len(value) != 1:
"""Replace the node's input, preserving its schema when both are known.

Raises:
ValueError: If there is not exactly one input or the known schemas differ.
"""
if self._function_pod is not None and self._input_stream is not None:
require_same_upstream_schemas(self, value, fixed_arity=True)
elif len(value) != 1:
raise ValueError("FunctionPod can only have one upstream")
self._input_stream = value[0]
self._forget_output_schema()
Expand Down Expand Up @@ -599,6 +608,7 @@ def output_schema(
restored to a Python type (an unregistered logical type).
"""
if self._function_pod is None:
require_schema_work_allowed()
from orcapod.pipeline.serialization import (
deserialize_output_schema,
SavedSchemaVersionError,
Expand Down
13 changes: 10 additions & 3 deletions src/orcapod/core/nodes/operator_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@

from orcapod import contexts
from orcapod.core.nodes.provenance_methods import ProvenanceMethods
from orcapod.core.nodes.upstream_schema import require_same_upstream_schemas
from orcapod.core.schema_read import require_schema_work_allowed
from orcapod.core.data_tags import (
mark_data_tags,
data_tag_names,
Expand Down Expand Up @@ -363,15 +365,19 @@ def cache_mode(self) -> CacheMode:

@upstreams.setter
def upstreams(self, value: tuple[StreamProtocol, ...]) -> None:
"""Replace the node's inputs.
"""Replace the node's inputs, preserving schemas known without reading rows.

Raises:
ValueError: If the node caches (``LOG`` or ``REPLAY``) and a source
feeding ``value`` is restricted (ITL-1218); nothing changes.
ValueError: If all input schemas are available for a live operator and
the input count or schema multiset changes, or if the node caches
(``LOG`` or ``REPLAY``) and a source feeding ``value`` is restricted
(ITL-1218).
"""
from orcapod.pipeline.restrictions import refuse_restricted_operator_cache

refuse_restricted_operator_cache(self, self.cache_mode, streams=value)
if self._operator is not None:
require_same_upstream_schemas(self, value)
self._input_streams = value
self._forget_output_schema()

Expand Down Expand Up @@ -474,6 +480,7 @@ def output_schema(
restored to a Python type (an unregistered logical type).
"""
if self._operator is None:
require_schema_work_allowed()
from orcapod.pipeline.serialization import (
deserialize_output_schema,
SavedSchemaVersionError,
Expand Down
3 changes: 3 additions & 0 deletions src/orcapod/core/nodes/source_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from orcapod.core.base import TraceableBase
from orcapod.core.datagrams import Data, Tag
from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied
from orcapod.core.schema_read import require_schema_work_allowed
from orcapod.core.sources.base import table_is_rows
from orcapod.core.streams.arrow_table_stream import ArrowTableStream
from orcapod.core.streams.base import (
Expand Down Expand Up @@ -681,6 +682,7 @@ def _resolve(self) -> bool:
texts = self._saved_arrow_texts
if texts is None:
return True
require_schema_work_allowed()
# Local import: orcapod.pipeline imports the node modules.
from orcapod.pipeline.serialization import (
arrow_schema_from_texts,
Expand Down Expand Up @@ -879,6 +881,7 @@ def _schema_hash_str(self) -> str:
Returns:
Hex string schema hash.
"""
require_schema_work_allowed()
if not self._resolve():
# The saved type text stands in until the class is registered (ITL-1138).
return self.data_context.semantic_hasher.hash_object(
Expand Down
85 changes: 85 additions & 0 deletions src/orcapod/core/nodes/upstream_schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"""Schema validation for node upstream setters."""

from orcapod.core.schema_read import declared_schema_only
from orcapod.core.streams.base import StreamBase, temporary_output_schema_memos
from orcapod.protocols.core_protocols import StreamProtocol
from orcapod.system_constants import constants
from orcapod.types import ColumnConfig, Schema

_SCHEMA_COLUMNS = ColumnConfig(system_tags=True)
_SchemaPair = tuple[Schema, Schema]


def _available_schema(
node: StreamBase, stream: StreamProtocol | None
) -> _SchemaPair | None:
"""Read the tag and data declarations, omitting data-only meta fields."""
# The node's current output describes its old wiring. It cannot declare its
# own prospective input schema. The run diagnoses cycles.
if stream is None or stream is node:
return None
with declared_schema_only(), temporary_output_schema_memos():
try:
tag, data = stream.output_schema(columns=_SCHEMA_COLUMNS)
except Exception:
# An unreadable declaration must fall back to the original setter behavior.
return None
meta = [
name
for name in data
if name.startswith(constants.META_PREFIX) and name not in tag
]
return tag, data.drop(*meta) if meta else data


def _describe(schemas: tuple[_SchemaPair | None, ...]) -> tuple[_SchemaPair | str, ...]:
"""Describe schemas for a setter error without consulting the input streams."""
return tuple(
schema if schema is not None else "<unavailable without work>"
for schema in schemas
)


def require_same_upstream_schemas(
node: StreamBase,
replacements: tuple[StreamProtocol, ...],
*,
fixed_arity: bool = False,
) -> None:
"""Require a wired node to keep its input count and multiset of known schemas.

Args:
node: The wired node.
replacements: The proposed upstreams.
fixed_arity: Whether the node already requires a fixed input count even
when some schemas are unavailable.

Raises:
ValueError: If all schemas are available and their counts or schema pairs
differ, or if the node has fixed arity and the count changes.
"""
current = tuple(_available_schema(node, stream) for stream in node.upstreams)
proposed = tuple(_available_schema(node, stream) for stream in replacements)
available = all(schema is not None for schema in (*current, *proposed))
if len(current) != len(proposed) and (available or fixed_arity):
raise ValueError(
f"Cannot rewire node {node.label!r} with a different upstream count: "
+ f"current schemas {_describe(current)!r}, "
+ f"replacement schemas {_describe(proposed)!r}"
)

if not available:
return
remaining = [schema for schema in proposed if schema is not None]
for old in current:
assert old is not None
for index, new in enumerate(remaining):
if old == new:
_ = remaining.pop(index)
break
else:
raise ValueError(
f"Cannot rewire node {node.label!r} with a different schema multiset "
+ "(tags including system-tag columns, and data): "
+ f"current schemas {current!r}, replacement schemas {proposed!r}"
)
2 changes: 2 additions & 0 deletions src/orcapod/core/operators/static_output_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
warn_provisional_operator,
)
from orcapod.utils.provisional import note_provisional_use, provisional_class_name
from orcapod.core.schema_read import require_schema_work_allowed
from orcapod.core.streams.arrow_table_stream import ArrowTableStream
from orcapod.core.streams.base import (
ZERO_ROW_INPUT_COLUMNS,
Expand Down Expand Up @@ -1580,6 +1581,7 @@ def __init__(
def built(self) -> StreamProtocol:
"""The stream, built from the rows on the first call (``main``'s row path)."""
if self._stream is None:
require_schema_work_allowed()
self._stream = StaticOutputOperatorPod._materialize_upstream(
self._rows, self._node
)
Expand Down
32 changes: 32 additions & 0 deletions src/orcapod/core/schema_read.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""Prevent new computation while inspecting declared output schemas."""

from collections.abc import Iterator
from contextlib import contextmanager
from contextvars import ContextVar

_declared_only = ContextVar("declared_schema_only", default=False)


class SchemaWorkRequired(Exception):
"""The requested schema needs work beyond reading its declaration."""


@contextmanager
def declared_schema_only() -> Iterator[None]:
"""Read declared schemas and cached dependencies without producing new results."""
token = _declared_only.set(True)
try:
yield
finally:
_declared_only.reset(token)


def require_schema_work_allowed() -> None:
"""Raise when a declared-schema read tries to perform additional work."""
if is_declared_schema_only():
raise SchemaWorkRequired


def is_declared_schema_only() -> bool:
"""Whether the caller can use existing Python schemas only."""
return _declared_only.get()
2 changes: 2 additions & 0 deletions src/orcapod/core/sources/derived_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
)
from typing_extensions import override

from orcapod.core.schema_read import require_schema_work_allowed
from orcapod.core.sources.base import RootSource
from orcapod.core.sources.provisional import warn_provisional_source
from orcapod.core.sources.reload import same_rows
Expand Down Expand Up @@ -469,6 +470,7 @@ def _columns_stream(self, tags_as_data: Mapping[str, str]) -> ArrowTableStream:
if self._cached_stream is not None:
return self._cached_stream
if self._zero_row_stream is None:
require_schema_work_allowed()
self._zero_row_stream = self._derive_from(
self._empty_origin_table(), tags_as_data
)
Expand Down
3 changes: 3 additions & 0 deletions src/orcapod/core/sources/polling_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import pyarrow as pa
from typing_extensions import override

from orcapod.core.schema_read import require_schema_work_allowed
from orcapod.core.sources.base import RootSource
from orcapod.core.sources.source_ids import hash_source_name
from orcapod.logical_types.canonical_form import declaration_form_schema
Expand Down Expand Up @@ -399,6 +400,7 @@ def _declared_schema_hash(self) -> str | None:
Hex schema-hash string, or ``None`` if ``impl.schema()`` returned
``None`` (schema not yet known).
"""
require_schema_work_allowed()
declared = self._declared_arrow_pair()
if declared is None:
return None
Expand Down Expand Up @@ -765,6 +767,7 @@ def _sync_poll_and_commit(self) -> bool:

Safe to call concurrently with ``async_iter_data``.
"""
require_schema_work_allowed()
with self._state_lock:
cursor_snapshot = self._cursor

Expand Down
Loading
Loading