diff --git a/.zed/rules b/.zed/rules index cfef12e6a..67c9e3496 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1501,6 +1501,10 @@ data. The rules: are not concerned. The refusal is for now: how an operator node logs and replays is to be redesigned to load its cache and then apply the restriction (TODO(ITL-1219)). - Empty data → ArrowTableSource raises ValueError("Table is empty"). +- An observer only watches (developer, November 22, 2026, ITL-1369): an observer or callback + that changes the job, its nodes or its bound sources during a run is unsupported; what the + run then does is undefined and is not part of the equality with main. Preventing it (a + guard, then a read-only view) is ITL-1369; never chase a case that needs such a change. - A side-effect job node delivers only when it runs (developer, November 13, 2026, ITL-1091): job.run(), node.run() (state-driven, ITL-1095: a node holding a current run delivers nothing, so clear_cache() it first to deliver again; otherwise the job run's work for that diff --git a/CLAUDE.md b/CLAUDE.md index 2a0616434..84a08370b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1548,6 +1548,10 @@ data. The rules: are not concerned. The refusal is for now: how an operator node logs and replays is to be redesigned to load its cache and then apply the restriction (`TODO(ITL-1219)`). - Empty data → `ArrowTableSource` raises `ValueError("Table is empty")`. +- An observer only watches (developer, November 22, 2026, ITL-1369): an observer or callback + that changes the job, its nodes or its bound sources during a run is unsupported; what the + run then does is undefined and is not part of the equality with `main`. Preventing it (a + guard, then a read-only view) is ITL-1369; never chase a case that needs such a change. - A side-effect job node delivers only when it runs (developer, November 13, 2026, ITL-1091): `job.run()`, `node.run()` (state-driven, ITL-1095: a node holding a current run delivers nothing, so `clear_cache()` it first to deliver again; otherwise the job run's work for that diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md new file mode 100644 index 000000000..8121d7e70 --- /dev/null +++ b/changelog.d/ITL-1360.md @@ -0,0 +1,41 @@ +### Changed + +- **A job node's `execute` returns its output stream** — `execute` of a source, operator, + function and side-effect job node (and of the node protocols) returned the node's rows as + a list of (tag, data) pairs, and the sync orchestrator rebuilt a table from them for each + successor. It now returns the node's output stream, which the sync orchestrator hands to + every successor. Where that table is provably the rows' own, the node gives it + without making the rows: a node bound to an instance of exactly a library source kind + whose table is its rows (`TABLE_IS_ROWS`, never inherited by a subclass), and an + operator node whose result yields its rows from exactly an `ArrowTableStream`, in that + stream's row order (REPLAY: its stored table), each only when the rows report the + node's data context and every system tag is non-null text, as rows give it. Every other + output (a narrower bind, a subclass or another kind of bound stream or result, rows of + another data context, system tags of another type, a table the whole-table build + cannot use, a result with no row, a held node, a function or side-effect node) is the + node's rows, unchanged, whose table is built where a successor reads it, as before; a + retained one keeps only its rows once every successor has read it. + `OrchestratorResult.node_outputs` holds each node's output stream: its rows + (`iter_data()`) are the rows the node returned, and its table is built when the table + is first read (`as_table()`, a successor's edge); on the sync path a held node gives + the stream of its held rows, and the async path still sends a held node's rows as the + run's plan took them (`held_rows`). Every successor's input is unchanged: columns, + types, row order, system tags, source info, pipeline and content hashes, and an error + surfaces where and when it did. No hash, stored table or output changes. An operator + node's table is built once, for what it keeps and for every successor, instead of once + to keep and once per successor. The first two stages of the table transport between + job nodes (`docs/dev/specs/itl-1347-job-table-transport.md`). + (ITL-1347, ITL-1360) + +### Added + +- **`arrow_schema()` and `arrow_types_declared` on every stream** — `StreamProtocol`, + every stream and every source node state the Arrow schema of the columns a job node + passes on (user tags, system tags, data and source info), without reading, computing or + polling a row. System-tag and source-info fields are stated nullable and a source-info + field's type as the declared token type: a complete table decides both from its values, + so a consumer must not rely on them. A `null` column keeps the `null` type of a table + with no rows. `arrow_types_declared` is false where the rows decide the types: a stream + that cannot type itself without rows (an unbound slot, a `PollingSource` not yet + polled), a narrower bind, and an output held as its rows. Such a description gives the + declared names and types, in no guaranteed order. (ITL-1360) diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 625400b73..e234ac81b 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -62,7 +62,9 @@ Among `job.run()`'s optional arguments, the tutorial's [Part 9](../tutorial/09-when-things-go-wrong.md) demonstrates `orchestrator=` (for example `SyncPipelineOrchestrator(error_policy="fail_fast")` to stop at the first failing row; the default policy skips failed rows and continues) and `observer=` (`StatusObserver`, -`LoggingObserver`) to record what happened during the run. `load_only=True` fills the nodes +`LoggingObserver`) to record what happened during the run. An observer only watches: one +that changes the job, its nodes or its bound sources during a run is unsupported, and what +the run then does is undefined (ITL-1369). `load_only=True` fills the nodes from what is already stored and computes nothing; see [Loading without computing](function-pods.md#loading-without-computing-runload_onlytrue). diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index ce0097d17..21769a847 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -194,9 +194,13 @@ A run checks its sources first (ITL-1102), which polls them. **ITL-1307 later.** When `Schema` carries its Arrow schema, `arrow_schema()` reads the two schemas plus the system-tag and source-info fields, in one place (`StreamBase`). -Two exceptions keep today's bytes: -- **Source-info nullability** is decided by a complete Arrow table's values (F step 5). - `arrow_schema()` states those fields nullable (question 5). +Three exceptions keep today's bytes: +- **Source-info and system-tag nullability** is decided by a complete Arrow table's values + (F step 5). `arrow_schema()` states those fields nullable (question 5). +- **Source-info types** are decided by a complete Arrow table's tokens, as each row types + its tokens from their values (`_type_source_info_by_values`): a list of `None` or of + empty lists shows fewer list levels than its column declares. `arrow_schema()` states the + declared token type; consumers must not rely on it (Codex on PR #485). - **`null` columns.** Rows carry `large_string`, and a zero-row Arrow table carries `null`, as today (ITL-1319). @@ -511,7 +515,33 @@ rows; they are kept as `main` has them, and documented below. **No row changes a sync-path result.** On the sync path the branch equals `main` byte for byte. Stages 1–4 hold this by construction and by L0–L5, and a lemma that fails stops its -stage. +stage. Where building a node's output from its whole table is not provably `main`'s result +(a narrower bind, a whole-table build that is unavailable, an odd stored table, a held +node, a node whose output is still its rows), the node hands on its rows and the table is +built from them by `main`'s row path where a successor reads them (`RowsOnRead`, +`at_edge`): `main`'s order, error and moment by construction (Codex on PR #485, round 3). +"Provably" is one precondition, positive and exact, never an inspection of overrides +(Codex on PR #485, final check and round 7): **the stream that holds the rows is exactly a +class whose whole-table read is its rows, nothing on the instance shadows one of that +class's methods or properties** (`reads_as_its_class`), **its rows report the node's data +context, and every system-tag field of its table is what the rows give, non-null +`large_string`** (`system_tags_as_rows_give`). It is applied in two places: + +- a bound source: its class is a library source kind that itself declares + `TABLE_IS_ROWS` (`table_is_rows`); +- an operator's result: the stream it yields its rows from, followed through every + `DynamicPodStream` that is itself proven (`produced_stream`; a subclass or a wrapper + with a replaced member stops the chain), is `ArrowTableStream` in the node's data + context (its rows report that context, as `main`'s rows did), and its own `keys()` (the + keys `iter_data` reads its rows with, tags in its tag-column order) give the order. + +Any subclass, replaced reader, other stream kind, other data context or other system-tag +type takes `main`'s row path. A retained output held as its rows (`RowsOnRead`) keeps +only its rows once every successor has read it (`release_built`), as `main` retained +only the rows. +An observer or callback that changes the job, its nodes or its bound sources during a run +is unsupported; what the run then does is undefined and is not part of the equality with +`main` (ITL-1369; developer, November 22, 2026). | # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | |---|---|---|---|---|---| diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 6b8ee6a3a..ebd445e5c 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -282,6 +282,27 @@ def _with_datagram_id(data: Data, datagram_id: uuid.UUID) -> Data: ) +def rows_as_output_stream( + rows: Sequence[tuple[TagProtocol, DataProtocol]], node: StreamProtocol +) -> StreamProtocol: + """Return ``rows`` as ``node``'s output stream: the rows, built when read. + + For the job nodes whose output is still their rows (function and side-effect + nodes, until ITL-1347 stages 3 and 4): ``RowsOnRead``, built by ``main``'s row path + where a successor reads it. One place imports the operator module for them. + + Args: + rows: The node's output rows, in order. + node: The node. + + Returns: + The node's output stream. + """ + from orcapod.core.operators.static_output_pod import rows_on_read + + return rows_on_read(rows, node) + + def _executor_supports_concurrent( data_function: DataFunctionProtocol, ) -> bool: @@ -2456,6 +2477,19 @@ def as_node(self) -> FunctionNode: # Data processing # ------------------------------------------------------------------ + def _output_stream( + self, rows: list[tuple[TagProtocol, DataProtocol]] + ) -> StreamProtocol: + """The output stream of a run whose output rows are ``rows``. + + The rows, their table built when read by ``main``'s row path + (``RowsOnRead``): the sync orchestrator builds it where a successor reads it, + as ``main`` rebuilt the rows there, and a leaf's is never built (ITL-1347). + """ + from orcapod.core.operators.static_output_pod import rows_on_read + + return rows_on_read(rows, self) + def execute_data( self, tag: TagProtocol, @@ -2485,7 +2519,7 @@ def execute( error_policy: Literal["continue", "fail_fast"] = "continue", run_id: str | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: + ) -> StreamProtocol: """Execute all data from a stream: compute, persist, and cache. For each data: fire ``on_data_start``, check the in-memory cache @@ -2511,8 +2545,10 @@ def execute( this way. Returns: - Materialized list of (tag, output_data) pairs, excluding - ``None`` outputs and failed data. + The node's output stream: its output rows (no row for a ``None`` output or + a failed row) as the table ``_rows_to_table`` builds from them, with this + node's identity (``StaticOutputOperatorPod._materialize_upstream``). The sync + orchestrator hands it to every successor (ITL-1347, stage 2). Raises: RuntimeError: If the node was loaded by ``PipelineJob.load`` and so @@ -2524,7 +2560,7 @@ def execute( from orcapod.pipeline.observer import NoOpObserver if load_only: - return self._execute_load_only(input_stream, observer) + return self._output_stream(self._execute_load_only(input_stream, observer)) if self._function_pod is None: raise self._cannot_compute_error() @@ -2653,7 +2689,7 @@ def execute( self.clear_cache() raise - return output + return self._output_stream(output) def _empty_data_cache_hit( self, tag: TagProtocol, data: EmptyData, base_entry_id: bytes diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index d66d479c6..9e28abc91 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -38,13 +38,20 @@ ) from orcapod.channels import Channel, ChannelClosed, ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.operators.static_output_pod import ( + RowBuiltFormUnavailable, + StaticOutputOperatorPod, + produced_stream, + rows_on_read, +) from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, StreamBase, check_head_size, + reads_as_its_class, short_stream_repr, + system_tags_as_rows_give, ) from orcapod.core.streams.view import ( JOB_NODE_NOT_RUN_NOTE, @@ -1645,7 +1652,7 @@ def execute( *input_streams: StreamProtocol, observer: ExecutionObserverProtocol | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: + ) -> StreamProtocol: """Execute input streams: compute, persist, and cache. Args: @@ -1657,7 +1664,10 @@ def execute( as in any run. Returns: - Materialized list of (tag, data) pairs. + The node's output stream: its rows as the table ``_rows_to_table`` builds + from them (``StaticOutputOperatorPod._output_stream``), with this node's + identity, built from the operator's result table without making rows + (ITL-1347, stage 2). The sync orchestrator hands it to every successor. Raises: ValueError: If the node caches (``LOG`` or ``REPLAY``) and a source @@ -1685,20 +1695,84 @@ def execute( # Check REPLAY cache first cached_output = self.get_cached_output() if cached_output is not None: - output = list(cached_output.iter_data()) + try: + output = StaticOutputOperatorPod._output_stream( + cached_output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), + cached_output.keys(), + self, + ) + except RowBuiltFormUnavailable: + # A stored table F cannot build from: its rows, built when read, + # as main handed them on (ITL-1347). + output = rows_on_read(cached_output.iter_data(), self) ctx_obs.on_node_end(node_label, node_hash) return output # Compute result_stream = self._operator.process(*input_streams) - - # Materialize - output = list(result_stream.iter_data()) - - # Cache, in row order with or without rows (ITL-1131, ITL-1133) - self._cached_output_stream = StaticOutputOperatorPod._kept_output( - result_stream, output - ) + produced = produced_stream(result_stream) + + output: StreamProtocol + # The result's table, as the table built from its rows would be, without + # making the rows (ITL-1347, stage 2), when it provably is its rows: the + # stream holding them is exactly an ``ArrowTableStream`` in the node's + # data context, whose system tags are what the rows give. + result_table: pa.Table | None = None + if ( + reads_as_its_class(produced, ArrowTableStream) + and produced.data_context_key == self.data_context_key + ): + # From the captured stream: reading the wrapper again could run the + # operator again (an upstream with no modified time), so the table, + # the keys and the gate describe one computation. + result_table = produced.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + if not system_tags_as_rows_give(result_table.schema): + result_table = None + if result_table is None: + # Otherwise (a custom stream kind, a replaced reader, rows of another + # data context, system tags the rows type otherwise): main's own row + # path, its rows read once and handed on unchanged, its table built + # where a successor reads it (ITL-1347). + # The rows of the computation already made (``produced``), read once. + rows = list(produced.iter_data()) + self._cached_output_stream = StaticOutputOperatorPod._kept_output( + result_stream, rows + ) + output = rows_on_read(rows, self) + else: + # An exact ``ArrowTableStream``'s ``keys()`` are the keys its rows are + # read with (``iter_data``), so they are the order of the result's + # rows, to any depth of composition, never the prediction. + keys = produced.keys() + tag_keys = keys[0] + data_tags = data_tag_names(*keys) + + # Cache, in row order with or without rows (ITL-1131, ITL-1133). + if result_table.num_rows: + try: + kept_table = StaticOutputOperatorPod._row_built_form( + result_table, keys + ) + except RowBuiltFormUnavailable as error: + StaticOutputOperatorPod._raise_as_rows_do( + produced.iter_data(), error + ) + self._cached_output_stream = ArrowTableStream( + kept_table, tag_columns=tag_keys, data_tags=data_tags + ) + # The output stream, built once the node holds its run (as the + # sync orchestrator built a successor's input after ``execute`` + # returned). + output = StaticOutputOperatorPod._as_upstream_stream( + kept_table, tag_keys, data_tags, self + ) + else: + self._cached_output_stream = ( + StaticOutputOperatorPod._zero_rows_in_row_order(result_stream) + ) + # Its zero-row form is derived where a successor reads it, as on + # main: the operator is not called again here (``RowsOnRead``). + output = rows_on_read([], self) self._update_modified_time() diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 9bb629109..76736f987 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -26,12 +26,17 @@ 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.sources.base import table_is_rows from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, + keys_of_rows, + system_tags_as_rows_give, row_built_columns, + stream_arrow_schema, schema_requires_io, typed_arrow_schemas, + typed_zero_row_input, typed_zero_row_table, ) from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel @@ -422,14 +427,11 @@ def _require_stream_arrow_types(stream: Any, slot: str) -> None: class _ExecuteOutputFeed: """The record batches of a source node's own ``execute()`` output. - Built at the first read from the rows ``execute()`` gives, rebuilt as a job does - (``StaticOutputOperatorPod._materialize_upstream``): slow, and correct by - definition. One binding is read, at that moment. A batch is dropped once - delivered. + Built at the first read from the output stream ``execute()`` gives (ITL-1347, + stage 2: the table a job hands on, already in the row-built form). One binding is + read, at that moment. A batch is dropped once delivered. """ - # TODO(ITL-1360): the channel of stage 2's ``execute()`` output stream. - def __init__(self, node: SourceNodeBase) -> None: """Make the feed; nothing is read until the first ``next``. @@ -442,12 +444,7 @@ def __init__(self, node: SourceNodeBase) -> None: async def next(self) -> pa.RecordBatch | None: """Return the next record batch of the node's output, or ``None`` at the end.""" if self._batches is None: - from orcapod.core.operators.static_output_pod import ( - StaticOutputOperatorPod, - ) - - rows = self._node.execute() - output = StaticOutputOperatorPod._materialize_upstream(rows, self._node) # pyright: ignore[reportPrivateUsage] # the job's rebuild of a node's rows + output = self._node.execute() table = row_built_columns( output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), output.keys() ) @@ -1255,27 +1252,78 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Yield ``(tag, data)`` pairs, or raise if data is unavailable.""" ... + def _rows_table( + self, + ) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]] | None: + """The table of this node's rows (``iter_data``) and the rows' keys, or ``None``. + + ``None`` here: a node that carries no data of its own hands on its rows + (``RowsOnRead``), which raise what reading it raises. A bound job node gives + its bound source's table when F of it is provably the rows' own table. + """ + return None + + def arrow_schema(self) -> pa.Schema: + """The Arrow schema of the columns this stream passes between job nodes. + + See ``stream_arrow_schema`` (ITL-1347): never reads, computes or polls a row. + The columns are in the order of the node's rows (``_row_keys``). + """ + return stream_arrow_schema(self, self._row_keys()) + + def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The tag and data keys of this node's rows: its own keys.""" + return self.keys() + + @property + def arrow_types_declared(self) -> bool: + """Whether ``arrow_schema()`` holds the rows' own Arrow types (ITL-1089, ITL-1347).""" + return typed_zero_row_table(self) is not None + def execute( self, *, observer: ExecutionObserverProtocol | None = None, - ) -> list[tuple[TagProtocol, DataProtocol]]: - """Execute this source node: materialize and return data. + ) -> StreamProtocol: + """Execute this source node: read its source once and return its output stream. + + The source's table, as the table built from its rows would be + (``StaticOutputOperatorPod._output_stream``), with this node's identity, built + without making rows (ITL-1347, stage 2). The sync orchestrator hands it to every + successor. Args: observer: Optional execution observer. Returns: - List of (tag, data) tuples. + The node's output stream. Raises: UnboundSourceError: When no concrete data is available. """ + from orcapod.core.operators.static_output_pod import ( + RowBuiltFormUnavailable, + StaticOutputOperatorPod, + rows_on_read, + ) + node_label = self.label node_hash = self.content_hash().to_string() if observer is not None: observer.on_node_start(node_label, node_hash) - result = list(self.iter_data()) + # The table and keys of this node's rows, when F of the table is provably the + # rows' own table; otherwise (a narrower bind) the rows, built when read. + rows_table = self._rows_table() + result: StreamProtocol + if rows_table is None: + result = rows_on_read(self.iter_data(), self) + else: + table, keys = rows_table + try: + result = StaticOutputOperatorPod._output_stream(table, keys, self) + except RowBuiltFormUnavailable: + # The rows decide (read once, here), built when read, as on main. + result = rows_on_read(self.iter_data(), self) if observer is not None: observer.on_node_end(node_label, node_hash) return result @@ -1737,6 +1785,75 @@ def identity_structure(self) -> Any: return self._bound_source.identity_structure() return super().identity_structure() + def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The tag and data keys of this node's rows, known without reading a row. + + The bound source's rows have the keys of its table (``keys_of_rows``, over its + typed zero-row table, which reads no row). A narrower bind (``_DeclaredForm``) + 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: + return self.keys() + table = typed_zero_row_input(self._bound_source) + if table is None: + return self.keys() + return keys_of_rows(table, self._bound_source.keys()) + + def arrow_schema(self) -> pa.Schema: + """The Arrow schema of the columns this stream passes between job nodes. + + See ``stream_arrow_schema``. A narrower bind hands on its rows as ``main`` gives + them (``RowsOnRead``), so its description is the declared Python schema's + (``arrow_types_declared`` is false): no second placement rule. + """ + if self._declared_form is not None: + return stream_arrow_schema(self, self.keys(), from_table=False) + return stream_arrow_schema(self, self._row_keys()) + + @property + def arrow_types_declared(self) -> bool: + """False for a narrower bind (see ``arrow_schema``), else as every source node.""" + if self._declared_form is not None: + return False + return super().arrow_types_declared + + def _rows_table( + self, + ) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]] | None: + """The bound source's table and the keys of its rows (``keys_of_rows``). + + ``None`` for a narrower bind (its rows are given as the declared schema one by + one, ``_declared_rows``) and for a bound stream that is not a library source + kind whose table is its rows (``TABLE_IS_ROWS``): the node then hands on those + rows (``RowsOnRead``). + + Raises: + UnboundSourceError: When no concrete source is attached. + """ + if self._bound_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 not None: + return None + if ( + not table_is_rows(self._bound_source) + or self._bound_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) + if not system_tags_as_rows_give(table.schema): + # 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()) + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Delegate to concrete source, or raise if unbound. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f930515f4..fbc698435 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -3,9 +3,15 @@ import asyncio import logging from abc import abstractmethod -from collections.abc import Collection, Iterator, Sequence +from collections.abc import ( + AsyncIterator, + Collection, + Iterable, + Iterator, + Sequence, +) from datetime import datetime, timezone -from typing import TYPE_CHECKING, Any, ClassVar, cast +from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, cast import pyarrow as pa @@ -37,6 +43,7 @@ ZERO_ROW_INPUT_COLUMNS, StreamBase, check_head_size, + reads_as_its_class, short_stream_repr, typed_zero_row_input, typed_zero_row_table, @@ -66,6 +73,23 @@ from orcapod.protocols.hashing_protocols import SemanticHasherProtocol +class RowBuiltFormUnavailable(ValueError): + """F cannot be built from the whole table (``_row_built_form``). + + The one signal that a node's output must come from its rows instead: the caller + builds the rows (``StaticOutputOperatorPod._rows_to_table``, through + ``_raise_as_rows_do``), which raises the error a table built from rows raises, so + the run fails as it does when rows are handed on, with the same observer events. + """ + + +class SourceInfoTypesDisagree(RowBuiltFormUnavailable): + """Two rows give one source-info column different types (``_row_built_form``). + + A table built from such rows cannot be concatenated. + """ + + class StaticOutputOperatorPod(TraceableBase): """Abstract base class for pods whose core logic yields a static output stream. @@ -493,27 +517,81 @@ def _flag_by_values(table: pa.Table) -> pa.Table: # Same arrays, new field flags: no cast, so no value or type can change. return pa.Table.from_arrays(table.columns, schema=pa.schema(fields)) + @staticmethod + def _type_source_info_by_values(table: pa.Table) -> pa.Table: + """Type each source-info column from its tokens, as the rows of a table built from rows do. + + A step of F (``_row_built_form``) on the complete table, beside + ``_flag_by_values``. A row's ``Data`` types each source-info token from its + value (``arrow_utils.source_info_arrow_type``, the one rule): a string or + ``None`` as ``large_string``, a list as ``large_list`` of its first informative + element's type, so a list of ``None`` or of empty lists shows fewer levels than + its column may declare. The rows' tables are then concatenated, which needs + every row to give a column one type. This step gives each column that type, + built from the same values. A ``large_string`` column is every row's type + already and is left as it is. + + Args: + table: A table of user tags, system tags, data and source info, after the + per-slice steps (``streams.base.row_built_columns``). + + Returns: + The table with each source-info column of the type its tokens give. + + Raises: + SourceInfoTypesDisagree: If two rows give one source-info column different + types, where the rows' tables cannot be concatenated. The caller builds + the rows (``_rows_to_table``), which raises the error a table built from + rows raises. + """ + from orcapod.system_constants import constants + from orcapod.utils import arrow_utils + + columns = list(table.columns) + fields = list(table.schema) + changed = False + for index, field in enumerate(fields): + if not field.name.startswith(constants.SOURCE_PREFIX): + continue + if pa.types.is_large_string(field.type): + continue + values = table.column(index).to_pylist() + kinds = {arrow_utils.source_info_arrow_type(value) for value in values} + if len(kinds) != 1: + raise SourceInfoTypesDisagree(field.name) + (kind,) = kinds + if kind == field.type: + continue + columns[index] = pa.chunked_array([pa.array(values, type=kind)]) + fields[index] = pa.field(field.name, kind, nullable=field.nullable) + changed = True + if not changed: + return table + return pa.Table.from_arrays( + columns, + schema=pa.schema( + fields, + cast("dict[bytes | str, bytes | str] | None", table.schema.metadata), + ), + ) + @staticmethod def _row_built_form( table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] ) -> pa.Table: """Return ``table`` as ``_rows_to_table`` builds it from the table's own rows. - F in the ITL-1347 spec: the same table, without making the rows. The columns, - their order and their types are decided row by row - (``streams.base.row_built_columns``), the system-tag and source-info field flags - by their values over the whole table (``_flag_by_values``). The equality with - ``_rows_to_table`` is tested over every operator, source kind and column role - (ITL-1347, L0-L2). - - Its domain: F equals ``_rows_to_table`` for every stream whose source-info tokens - are strings or non-empty lists of tokens, which is every stream a source or an - operator makes (a token list has one element per member of a batch, group or - merge). The one exception is a hand-built raw ``ArrowTableStream`` whose - source-info column is a list type holding only empty lists: a row types its - tokens from their values, so ``_rows_to_table`` loses the list levels the - empty lists do not show, while F keeps the column's type. Such a stream reaches - a job only when bound to a slot with a copied source-id and record-id pair. + F in the ITL-1347 spec: the same table, without making the rows. Two steps: + + - per slice (``streams.base.row_built_columns``), what each row decides on its + own: the columns, their order, their large types, and the provenance fields' + form (no system-tag field metadata, source-info lists of nullable items); + - on the complete table, what depends on the values of every row: each + source-info column's type, from its tokens (``_type_source_info_by_values``), + then the system-tag and source-info field flags (``_flag_by_values``). + + The equality with ``_rows_to_table`` is tested over every operator, source kind, + column role and raw-stream provenance shape (ITL-1347, L0-L2). Args: table: A table of user tags, system tags, data and source info, with rows. @@ -522,8 +600,47 @@ def _row_built_form( Returns: The table ``_rows_to_table`` would build from its rows. + + Raises: + RowBuiltFormUnavailable: If the whole table cannot be built: the rows' + tokens give a source-info column two types + (``SourceInfoTypesDisagree``), or an Arrow conversion fails. The node + then builds its rows (``_raise_as_rows_do``). """ - return StaticOutputOperatorPod._flag_by_values(row_built_columns(table, keys)) + try: + return StaticOutputOperatorPod._flag_by_values( + StaticOutputOperatorPod._type_source_info_by_values( + row_built_columns(table, keys) + ) + ) + except RowBuiltFormUnavailable: + raise + except pa.ArrowException as error: + # Values the whole table cannot be built from (a token the rows' own + # conversion refuses too): the rows decide, as on ``main``. + raise RowBuiltFormUnavailable(str(error)) from error + + @staticmethod + def _raise_as_rows_do( + rows: Iterable[tuple[TagProtocol, DataProtocol]], + error: RowBuiltFormUnavailable, + ) -> NoReturn: + """Build ``rows`` into a table to raise the error a table built from them raises. + + Called when ``_row_built_form`` finds rows whose source-info tokens cannot make + one table (``RowBuiltFormUnavailable``): the rows' own concatenation + (``_rows_to_table``) raises exactly what a run that hands rows on raises. + + Args: + rows: The rows of the table F was given, in order. + error: The disagreement F found, raised if the rows do concatenate. + + Raises: + pyarrow.ArrowInvalid: As ``_rows_to_table`` raises it. + RowBuiltFormUnavailable: ``error``, if the rows build after all. + """ + StaticOutputOperatorPod._rows_to_table(list(rows)) + raise error @staticmethod def _output_stream( @@ -547,19 +664,16 @@ def _output_stream( The output stream, with ``node``'s identity. """ if table.num_rows == 0: - stream = StaticOutputOperatorPod._materialize_upstream([], node) - else: - tag_keys, data_keys = keys - stream = StaticOutputOperatorPod._as_upstream_stream( - StaticOutputOperatorPod._row_built_form(table, keys), - tag_keys, - data_tag_names(tag_keys, data_keys), - node, - ) - # The one place a stream is marked as a complete, immutable output in the - # row-built form (ITL-1347): ``InputChannel.to_stream`` may give it as it is. - setattr(stream, ROW_BUILT_OUTPUT, True) - return stream + # No row: the zero-row input is derived where a successor reads it, as on + # main (``RowsOnRead``): nothing is prepared before then. + return rows_on_read([], node) + tag_keys, data_keys = keys + return StaticOutputOperatorPod._as_upstream_stream( + StaticOutputOperatorPod._row_built_form(table, keys), + tag_keys, + data_tag_names(tag_keys, data_keys), + node, + ) @staticmethod def _flag_source_info_nullability(table: pa.Table) -> pa.Table: @@ -674,7 +788,23 @@ def _materialize_to_stream( Raises: ValueError: If ``rows`` is empty. """ - table, tag_keys, data_tags = StaticOutputOperatorPod._rows_to_table(rows) + return StaticOutputOperatorPod._stream_over_row_table( + StaticOutputOperatorPod._rows_to_table(rows) + ) + + @staticmethod + def _stream_over_row_table( + row_table: tuple[pa.Table, tuple[str, ...], tuple[str, ...]], + ) -> StreamProtocol: + """The stream ``_materialize_to_stream`` builds, over ``_rows_to_table``'s result. + + Args: + row_table: The table, user tag keys and data-tags ``_rows_to_table`` returns. + + Returns: + A stream over the table's rows, in order. + """ + table, tag_keys, data_tags = row_table # No ``source_info`` argument: the table's own ``_source_*`` columns # pass through, one value per row. return ArrowTableStream(table, tag_columns=tag_keys, data_tags=data_tags) @@ -721,6 +851,8 @@ def _materialize_upstream( ) typed = StaticOutputOperatorPod._zero_row_input(upstream) if typed is not None: + # A complete output with no row, in the row-built form (``ROW_BUILT_OUTPUT``). + setattr(typed, ROW_BUILT_OUTPUT, True) return typed # Build an empty table preserving declared field nullability. tag_schema, data_schema = upstream.output_schema( @@ -779,7 +911,7 @@ def _as_upstream_stream( # otherwise it would fall back to a root's schema-only hash and an # operator would name its system tags after that. A source's pipeline # hash is that schema-only hash already. - return _RowsOfStream( + stream: StreamProtocol = _RowsOfStream( table, tag_columns=tag_keys, pipeline_hash=upstream.pipeline_hash(), @@ -787,16 +919,23 @@ def _as_upstream_stream( upstreams=upstream.upstreams, data_context=context, ) - # No ``source_info`` argument: the table's own ``_source_*`` columns - # pass through, one value per row. - return ArrowTableStream( - table, - tag_columns=tag_keys, - data_tags=data_tags, - producer=upstream.producer, - upstreams=upstream.upstreams, - data_context=context, - ) + else: + # No ``source_info`` argument: the table's own ``_source_*`` columns + # pass through, one value per row. + stream = ArrowTableStream( + table, + tag_columns=tag_keys, + data_tags=data_tags, + producer=upstream.producer, + upstreams=upstream.upstreams, + data_context=context, + ) + # Every complete node output in the row-built form ends here (the rows' + # rebuild, F's output, a stored-table output) or, with no row, in + # ``_materialize_upstream``'s zero-row input: the places that mark it + # (ITL-1347): ``InputChannel.to_stream`` may give it as it is. + setattr(stream, ROW_BUILT_OUTPUT, True) + return stream @staticmethod def _materialize_input_stream( @@ -1051,12 +1190,18 @@ def transport_schema(stream: StreamProtocol) -> pa.Schema | None: Returns: The schema, or ``None`` for a stream that cannot say its Arrow types without - rows (an unbound input slot, a source that has not polled yet). + rows (an unbound input slot, a source that has not polled yet, a description + whose types are undeclared: ``arrow_types_declared`` false). """ # TODO(ITL-1360): ``stream.arrow_schema()``, once every stream has it. from orcapod.core.streams.base import row_built_names, row_built_provenance from orcapod.utils import arrow_utils + if not getattr(stream, "arrow_types_declared", True): + # The rows decide the types (and the column order) of a description whose + # types are undeclared (a narrower bind, ``RowsOnRead``): the first batch sets + # them. + return None typed = StaticOutputOperatorPod._zero_row_input(stream) # pyright: ignore[reportPrivateUsage] # the zero-row form of an input if typed is None: return None @@ -1076,11 +1221,13 @@ def transport_schema(stream: StreamProtocol) -> pa.Schema | None: ROW_BUILT_OUTPUT = "_orcapod_row_built_output" -"""The attribute that marks a stream ``_output_stream`` built (ITL-1347). +"""The attribute that marks a complete node output in the row-built form (ITL-1347). -Set in that one place, never inferred from a class: such a stream is a complete, -immutable output already in the row-built form, so a consumer of its record batches -would rebuild exactly it, and ``InputChannel.to_stream`` may give it without reading. +Set where every such output is made (``_as_upstream_stream``, and the zero-row input +of ``_materialize_upstream``), never inferred from a class: such a stream is a +complete, immutable output already in the row-built form, so a consumer of its record +batches would rebuild exactly it, and ``InputChannel.to_stream`` may give it without +reading. """ @@ -1169,6 +1316,201 @@ def with_open_provenance_flags(batch: pa.RecordBatch) -> pa.RecordBatch: return pa.RecordBatch.from_arrays(batch.columns, schema=schema) +class RowsOnRead: + """A node's output held as its rows, its table built on first read (ITL-1347). + + The one rule for every route where building the output from the whole table is + not provably ``main``'s result (a narrower bind, a bound stream that is not a + library source kind, a whole-table build that is unavailable, an odd stored table, + a held node, a result with no row, a node whose output is still its rows): the node + hands on the rows ``main`` would hold, and the table is built from them by + ``main``'s own row path (``StaticOutputOperatorPod._materialize_upstream``) when + the table is first read. The sync orchestrator reads each input of a node before + running it (``at_edge``), where ``main`` rebuilt it; a stream nobody reads is never + built, as ``main`` never rebuilt a leaf's rows. + + It is a stream (``StreamProtocol``), structurally: every member of the protocol is + the built stream's, except those that read nothing. Its rows (``iter_data``, + iteration) are the rows it holds, unchanged, as ``main`` returned them. Its + description (``arrow_schema``) is the node's declared one and builds nothing + (``arrow_types_declared`` is false). Opening a channel builds nothing; the + channel's first read does. + """ + + # Not a stream the row-built form already made: a channel opened on it reads it. + _orcapod_row_built_output = False + + def __init__( + self, rows: Iterable[tuple[TagProtocol, DataProtocol]], node: StreamProtocol + ) -> None: + """Hold ``node``'s rows; nothing is built. + + Args: + rows: The rows ``main`` would hold, in order (read once, here). + node: The node (or stream) whose output they are. + """ + self._rows: list[tuple[TagProtocol, DataProtocol]] = list(rows) + self._node = node + self._stream: StreamProtocol | None = None + + def built(self) -> StreamProtocol: + """The stream, built from the rows on the first call (``main``'s row path).""" + if self._stream is None: + self._stream = StaticOutputOperatorPod._materialize_upstream( + self._rows, self._node + ) + return self._stream + + def release_built(self) -> None: + """Drop the built stream and keep only the rows. + + The sync orchestrator calls this on an output it retains once every successor + has read it: ``main`` held only the rows, so the retained output holds one + representation, and a later read builds the same table again from them. + """ + self._stream = None + + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: + """The rows it holds, unchanged (their meta columns included), as ``main``.""" + return iter(self._rows) + + def __iter__(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: + return self.iter_data() + + async def async_iter_data( + self, + ) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: + """The rows it holds, unchanged.""" + for row in self._rows: + yield row + + def arrow_schema(self) -> pa.Schema: + """The node's own description (``arrow_schema()``); builds nothing. + + The rows decide the Arrow types (``arrow_types_declared`` is false): the + description gives the node's names and declared types, with no guaranteed + order. + """ + describe = getattr(self._node, "arrow_schema", None) + if callable(describe): + return cast(pa.Schema, describe()) + from orcapod.core.streams.base import stream_arrow_schema + + return stream_arrow_schema(self._node, from_table=False) + + @property + def arrow_types_declared(self) -> bool: + """False: the rows decide the types (see ``arrow_schema``).""" + return False + + def open_channel(self) -> Any: + """Open an input channel on this stream; its first read builds the table.""" + from orcapod.core.streams.base import CompleteStreamFeed + from orcapod.core.streams.record_batch_input import InputChannel + + return InputChannel( + cast(StreamProtocol, cast(object, self)), + CompleteStreamFeed(cast(StreamProtocol, cast(object, self))), + ) + + # The members that tell what the output is without reading it: the node's, which + # the built stream takes too (``_as_upstream_stream``), or the built stream's once + # it is built. A protocol check (``isinstance``) reads them and builds nothing. + @property + def producer(self) -> Any: + return self._node.producer + + @property + def upstreams(self) -> tuple[StreamProtocol, ...]: + return self._node.upstreams + + @property + def data_context_key(self) -> str: + return self._node.data_context_key + + @property + def label(self) -> Any: + source = self._stream if self._stream is not None else self._node + return getattr(source, "label", None) + + @property + def last_modified(self) -> Any: + source = self._stream if self._stream is not None else self._node + return getattr(source, "last_modified", None) + + def __getattr__(self, name: str) -> Any: + # Every other member (``join``, ``as_polars_df``, ...) is the built stream's. + return getattr(self.built(), name) + + def __repr__(self) -> str: + return f"RowsOnRead({short_stream_repr(self._node)})" + + +def _stream_protocol_members() -> list[str]: + """The members ``StreamProtocol`` declares, its bases' included. + + What ``isinstance(x, StreamProtocol)`` looks for on the class: declaring each one + there lets ``RowsOnRead`` pass the check on every supported Python. + """ + names: set[str] = set() + protocol = cast(type, cast(object, StreamProtocol)) + for base in protocol.__mro__: + if base is object or base.__name__ in ("Protocol", "Generic"): + continue + names.update(name for name in vars(base) if not name.startswith("_")) + return sorted(names) + + +def _delegated(name: str) -> Any: + """A method of ``RowsOnRead`` that is the built stream's (``RowsOnRead.built``).""" + + def delegate(self: RowsOnRead, *args: Any, **kwargs: Any) -> Any: + return getattr(self.built(), name)(*args, **kwargs) + + delegate.__name__ = name + return delegate + + +for _name in _stream_protocol_members(): + if _name not in vars(RowsOnRead): + setattr(RowsOnRead, _name, _delegated(_name)) + + +def rows_on_read( + rows: Iterable[tuple[TagProtocol, DataProtocol]], node: StreamProtocol +) -> StreamProtocol: + """``RowsOnRead`` of ``rows`` as a stream (it delegates every member to the built one). + + Args: + rows: The rows ``main`` would hold, in order (read once, here). + node: The node (or stream) whose output they are. + + Returns: + The output, built from the rows when first read. + """ + # ``RowsOnRead`` stands for the stream it builds; the checker cannot see that + # through its delegation, so the cast goes through object. + return cast(StreamProtocol, cast(object, RowsOnRead(rows, node))) + + +def at_edge(stream: StreamProtocol) -> StreamProtocol: + """``stream`` as a node's input: a ``RowsOnRead`` output is built here. + + The sync orchestrator reads every input of a node before it runs the node, where + ``main`` rebuilt the rows of the node before it, so an error of that build surfaces + at the same point, after the same observer events. + + Args: + stream: An output a node handed on. + + Returns: + The stream to give the node. + """ + if isinstance(stream, RowsOnRead): + return stream.built() + return stream + + class _RowsOfStream(ArrowTableStream): """Rows standing in for the stream they came from, with its pipeline hash. @@ -1224,6 +1566,31 @@ def pipeline_hash( return self._input_pipeline_hash +def produced_stream(stream: StreamProtocol) -> StreamProtocol: + """Return the stream whose rows ``stream`` yields, through any depth of composition. + + An operator's result is a ``DynamicPodStream`` whose rows are those of the stream + its ``static_process`` returned, which may itself be another operator's + ``DynamicPodStream``: this follows them all to the stream that holds the rows + (ITL-1347). A wrapper is followed only when it reads as ``DynamicPodStream`` itself + (``reads_as_its_class``: its rows are then exactly those of the stream it holds); a + subclass or a wrapper with a member replaced on the instance is where the chain + stops, so the caller, which proves the stream it is given, takes the row path. + + Args: + stream: An operator's result, or any stream. + + Returns: + The stream that holds ``stream``'s rows, or the first wrapper not proven to + read through the stream it holds. + """ + while isinstance(stream, DynamicPodStream) and reads_as_its_class( + stream, DynamicPodStream + ): + stream = stream.produced_stream() + return stream + + class DynamicPodStream(StreamBase): """Recomputable stream wrapping a ``StaticOutputOperatorPod`` invocation.""" @@ -1452,6 +1819,18 @@ def iter_data( ) return self._cached_stream.iter_data() + def produced_stream(self) -> StreamProtocol: + """The stream the operator returned for the current inputs (computed if stale). + + Its rows are this stream's rows; ``produced_stream`` (the module function) + follows it through every ``DynamicPodStream`` to the stream that holds them. + """ + self._refresh() + assert self._cached_stream is not None, ( + "StreamProtocol has not been updated or is empty." + ) + return self._cached_stream + def head( self, n: int = 10, diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 66527f145..d744f3c22 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -22,6 +22,7 @@ from orcapod.channels import ChannelClosed from orcapod.core.operators.static_output_pod import ( + SourceInfoTypesDisagree, stream_from_batches, transport_schema, ) @@ -150,6 +151,9 @@ def __init__( # batch's when the stream cannot say its Arrow types without rows. self._schema: pa.Schema | None = None self._schema_known = False + # Each source-info column's token type as the batches accepted so far settle it + # (``_settled_token_types``): a later batch must settle with it. + self._token_types: dict[str, pa.DataType] = {} self._changed = asyncio.Event() @property @@ -191,9 +195,10 @@ def _check_schema(self, batch: pa.RecordBatch) -> None: if schema is None: # No Arrow types in the description: the first batch that passes sets them # (they must be in the large variants), but the names are still the - # stream's. A refused batch sets nothing. + # stream's, in no guaranteed order (an undeclared description gives names + # only). A refused batch sets nothing. names = batch.schema.names - if names != row_built_names(names, self._stream.keys()): + if sorted(names) != sorted(row_built_names(names, self._stream.keys())): raise ValueError( f"A record batch sent as {_named(self._stream)} does not have that " + f"stream's columns: it has {names}, the stream's keys are " @@ -206,7 +211,9 @@ def _check_schema(self, batch: pa.RecordBatch) -> None: f"A record batch sent as {_named(self._stream)} does not have that " + f"stream's columns: {mismatch}." ) + token_types = _settled_token_types(batch, self._token_types) self._schema = schema + self._token_types = token_types async def send(self, batch: pa.RecordBatch) -> None: """Send one Arrow record batch of the stream's transport columns. @@ -355,6 +362,49 @@ def _named(stream: Any) -> str: # pyright: ignore[reportExplicitAny] # any str return repr(label) if label else repr(stream) +def _settled_token_types( + batch: pa.RecordBatch, accepted: dict[str, pa.DataType] +) -> dict[str, pa.DataType]: + """Each source-info column's token type, settled with the batches already accepted. + + A source-info column's type follows its tokens over the complete table + (``StaticOutputOperatorPod._type_source_info_by_values``): the description leaves it + open, but the channel's batches must settle together, or their result could not be + built. A batch whose tokens give a column a type the accepted batches do not is + refused at send, with the error the complete table would raise. + + Args: + batch: The batch being sent. + accepted: Each column's token type from the batches accepted so far. + + Returns: + The token types with this batch accepted. + + Raises: + SourceInfoTypesDisagree: If the batch's tokens give a column two types, or a + type other than the accepted batches'. + """ + settled = dict(accepted) + for field, column in zip(batch.schema, batch.columns, strict=True): + if not field.name.startswith(constants.SOURCE_PREFIX): + continue + kinds: set[pa.DataType] + if pa.types.is_large_string(field.type): + kinds = {pa.large_string()} + else: + kinds = { + arrow_utils.source_info_arrow_type(value) + for value in column.to_pylist() + } + if field.name in settled: + kinds.add(settled[field.name]) + if len(kinds) > 1: + raise SourceInfoTypesDisagree(field.name) + if kinds: + (settled[field.name],) = kinds + return settled + + def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: """Say how a record batch's columns differ from a channel's, or ``None``. @@ -364,7 +414,10 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: ``null`` type of the description (anywhere in a column's type) is carried as ``large_string``, as a row's datagram stores it, and only null values are taken there. Whether a system-tag or source-info field is nullable is not compared: it - follows the values of the complete table (``_flag_by_values``). + follows the values of the complete table (``_flag_by_values``). Nor is a + source-info column's type, which follows its tokens over the complete table + (``_type_source_info_by_values``): it must only be a token type (``large_string``, + or ``large_list`` of a token type). """ sent = batch.schema if declared.names != sent.names: @@ -372,6 +425,14 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: provenance = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) for index, (expected, column) in enumerate(zip(declared, sent)): carried = arrow_utils.normalize_to_large_types(expected.type) + if column.name.startswith(constants.SOURCE_PREFIX): + if not _is_token_type(column.type): + return f"column {column.name!r} is {column.type}, not a token type" + if column.metadata or not column.type.equals( + _without_metadata(column.type), check_metadata=True + ): + return f"column {column.name!r} carries field metadata" + continue if column.type != carried: return f"column {column.name!r} is {column.type}, the stream's is {carried}" if carried != expected.type and not _holds_only_nulls( @@ -404,6 +465,18 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: return None +def _is_token_type(kind: pa.DataType) -> bool: + """Whether ``kind`` is a source-info token type: ``large_string``, or a list of one. + + The types ``arrow_utils.source_info_arrow_type`` gives a token. + """ + if pa.types.is_large_string(kind): + return True + if isinstance(kind, pa.LargeListType): + return _is_token_type(kind.value_type) # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType] + return False + + def _without_metadata(kind: pa.DataType) -> pa.DataType: """``kind`` with the field metadata of every nested field removed.""" if isinstance(kind, pa.LargeListType): diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index 460075915..5af85d506 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -89,6 +89,7 @@ class ArrowTableSource(RootSource): # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "arrow_table" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 1eed1f022..fdaa3cdd1 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -6,6 +6,7 @@ from orcapod.config import OrcapodConfig from orcapod.core.streams.base import ( StreamBase, + reads_as_its_class, typed_arrow_schemas, typed_zero_row_table, ) @@ -47,6 +48,26 @@ def saved_tag_only_columns(config: dict[str, Any]) -> bool | list[str]: return config["tag_only_columns"] +def table_is_rows(source: object) -> bool: + """Whether ``source``'s ``as_table()`` and ``iter_data()`` provably read the same data. + + Positive and exact (ITL-1347): true only when ``source``'s class itself declares + ``TABLE_IS_ROWS = True`` (a library source kind) and ``source`` reads as that class + (``reads_as_its_class``: its exact type, no member replaced on the instance). Any + subclass, a mixin, a replaced reader or a property that changes what the source + reads through is not proven, and a job node bound to it hands on its rows, as + ``main`` iterated them. + + Args: + source: The object bound to a source slot. + + Returns: + Whether F of its table is the table its rows give. + """ + kind = type(source) + return vars(kind).get("TABLE_IS_ROWS") is True and reads_as_its_class(source, kind) + + class RootSource(StreamBase): """Abstract base class for all root sources in Orcapod. @@ -93,6 +114,18 @@ class RootSource(StreamBase): identifier, config or stored path. """ + TABLE_IS_ROWS: ClassVar[bool] = False + """Whether ``as_table()`` and ``iter_data()`` read the same data, with no effect. + + Declared ``True`` only by the library source kinds that read one stream either way, + each on its own class: it is read for the exact class only, never inherited + (``table_is_rows``; ITL-1347). A job node bound to an instance of exactly such a + class hands on F of its table, which equals the table built from its rows. Any + other bound stream (a subclass, a side-effect or function pod stream, an operator's + result, a raw stream, a source kind that polls or delivers on a read) hands on its + rows (``RowsOnRead``), as ``main`` iterated them. + """ + def __init__( self, source_id: str | None = None, diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 308a24fb6..a9bfd8f08 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -80,6 +80,7 @@ class CachedSource(RootSource): SOURCE_KIND: ClassVar[str] = "cached" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True HASH_COLUMN_NAME = "_record_hash" diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index cd780ab1e..9a0d99dcf 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -277,6 +277,7 @@ class CSVSource(RootSource): SOURCE_KIND: ClassVar[str] = "csv" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 5db583ec2..f973c9647 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -44,6 +44,7 @@ class DataFrameSource(RootSource): # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "data_frame" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index decdc09ea..a95c316f2 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -81,6 +81,7 @@ class DBTableSource(RootSource): SOURCE_KIND: ClassVar[str] = "db_table" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index ae623bdec..c744b3913 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -50,6 +50,7 @@ class DeltaTableSource(RootSource): SOURCE_KIND: ClassVar[str] = "delta_table" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1a7a58a93..1464e3f08 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -191,6 +191,7 @@ class DerivedSource(RootSource): # The config type key (names the class a saved config is rebuilt with) and # the kind prefix of the plain form's default source id. SOURCE_KIND: ClassVar[str] = "derived" + TABLE_IS_ROWS: ClassVar[bool] = True PROVISIONAL = True """Provisional in data context v1, both forms (ITL-1331, ``PROVISIONAL_SOURCES``).""" diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index bb99e1f9c..5a3935153 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -40,6 +40,7 @@ class DictSource(RootSource): # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "dict" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index 48d8eae61..0b42e33ef 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -39,6 +39,7 @@ def _default_tag(element: Any, idx: int) -> dict[str, Any]: # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "list" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index 0f12aa372..bc2b437b2 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -172,6 +172,7 @@ class PostgreSQLTableSource(DBTableSource): SOURCE_KIND: ClassVar[str] = "postgresql_table" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 8b022ff87..c6c271657 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -375,6 +375,7 @@ class SpiralDBTableSource(RootSource): SOURCE_KIND: ClassVar[str] = "spiraldb_table" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True # Whether a notebook display reads the first rows. False shows the schema and the diff --git a/src/orcapod/core/sources/sqlite_table_source.py b/src/orcapod/core/sources/sqlite_table_source.py index f4e753553..9353ea07c 100644 --- a/src/orcapod/core/sources/sqlite_table_source.py +++ b/src/orcapod/core/sources/sqlite_table_source.py @@ -101,6 +101,7 @@ class SQLiteTableSource(DBTableSource): SOURCE_KIND: ClassVar[str] = "sqlite_table" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 3d941e5cb..d2ec40632 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1,5 +1,7 @@ from __future__ import annotations +import functools +import inspect import logging from abc import abstractmethod from collections import deque @@ -22,6 +24,7 @@ import pyarrow as pa from orcapod.core.base import TraceableBase +from orcapod.core.data_tags import data_tag_names from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, @@ -47,6 +50,59 @@ logger = logging.getLogger(__name__) +def reads_as_its_class(obj: object, cls: type) -> bool: + """Whether ``obj`` is exactly ``cls`` and reads only through ``cls``'s own members. + + Exact, never by inspection of what a subclass overrides: ``type(obj) is cls``, and + ``obj`` holds no attribute of its own that shadows a method or a property of + ``cls`` (an ``iter_data`` replaced on the instance). A ``functools.cached_property`` + keeps its value in the instance by design and is not a shadow. A subclass, however + small, is never ``cls`` here (ITL-1347). + + Args: + obj: The object to check. + cls: The class whose reading is proven. + + Returns: + Whether ``obj`` reads as ``cls`` does. + """ + if type(obj) is not cls: + return False + own = getattr(obj, "__dict__", None) + if not own: + return True + missing = object() + for name in own: + member = inspect.getattr_static(cls, name, missing) + if member is missing or isinstance(member, functools.cached_property): + continue + if callable(member) or hasattr(type(member), "__get__"): + return False + return True + + +def system_tags_as_rows_give(schema: pa.Schema) -> bool: + """Whether every system-tag field is what the row rebuild gives: non-null text. + + ``main`` rebuilt a node's table from its rows, whose system tags are typed from + their values: a ``large_string`` field, non-nullable (the only kind library code + makes). A whole table is its rows only when its system tags are already so; a + narrow integer, a nullable field or any other type is decided by the rows + (ITL-1347). + + Args: + schema: The table's schema. + + Returns: + Whether every system-tag field is non-nullable ``large_string``. + """ + return all( + field.type == pa.large_string() and not field.nullable + for field in schema + if field.name.startswith(constants.SYSTEM_TAG_PREFIX) + ) + + def schema_requires_io(stream: object, config: ColumnConfig) -> bool: """Whether reading ``stream``'s schema with ``config`` would read or poll a source. @@ -336,6 +392,121 @@ def row_built_names( return [*tag_keys, *system_tags, *data, *source_info] +def keys_of_rows( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Return the tag and data keys a source's rows have, given its table and ``keys()``. + + A source's rows come from a stream over its table (``ArrowTableStream``), whose rows + list their tags in the stream's tag order and their data with the data-tags first, + in tag order, then the other data columns in the table's order. A source whose + ``keys()`` states its declared order (a ``PollingSource`` whose fetched table has + another column order) has rows in the table's order all the same, as a table built + from its rows does (Codex on PR #485). + + Args: + table: The source's table, as its rows are read from it. + keys: The source's ``keys()``. + + Returns: + The tag keys, and the data keys in the order of the rows. + """ + tag_keys, data_keys = (tuple(keys[0]), tuple(keys[1])) + data_tags = data_tag_names(tag_keys, data_keys) + data = set(data_keys) - set(tag_keys) + in_table = tuple(name for name in table.column_names if name in data) + return tag_keys, (*data_tags, *in_table) + + +def stream_arrow_schema( + stream: object, + keys: tuple[Sequence[str], Sequence[str]] | None = None, + *, + from_table: bool = True, +) -> pa.Schema: + """Return ``stream``'s declared Arrow schema: what ``arrow_schema()`` answers (ITL-1347). + + The schema of the columns a job node passes on, without reading, computing or + polling a row: the stream's zero-row input (``typed_zero_row_input``, the Arrow types + its rows have) with the columns of F, in F's order + (``row_built_names``: user tags, system tags, data, source + info, data and source info in data-key order), with no context and no meta column. A + stream that cannot type itself without rows answers with its Python schema + converted by its data context (``arrow_types_declared`` is then false), and one + whose schema is known only by polling (nothing declared, nothing polled: + ``schema_requires_io``) answers with no column. Each + system-tag and source-info field is stated nullable: a table decides its flag from + its values (F's last step). A source-info field's type is stated as the declared + token type; a complete table decides it from its tokens + (``StaticOutputOperatorPod._type_source_info_by_values``), so consumers must not + rely on it. A ``null`` column keeps the zero-row ``null`` type; rows + carry ``large_string`` (ITL-1319). ITL-1307 later reads it from ``Schema`` instead, + here. + + Args: + stream: The stream, source or node. + keys: The tag and data keys of the stream's rows, when they differ from + ``keys()`` (a source slot gives its bound source's rows); default ``keys()``. + from_table: Take the stream's typed zero-row table (``typed_zero_row_input``); + ``False`` describes it from its declared Python schema only (a narrower + bind, whose rows ``main``'s row path places). + + Returns: + The declared Arrow schema. + """ + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + typed = cast(StreamProtocol, stream) + given_keys = keys + table = typed_zero_row_input(stream) if from_table else None + if table is None and schema_requires_io(stream, ColumnConfig(system_tags=True)): + # Nothing declared, nothing polled (a poller with no declared schema): the + # columns are known only from rows, and a description never polls. No column, + # as a head says (``SCHEMA_NEEDS_POLL_NOTE``); ``arrow_types_declared`` is false. + return pa.schema([]) + if table is None: + # Only what the stream declares: asking for its source-info columns would make + # a source that has not polled poll (a description never computes, polls or + # reads). A source's tokens are strings, so each data column's source info is + # a string field. + tag_schema, data_schema = typed.output_schema(columns={"system_tags": True}) + stated = getattr(stream, "arrow_schemas", None) + if isinstance(stated, tuple): + # The Arrow types the stream declares itself (a slot): never a conversion + # of its Python types, which may have no Arrow type of their own. + tag_arrow, data_arrow = cast("tuple[pa.Schema, pa.Schema]", stated) + fields = [ + *tag_arrow, + *( + pa.field(name, pa.large_string()) + for name in tag_schema + if name not in tag_arrow.names + ), + *(f for f in data_arrow if f.name not in tag_arrow.names), + ] + table = pa.schema(fields).empty_table() + else: + converter = StaticOutputOperatorPod._upstream_context(typed).type_converter # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context + table = arrow_utils.make_empty_table( + {**tag_schema, **data_schema}, converter + ) + for name in data_schema: + table = table.append_column( + pa.field(f"{constants.SOURCE_PREFIX}{name}", pa.large_string()), + pa.array([], pa.large_string()), + ) + # The rows' keys: the data in the order of the stream's table (a poller that + # fetched its columns in another order than it declares lists them so). + keys = given_keys if given_keys is not None else keys_of_rows(table, typed.keys()) + names = row_built_names(table.column_names, keys) + schema = row_built_provenance(table.select(names)).schema + prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + for index, field in enumerate(schema): + if field.name.startswith(prefixes): + schema = schema.set(index, field.with_nullable(True)) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized + return schema + + class CompleteStreamFeed: """The record batches of a complete stream, read at one reader's own position. @@ -1121,6 +1292,18 @@ def index( return Index(column, i, out=out, fail_on_miss=fail_on_miss)(self, label=label) + def arrow_schema(self) -> pa.Schema: + """The Arrow schema of the columns this stream passes between job nodes. + + See ``stream_arrow_schema`` (ITL-1347): never reads, computes or polls a row. + """ + return stream_arrow_schema(self) + + @property + def arrow_types_declared(self) -> bool: + """Whether ``arrow_schema()`` holds the rows' own Arrow types (ITL-1089, ITL-1347).""" + return typed_zero_row_table(self) is not None + @abstractmethod def keys( self, diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 55cd52d5e..9edd1614e 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -24,7 +24,7 @@ OrcapodDatabaseWriteError, TypeIdentityError, ) -from orcapod.pipeline.result import OrchestratorResult +from orcapod.pipeline.result import OrchestratorResult, StreamsOnRead from orcapod.utils.database_errors import keep_database_error from orcapod.protocols.node_protocols import ( is_function_node, @@ -39,7 +39,10 @@ from orcapod.channels import WritableChannel from orcapod.pipeline.dag import GraphProtocol - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import ( + DataProtocol, + TagProtocol, + ) from orcapod.protocols.observability_protocols import ExecutionObserverProtocol logger = logging.getLogger(__name__) @@ -177,8 +180,9 @@ async def run_async( pipeline_uri: Opaque URI string identifying this pipeline run. Forwarded verbatim to ``observer.on_run_start``. load_only: As for ``SyncPipelineOrchestrator.run``. - held_rows: As for ``SyncPipelineOrchestrator.run``: nodes not run, whose - rows feed their successors. + held_rows: Nodes not run, with the rows of their current run as the run's + plan took them (``RunPlan.held_rows``): those rows feed their + successors. The async path carries rows until ITL-1347 stage 5. Returns: OrchestratorResult with node outputs. @@ -205,6 +209,9 @@ async def _run_async( held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, ) -> OrchestratorResult: """Core async logic: wire channels, launch tasks, collect results.""" + from orcapod.core.operators.static_output_pod import ( + rows_on_read, + ) from orcapod.pipeline.observer import NoOpObserver run_id = run_id or str(uuid.uuid4()) @@ -271,7 +278,11 @@ async def _run_async( for upstream in in_edges.get(node, []): tg.create_task(_drain(edge_readers[(upstream, node)])) _start_node( - tg, failed_nodes, node, _send_held(held_rows[node], writer) + tg, + failed_nodes, + node, + # The rows the plan took (ITL-1347, stage 5 changes it). + _send_held(held_rows[node], writer), ) elif is_source_node(node): _start_node( @@ -355,7 +366,11 @@ async def _run_async( tg.create_task(ch.reader.collect()) return OrchestratorResult( - node_outputs=collectors if materialize_results else {} + node_outputs=( + StreamsOnRead(collectors, rows_on_read) + if materialize_results + else {} + ) ) except ExceptionGroup as group: # A failed database read or write stops the run. Raise it on its own, as the diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index ea3f5570f..e2b84a81a 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -990,15 +990,28 @@ def run( counter = RunCountingObserver() effective_orchestrator = orchestrator or SyncPipelineOrchestrator() with self._executing(prepared, plan, commit_every_rows, load_only=load_only): - _ = effective_orchestrator.run( - plan.dag, - observer=_with_counter(observer, counter), - run_id=prepared.run_id, - pipeline_uri=prepared.pipeline_uri, - materialize_results=materialize_results, - load_only=load_only, - held_rows=plan.held_rows, - ) + if isinstance(effective_orchestrator, SyncPipelineOrchestrator): + # Held nodes give their output streams on the sync path (ITL-1347). + _ = effective_orchestrator.run( + plan.dag, + observer=_with_counter(observer, counter), + run_id=prepared.run_id, + pipeline_uri=prepared.pipeline_uri, + materialize_results=materialize_results, + load_only=load_only, + held=plan.held, + ) + else: + # The async path sends the rows the plan took (until stage 5). + _ = effective_orchestrator.run( + plan.dag, + observer=_with_counter(observer, counter), + run_id=prepared.run_id, + pipeline_uri=prepared.pipeline_uri, + materialize_results=materialize_results, + load_only=load_only, + held_rows=plan.held_rows, + ) summary = self._finish_run( prepared, counter, diff --git a/src/orcapod/pipeline/loaded_side_effects.py b/src/orcapod/pipeline/loaded_side_effects.py index fc8d6ca79..aa5182742 100644 --- a/src/orcapod/pipeline/loaded_side_effects.py +++ b/src/orcapod/pipeline/loaded_side_effects.py @@ -263,7 +263,7 @@ def execute( observer: ExecutionObserverProtocol | None = None, run_id: str | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: + ) -> StreamProtocol: """Pass every row on in a load-only run, as every side-effect job node does. Args: @@ -273,7 +273,8 @@ def execute( load_only: Must be true: the node can only pass rows on. Returns: - The rows of ``input_stream``, which the node then holds as loaded only. + The output stream of the rows of ``input_stream``, which the node then holds + as loaded only. Raises: RuntimeError: If ``load_only`` is false; nothing is read then. diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 44ae96fb9..88a0e5ffe 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -14,7 +14,7 @@ from __future__ import annotations -from collections.abc import Iterable, Iterator, Sequence +from collections.abc import Iterable, Iterator, Mapping, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any @@ -25,6 +25,7 @@ run_node_summaries, ) from orcapod.pipeline.restrictions import restrictions_in_force, source_name +from orcapod.pipeline.result import StreamsOnRead from orcapod.utils.database_errors import flush_best_effort if TYPE_CHECKING: @@ -242,6 +243,13 @@ def check_sources(streams: Iterable[Any]) -> tuple[str, ...]: return tuple(unchecked) +def _rows_on_read(rows: Sequence[Any], node: Any) -> Any: + """A held node's output: its rows, built where a successor reads them (``RowsOnRead``).""" + from orcapod.core.operators.static_output_pod import rows_on_read + + return rows_on_read(rows, node) + + @dataclass(frozen=True) class RunPlan: """What a run does with each node of its graph (ITL-1095). @@ -249,18 +257,22 @@ class RunPlan: Attributes: dag: The nodes the run touches: those it runs, and the predecessors that feed them (a source slot is read; any other one is held). - held_rows: The rows of each held node of ``dag``: the rows of its current run, - or of a stream outside the job; they feed the nodes after it as if it had - just run. + held: The output stream of each held node of ``dag``: of its current run, or + of a stream outside the job; it feeds the nodes after it as if the node had + just run (the sync orchestrator). Built when read (``RowsOnRead``). + held_rows: The rows of each held node, as the plan took them; ``held`` is + built from them. The async orchestrator sends them (it carries rows until + ITL-1347 stage 5). to_run: The nodes the run runs, in dependency order. held_counts: Every node of the whole graph that holds a current run, with its row count, for the summary. """ dag: Any - held_rows: dict[Any, list[Any]] + held: Mapping[Any, Any] to_run: list[Any] held_counts: dict[Any, int] + held_rows: dict[Any, list[Any]] def plan_run(graph: Any, *, load_only: bool, outside: Sequence[Any] = ()) -> RunPlan: @@ -332,15 +344,22 @@ def is_source(node: Any) -> bool: for node in to_run: for upstream in graph.predecessors(node): dag.add_edge(upstream, node) + # A held node's output stream: what the sync orchestrator built from its rows for + # the nodes after it, exactly (ITL-1347, stage 2). held_rows = { node: list(node.iter_data()) for node in included if not any(node is r for r in to_run) and not is_source(node) } + # The rows main held, built where a successor reads them (``RowsOnRead``, + # ``at_edge``), never while planning; an async run reads only the rows. + # The plan keeps no output it handed out (``keep=False``): the orchestrator drops + # each once the node's successors ran. + held = StreamsOnRead(held_rows, _rows_on_read, keep=False) # Counted from what each node holds: iterating an operator's rows would build a # (Tag, Data) pair per row only to count them (ITL-1351). held_counts = {node: node.held_row_count() for node in current} - return RunPlan(dag, held_rows, to_run, held_counts) + return RunPlan(dag, held, to_run, held_counts, held_rows) def commit_run(databases: Sequence[ArrowDatabaseProtocol], ran: Sequence[Any]) -> None: @@ -425,7 +444,7 @@ def visit(node: Any) -> None: counter = RunCountingObserver() try: _ = SyncPipelineOrchestrator().run( - plan.dag, observer=counter, load_only=load_only, held_rows=plan.held_rows + plan.dag, observer=counter, load_only=load_only, held=plan.held ) except BaseException as run_error: if isinstance(run_error, Exception) and not load_only: diff --git a/src/orcapod/pipeline/result.py b/src/orcapod/pipeline/result.py index 94d158184..c0a95a4a7 100644 --- a/src/orcapod/pipeline/result.py +++ b/src/orcapod/pipeline/result.py @@ -2,11 +2,62 @@ from __future__ import annotations +from collections.abc import Callable, Iterator, Mapping from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any if TYPE_CHECKING: - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import StreamProtocol + + +class StreamsOnRead(Mapping[Any, "StreamProtocol"]): + """Each node's output stream, built from its rows when it is read. + + The async orchestrator collects each node's rows as they are sent; a node's stream + is built from them (``build``) when it is read. A run whose rows cannot make one + table (rows of a store written before ITL-928) therefore finishes, as it does on + ``main``, and only reading that node's output raises, as reading its rows as a + table does (ITL-1360). Membership, length and iteration never build a stream. A run + plan's held streams are built the same way, when the sync orchestrator reaches the + node, and are not kept (``keep=False``): the orchestrator drops each one once its + successors have run. + """ + + def __init__( + self, + rows: Mapping[Any, Any], + build: Callable[[Any, Any], "StreamProtocol"], + *, + keep: bool = True, + ) -> None: + """Hold each node's rows and how a stream is built from them. + + Args: + rows: Each node's rows. + build: Builds a node's stream from its rows, given ``(rows, node)``. + keep: Keep a stream once built, so a second read returns it again. + """ + self._rows = dict(rows) + self._build = build + self._keep = keep + self._built: dict[Any, StreamProtocol] = {} + + def __getitem__(self, node: Any) -> "StreamProtocol": + if node in self._built: + return self._built[node] + stream = self._build(self._rows[node], node) + if self._keep: + self._built[node] = stream + return stream + + def __contains__(self, node: object) -> bool: + return node in self._rows + + def __iter__(self) -> Iterator[Any]: + return iter(self._rows) + + def __len__(self) -> int: + return len(self._rows) @dataclass @@ -14,10 +65,10 @@ class OrchestratorResult: """Result of an orchestrator run. Attributes: - node_outputs: Mapping from graph node to its computed (tag, data) - pairs. Empty when ``materialize_results=False``. + node_outputs: Mapping from graph node to its output stream (backed by an + Arrow table; ``as_table()`` gives it, ``iter_data()`` its rows). Empty when + ``materialize_results=False``. The async orchestrator builds each stream + when it is first read (``StreamsOnRead``). """ - node_outputs: dict[Any, list[tuple["TagProtocol", "DataProtocol"]]] = field( - default_factory=dict - ) + node_outputs: Mapping[Any, "StreamProtocol"] = field(default_factory=dict) diff --git a/src/orcapod/pipeline/sync_orchestrator.py b/src/orcapod/pipeline/sync_orchestrator.py index bf9708a39..3286caab7 100644 --- a/src/orcapod/pipeline/sync_orchestrator.py +++ b/src/orcapod/pipeline/sync_orchestrator.py @@ -26,7 +26,7 @@ from orcapod.pipeline.dag import GraphProtocol from orcapod.protocols.observability_protocols import ExecutionObserverProtocol - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import StreamProtocol logger = logging.getLogger(__name__) @@ -38,8 +38,9 @@ class SyncPipelineOrchestrator: to ``node.execute(observer=...)`` which owns all per-data logic, cache lookups, and observer hooks internally. - The orchestrator is responsible only for topological ordering, - buffer management, and stream materialization between nodes. + The orchestrator is responsible only for topological ordering and for handing + each node's output stream to its successors: a node's ``execute`` returns the + stream every successor reads (ITL-1347, stage 2). """ def __init__( @@ -57,16 +58,16 @@ def run( run_id: str | None = None, pipeline_uri: str = "", load_only: bool = False, - held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, + held: Mapping[Any, StreamProtocol] | None = None, ) -> OrchestratorResult: """Execute the node graph synchronously. Args: graph: A ``GraphProtocol`` DAG with GraphNode objects as vertices. observer: Optional execution observer forwarded to nodes. - materialize_results: If True, keep all node outputs in memory - and return them. If False, discard buffers after downstream - consumption (only DB-persisted results survive). + materialize_results: If True, keep every node's output stream and return + them. If False, drop each one once its successors have run (only + DB-persisted results survive). run_id: Optional run identifier. If not provided, a UUID is generated automatically. pipeline_uri: Opaque URI string identifying this pipeline run @@ -76,13 +77,13 @@ def run( (ITL-1095): function nodes load their inputs' stored results and skip the others, operators run without storing, and a side-effect node passes its rows on and delivers nothing. - held_rows: Nodes of ``graph`` that are not run: each one's rows (the rows - of its current run, or of a stream outside the job) feed its - successors as if it had just run. Used by ``node.run()``, which runs - only the nodes it depends on that hold no current run (ITL-1095). + held: Nodes of ``graph`` that are not run: each one's output stream (of + its current run, or of a stream outside the job) feeds its successors + as if it had just run. Used by ``node.run()``, which runs only the + nodes it depends on that hold no current run (ITL-1095). Returns: - OrchestratorResult with node outputs. + OrchestratorResult with each node's output stream. """ from orcapod.pipeline.observer import NoOpObserver @@ -94,23 +95,29 @@ def run( current: Any = None try: topo_order = list(graph.topological_sort()) - buffers: dict[Any, list[tuple[TagProtocol, DataProtocol]]] = {} + # Taken before any node runs: an observer may rebind a source, which + # changes how the graph finds that node afterwards. + neighbours = ( + { + id(n): (list(graph.predecessors(n)), list(graph.successors(n))) + for n in topo_order + } + if materialize_results + else {} + ) + outputs: dict[Any, StreamProtocol] = {} processed: set[Any] = set() - held = held_rows if held_rows is not None else {} + held_streams = held if held is not None else {} for node in topo_order: current = node - if node in held: - buffers[node] = list(held[node]) + if node in held_streams: + outputs[node] = held_streams[node] elif is_source_node(node): - buffers[node] = node.execute(observer=effective_observer) + outputs[node] = node.execute(observer=effective_observer) elif is_function_node(node) or is_side_effect_function_node(node): - upstream_buf = self._gather_upstream(node, graph, buffers) - upstream_node = list(graph.predecessors(node))[0] - input_stream = self._materialize_as_stream( - upstream_buf, upstream_node - ) - buffers[node] = node.execute( + input_stream = self._single_input(node, graph, outputs) + outputs[node] = node.execute( input_stream, observer=effective_observer, error_policy=self._error_policy, @@ -118,22 +125,14 @@ def run( load_only=load_only, ) elif is_operator_node(node): - upstream_buffers = self._gather_upstream_multi(node, graph, buffers) - input_streams = [ - self._materialize_as_stream(buf, upstream_node) - for buf, upstream_node in upstream_buffers - ] - buffers[node] = node.execute( + input_streams = self._ordered_inputs(node, graph, outputs) + outputs[node] = node.execute( *input_streams, observer=effective_observer, load_only=load_only ) elif is_side_effect_node(node): - upstream_buf = self._gather_upstream(node, graph, buffers) - upstream_node = list(graph.predecessors(node))[0] - input_stream = self._materialize_as_stream( - upstream_buf, upstream_node - ) + input_stream = self._single_input(node, graph, outputs) # In a load-only run the node passes its rows on and delivers nothing. - buffers[node] = node.execute( + outputs[node] = node.execute( input_stream, observer=effective_observer, run_id=run_id, @@ -147,12 +146,14 @@ def run( processed.add(node) if not materialize_results: - self._gc_buffers(node, graph, buffers, processed) + self._gc_outputs(node, graph, outputs, processed) + else: + self._release_built_inputs(node, neighbours, outputs, processed) if not materialize_results: - buffers.clear() + outputs.clear() - return OrchestratorResult(node_outputs=buffers) + return OrchestratorResult(node_outputs=outputs) except OrcapodDatabaseError as exc: # Name the node the failure belongs to, if the raising site did not. if current is not None: @@ -170,70 +171,80 @@ def run( effective_observer.on_run_end(run_id) @staticmethod - def _gather_upstream( + def _single_input( node: Any, graph: "GraphProtocol[Any]", - buffers: dict[Any, list[tuple[Any, Any]]], - ) -> list[tuple[Any, Any]]: - """Gather a single upstream buffer (for function nodes).""" + outputs: dict[Any, StreamProtocol], + ) -> StreamProtocol: + """The output stream of a node's one predecessor (function and side-effect nodes).""" predecessors = list(graph.predecessors(node)) if len(predecessors) != 1: raise ValueError( f"FunctionNode expects exactly 1 upstream, got {len(predecessors)}" ) - return buffers[predecessors[0]] + from orcapod.core.operators.static_output_pod import at_edge + + return at_edge(outputs[predecessors[0]]) @staticmethod - def _gather_upstream_multi( + def _ordered_inputs( node: Any, graph: "GraphProtocol[Any]", - buffers: dict[Any, list[tuple[Any, Any]]], - ) -> list[tuple[list[tuple[Any, Any]], Any]]: - """Gather multiple upstream buffers with their nodes (for operators). - - Returns list of (buffer, upstream_node) tuples preserving the - order that matches the operator's input_streams order. - """ + outputs: dict[Any, StreamProtocol], + ) -> list[StreamProtocol]: + """The output streams of an operator node's predecessors, in ``node.upstreams`` order.""" predecessors = list(graph.predecessors(node)) upstream_order = {id(upstream): i for i, upstream in enumerate(node.upstreams)} sorted_preds = sorted( predecessors, key=lambda p: upstream_order.get(id(p), 0), ) - return [(buffers[p], p) for p in sorted_preds] + from orcapod.core.operators.static_output_pod import at_edge + + return [at_edge(outputs[p]) for p in sorted_preds] @staticmethod - def _materialize_as_stream(buf: list[tuple[Any, Any]], upstream_node: Any) -> Any: - """Wrap a (tag, data) buffer as the upstream node's stream. + def _release_built_inputs( + current_node: Any, + neighbours: dict[int, tuple[list[Any], list[Any]]], + outputs: dict[Any, StreamProtocol], + processed: set[Any], + ) -> None: + """Keep a retained output read by all its successors as its rows only. - ``StaticOutputOperatorPod._materialize_upstream`` builds it, the one - definition an async operator node shares when it rebuilds its inputs - for a run that produced no row. + A ``RowsOnRead`` output builds its table at each successor's edge; once every + successor has run, the retained output drops the built stream and keeps the + rows, which is all ``main`` retained (ITL-1347). A later read builds it again. Args: - buf: List of (tag, data) tuples. - upstream_node: The node that produced this buffer. - - Returns: - An ArrowTableStream. + current_node: The node that just ran. + neighbours: Each node's predecessors and successors, by ``id``, taken + before the run. + outputs: The retained outputs. + processed: The nodes that ran. """ - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.core.operators.static_output_pod import RowsOnRead - return StaticOutputOperatorPod._materialize_upstream(buf, upstream_node) + for pred in neighbours[id(current_node)][0]: + output = outputs.get(pred) + if isinstance(output, RowsOnRead) and all( + succ in processed for succ in neighbours[id(pred)][1] + ): + output.release_built() @staticmethod - def _gc_buffers( + def _gc_outputs( current_node: Any, graph: "GraphProtocol[Any]", - buffers: dict[Any, list[tuple[Any, Any]]], + outputs: dict[Any, StreamProtocol], processed: set[Any], ) -> None: - """Discard buffers no longer needed by any unprocessed downstream.""" + """Drop output streams no unprocessed successor still needs.""" for pred in graph.predecessors(current_node): - if pred not in buffers: + if pred not in outputs: continue all_successors_done = all( succ in processed for succ in graph.successors(pred) ) if all_successors_done: - del buffers[pred] + del outputs[pred] diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 7cb868e90..c5d4e9d34 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -172,6 +172,41 @@ def output_schema( """ ... + def arrow_schema(self) -> "pa.Schema": + """The Arrow schema of the columns the stream passes between job nodes. + + The user tags, system tags, data and source-info columns, in row order (user + tags, system tags, data, source info; data and source info in data-key order), + with the Arrow types, nullability and field metadata of the rows; no context and + no meta column (ITL-1347). Known without reading, computing or polling a row. + Three properties are decided by the values of a complete table, not by the + description: whether a system-tag or source-info field is nullable (stated + nullable here), and a source-info field's type (stated as the declared token + type; a list of ``None`` or of empty lists shows fewer levels, so consumers must + not rely on it). And a ``null`` column keeps the ``null`` type a zero-row table + has (rows carry ``large_string``; ITL-1319). + + Returns: + The declared Arrow schema. + """ + ... + + @property + def arrow_types_declared(self) -> bool: + """Whether ``arrow_schema()`` holds the rows' own Arrow types. + + ``False`` when the stream cannot type itself without rows (an unbound slot, a + ``PollingSource`` never polled; ITL-1089), or its rows decide its types (a + narrower bind, an output held as its rows). Its schema is then the best + description available without reading a row: a slot's or source's explicit + Arrow declaration when it states one, otherwise its Python schema converted; + a source whose schema is known only by polling, and which has not polled, has + an empty schema. So a ``False`` description is not guaranteed to hold the + stream's column names, and the names it holds come in no guaranteed order; no + consumer relies on either (ITL-1347). + """ + ... + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """ Generates explicit iterator over (tag, data) pairs in the stream. diff --git a/src/orcapod/protocols/node_protocols.py b/src/orcapod/protocols/node_protocols.py index 499c74b53..cf1080c53 100644 --- a/src/orcapod/protocols/node_protocols.py +++ b/src/orcapod/protocols/node_protocols.py @@ -46,7 +46,7 @@ def execute( self, *, observer: ExecutionObserverProtocol | None = None, - ) -> list[tuple[TagProtocol, DataProtocol]]: ... + ) -> StreamProtocol: ... async def async_execute( self, @@ -89,7 +89,7 @@ def execute( error_policy: Literal["continue", "fail_fast"] = "continue", run_id: str | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: ... + ) -> StreamProtocol: ... async def async_execute( self, @@ -129,7 +129,7 @@ def execute( *input_streams: StreamProtocol, observer: ExecutionObserverProtocol | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: ... + ) -> StreamProtocol: ... async def async_execute( self, @@ -162,7 +162,7 @@ def execute( observer: "ExecutionObserverProtocol | None" = None, run_id: str | None = None, load_only: bool = False, - ) -> "list[tuple[TagProtocol, DataProtocol]]": ... + ) -> "StreamProtocol": ... async def async_execute( self, diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index de75192ef..071aa82ac 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -13,14 +13,18 @@ import datetime import logging from collections.abc import Callable, Collection, Iterator, Sequence -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING, Any, Literal, cast import pyarrow as pa from typing_extensions import override from orcapod.core.base import TraceableBase from orcapod.core.nodes.staleness import RunHoldingNode -from orcapod.core.nodes.function_node import _build_record_id_preimage, run_job_node +from orcapod.core.nodes.function_node import ( + _build_record_id_preimage, + rows_as_output_stream, + run_job_node, +) from orcapod.core.streams.base import ( StreamBase, check_head_size, @@ -1225,7 +1229,7 @@ def execute( observer: ExecutionObserverProtocol | None = None, run_id: str | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: + ) -> StreamProtocol: """Execute side-effect delivery for all rows in ``input_stream``. Args: @@ -1239,7 +1243,10 @@ def execute( delivering (ITL-1091). A run that raises leaves the node with no rows. Returns: - List of ``(tag, data)`` tuples — the pass-through rows. + The node's output stream: the rows it passed on, as the table + ``_rows_to_table`` builds from them, with this node's identity + (``StaticOutputOperatorPod._materialize_upstream``). The sync orchestrator + hands it to every successor (ITL-1347, stage 2). Raises: SideEffectLogDataContextError: If the invocation log holds deliveries @@ -1254,7 +1261,7 @@ def execute( self.clear_cache() raise self._hold(rows, load_only=True) - return rows + return self._output_stream(rows) try: results = self._deliver_rows(input_stream, run_id=run_id) except BaseException: @@ -1263,7 +1270,20 @@ def execute( self.clear_cache() raise self._hold(results) - return results + return self._output_stream(results) + + def _output_stream( + self, rows: list[tuple[TagProtocol, DataProtocol]] + ) -> StreamProtocol: + """The output stream of a run that passed ``rows`` on. + + What the sync orchestrator built from a node's rows for its successors + (``StaticOutputOperatorPod._materialize_upstream``, through + ``rows_as_output_stream``). + """ + # A side-effect job node is a ``StreamBase``; the checker cannot match its + # mixin members against ``StreamProtocol``, so the cast goes through object. + return rows_as_output_stream(rows, cast("StreamProtocol", cast(object, self))) def _deliver_rows( self, input_stream: StreamProtocol, *, run_id: str | None diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 16d16b44d..e2836eddf 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -175,7 +175,7 @@ def test_a_bound_source_node_sends_its_rows_in_their_own_column_order() -> None: ) node = SourceJobNode.from_stream(stream, name="ordered") assert node.keys()[0] != stream.keys()[0] # the slot's order is another - rows = node.execute() + rows = list(node.iter_data()) # the rows execute() returned before ITL-1347 stage 2 expected = StaticOutputOperatorPod._rows_to_table(rows)[0] batches = run(node.open_channel().collect) assert pa.Table.from_batches(batches).schema.names == expected.schema.names @@ -240,7 +240,9 @@ def test_a_source_nodes_channel_carries_its_execute_output( if bind == "transparent" else _declared_node(source) ) - expected = StaticOutputOperatorPod._materialize_upstream(node.execute(), node) # pyright: ignore[reportPrivateUsage] # the job's rebuild of the rows + expected = StaticOutputOperatorPod._materialize_upstream( + list(node.iter_data()), node + ) # pyright: ignore[reportPrivateUsage] # the job's rebuild of the rows wanted = expected.as_table(columns=ALL) assert any( name.startswith("_source_") and name.removeprefix("_source_") in ("j", "k") @@ -267,7 +269,9 @@ def test_a_rebind_before_the_first_read_is_read_whole() -> None: node = SourceJobNode.from_stream(_keyed_source(()), name="keyed") channel = node.open_channel() node.bound_source = _keyed_source((), source_id="other", offset=10) - expected = StaticOutputOperatorPod._materialize_upstream(node.execute(), node) # pyright: ignore[reportPrivateUsage] # the job's rebuild of the rows + expected = StaticOutputOperatorPod._materialize_upstream( + list(node.iter_data()), node + ) # pyright: ignore[reportPrivateUsage] # the job's rebuild of the rows batches = run(channel.collect) assert same(pa.Table.from_batches(batches), R(expected)) @@ -1903,3 +1907,50 @@ def test_stream_from_batches_is_the_one_conversion() -> None: made = stream_from_batches(stream, batches_of(stream, rows)) assert same(made.as_table(columns=ALL), R(stream)) assert stream_from_batches(stream, []).as_table().num_rows == 0 + + +def test_a_batch_with_a_duplicate_column_is_refused() -> None: + """Without Arrow types the names are compared as a multiset: a duplicate is refused + (Codex on PR #485, round 5).""" + table = source().as_table(columns=ALL) + stream = _UntypedStream( + table, tag_columns=["subject", "trial"], data_tags=["trial"] + ) + (batch,) = batches_of(stream) + name = next(n for n in batch.schema.names if not n.startswith(("_", "subject"))) + doubled = batch.append_column(batch.schema.field(name), batch.column(name)) + + async def write() -> None: + output = OutputChannel(stream) + await output.send(doubled) + + with pytest.raises(ValueError, match="the stream's keys are"): + run(write) + + +def test_a_batch_whose_tokens_cannot_settle_with_accepted_ones_is_refused() -> None: + """A second batch with list tokens where the first had string tokens is refused at + send, with the error the complete table would raise (Codex on PR #485, round 5).""" + from orcapod.core.operators.static_output_pod import SourceInfoTypesDisagree + + stream = source() + (batch,) = batches_of(stream) + column = next(n for n in batch.schema.names if n.startswith("_source_")) + position = batch.schema.get_field_index(column) + tokens = pa.large_list(pa.large_string()) + listed = pa.RecordBatch.from_arrays( + [ + *batch.columns[:position], + pa.array([["t"]] * batch.num_rows, tokens), + *batch.columns[position + 1 :], + ], + schema=batch.schema.set(position, pa.field(column, tokens, nullable=True)), + ) + + async def write() -> None: + output = OutputChannel(stream) + await output.send(batch) + await output.send(listed) + + with pytest.raises(SourceInfoTypesDisagree, match=column): + run(write) diff --git a/tests/test_core/function_pod/test_ephemeral_result.py b/tests/test_core/function_pod/test_ephemeral_result.py index 799c83bc1..2d0e6cfd1 100644 --- a/tests/test_core/function_pod/test_ephemeral_result.py +++ b/tests/test_core/function_pod/test_ephemeral_result.py @@ -152,7 +152,7 @@ def test_is_ephemeral_false_written_to_pipeline_db(self): stream = _make_stream([{"id": 0, "x": 10}]) node, db = _make_node(stream) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 all_records = db.get_all_records(node._versioned_pipeline_path) @@ -171,7 +171,7 @@ def test_is_ephemeral_true_written_to_pipeline_db(self): node, _ = _make_node(stream, pipeline_db=pipeline_db, is_result_ephemeral=True) node.set_ephemeral_database(ephemeral_store) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 all_records = pipeline_db.get_all_records(node._versioned_pipeline_path) @@ -191,7 +191,7 @@ def test_ephemeral_false_unchanged(self): """is_result_ephemeral=False: execute() behaves identically to current implementation.""" stream = _make_stream([{"id": 0, "x": 10}, {"id": 1, "x": 20}]) node, _ = _make_node(stream) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 2 vals = {tag.as_dict()["id"]: data.as_dict()["result"] for tag, data in results} assert vals == {0: 20, 1: 40} @@ -211,7 +211,7 @@ def test_ephemeral_result_written_to_memory_not_persistent_db(self): ) node.node_config = NodeConfig(is_result_ephemeral=True) node.set_ephemeral_database(ephemeral_store) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 @@ -311,7 +311,7 @@ def counting_double(x: int) -> int: node.set_ephemeral_database(InMemoryArrowDatabase()) # Run 1: writes to persistent DB (is_result_ephemeral=False) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 assert call_count["n"] == 1 @@ -320,7 +320,7 @@ def counting_double(x: int) -> int: node._cached_output_datas.clear() # Run 2: Phase 1 must find persistent result — no recompute - results2 = node.execute(stream) + results2 = list(node.execute(stream).iter_data()) assert len(results2) == 1 assert results2[0][1].as_dict()["result"] == 20 assert call_count["n"] == 1 # NOT recomputed @@ -374,7 +374,7 @@ def counting_double(x: int) -> int: node_both.set_ephemeral_database(ephemeral_store) node_both._cached_output_datas.clear() - results = node_both.execute(stream_both) + results = list(node_both.execute(stream_both).iter_data()) assert len(results) == 2 vals = {tag.as_dict()["id"]: data.as_dict()["result"] for tag, data in results} assert vals == {0: 20, 1: 40} @@ -482,7 +482,7 @@ def counting_double(x: int) -> int: # The anti-join should exclude the ephemeral row (entry_id clash with persistent row), # returning only the persistent result. No recomputation. - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 # call_count did not increase — persistent hit from anti-join merge, no recomputation @@ -524,7 +524,7 @@ def test_ephemeral_only_node(self): ) node.node_config = NodeConfig(is_result_ephemeral=True) node.set_ephemeral_database(ephemeral_store) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 @@ -740,7 +740,7 @@ def test_persistent_miss_warns_and_recomputes(self, caplog): with caplog.at_level( logging.WARNING, logger="orcapod.core.nodes.function_node" ): - results = node2.execute(stream) + results = list(node2.execute(stream).iter_data()) assert len(results) == 1 # recomputed assert any( @@ -818,7 +818,7 @@ def test_ephemeral_only_node_no_persistent_db(self): ) node.node_config = NodeConfig(is_result_ephemeral=True) node.set_ephemeral_database(ephemeral_store) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 2 vals = {tag.as_dict()["id"]: data.as_dict()["result"] for tag, data in results} @@ -1021,7 +1021,7 @@ def test_legacy_records_without_ephemeral_col_treated_as_persistent(self): pipeline_database=pipeline_db, result_database=result_db, ) - results = node2.execute(stream) + results = list(node2.execute(stream).iter_data()) # Result must be served (from result DB cache or recomputed) assert len(results) == 1 @@ -1082,7 +1082,7 @@ def counting_double(x: int) -> int: result_database=result_db, ) count_before_session2 = call_count["n"] - results = node2.execute(stream) + results = list(node2.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 assert call_count["n"] == count_before_session2 # NOT recomputed diff --git a/tests/test_core/function_pod/test_function_node_arrow_types.py b/tests/test_core/function_pod/test_function_node_arrow_types.py index 3dc4e70e8..195d72133 100644 --- a/tests/test_core/function_pod/test_function_node_arrow_types.py +++ b/tests/test_core/function_pod/test_function_node_arrow_types.py @@ -303,7 +303,8 @@ def test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column( A Delta database written before ITL-928 gives a ``uint32`` tag back as ``int32``: rows served from it and rows computed now disagree, and the node says so instead - of picking a type. Such a database must be rebuilt. + of picking a type. Such a database must be rebuilt. A leaf's run completes (its + rows are never built into one table, ``RowsOnRead``), as on ``main``. """ _build(DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2)).run() _as_written_before_the_fix(tmp_path) @@ -319,6 +320,30 @@ def test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column( assert "uint32" in message +def test_rows_over_a_store_written_before_the_fix_fail_at_the_successor( + tmp_path: pathlib.Path, +) -> None: + """With a successor, the run fails where the rows are built for it, as on ``main``. + + The node's rows are built into one table where its successor reads them + (``at_edge``): the concatenation raises ``ArrowInvalid`` there, as ``main``'s row + rebuild does. The computed row is stored, as on ``main``. + """ + _build( + DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2), chained=True + ).run() + _as_written_before_the_fix(tmp_path) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32"), chained=True) + + with pytest.raises(pa.ArrowInvalid): + job.run() + + stored = _build(DeltaTableDatabase(tmp_path), _source_table("uint32")) + records = stored.nodes["double"].get_all_records() + assert records is not None + assert records.num_rows == 3 + + def test_new_rows_over_a_store_written_after_the_fix_keep_the_tag_type( tmp_path: pathlib.Path, ) -> None: @@ -376,3 +401,111 @@ def test_a_null_typed_row_is_compared_as_null() -> None: with pytest.raises(InputValidationError, match="'k': null and int64"): _concat_row_tables(rows) + + +@pytest.mark.parametrize("materialize_results", [True, False]) +def test_an_async_run_over_a_store_written_before_the_fix_finishes( + materialize_results: bool, tmp_path: pathlib.Path +) -> None: + """e9 is sync only: an async run over such a store finishes and holds its rows. + + The async orchestrator builds a node's output stream when it is read + (``StreamsOnRead``), so the run finishes as on ``main`` with either value of + ``materialize_results``; reading the node's rows as one table raises, as it does + on ``main``. + """ + from orcapod.pipeline import AsyncPipelineOrchestrator + + _build(DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2)).run() + _as_written_before_the_fix(tmp_path) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32")) + job.run( + orchestrator=AsyncPipelineOrchestrator(), + materialize_results=materialize_results, + ) + + node = job.nodes["double"] + assert len(list(node.iter_data())) == 3 + with pytest.raises(InputValidationError, match="'k'"): + node.as_table() + + +def test_a_second_async_run_holds_the_node_and_sends_its_rows( + tmp_path: pathlib.Path, +) -> None: + """The plan builds no held stream for an async run: it sends the held rows as on main. + + Over a store written before ITL-928, the held ``double`` holds rows that cannot + make one table; a second async run (``increment`` cleared) holds it and sends its + three rows on, as on ``main`` (Codex on PR #485, round 2). + """ + from orcapod.pipeline import AsyncPipelineOrchestrator + from orcapod.pipeline.observer import NoOpObserver + + class DataStarts(NoOpObserver): + def __init__(self) -> None: + self.count = 0 + + def contextualize(self, *identity_path: str) -> DataStarts: + return self + + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: + if node_label == "increment": + self.count += 1 + + _build( + DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2), chained=True + ).run() + _as_written_before_the_fix(tmp_path) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32"), chained=True) + job.run(orchestrator=AsyncPipelineOrchestrator()) + job.nodes["increment"].clear_cache() + observer = DataStarts() + summary = job.run(orchestrator=AsyncPipelineOrchestrator(), observer=observer) + assert summary.nodes["double"].held == 3 + assert observer.count == 3 + + +def test_a_held_nodes_rows_are_built_at_its_successors_edge( + tmp_path: pathlib.Path, +) -> None: + """A held node's rows are built where its successor reads them, as on ``main``. + + A direct sync run: ``double`` held (its rows cannot make one table), an independent + source, then ``increment`` after ``double``. The independent source runs before + ``increment``'s input is built and raises (Codex on PR #485, round 3). + """ + from orcapod.core.operators.static_output_pod import rows_on_read + from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator + from orcapod.pipeline.dag import OrcaDAG + from orcapod.pipeline.observer import NoOpObserver + + _build( + DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2), chained=True + ).run() + _as_written_before_the_fix(tmp_path) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32"), chained=True) + job.run(orchestrator=AsyncPipelineOrchestrator()) + double, increment = job.nodes["double"], job.nodes["increment"] + increment.clear_cache() + independent = _build(InMemoryArrowDatabase(), _source_table("uint32")).nodes["src"] + + starts: list[str] = [] + + class Starts(NoOpObserver): + def contextualize(self, *identity_path: str) -> Starts: + return self + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + starts.append(node_label) + + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(double) + dag.add_node(independent) + dag.add_edge(double, increment) + held = {double: rows_on_read(double.iter_data(), double)} + with pytest.raises(pa.ArrowInvalid): + SyncPipelineOrchestrator().run(dag, observer=Starts(), held=held) + assert starts == ["src"] diff --git a/tests/test_core/function_pod/test_function_pod_ctx_arg.py b/tests/test_core/function_pod/test_function_pod_ctx_arg.py index 9a4460448..4ab26113a 100644 --- a/tests/test_core/function_pod/test_function_pod_ctx_arg.py +++ b/tests/test_core/function_pod/test_function_pod_ctx_arg.py @@ -156,14 +156,14 @@ def my_fn(value: int, ctx: InvocationContext) -> str: node1 = FunctionJobNode(function_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=pipeline_db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 2 assert call_count == 2 # Second run — same pod, same data, same DB — must NOT call fn again node2 = FunctionJobNode(function_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=pipeline_db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 2 assert call_count == 2 # NOT incremented diff --git a/tests/test_core/nodes/test_function_node_iteration.py b/tests/test_core/nodes/test_function_node_iteration.py index 29b5123eb..d5b79758e 100644 --- a/tests/test_core/nodes/test_function_node_iteration.py +++ b/tests/test_core/nodes/test_function_node_iteration.py @@ -9,6 +9,8 @@ from unittest.mock import patch +from typing import Any + import pyarrow as pa import pytest @@ -171,11 +173,17 @@ def sometimes_fail(x: int) -> int: from orcapod.pipeline.observer import NoOpObserver class CapturingObserver(NoOpObserver): - def on_data_crash(self, node_label, tag, data, exc): - errors.append(exc) - - results = node.execute( - node._input_stream, observer=CapturingObserver(), error_policy="continue" + def on_data_crash( + self, node_label: str, tag: Any, data: Any, error: Exception + ) -> None: + errors.append(error) + + results = list( + node.execute( + node._input_stream, + observer=CapturingObserver(), + error_policy="continue", + ).iter_data() ) assert len(errors) == 1 assert isinstance(errors[0], ValueError) diff --git a/tests/test_core/nodes/test_node_execute.py b/tests/test_core/nodes/test_node_execute.py index 447ad1c1e..b34401b7e 100644 --- a/tests/test_core/nodes/test_node_execute.py +++ b/tests/test_core/nodes/test_node_execute.py @@ -101,7 +101,7 @@ def test_caches_internally(self, function_node_with_db): class TestFunctionNodeExecute: def test_returns_materialized_results(self, function_node_with_db): node, _, _ = function_node_with_db - results = node.execute(node._input_stream) + results = list(node.execute(node._input_stream).iter_data()) assert isinstance(results, list) assert len(results) == 2 values = sorted([pkt.as_dict()["result"] for _, pkt in results]) @@ -162,7 +162,7 @@ def operator_no_db(): class TestOperatorNodeExecute: def test_returns_materialized_results(self, operator_no_db): node, src = operator_no_db - results = node.execute(src) + results = list(node.execute(src).iter_data()) assert isinstance(results, list) assert len(results) == 2 @@ -181,6 +181,6 @@ def test_caches_internally(self, operator_no_db): def test_noop_db_in_off_mode(self, operator_no_db): node, src = operator_no_db - results = node.execute(src) + results = list(node.execute(src).iter_data()) assert len(results) == 2 assert node.get_all_records() is None diff --git a/tests/test_core/operators/test_materialize_source_info.py b/tests/test_core/operators/test_materialize_source_info.py index c6fee9a91..51368151b 100644 --- a/tests/test_core/operators/test_materialize_source_info.py +++ b/tests/test_core/operators/test_materialize_source_info.py @@ -1,7 +1,7 @@ """Every materialized row keeps its own source info (ITL-845). ``StaticOutputOperatorPod._materialize_to_stream`` and -``SyncPipelineOrchestrator._materialize_as_stream`` turn collected (Tag, Data) +``StaticOutputOperatorPod._materialize_upstream`` turn collected (Tag, Data) pairs back into a stream. They used to read row 0's source info and stamp it on every row, so rows from index 1 onward were attributed to row 0. These tests send rows with distinct source-info tokens through every path that materializes @@ -42,7 +42,6 @@ from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.sources import ArrowTableSource, DictSource from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase -from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants @@ -136,9 +135,9 @@ def _materialize(rows: Sequence[Row]) -> StreamProtocol: def _materialize_buffer(buf: Sequence[Row], node: Any) -> StreamProtocol: - """Call ``SyncPipelineOrchestrator._materialize_as_stream``, the helper under test.""" + """Call ``StaticOutputOperatorPod._materialize_upstream``, the helper under test.""" # Non-public on purpose: these tests are about this helper itself. - return SyncPipelineOrchestrator._materialize_as_stream(list(buf), node) # pyright: ignore[reportPrivateUsage] + return StaticOutputOperatorPod._materialize_upstream(list(buf), node) # pyright: ignore[reportPrivateUsage] def _broadcast_row_zero(monkeypatch: pytest.MonkeyPatch) -> None: @@ -155,9 +154,29 @@ def broadcasting( [(tag, data.with_source_info(**row_zero)) for tag, data in rows] ) + original_form = StaticOutputOperatorPod._row_built_form # pyright: ignore[reportPrivateUsage] + + def broadcasting_form( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] + ) -> pa.Table: + """Stamp row 0's source info on every row of the row-built form (ITL-1347).""" + formed = original_form(table, keys) + for i, name in enumerate(formed.column_names): + if name.startswith(constants.SOURCE_PREFIX): + column = formed.column(i) + first = column.slice(0, 1).combine_chunks() + repeated = pa.concat_arrays([first] * formed.num_rows) + formed = formed.set_column(i, formed.schema.field(i), repeated) + return formed + monkeypatch.setattr( StaticOutputOperatorPod, "_rows_to_table", staticmethod(broadcasting) ) + # An operator node keeps the row-built form of its result's table, without + # making the rows (ITL-1347, stage 2). + monkeypatch.setattr( + StaticOutputOperatorPod, "_row_built_form", staticmethod(broadcasting_form) + ) def _stored_source(node: OperatorJobNode, column: str = "x") -> list[Any]: @@ -688,7 +707,7 @@ def test_rerun_after_pre_fix_store(self, monkeypatch: pytest.MonkeyPatch): assert _stored_source(old) == [tokens[0]] * 3 new = self._node(db) - out = new.execute(_pin_source()) + out = list(new.execute(_pin_source()).iter_data()) # The run itself emits the corrected rows. assert _source_info_tokens(out) == tokens diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 6615b8867..61f08be7e 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -603,15 +603,11 @@ def _schema_outcome(make: Callable[[], StreamProtocol]) -> tuple[str, Any]: @pytest.mark.parametrize("layout", ["one_batch", "one_row_per_batch"]) -def test_empty_source_info_lists_are_outside_the_row_built_forms_domain( - layout: str, -) -> None: - """Pins a documented exception of F (``_row_built_form``): F equals the table built - from rows for every stream whose source-info tokens are strings or non-empty - lists, which is every stream a source or an operator makes. A hand-built raw - stream whose source-info column is a nested list type holding only empty lists is - outside that domain: the channel keeps the column's two list levels, while the - job's sync path rebuilds the tokens from their values and gives one.""" +def test_empty_source_info_lists_are_typed_from_their_tokens(layout: str) -> None: + """A raw stream whose source-info column is a nested list type holding only empty + lists: the channel's result equals the job's sync path, both typing the tokens from + their values over the complete table (``_type_source_info_by_values``), as the rows + do: one list level, not the column's two.""" raw = ArrowTableStream( pa.table( { @@ -629,11 +625,9 @@ def test_empty_source_info_lists_are_outside_the_row_built_forms_domain( job_sync = _job_sync(SelectDataColumns(["x"]), raw) got = channel.as_table(columns=ALL) rebuilt = job_sync.as_table(columns=ALL) - assert got.to_pylist() == rebuilt.to_pylist() # the same rows - assert got.schema.field("_source_x").type == pa.large_list( - pa.large_list(pa.large_string()) - ) - assert rebuilt.schema.field("_source_x").type == pa.large_list(pa.large_string()) + assert got.to_pylist() == rebuilt.to_pylist() + assert got.schema.equals(rebuilt.schema) + assert got.schema.field("_source_x").type == pa.large_list(pa.large_string()) def test_a_system_tag_with_a_null_is_refused_by_the_job_sync_path() -> None: diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py new file mode 100644 index 000000000..c511d1b5c --- /dev/null +++ b/tests/test_core/operators/test_row_built_form.py @@ -0,0 +1,409 @@ +"""F, the row-built form of a table, equals the table built from its rows (ITL-1347, L0). + +``StaticOutputOperatorPod._row_built_form`` (F in the spec, +``docs/dev/specs/itl-1347-job-table-transport.md``) gives a node's output table as +``_rows_to_table`` (R) builds it from the node's rows, without making the rows. Every +operator, column role and arrangement of the async-sync matrix is checked: the column +names and their order, every field (type, nullability, field metadata), the schema +metadata, and every value (floats by their bits). + +Two properties each case covers by construction: + +- A data-tag's source info comes first among the source info, in tag order, whatever + its column's place in the table (``source_mid``, ``tag_by``): a row lists its source + info in the order of its data keys. +- A system-tag field is nullable only when a value is null: a join over inputs tied on + pipeline hash (``ref_join_3_tied``) declares its system tags nullable, a table built + from rows does not. +""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa +import pyarrow.compute as pc +import pytest + +from orcapod import PipelineJob +from orcapod.core.operators import Batch, DropNulls, SelectDataColumns +from orcapod.core.operators.static_output_pod import ( + SourceInfoTypesDisagree, + StaticOutputOperatorPod, +) +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline.observer import NoOpObserver +from orcapod.types import CacheMode +from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns +from orcapod.system_constants import constants +from tests.test_core.operators.test_async_sync_equivalence import ( + AFTER_OPERATOR_CASES, + CASES, + FUNCTION_POD_CASES, + Case, +) + + +_FLOAT_BITS = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()} + + +def _as_bits(array: Any) -> Any: # pyright: ignore[reportExplicitAny] # any Arrow array kind + """``array``'s values, with every float, at any depth, as its bit pattern. + + Arrow's ``equals`` holds NaN unequal to itself, so floats are compared as unsigned + integers of their width. Lists and structs are taken apart into their validity, their + lengths and their children's values, so the physical layout (a list's first offset, + the bytes behind a null) does not count. + """ + kind = array.type + if isinstance(array, pa.ExtensionArray): + return ("extension", _as_bits(array.storage)) + if pa.types.is_floating(kind): + filled = pc.if_else(pc.is_null(array), pa.scalar(0, kind), array) + return ("float", array.is_null(), filled.view(_FLOAT_BITS[kind.bit_width])) + if pa.types.is_map(kind): + return ( + "map", + array.is_null(), + pc.list_value_length(array), + _as_bits(array.keys), + _as_bits(array.items), + ) + if ( + pa.types.is_list(kind) + or pa.types.is_large_list(kind) + or pa.types.is_fixed_size_list(kind) + ): + return ( + "list", + array.is_null(), + pc.list_value_length(array), + _as_bits(array.flatten()), + ) + if pa.types.is_struct(kind): + return ( + "struct", + array.is_null(), + tuple(_as_bits(child) for child in array.flatten()), + ) + return ("value", array) + + +def assert_same_values(formed: pa.Table, built: pa.Table) -> None: + """Every column of ``formed`` holds the values of ``built``, floats by their bits. + + The physical layout (a list's first offset, the bytes behind a null) is not a + value and may differ. + """ + for name in built.column_names: + expected, got = built.column(name), formed.column(name) + assert got.type == expected.type, name + assert _as_bits(got.combine_chunks()) == _as_bits(expected.combine_chunks()), ( + name + ) + + +def _all_cases() -> list[Any]: + cases: list[Any] = [pytest.param(c, id=c.label) for c in CASES] + cases += list(AFTER_OPERATOR_CASES) + cases += [pytest.param(c, id=f"fp-{c.label}") for c in FUNCTION_POD_CASES] + return cases + + +@pytest.mark.parametrize("case", _all_cases()) +def test_row_built_form_equals_the_table_built_from_rows(case: Case) -> None: + """F of an operator's result table equals R of its rows, field and bit for bit.""" + result = case.make_op()(*case.make_sources()) + rows = list(result.iter_data()) + if not rows: + pytest.skip("no rows: F is defined on a table with rows") + built, _, _ = StaticOutputOperatorPod._rows_to_table(rows) # pyright: ignore[reportPrivateUsage] # R, the oracle + formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + result.as_table(columns=ZERO_ROW_INPUT_COLUMNS), result.keys() + ) + assert formed.column_names == built.column_names + assert formed.schema.equals(built.schema, check_metadata=True) + assert_same_values(formed, built) + + +def test_row_built_columns_is_the_same_on_every_slice() -> None: + """The row-by-row steps of F give the same columns on a slice as on the whole.""" + case = next(c for c in CASES if c.label == "ref_join_3_tied") + result = case.make_op()(*case.make_sources()) + table = result.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + keys = result.keys() + whole = row_built_columns(table, keys) + for start in range(table.num_rows): + part = row_built_columns(table.slice(start, 1), keys) + assert part.schema.equals(whole.schema, check_metadata=True) + assert part.equals(whole.slice(start, 1)) + + +def _raw_stream() -> ArrowTableStream: + """A raw stream with provenance fields no source writes (Codex on PR #483). + + A system-tag field with field metadata, a list-valued source-info column whose item + field is named ``member`` and non-nullable, and a meta (``__``) data column with + its own source info. + """ + system_tag = f"{constants.SYSTEM_TAG_PREFIX}source_id::abc" + member = pa.field("member", pa.large_string(), nullable=False) + table = pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "j": pa.array(["a", "b"], pa.large_string()), + system_tag: pa.array(["s1", "s2"], pa.large_string()), + "x": pa.array([1.0, float("nan")]), + "z": pa.array([3, None], pa.int8()), + "__note": pa.array(["a", "b"]), + "_source_x": pa.array([["a", "b"], ["c"]], pa.large_list(member)), + "_source_z": pa.array(["t1", "t2"], pa.large_string()), + "_source___note": pa.array(["n1", "n2"], pa.large_string()), + } + ) + position = table.schema.get_field_index(system_tag) + schema = table.schema.set( + position, table.schema.field(position).with_metadata({b"m": b"v"}) + ) + return ArrowTableStream( + pa.Table.from_arrays(table.columns, schema=schema), tag_columns=["k", "j"] + ) + + +@pytest.mark.parametrize( + "make", + [ + pytest.param(_raw_stream, id="raw"), + pytest.param( + lambda: SelectDataColumns(["z", "x"])(_raw_stream()), id="select-z-x" + ), + pytest.param(lambda: DropNulls(["j", "k"])(_raw_stream()), id="drop-nulls"), + ], +) +def test_row_built_form_of_a_raw_stream(make: Any) -> None: + """F equals R on a raw stream: provenance fields as rows build them, no meta. + + R takes a system tag and a source-info token from its values, so the system-tag + field has no metadata and a list token's item field is nullable ``item``; a meta + column is not data, so neither it nor its source info is passed on. + """ + stream = make() + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle + formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + ) + assert "__note" not in formed.column_names + assert "_source___note" not in formed.column_names + assert formed.column_names == built.column_names + assert formed.schema.equals(built.schema, check_metadata=True) + assert_same_values(formed, built) + + +def _source_table() -> pa.Table: + """A source's table with its system tags and source info (one tag, one data).""" + from orcapod.sources import DictSource + + source = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + return source.as_table(columns={"source": True, "system_tags": True}) + + +def _with_source_x(values: list[Any], kind: pa.DataType) -> ArrowTableStream: + """A source's rows as a raw stream, ``_source_x`` replaced by ``values`` of ``kind``. + + It keeps the source's system-tag pair, so a job slot accepts it (Codex on PR #485). + """ + table = _source_table() + position = table.schema.get_field_index("_source_x") + return ArrowTableStream( + table.set_column( + position, + pa.field("_source_x", kind, nullable=True), + pa.array(values, kind), + ), + tag_columns=["k"], + ) + + +_STRINGS = pa.large_list(pa.large_string()) +_NESTED = pa.large_list(_STRINGS) + + +@pytest.mark.parametrize( + "make", + [ + pytest.param(lambda: _with_source_x([[], []], _NESTED), id="empty-lists"), + pytest.param(lambda: _with_source_x([None, None], _STRINGS), id="null-lists"), + pytest.param( + lambda: _with_source_x([[None], [None]], _NESTED), id="lists-of-null" + ), + pytest.param( + lambda: Batch(batch_size=1)( + _with_source_x([None, None], pa.large_string()) + ), + id="batch-1-of-null-tokens", + ), + pytest.param( + lambda: Batch(batch_size=2)(_with_source_x([None, None], _STRINGS)), + id="batch-2-of-null-lists", + ), + pytest.param(lambda: _with_source_x([None, None], pa.null()), id="null-type"), + ], +) +def test_source_info_types_follow_the_tokens(make: Any) -> None: + """F types each source-info column from its tokens, as the rows do. + + A list of ``None`` or of empty lists shows fewer levels than its column declares; + the rows type it from the tokens (``arrow_utils.source_info_arrow_type``), and so + does F, over the whole table. + """ + stream = make() + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle + formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + ) + assert formed.column_names == built.column_names + assert formed.schema.equals(built.schema, check_metadata=True) + assert_same_values(formed, built) + + +def test_tokens_of_two_types_raise_as_the_rows_do() -> None: + """A list token on one row and ``None`` on another: no table holds both rows. + + The rows' tables cannot be concatenated (``ArrowInvalid``); F says so + (``SourceInfoTypesDisagree``), and a node then builds the rows, which raise. + """ + stream = _with_source_x([["s"], None], _STRINGS) + with pytest.raises(pa.ArrowInvalid, match="Schema at index 1 was different"): + StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle + with pytest.raises(SourceInfoTypesDisagree, match="_source_x"): + StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + ) + + +class _NodeEvents(NoOpObserver): + """Records node starts and ends.""" + + def __init__(self) -> None: + self.events: list[tuple[str, str]] = [] + + def contextualize(self, *identity_path: str) -> _NodeEvents: + return self + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + self.events.append(("start", node_label)) + + def on_node_end(self, node_label: str, node_hash: str) -> None: + self.events.append(("end", node_label)) + + +def _batched_job(database: InMemoryArrowDatabase) -> PipelineJob: + """``source -> select x -> Batch(2)``, the batch node in ``LOG`` mode.""" + from orcapod.sources import DictSource + + source = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + job = PipelineJob(name="source_info_types", database=database) + with job: + Batch(batch_size=2)(source.select_data_columns(["x"]), label="batched") + job.nodes["batched"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + return job + + +def test_a_job_keeps_and_stores_the_token_type_the_rows_give() -> None: + """A bound raw source with null list tokens, through ``Batch(2)`` in ``LOG`` mode. + + The rows type ``[None, None]`` as ``large_list``: kept and stored so, + as on ``main``, not as the list of the input's declared list type. + """ + database = InMemoryArrowDatabase() + job = _batched_job(database) + job.bind(sources={"s": _with_source_x([None, None], _STRINGS)}) + job.run() + node = job.nodes["batched"] + kept = node.as_table(columns={"source": True}) + assert kept.schema.field("_source_x").type == _STRINGS + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + assert stored.schema.field("_source_x").type == _STRINGS + + +def test_a_job_over_tokens_of_two_types_fails_as_main_does() -> None: + """The run raises the rows' ``ArrowInvalid`` after the source node has ended. + + On ``main`` the source node hands its rows on, and the run fails where they are + concatenated for its successor: the same error, after the same events. + """ + job = _batched_job(InMemoryArrowDatabase()) + job.bind(sources={"s": _with_source_x([["s"], None], _STRINGS)}) + observer = _NodeEvents() + with pytest.raises(pa.ArrowInvalid, match="Schema at index 1 was different"): + job.run(observer=observer) + assert observer.events == [("start", "s"), ("end", "s")] + + +def test_a_source_with_a_nullable_system_tag_is_not_bound() -> None: + """A system-tag field with a null never reaches a job: a slot refuses the source. + + So F never meets one; ``_rows_to_table`` could not build its rows (two rows would + give the field two nullability flags). + """ + from orcapod import PipelineJob + from orcapod.databases import InMemoryArrowDatabase + from orcapod.errors import SourceSpecMismatchError + from orcapod.sources import DictSource + + source = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + job = PipelineJob(name="nullable_system_tag", database=InMemoryArrowDatabase()) + with job: + source.select_data_columns(["x"], label="selected") + table = _source_table() + record_id = next( + name + for name in table.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) and "record_id" in name + ) + position = table.schema.get_field_index(record_id) + with_null = table.set_column( + position, + pa.field(record_id, pa.large_string(), nullable=True), + pa.array(["row_0", None], pa.large_string()), + ) + slot = next(label for label in job.nodes if label != "selected") + with pytest.raises(SourceSpecMismatchError, match="record_id"): + job.bind(sources={slot: ArrowTableStream(with_null, tag_columns=["k"])}) + + +def test_a_token_the_rows_cannot_convert_fails_as_main_does() -> None: + """A conversion failure of F's whole-table build falls back to the rows, as on main. + + Each row's token ``[None, [[]]]`` gives one list level (``source_info_arrow_type``), + whose conversion fails (``ArrowTypeError``). The node builds its rows, which raise + the same error, after the source node has ended (Codex on PR #485, round 2). + """ + nested = pa.large_list(_NESTED) + job = _batched_job(InMemoryArrowDatabase()) + job.bind(sources={"s": _with_source_x([[None, [[]]], [None, [[]]]], nested)}) + observer = _NodeEvents() + with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): + job.run(observer=observer) + assert observer.events == [("start", "s"), ("end", "s")] diff --git a/tests/test_core/side_effect_function/test_side_effect_function_pod.py b/tests/test_core/side_effect_function/test_side_effect_function_pod.py index ae7d470d1..0543c1ab7 100644 --- a/tests/test_core/side_effect_function/test_side_effect_function_pod.py +++ b/tests/test_core/side_effect_function/test_side_effect_function_pod.py @@ -176,14 +176,14 @@ def my_fn(value: int, ctx: InvocationContext) -> str: node1 = FunctionJobNode(function_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=pipeline_db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 2 assert call_count == 2 # Second run — same pod, same data, same DB — fn must NOT be called again node2 = FunctionJobNode(function_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=pipeline_db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 2 assert call_count == 2 # NOT incremented — cache hit diff --git a/tests/test_core/side_effect_pod/test_side_effect_pod.py b/tests/test_core/side_effect_pod/test_side_effect_pod.py index 18be593e4..f5eb4487d 100644 --- a/tests/test_core/side_effect_pod/test_side_effect_pod.py +++ b/tests/test_core/side_effect_pod/test_side_effect_pod.py @@ -320,7 +320,7 @@ def fn(value, ctx): calls.append(True) node, stream, db = self._make_node_with_db(fn) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 3 assert len(calls) == 3 @@ -356,14 +356,14 @@ def fn(value, ctx): node1 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 2 assert len(calls) == 2 # Second run with same DB node2 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 2 # rows still emitted (pass-through) assert len(calls) == 2 # fn NOT called again — completion check triggered @@ -441,7 +441,7 @@ def fn(value, ctx): # Run 1: fn raises → nothing written to DB. node1 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 1 # row still emitted (drop_on_failure=False) assert call_count == 1 # fn was invoked @@ -451,7 +451,7 @@ def fn(value, ctx): # Run 2: no record found → fn is called again, still fails. node2 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 1 assert call_count == 2 # retried — fn called a second time @@ -490,7 +490,7 @@ def fn(value, ctx): # Run 1: fn raises → no DB record. node1 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 1 # emitted despite failure assert call_count == 1 @@ -500,7 +500,7 @@ def fn(value, ctx): # Run 2: no record → fn retried → succeeds → record written. node2 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 1 assert call_count == 2 # fn called exactly once more @@ -512,7 +512,7 @@ def fn(value, ctx): # Run 3: record found → fn NOT called → row re-emitted from cache. node3 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node3.attach_databases(pipeline_database=db) - results3 = node3.execute(stream) + results3 = list(node3.execute(stream).iter_data()) assert len(results3) == 1 assert call_count == 2 # still 2 — fn was skipped entirely diff --git a/tests/test_core/sources/test_postgresql_table_source_integration.py b/tests/test_core/sources/test_postgresql_table_source_integration.py index 46592b213..8dca286db 100644 --- a/tests/test_core/sources/test_postgresql_table_source_integration.py +++ b/tests/test_core/sources/test_postgresql_table_source_integration.py @@ -253,7 +253,9 @@ def double_response(trial: int, response: float) -> float: result = orch.run(exec_dag) fn_outputs = [ - v for k, v in result.node_outputs.items() if k.node_type == "function" + list(v.iter_data()) + for k, v in result.node_outputs.items() + if k.node_type == "function" ] assert len(fn_outputs) == 1 assert len(fn_outputs[0]) == 3 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 db78b7787..05a84a55f 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -1933,7 +1933,9 @@ def test_execute_over_unrestricted_streams_still_caches( (("m2", 5), 5.5, 1), ] - logged = node.execute(_source(source_id="events", tag_only_columns=True)) + logged = list( + node.execute(_source(source_id="events", tag_only_columns=True)).iter_data() + ) assert self._keyed(logged) == expected stored = node.as_source().as_table().to_pylist() @@ -1952,7 +1954,7 @@ def test_execute_over_unrestricted_streams_still_caches( ) scans = len(fake_pyspiral.scan_log) - replayed = node.execute(other) + replayed = list(node.execute(other).iter_data()) assert self._keyed(replayed) == expected assert len(fake_pyspiral.scan_log) == scans diff --git a/tests/test_core/sources/test_sqlite_table_source.py b/tests/test_core/sources/test_sqlite_table_source.py index fe74de6ce..91008dc35 100644 --- a/tests/test_core/sources/test_sqlite_table_source.py +++ b/tests/test_core/sources/test_sqlite_table_source.py @@ -611,7 +611,9 @@ def double_response(trial: int, response: float) -> float: result = orch.run(exec_dag) fn_outputs = [ - v for k, v in result.node_outputs.items() if k.node_type == "function" + list(v.iter_data()) + for k, v in result.node_outputs.items() + if k.node_type == "function" ] assert len(fn_outputs) == 1 assert len(fn_outputs[0]) == 3 diff --git a/tests/test_core/test_tracker.py b/tests/test_core/test_tracker.py index 8f28798be..046239abb 100644 --- a/tests/test_core/test_tracker.py +++ b/tests/test_core/test_tracker.py @@ -251,7 +251,7 @@ def test_run_equivalent(self): """execute() on SourceJobNode returns all data rows.""" stream = _make_source() node = self._make_job_node(stream) - result = node.execute() + result = list(node.execute().iter_data()) assert len(result) == stream.as_table().num_rows def test_data_context_key(self): diff --git a/tests/test_pipeline/test_declared_slot_one_data_tag.py b/tests/test_pipeline/test_declared_slot_one_data_tag.py new file mode 100644 index 000000000..88fcc4045 --- /dev/null +++ b/tests/test_pipeline/test_declared_slot_one_data_tag.py @@ -0,0 +1,87 @@ +"""A declared slot over a narrower source with one data-tag among two tags (ITL-1366). + +A source slot declared from a source whose ``x`` is ``int | None``, bound to the same +table with ``x: int`` (a narrower source, given as the declared schema), feeding an +operator. On ``main`` the run raises ``ValueError`` ("Duplicate column name") where the +source's rows are rebuilt for its successor, when exactly one of the two tags is a +data-tag and the tags are declared ``j, k`` (ITL-1366, a ``main`` bug fixed there +separately). A narrower bind hands on its rows as ``main`` gives them (``RowsOnRead``), +built where the successor reads them: the branch raises the same error at the same +point, on the sync and the async path, and completes every other arrangement. +""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.sources import ArrowTableSource + +ROWS = [ + {"j": 3, "k": 5, "x": 1, "y": 7.5}, + {"j": 4, "k": 6, "x": 2, "y": 8.5}, +] + +ROLES: dict[str, bool | tuple[str, ...]] = { + "no_data_tag": True, + "k_data_tag": ("j",), + "j_data_tag": ("k",), + "both_data_tags": (), +} + + +def _source(nullable_x: bool, order: tuple[str, str], roles: Any) -> ArrowTableSource: + table = pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ) + table = table.cast( + pa.schema([f.with_nullable(f.name == "x" and nullable_x) for f in table.schema]) + ) + return ArrowTableSource( + table, tag_columns=list(order), tag_only_columns=roles, source_id="s" + ) + + +def _bound_job(order: tuple[str, str], roles: Any) -> PipelineJob: + """The slot declared with ``x: int | None``, bound to the table with ``x: int``.""" + job = PipelineJob(name="declared_one_data_tag", database=InMemoryArrowDatabase()) + with job: + _source(True, order, roles).select_data_columns(["y", "x"], label="selected") + slot = next(label for label in job.nodes if label != "selected") + job.bind(sources={slot: _source(False, order, roles)}) + return job + + +def _rows(job: PipelineJob) -> list[dict[str, Any]]: + table = job.nodes["selected"].as_table() + return sorted(table.to_pylist(), key=lambda row: row["j"]) + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("roles", list(ROLES), ids=list(ROLES)) +@pytest.mark.parametrize("order", [("j", "k"), ("k", "j")], ids=["j-k", "k-j"]) +def test_the_run_is_as_on_main( + order: tuple[str, str], roles: str, asynchronous: bool +) -> None: + """Raises where ``main`` raises (ITL-1366), else gives the bound table's rows.""" + job = _bound_job(order, ROLES[roles]) + kwargs: dict[str, Any] = ( + {"orchestrator": AsyncPipelineOrchestrator()} if asynchronous else {} + ) + raises_on_main = order == ("j", "k") and roles in ("k_data_tag", "j_data_tag") + if raises_on_main: + with pytest.raises(ValueError, match="Duplicate column name"): + job.run(**kwargs) + else: + job.run(**kwargs) + assert _rows(job) == ROWS diff --git a/tests/test_pipeline/test_error_policy_continue.py b/tests/test_pipeline/test_error_policy_continue.py index 31ad95450..88e99241c 100644 --- a/tests/test_pipeline/test_error_policy_continue.py +++ b/tests/test_pipeline/test_error_policy_continue.py @@ -14,6 +14,7 @@ from orcapod.core.sources import ArrowTableSource from orcapod.databases import InMemoryArrowDatabase from orcapod.pipeline.job import PipelineJob +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator @@ -80,7 +81,7 @@ def identity(value: int) -> int: # Don't run — buffer will be empty node = job.nodes["fn"] - stream = SyncPipelineOrchestrator._materialize_as_stream([], node) + stream = StaticOutputOperatorPod._materialize_upstream([], node) tag_schema, data_schema = stream.output_schema() # "result" is declared as int (required), must NOT become int | None diff --git a/tests/test_pipeline/test_held_streams_on_read.py b/tests/test_pipeline/test_held_streams_on_read.py new file mode 100644 index 000000000..daed771fc --- /dev/null +++ b/tests/test_pipeline/test_held_streams_on_read.py @@ -0,0 +1,112 @@ +"""Held streams and async outputs are built when read (ITL-1360; Codex on PR #485). + +A run plan's held streams (``RunPlan.held``) and the async orchestrator's +``node_outputs`` are ``StreamsOnRead``: a node's stream is built from its rows when it +is read. Membership, length and iteration never build one; the plan keeps no held +stream it has built, so the sync orchestrator releases it once its successors ran. +""" + +from __future__ import annotations + +import gc +import weakref +from typing import Any + +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline.observer import NoOpObserver +from orcapod.pipeline.result import StreamsOnRead +from orcapod.sources import DictSource + + +def test_membership_length_and_iteration_build_nothing() -> None: + """``in``, ``len`` and iteration read the nodes only; reading a value builds it.""" + + def build(rows: Any, node: Any) -> Any: + raise AssertionError(f"built {node}") + + outputs = StreamsOnRead({"a": [], "b": []}, build) + assert "a" in outputs + assert "c" not in outputs + assert len(outputs) == 2 + assert list(outputs) == ["a", "b"] + with pytest.raises(AssertionError, match="built a"): + _ = outputs["a"] + + +def test_a_kept_stream_is_built_once_and_an_unkept_one_each_read() -> None: + built: list[Any] = [] + + def build(rows: Any, node: Any) -> Any: + built.append(node) + return object() + + kept = StreamsOnRead({"a": []}, build) + assert kept["a"] is kept["a"] + unkept = StreamsOnRead({"a": []}, build, keep=False) + _ = unkept["a"] + _ = unkept["a"] + assert built == ["a", "a", "a"] + + +@function_pod(output_keys="y") +def step(x: int) -> int: + return x + 1 + + +def test_a_held_stream_is_released_once_its_successors_ran( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """``source -> a -> b -> c -> d`` with ``a`` held: its stream is gone when ``c`` starts.""" + job = PipelineJob(name="held_lifetime", database=InMemoryArrowDatabase()) + with job: + source = DictSource( + [{"k": i, "x": i} for i in range(3)], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + a: Any = step.pod(source, label="a") + b: Any = step.pod(a.map_data({"y": "x"}), label="b") + c: Any = step.pod(b.map_data({"y": "x"}), label="c") + step.pod(c.map_data({"y": "x"}), label="d") + job.run() + for label in ("b", "c", "d"): + job.nodes[label].clear_cache() + for node in job.nodes.values(): + if node.label.startswith("MapData"): + node.clear_cache() + + held: list[weakref.ref[Any]] = [] + original = StaticOutputOperatorPod._materialize_upstream # pyright: ignore[reportPrivateUsage] # the held stream's build + + def materialize(rows: Any, upstream: Any, **kwargs: Any) -> Any: + stream = original(rows, upstream, **kwargs) + if getattr(upstream, "label", None) == "a": + held.append(weakref.ref(stream)) + return stream + + monkeypatch.setattr( + StaticOutputOperatorPod, "_materialize_upstream", staticmethod(materialize) + ) + + alive_at_c: list[bool] = [] + + class AtC(NoOpObserver): + def contextualize(self, *identity_path: str) -> AtC: + return self + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + if node_label == "c": + gc.collect() + alive_at_c.append(any(ref() is not None for ref in held)) + + summary = job.run(observer=AtC(), materialize_results=False) + assert summary.nodes["a"].held == 3 + assert held + assert alive_at_c == [False] 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 6d00c1154..04ba3867a 100644 --- a/tests/test_pipeline/test_job_node_rows_after_run.py +++ b/tests/test_pipeline/test_job_node_rows_after_run.py @@ -422,7 +422,7 @@ def test_sync_one_of_two_equal_inputs_fails(self) -> None: node = self._node(self._flaky_pod()) received = sorted( (tag.as_dict()["k"], data.as_dict()["y"]) - for tag, data in node.execute(node.upstreams[0]) + for tag, data in list(node.execute(node.upstreams[0]).iter_data()) ) assert received == [(0, 6), (2, 8)] assert self._held(node) == received diff --git a/tests/test_pipeline/test_narrower_bind_order.py b/tests/test_pipeline/test_narrower_bind_order.py new file mode 100644 index 000000000..45bca4160 --- /dev/null +++ b/tests/test_pipeline/test_narrower_bind_order.py @@ -0,0 +1,124 @@ +"""A narrower bind hands on its rows in their order (ITL-1360, L2; Codex on PR #485). + +A source slot declared from a source whose ``x`` is ``int | None``, bound to the same +columns with ``x: int`` (a narrower source, given as the declared schema), feeding a +``Batch`` node in ``LOG`` mode. The source node hands on its rows as ``main`` gives +them (``_declared_rows``), built where the successor reads them (``RowsOnRead``). +Every pairing of declared layout, tag +order and data-tag roles must keep and store what the row path keeps and stores: the +same run with the source's output built from its rows +(``StaticOutputOperatorPod._materialize_upstream``), as on ``main``, also where the +row path raises (one data-tag of two, ITL-1366). +""" + +from __future__ import annotations + +import itertools +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.core.nodes.source_node import SourceNodeBase +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.operators import Batch +from orcapod.sources import ArrowTableSource +from orcapod.types import CacheMode + +ROLES: dict[str, bool | tuple[str, ...]] = { + "no_data_tag": True, + "a_data_tag": ("b",), + "b_data_tag": ("a",), + "both_data_tags": (), +} + + +def _source( + nullable_x: bool, layout: tuple[str, ...], tag_order: tuple[str, str], roles: Any +) -> ArrowTableSource: + columns = { + "x": pa.array([1, 2], pa.int64()), + "a": pa.array([5, 6], pa.int64()), + "b": pa.array([3, 4], pa.int64()), + } + table = pa.table({name: columns[name] for name in layout}) + table = table.cast( + pa.schema([f.with_nullable(f.name == "x" and nullable_x) for f in table.schema]) + ) + return ArrowTableSource( + table, tag_columns=list(tag_order), tag_only_columns=roles, source_id="s" + ) + + +def _run( + layout: tuple[str, ...], tag_order: tuple[str, str], roles: Any +) -> tuple[list[str], pa.Schema]: + """Run the job; return the batch node's kept columns and its raw stored schema.""" + database = InMemoryArrowDatabase() + job = PipelineJob(name="narrower_bind_order", database=database) + with job: + Batch(batch_size=2)(_source(True, layout, tag_order, roles), label="batched") + job.nodes["batched"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + slot = next(label for label in job.nodes if label != "batched") + job.bind(sources={slot: _source(False, ("x", "a", "b"), tag_order, roles)}) + job.run() + node = job.nodes["batched"] + kept = node.as_table(columns={"source": True}).column_names + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + return kept, stored.schema + + +def _row_path(monkeypatch: pytest.MonkeyPatch) -> None: + """Make every source node hand on its rows rebuilt, as on ``main``.""" + + def execute(self: Any, *, observer: Any = None) -> Any: + if observer is not None: + observer.on_node_start(self.label, self.content_hash().to_string()) + out = StaticOutputOperatorPod._materialize_upstream( + list(self.iter_data()), self + ) # pyright: ignore[reportPrivateUsage] # the row path + if observer is not None: + observer.on_node_end(self.label, self.content_hash().to_string()) + return out + + monkeypatch.setattr(SourceNodeBase, "execute", execute) + + +def _outcome(layout: tuple[str, ...], tag_order: tuple[str, str], roles: Any) -> Any: + """The run's kept columns and raw stored schema, or the error it raised.""" + try: + return _run(layout, tag_order, roles) + except ValueError as error: + return (type(error), str(error)) + + +@pytest.mark.parametrize("roles", list(ROLES), ids=list(ROLES)) +@pytest.mark.parametrize("tag_order", [("a", "b"), ("b", "a")], ids=["a-b", "b-a"]) +@pytest.mark.parametrize( + "layout", list(itertools.permutations(("a", "b", "x"))), ids="".join +) +def test_a_narrower_bind_keeps_and_stores_as_the_row_path( + layout: tuple[str, ...], + tag_order: tuple[str, str], + roles: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Kept columns and the raw stored schema equal the row path's, in order. + + Where the row path raises (one data-tag of two, ITL-1366, a ``main`` bug), the + branch raises the same error. + """ + got = _outcome(layout, tag_order, ROLES[roles]) + with monkeypatch.context() as patch: + _row_path(patch) + expected = _outcome(layout, tag_order, ROLES[roles]) + if isinstance(expected[1], str): + assert got == expected + return + assert got[0] == expected[0] + assert got[1].equals(expected[1], check_metadata=True) diff --git a/tests/test_pipeline/test_node_protocols.py b/tests/test_pipeline/test_node_protocols.py index fbd08b867..23482ce18 100644 --- a/tests/test_pipeline/test_node_protocols.py +++ b/tests/test_pipeline/test_node_protocols.py @@ -3,6 +3,8 @@ from __future__ import annotations +from typing import Any + import pytest from unittest.mock import MagicMock @@ -15,6 +17,7 @@ is_operator_node, ) import pyarrow as pa +from orcapod.pipeline.observer import NoOpObserver from orcapod.core.sources import ArrowTableSource from orcapod.core.nodes.source_node import SourceJobNode from orcapod.channels import Channel @@ -200,14 +203,14 @@ def _make_source_node(self): def test_execute_returns_list(self): node = self._make_source_node() - result = node.execute() + result = list(node.execute().iter_data()) assert isinstance(result, list) assert len(result) == 3 def test_execute_populates_cached_results(self): """execute() on SourceJobNode returns correct data (no caching field).""" node = self._make_source_node() - result = node.execute() + result = list(node.execute().iter_data()) assert len(result) == 3 def test_execute_with_observer(self): @@ -234,7 +237,7 @@ def on_data_end(self, node_label, t, ip, op, cached): def test_execute_without_observer(self): """execute() works fine with no observer.""" node = self._make_source_node() - result = node.execute() + result = list(node.execute().iter_data()) assert len(result) == 3 @@ -312,32 +315,33 @@ def test_execute_with_observer(self): node = self._make_function_node() events = [] - class Obs: - def contextualize(self, *identity_path): + class Obs(NoOpObserver): + def contextualize(self, *identity_path: str) -> Obs: return self - def on_node_start(self, node_label, node_hash, **kwargs): + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: events.append(("node_start", node_label)) - def on_node_end(self, node_label, node_hash, **kwargs): + def on_node_end(self, node_label: str, node_hash: str) -> None: events.append(("node_end", node_label)) - def on_data_start(self, node_label, t, p): + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: events.append(("data_start",)) - def on_data_end(self, node_label, t, ip, op, cached): + def on_data_end( + self, + node_label: str, + tag: Any, + input_data: Any, + output_data: Any, + cached: bool, + ) -> None: events.append(("data_end", cached)) - def on_data_crash(self, node_label, t, p, exc): - pass - - def create_data_logger(self, t, p, **kwargs): - from orcapod.pipeline.observer import _NOOP_LOGGER - - return _NOOP_LOGGER - input_stream = node._input_stream - result = node.execute(input_stream, observer=Obs()) + result = list(node.execute(input_stream, observer=Obs()).iter_data()) assert len(result) == 2 assert events[0][0] == "node_start" @@ -348,7 +352,7 @@ def create_data_logger(self, t, p, **kwargs): def test_execute_without_observer(self): node = self._make_function_node() input_stream = node._input_stream - result = node.execute(input_stream) + result = list(node.execute(input_stream).iter_data()) assert len(result) == 2 values = sorted([pkt.as_dict()["result"] for _, pkt in result]) assert values == [2, 4] @@ -472,30 +476,26 @@ def test_execute_with_observer(self): node = self._make_join_node() events = [] - class Obs: - def contextualize(self, *identity_path): + class Obs(NoOpObserver): + def contextualize(self, *identity_path: str) -> Obs: return self - def on_node_start(self, node_label, node_hash, **kwargs): + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: events.append(("node_start", node_label)) - def on_node_end(self, node_label, node_hash, **kwargs): + def on_node_end(self, node_label: str, node_hash: str) -> None: events.append(("node_end", node_label)) - def on_data_start(self, node_label, t, p): - pass - - def on_data_end(self, node_label, t, ip, op, cached): - pass - - result = node.execute(*node._input_streams, observer=Obs()) + result = list(node.execute(*node._input_streams, observer=Obs()).iter_data()) assert len(result) == 2 assert events[0][0] == "node_start" assert events[1][0] == "node_end" def test_execute_without_observer(self): node = self._make_join_node() - result = node.execute(*node._input_streams) + result = list(node.execute(*node._input_streams).iter_data()) assert len(result) == 2 diff --git a/tests/test_pipeline/test_operator_node_async_readback.py b/tests/test_pipeline/test_operator_node_async_readback.py index 7e7189be4..345d738a6 100644 --- a/tests/test_pipeline/test_operator_node_async_readback.py +++ b/tests/test_pipeline/test_operator_node_async_readback.py @@ -287,7 +287,7 @@ def make_node() -> OperatorJobNode: ) sync_node, async_node = make_node(), make_node() - sync_rows = sync_node.execute(source) + sync_rows = list(sync_node.execute(source).iter_data()) async def run() -> list[tuple[TagProtocol, DataProtocol]]: """Drive the node's public channel interface and collect forwarded rows.""" diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py new file mode 100644 index 000000000..2ffc76211 --- /dev/null +++ b/tests/test_pipeline/test_rows_on_read.py @@ -0,0 +1,1103 @@ +"""Outputs held as rows, built where a successor reads them (ITL-1347; Codex on PR #485). + +On every route where building a node's output from its whole table is not provably +``main``'s result, the node hands on its rows (``RowsOnRead``), built by ``main``'s row +path where the sync orchestrator gives them to a successor (``at_edge``). So the +order, the error and the moment it surfaces are ``main``'s: a narrower bind, a source +whose whole-table build is unavailable (its rows read once), a held node. A leaf +nobody reads is never built. +""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.operators import Batch +from orcapod.pipeline.dag import OrcaDAG +from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator +from orcapod.sources import ArrowTableSource, DictSource +from orcapod.types import CacheMode +from tests.test_core.operators.test_row_built_form import ( + _NESTED, # pyright: ignore[reportPrivateUsage] # the shared provenance fixtures + _NodeEvents, # pyright: ignore[reportPrivateUsage] + _source_table, # pyright: ignore[reportPrivateUsage] + _with_source_x, # pyright: ignore[reportPrivateUsage] +) + +_UNCONVERTIBLE = pa.large_list(_NESTED) + + +def _unconvertible() -> ArrowTableStream: + """Tokens ``[None, [[]]]``: the whole-table build is unavailable, the rows raise.""" + return _with_source_x([[None, [[]]], [None, [[]]]], _UNCONVERTIBLE) + + +def _plain() -> DictSource: + return DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + + +def test_a_fallback_source_reads_its_rows_once() -> None: + """A source whose whole-table build is unavailable: its rows are read once, when it + runs, and the successor's edge raises the rows' ``ArrowTypeError`` after the + source's end and before the successor starts, as on ``main``.""" + job = PipelineJob(name="read_once", database=InMemoryArrowDatabase()) + with job: + Batch(batch_size=2)( + _plain().select_data_columns(["x"], label="selected"), label="batched" + ) + source: Any = _unconvertible() + reads: list[int] = [] + read = source.iter_data + + def counted() -> Any: + reads.append(1) + return read() + + source.iter_data = counted + job.bind(sources={"s": source}) + observer = _NodeEvents() + with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): + job.run(observer=observer) + assert len(reads) == 1 + assert ("end", "s") in observer.events + assert ("start", "selected") not in observer.events + + +def test_a_fallback_source_nobody_reads_completes() -> None: + """A source whose rows cannot be built, as a leaf of a direct sync run: it completes. + + ``main`` never rebuilt a leaf's rows; neither does the branch (``RowsOnRead``). + """ + job = PipelineJob(name="leaf", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + job.bind(sources={"s": _unconvertible()}) + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(job.nodes["s"]) + observer = _NodeEvents() + SyncPipelineOrchestrator().run(dag, observer=observer, materialize_results=False) + assert observer.events == [("start", "s"), ("end", "s")] + + +def test_a_narrower_raw_bind_keeps_the_slots_system_tag_order() -> None: + """A raw stream whose system tags are record id then source id, bound narrower. + + ``main`` gives each row the slot's order (source id, then record id); so do the + kept and the raw stored tables (Codex on PR #485, round 3). + """ + from orcapod.system_constants import constants + + table = _source_table() + source_id = next(n for n in table.column_names if "source_id" in n) + record_id = next(n for n in table.column_names if "record_id" in n) + others = [n for n in table.column_names if n not in (source_id, record_id)] + reversed_pair = table.select([*others, record_id, source_id]) + raw = ArrowTableStream(reversed_pair, tag_columns=["k"]) + + database = InMemoryArrowDatabase() + job = PipelineJob(name="reversed_pair", database=database) + with job: + declared = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": None}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(declared, label="batched") + job.nodes["batched"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.bind(sources={"s": raw}) + job.run() + node = job.nodes["batched"] + kept = node.as_table(columns={"system_tags": True}).column_names + system_tags = [n for n in kept if n.startswith(constants.SYSTEM_TAG_PREFIX)] + assert ["source_id" in n for n in system_tags] == [True, False] + stored = node.get_all_records(columns={"system_tags": True}) + assert stored is not None + stored_tags = [ + n for n in stored.column_names if n.startswith(constants.SYSTEM_TAG_PREFIX) + ] + assert ["source_id" in n for n in stored_tags] == [True, False] + + +def test_a_narrower_bind_is_described_from_its_declared_schema() -> None: + """A narrower bind's description never places columns: its types are undeclared. + + With one data-tag among two tags (ITL-1366's input), the description does not + raise; ``arrow_types_declared`` is false (Codex on PR #485, round 3). + """ + table = pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ) + + def source(nullable_x: bool) -> ArrowTableSource: + fields = [f.with_nullable(f.name == "x" and nullable_x) for f in table.schema] + return ArrowTableSource( + table.cast(pa.schema(fields)), + tag_columns=["j", "k"], + tag_only_columns=("j",), + source_id="s", + ) + + job = PipelineJob(name="narrower_description", database=InMemoryArrowDatabase()) + with job: + source(True).select_data_columns(["y", "x"], label="selected") + slot = next(label for label in job.nodes if label != "selected") + job.bind(sources={slot: source(False)}) + node = job.nodes[slot] + schema = node.arrow_schema() + assert not node.arrow_types_declared + assert set(node.keys()[0]) <= set(schema.names) + + +def test_a_narrower_bind_channel_raises_as_its_rows_do() -> None: + """The source node's channel carries its rows: ITL-1366's input raises as on main. + + ``open_channel()`` reads the node's output, the rows built when read, which raise + the duplicate-column error ``main``'s row path raises. + """ + import asyncio + + table = pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ) + + def source(nullable_x: bool) -> ArrowTableSource: + fields = [f.with_nullable(f.name == "x" and nullable_x) for f in table.schema] + return ArrowTableSource( + table.cast(pa.schema(fields)), + tag_columns=["j", "k"], + tag_only_columns=("j",), + source_id="s", + ) + + job = PipelineJob(name="narrower_channel", database=InMemoryArrowDatabase()) + with job: + source(True).select_data_columns(["y", "x"], label="selected") + slot = next(label for label in job.nodes if label != "selected") + job.bind(sources={slot: source(False)}) + node: Any = job.nodes[slot] + with pytest.raises(ValueError, match="Duplicate column name"): + asyncio.run(node.open_channel().collect()) + + +def _replay_job(database: InMemoryArrowDatabase, *, with_successor: bool) -> Any: + """``source -> select x`` with the select node replaying from ``database``.""" + job = PipelineJob(name="replay_odd", database=InMemoryArrowDatabase()) + with job: + selected = _plain().select_data_columns(["x"], label="selected") + if with_successor: + Batch(batch_size=2)(selected, label="batched") + job.nodes["selected"].attach_databases( + pipeline_database=database, cache_mode=CacheMode.REPLAY + ) + return job + + +@pytest.mark.parametrize("with_successor", [False, True], ids=["leaf", "successor"]) +def test_replay_of_a_table_the_whole_table_build_cannot_use( + with_successor: bool, +) -> None: + """REPLAY of a stored table with unconvertible tokens hands on its rows. + + The node ends as usual; a leaf completes; a successor's edge raises the rows' + ``ArrowTypeError``, as ``main``'s row rebuild does (Codex on PR #485, round 3). + """ + logged = InMemoryArrowDatabase() + job = PipelineJob(name="replay_odd", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + node: Any = job.nodes["selected"] + node.attach_databases(pipeline_database=logged, cache_mode=CacheMode.LOG) + job.run() + path = node._stored_table_path # pyright: ignore[reportPrivateUsage] # the table to seed + stored = logged.get_all_records(path, record_id_column="__record_id") + assert stored is not None + position = stored.schema.get_field_index("_source_x") + odd = stored.set_column( + position, + pa.field("_source_x", _UNCONVERTIBLE, nullable=True), + pa.array([[None, [[]]]] * stored.num_rows, _UNCONVERTIBLE), + ) + seeded = InMemoryArrowDatabase() + seeded.add_records(path, odd, record_id_column="__record_id") + + replay = _replay_job(seeded, with_successor=with_successor) + observer = _NodeEvents() + if with_successor: + with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): + replay.run(observer=observer) + assert ("end", "selected") in observer.events + assert ("start", "batched") not in observer.events + else: + replay.run(observer=observer) + assert ("end", "selected") in observer.events + + +# ── round 4: the boundary of the eager route, and the lazy output itself ────── + + +DELIVERED: list[int] = [] + + +def _deliver(x: int, ctx: Any) -> None: + DELIVERED.append(x) + + +def _leaf_run(job: PipelineJob, label: str) -> _NodeEvents: + """Run only ``label`` (a source node), as a leaf of a direct sync DAG.""" + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(job.nodes[label]) + observer = _NodeEvents() + SyncPipelineOrchestrator().run(dag, observer=observer, materialize_results=False) + return observer + + +def test_a_bound_tap_stream_delivers_every_row_as_main_does() -> None: + """A side-effect stream bound to a slot is not a library source kind: its rows. + + The node iterates it as ``main`` did, delivering every row, and a leaf completes + (Codex on PR #485, round 4: the eager route read ``as_table()`` instead). + """ + from orcapod.side_effects import tap_pod + + tap: Any = tap_pod(_deliver) + DELIVERED.clear() + raw = _with_source_x([[None, [[]]], [None, [[]]]], _UNCONVERTIBLE) + tapped: Any = tap.process(raw) + job = PipelineJob(name="tap_bound", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + job.bind(sources={"s": tapped}) + observer = _leaf_run(job, "s") + assert DELIVERED == [1, 2] + assert observer.events == [("start", "s"), ("end", "s")] + + +@pytest.mark.parametrize( + "make", + [ + pytest.param(lambda: _plain().select_data_columns(["x"]), id="operator"), + pytest.param( + lambda: ArrowTableStream(_source_table(), tag_columns=["k"]), id="raw" + ), + ], +) +def test_a_bound_stream_that_is_not_a_source_kind_hands_on_its_rows(make: Any) -> None: + """Only a library source kind whose table is its rows (``TABLE_IS_ROWS``) is eager.""" + from orcapod.core.operators.static_output_pod import RowsOnRead + + job = PipelineJob(name="bound_kinds", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + job.bind(sources={"s": make()}) + assert isinstance(job.nodes["s"].execute(), RowsOnRead) + + +def test_a_library_source_kind_is_eager() -> None: + from orcapod.core.operators.static_output_pod import RowsOnRead + + job = PipelineJob(name="eager_kind", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + assert not isinstance(job.nodes["s"].execute(), RowsOnRead) + + +def test_an_empty_output_is_derived_at_the_edge( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A source with no row: its zero-row input is built where the successor reads it, + after the source has ended and before the successor starts, as ``main`` rebuilt + it (Codex on PR #485, round 4).""" + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + field = pa.field("x", pa.int64(), nullable=False) + table = pa.Table.from_arrays( + [pa.array([], pa.int64()), pa.array([], pa.int64())], + schema=pa.schema([pa.field("k", pa.int64(), nullable=False), field]), + ) + job = PipelineJob(name="empty_edge", database=InMemoryArrowDatabase()) + with job: + ArrowTableSource(table, tag_columns=["k"], source_id="s").select_data_columns( + ["x"], label="selected" + ) + slot = next(label for label in job.nodes if label != "selected") + observer = _NodeEvents() + original = StaticOutputOperatorPod._materialize_upstream # pyright: ignore[reportPrivateUsage] # the row path, watched + + def watched(rows: Any, upstream: Any) -> Any: + observer.events.append(("build", str(upstream.label))) + return original(rows, upstream) + + monkeypatch.setattr( + StaticOutputOperatorPod, "_materialize_upstream", staticmethod(watched) + ) + job.run(observer=observer) + events = observer.events + built = events.index(("build", slot)) + assert events.index(("end", slot)) < built < events.index(("start", "selected")) + assert job.nodes["selected"].as_table().num_rows == 0 + + +def test_an_operator_with_an_empty_result_is_not_called_again() -> None: + """An empty result's zero-row form is derived at the edge, never by a second call. + + An operator that raises on empty input completes as a leaf, as on ``main`` + (Codex on PR #485, round 4). + """ + from orcapod.operators import SelectDataColumns + + calls: list[int] = [] + + class EmptyThenRaises(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + rows = stream.as_table().num_rows + calls.append(rows) + if rows == 0: + raise ValueError("cannot process empty input") + result: Any = super().unary_static_process(stream) + return result.polars_filter(x=-1) + + job = PipelineJob(name="empty_result", database=InMemoryArrowDatabase()) + with job: + EmptyThenRaises(["x"])(_plain(), label="emptied") + observer = _NodeEvents() + job.run(observer=observer) + assert ("end", "emptied") in observer.events + assert 0 not in calls + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_returned_function_rows_keep_their_meta(asynchronous: bool) -> None: + """``node_outputs[node].iter_data()`` gives the node's own rows, meta included.""" + from orcapod import function_pod + from orcapod.pipeline import AsyncPipelineOrchestrator + + @function_pod(output_keys="y") + def plus(x: int) -> int: + return x + 1 + + job = PipelineJob(name="returned_rows", database=InMemoryArrowDatabase()) + with job: + plus.pod(_plain(), label="plus") + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_edge(job.nodes["s"], job.nodes["plus"]) + orchestrator: Any = ( + AsyncPipelineOrchestrator() if asynchronous else SyncPipelineOrchestrator() + ) + result = orchestrator.run(dag) + rows = list(result.node_outputs[job.nodes["plus"]].iter_data()) + assert rows + assert all("__computed" in data.keys(columns={"meta": True}) for _, data in rows) + + +def test_a_lazy_output_is_described_and_opened_without_reading() -> None: + """Describing an unread output, or opening its channel, builds nothing. + + The first read of the channel raises what the rows' build raises (Codex on PR + #485, round 4). + """ + import asyncio + + from orcapod.core.operators.static_output_pod import RowsOnRead + from orcapod.protocols.core_protocols import StreamProtocol + + job = PipelineJob(name="lazy_out", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + job.bind(sources={"s": _unconvertible()}) + out: Any = job.nodes["s"].execute() + assert isinstance(out, RowsOnRead) + assert isinstance(out, StreamProtocol) + assert not out.arrow_types_declared + assert "x" in out.arrow_schema().names + channel = out.open_channel() + assert out._stream is None # pyright: ignore[reportPrivateUsage] # nothing built + with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): + asyncio.run(channel.collect()) + + +# ── round 5 ────────────────────────────────────────────────────────────────── + + +def _subclass_overriding(member: str) -> type: + """An ``ArrowTableSource`` subclass that overrides ``member`` (reading as before).""" + from orcapod.core.sources import ArrowTableSource as Base + + def through(self: Any, *args: Any, **kwargs: Any) -> Any: + return getattr(super(cls, self), member)(*args, **kwargs) + + cls = type(f"Overrides_{member}", (Base,), {member: through}) + return cls + + +@pytest.mark.parametrize( + "member", + ["iter_data", "as_table", "__iter__", "async_iter_data", "keys", "output_schema"], +) +def test_a_subclass_that_overrides_a_reader_is_not_a_table_is_rows_kind( + member: str, +) -> None: + """``TABLE_IS_ROWS`` is not inherited past an override of how rows are read.""" + from orcapod.core.sources.base import table_is_rows + + table = _source_table().select(["k", "x"]) + cls = _subclass_overriding(member) + source = cls(table, tag_columns=["k"], tag_only_columns=True, source_id="s") + assert not table_is_rows(source) + plain = ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + assert table_is_rows(plain) + # Exact, never by inspection: a subclass that overrides nothing is not proven. + subclass = type("Plain", (ArrowTableSource,), {}) + assert not table_is_rows( + subclass(table, tag_columns=["k"], tag_only_columns=True, source_id="s") + ) + + +def test_a_filtering_subclass_delivers_only_its_rows() -> None: + """A subclass whose ``iter_data`` filters is read through it, as on ``main``.""" + + class AboveTen(ArrowTableSource): + def iter_data(self) -> Any: + return (row for row in super().iter_data() if row[1]["x"] > 10) + + table = pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}) + job = PipelineJob(name="filtering", database=InMemoryArrowDatabase()) + with job: + ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ).select_data_columns(["x"], label="selected") + job.bind( + sources={ + "s": AboveTen( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + } + ) + job.run() + assert job.nodes["selected"].as_table()["x"].to_pylist() == [20] + + +def test_an_operator_result_keeps_its_own_column_order() -> None: + """A result laid out ``y, x`` against a prediction ``x, y`` is kept, stored and + handed on as ``y, x``, as ``main`` built it from the result's rows.""" + from orcapod.operators import SelectDataColumns + + class Reordered(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + out: Any = super().unary_static_process(stream) + table = out.as_table(columns={"source": True, "system_tags": True}) + names = [n for n in table.column_names if n not in ("x", "y")] + plain = [n for n in names if not n.startswith("_source_")] + source = ["_source_y", "_source_x"] + rest = [n for n in names if n.startswith("_source_") and n not in source] + return ArrowTableStream( + table.select([*plain, "y", "x", *source, *rest]), tag_columns=["k"] + ) + + database = InMemoryArrowDatabase() + job = PipelineJob(name="reordered", database=database) + with job: + source = DictSource( + [{"k": 1, "x": 1, "y": 2}, {"k": 2, "x": 3, "y": 4}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(Reordered(["x", "y"])(source, label="reordered"), label="b") + job.nodes["reordered"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.run() + expected = ["k", "y", "x", "_source_y", "_source_x"] + node = job.nodes["reordered"] + assert node.as_table(columns={"source": True}).column_names == expected + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + assert [n for n in stored.column_names if not n.startswith("__")] == expected + assert job.nodes["b"].as_table(columns={"source": True}).column_names == expected + + +# ── final check: the eager route is positive and exact ──────────────────────── + + +def _only_above_ten(rows: Any) -> Any: + return (row for row in rows if row[1]["x"] > 10) + + +class _FilteringStream(ArrowTableStream): + def iter_data(self) -> Any: + return _only_above_ten(super().iter_data()) + + +class _ReadsThroughAProperty(ArrowTableSource): + """Reads through a ``_stream`` property that hands on a filtering stream.""" + + @property + def _stream(self) -> Any: + return getattr(self, "saved_stream") + + @_stream.setter + def _stream(self, base: Any) -> None: + self.saved_stream = _FilteringStream( + base.as_table(columns={"source": True, "system_tags": True}), + tag_columns=["k"], + ) + + +def _bound_selection(source: Any) -> list[int]: + """Bind ``source`` to a slot feeding a selection; return what the sync run keeps.""" + table = pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}) + job = PipelineJob(name="exact", database=InMemoryArrowDatabase()) + with job: + ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ).select_data_columns(["x"], label="selected") + job.bind(sources={"s": source}) + job.run() + return job.nodes["selected"].as_table()["x"].to_pylist() + + +@pytest.mark.parametrize("how", ["instance_reader", "property", "plain_subclass"]) +def test_only_an_exact_unshadowed_library_source_is_eager(how: str) -> None: + """An ``iter_data`` replaced on the instance and a ``_stream`` property both read + the rows the reader gives (``[20]``, as ``main``); a plain subclass is not proven + either, and gives ``main``'s rows (Codex on PR #485, final check).""" + from orcapod.core.sources.base import table_is_rows + + table = pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}) + kwargs: dict[str, Any] = { + "tag_columns": ["k"], + "tag_only_columns": True, + "source_id": "s", + } + if how == "instance_reader": + source: Any = ArrowTableSource(table, **kwargs) + read = source.iter_data + source.iter_data = lambda: _only_above_ten(read()) + expected = [20] + elif how == "property": + source = _ReadsThroughAProperty(table, **kwargs) + expected = [20] + else: + source = type("Plain", (ArrowTableSource,), {})(table, **kwargs) + expected = [10, 20] + assert not table_is_rows(source) + assert _bound_selection(source) == expected + + +def test_an_exact_library_source_is_eager() -> None: + """The exact class, with nothing replaced on the instance, takes the eager route.""" + from orcapod.core.sources.base import table_is_rows + + table = pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}) + source = ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + source.as_table() + list(source.iter_data()) + assert table_is_rows(source) + assert _bound_selection(source) == [10, 20] + + +def _swapped(stream: Any, first: str, second: str, tags: list[str]) -> Any: + """``stream``'s table with ``first`` and ``second`` swapped, over ``tags``.""" + from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS + + table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + names = list(table.column_names) + a, b = names.index(first), names.index(second) + names[a], names[b] = names[b], names[a] + return ArrowTableStream(table.select(names), tag_columns=tags) + + +@pytest.mark.parametrize("replay", [False, True], ids=["log", "replay"]) +@pytest.mark.parametrize("layout", ["data", "tags"]) +def test_a_composed_operator_result_keeps_its_own_order( + layout: str, replay: bool +) -> None: + """An operator whose ``static_process`` returns ANOTHER operator's result keeps, + stores and hands on the order of the rows that result yields, to any depth: data + ``y, x`` (laid out so) and tags ``b, a`` (declared so), as ``main`` built them from + the rows; REPLAY of the stored table too (Codex on PR #485, final check).""" + from orcapod.operators import SelectDataColumns + + class Reordered(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + if layout == "data": + return _swapped(stream, "x", "y", ["a", "b"]) + return _swapped(stream, "x", "x", ["b", "a"]) + + class Composed(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + return Reordered(["x", "y"]).process(stream) + + database = InMemoryArrowDatabase() + job = PipelineJob(name="composed", database=database) + with job: + source = DictSource( + [{"a": 1, "b": 5, "x": 1, "y": 2}, {"a": 2, "b": 6, "x": 3, "y": 4}], + tag_columns=["a", "b"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(Composed(["x", "y"])(source, label="composed"), label="b") + node: Any = job.nodes["composed"] + node.attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.run() + if replay: + node.attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.REPLAY + ) + node.clear_cache() + job.run() + # ``main`` 321284ae, measured: the stored table keeps its tags in the slot's order, + # and REPLAY hands on the stored table's order. + data = ["a", "b", "y", "x", "_source_y", "_source_x"] + stored_tags = ["a", "b", "x", "y", "_source_x", "_source_y"] + result_tags = ["b", "a", "x", "y", "_source_x", "_source_y"] + if layout == "data": + kept, in_store = data, data + else: + kept, in_store = (stored_tags if replay else result_tags), stored_tags + assert node.as_table(columns={"source": True}).column_names == kept + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + assert [n for n in stored.column_names if not n.startswith("__")] == in_store + assert job.nodes["b"].as_table(columns={"source": True}).column_names == kept + + +def test_a_result_of_another_stream_kind_takes_mains_row_path() -> None: + """A result that is not exactly an ``ArrowTableStream`` is read as ``main`` read + it: its rows (here, the ones its iterator yields), never its table.""" + from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS + from orcapod.operators import SelectDataColumns + + class Filtering(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + return _FilteringStream(table, tag_columns=["k"]) + + database = InMemoryArrowDatabase() + job = PipelineJob(name="other_kind", database=database) + with job: + source = ArrowTableSource( + pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}), + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(Filtering(["x"])(source, label="filtered"), label="b") + node: Any = job.nodes["filtered"] + node.attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.run() + assert node.as_table()["x"].to_pylist() == [20] + stored = node.get_all_records() + assert stored is not None + assert stored["x"].to_pylist() == [20] + assert job.nodes["b"].as_table()["x"].to_pylist() == [[20]] + + +# ── CodeRabbit on 352ce7b9: every wrapper proven, and the rows' data context ───── + + +@pytest.mark.parametrize("how", ["subclass", "instance_reader"]) +def test_a_dynamic_stream_that_is_not_proven_stops_the_chain(how: str) -> None: + """A ``DynamicPodStream`` subclass, or one whose ``iter_data`` is replaced on the + instance, inside an operator's result is read through its own rows (``[20]``), + as ``main`` read them: the chain is followed only through proven wrappers.""" + from orcapod.core.operators.static_output_pod import DynamicPodStream + from orcapod.operators import SelectDataColumns + + class FilteringDynamic(DynamicPodStream): + def iter_data(self) -> Any: + return _only_above_ten(super().iter_data()) + + class Inner(SelectDataColumns): + pass + + class Outer(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + if how == "subclass": + return FilteringDynamic(Inner(["x", "y"]), (stream,)) + inner: Any = Inner(["x", "y"]).process(stream) + read = inner.iter_data + inner.iter_data = lambda: _only_above_ten(read()) + return inner + + database = InMemoryArrowDatabase() + job = PipelineJob(name="unproven", database=database) + with job: + source = ArrowTableSource( + pa.table({"k": [1, 2], "x": [10, 20], "y": [1, 2], "z": [5, 6]}), + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(Outer(["x", "y"])(source, label="outer"), label="b") + node: Any = job.nodes["outer"] + node.attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.run() + assert node.as_table()["x"].to_pylist() == [20] + stored = node.get_all_records() + assert stored is not None + assert stored["x"].to_pylist() == [20] + assert job.nodes["b"].as_table()["x"].to_pylist() == [[20]] + + +OTHER_CONTEXT = "std:v1:test-rows-on-read-other" + + +def test_a_result_in_another_data_context_hands_on_its_own_rows( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An operator node over a stream of another data context hands on the result's + rows as ``main`` returned them (in their own data context); what it keeps is in its + own data context, as on ``main``.""" + import dataclasses + + import orcapod.contexts as contexts + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.operators import SelectDataColumns + from orcapod.system_constants import constants + + other = dataclasses.replace( + contexts.get_default_context(), context_key=OTHER_CONTEXT + ) + registry = contexts._get_registry() # pyright: ignore[reportPrivateUsage] # the test registers a second context + original = registry.get_context + + def get_context(key: Any = None) -> contexts.DataContext: # pyright: ignore[reportExplicitAny] # the registry's own argument + return other if key == OTHER_CONTEXT else original(key) + + monkeypatch.setattr(registry, "get_context", get_context) + + def stream() -> ArrowTableStream: + table = pa.table( + { + "k": ["a", "b"], + "x": [1, 2], + "y": [3, 4], + constants.CONTEXT_KEY: pa.array([OTHER_CONTEXT] * 2, pa.large_string()), + } + ) + return ArrowTableStream(table, tag_columns=["k"], data_context=other) + + node = OperatorJobNode(SelectDataColumns(["x"]), [stream()]) + output: Any = node.execute(stream()) + assert [data.data_context_key for _, data in output.iter_data()] == [ + OTHER_CONTEXT + ] * 2 + kept = node.as_table(columns={"context": True})[constants.CONTEXT_KEY] + assert kept.to_pylist() == [node.data_context_key] * 2 + + +# ── Codex round 7: the source's data context, system tags, retained lifetime ─── + + +def test_a_source_in_another_data_context_hands_on_its_own_rows() -> None: + """An exact ``CachedSource`` with its own data context: the rows a sync run returns + report the source's context, as ``main`` returned them, and the edge table is built + in the slot's context, as ``main`` rebuilt it.""" + import dataclasses + + from orcapod.contexts import get_default_context + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.operators.static_output_pod import at_edge + from orcapod.sources import CachedSource + from orcapod.system_constants import constants + + custom = dataclasses.replace(get_default_context(), context_key="review:custom") + inner = DictSource( + [{"k": 1, "x": 10}, {"k": 2, "x": 20}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + data_context=custom, + ) + source = CachedSource( + inner, + cache_database=InMemoryArrowDatabase(), + source_id="cached", + data_context=custom, + ) + slot = SourceJobNode.from_stream(source) + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(slot) + output: Any = SyncPipelineOrchestrator().run(dag).node_outputs[slot] + assert [ + (tag.data_context_key, data.data_context_key) + for tag, data in output.iter_data() + ] == [("review:custom", "review:custom")] * 2 + edge = at_edge(output).as_table(columns={"context": True}) + assert edge[constants.CONTEXT_KEY].to_pylist() == [slot.data_context_key] * 2 + + +class _AddSystemTag: + """``SelectDataColumns`` whose result carries one more system tag, ``int16``.""" + + @staticmethod + def operator(values: list[int | None], exact: bool) -> Any: + from orcapod.operators import SelectDataColumns + from orcapod.system_constants import constants + + class Unproven(ArrowTableStream): + """Reads as ``ArrowTableStream``; not proven: ``main``'s row path.""" + + kind = ArrowTableStream if exact else Unproven + + class AddSystemTag(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + out: Any = super().unary_static_process(stream) + table = out.as_table(columns={"source": True, "system_tags": True}) + table = table.append_column( + f"{constants.SYSTEM_TAG_PREFIX}region", + pa.array(values[: table.num_rows], pa.int16()), + ) + return kind(table, tag_columns=["k"]) + + return AddSystemTag(["x"]) + + +def _system_tag_job(values: list[int | None], exact: bool) -> tuple[Any, Any]: + database = InMemoryArrowDatabase() + job = PipelineJob(name="system_tag", database=database) + with job: + source = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + _AddSystemTag.operator(values, exact)(source, label="marked") + job.nodes["marked"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + return job, database + + +def test_a_narrow_system_tag_is_stored_as_the_rows_give() -> None: + """A result over an exact ``ArrowTableStream`` with an ``int16`` system tag: kept, + stored and record-hashed as ``main``'s rows give it (``int64``, non-null), the + same as ``main``'s own row path (an unproven stream) gives.""" + from orcapod.system_constants import constants + + name = f"{constants.SYSTEM_TAG_PREFIX}region" + stored: dict[bool, Any] = {} + for exact in (True, False): + job, database = _system_tag_job([1, 2], exact) + job.run() + node: Any = job.nodes["marked"] + kept = node.as_table(columns={"system_tags": True}).schema.field(name) + assert (kept.type, kept.nullable) == (pa.int64(), False) + stored[exact] = database.at("log").get_all_records( + node._stored_table_path, # pyright: ignore[reportPrivateUsage] # the raw LOG table + record_id_column="_record_hash", + ) + for table in stored.values(): + field = table.schema.field(name) + assert (field.type, field.nullable) == (pa.int64(), False) + assert ( + stored[True]["_record_hash"].to_pylist() + == stored[False]["_record_hash"].to_pylist() + ) + + +def test_a_null_system_tag_raises_at_the_operator_as_main_does() -> None: + """With a null among its values, ``main``'s rows cannot make one table: the + operator raises ``ArrowInvalid`` before its end event, as on ``main``.""" + job, _ = _system_tag_job([None, 2], exact=True) + observer = _NodeEvents() + with pytest.raises(pa.ArrowInvalid): + job.run(observer=observer) + assert ("start", "marked") in observer.events + assert ("end", "marked") not in observer.events + + +def test_a_source_table_with_other_system_tags_is_not_its_rows() -> None: + """The source route's guard: an exact ``ArrowTableSource`` whose system tag is a + narrow integer has a table that is not its rows (they give ``int64``); a stock + source's system tags are what the rows give.""" + from orcapod.core.streams.base import system_tags_as_rows_give + + schema = pa.schema( + [ + pa.field("k", pa.int64(), nullable=False), + pa.field("x", pa.int64(), nullable=False), + pa.field("region", pa.int16(), nullable=False), + ] + ) + narrow = ArrowTableSource( + pa.Table.from_pylist( + [{"k": 1, "x": 10, "region": 1}, {"k": 2, "x": 20, "region": 2}], + schema=schema, + ), + tag_columns=["k"], + tag_only_columns=True, + system_tag_columns=["region"], + source_id="s", + ) + assert not system_tags_as_rows_give( + narrow.as_table(columns={"system_tags": True}).schema + ) + stock = _plain() + assert system_tags_as_rows_give( + stock.as_table(columns={"system_tags": True}).schema + ) + + +def test_a_retained_output_keeps_only_its_rows_once_read( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """With results retained, an output held as its rows drops its built stream once + every successor has read it (``main`` retained only the rows): no built stream + outlives the run, its rows are its own, and a later read builds the table again.""" + import gc + import weakref + + from orcapod import function_pod + from orcapod.core.operators.static_output_pod import ( + RowsOnRead, + StaticOutputOperatorPod, + ) + + @function_pod(output_keys="y") + def plus_one(x: int) -> int: + return x + 1 + + job = PipelineJob(name="retained", database=InMemoryArrowDatabase()) + with job: + computed: Any = plus_one.pod( + _plain().select_data_columns(["x"]), label="computed" + ) + computed.select_data_columns(["y"], label="second") + computed.select_data_columns(["y"], label="third") + + built: list[weakref.ref[Any]] = [] + original = StaticOutputOperatorPod._materialize_upstream # pyright: ignore[reportPrivateUsage] # the row path, watched + + def watched(*args: Any, **kwargs: Any) -> Any: + stream = original(*args, **kwargs) + built.append(weakref.ref(stream)) + return stream + + monkeypatch.setattr( + StaticOutputOperatorPod, "_materialize_upstream", staticmethod(watched) + ) + graph = job._node_graph # pyright: ignore[reportPrivateUsage] # the job's graph + assert graph is not None + result = SyncPipelineOrchestrator().run(graph) + output: Any = result.node_outputs[job.nodes["computed"]] + assert isinstance(output, RowsOnRead) + gc.collect() + assert built + assert all(ref() is None for ref in built) + assert len(list(output.iter_data())) == 2 + assert output.as_table().num_rows == 2 + + +# ── CodeRabbit on dd6b7cd4: one computation per run ─────────────────────────── + + +@pytest.mark.parametrize("mode", [CacheMode.OFF, CacheMode.LOG], ids=["off", "log"]) +@pytest.mark.parametrize("route", ["eager", "rows"]) +def test_an_operator_runs_once_over_an_undated_upstream( + route: str, mode: CacheMode +) -> None: + """Over an upstream with no modified time, every read of the operator's result + wrapper runs the operator again; the node reads its table, keys and rows from the + one computation it captured, so the operator runs once, as on ``main``.""" + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.operators import SelectDataColumns + + calls: list[int] = [] + + class Undated(ArrowTableStream): + @property + def last_modified(self) -> Any: + return None + + class Unproven(ArrowTableStream): + """Not proven: ``main``'s row path.""" + + class Counting(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + calls.append(1) + out: Any = super().unary_static_process(stream) + if route == "eager": + return out + table = out.as_table(columns={"source": True, "system_tags": True}) + return Unproven(table, tag_columns=["k"]) + + table = pa.table({"k": [1, 2], "x": [10, 20], "y": [1, 2]}) + upstream = Undated(table, tag_columns=["k"]) + node = OperatorJobNode( + Counting(["x"]), + [upstream], + pipeline_database=InMemoryArrowDatabase(), + cache_mode=mode, + ) + output: Any = node.execute(upstream) + assert len(list(output.iter_data())) == 2 + assert len(calls) == 1 + + +@pytest.mark.parametrize( + "kind", + [pa.time64("ns"), pa.decimal256(76, 40)], + ids=["time64ns", "decimal256"], +) +def test_a_lazy_output_describes_itself_without_converting_python_types( + kind: pa.DataType, +) -> None: + """Types with no Python type of their own are described from the node, never raised.""" + values = ( + pa.array([1, 2]).cast(kind) + if pa.types.is_decimal(kind) + else pa.array([1, 2], kind) + ) + base = pa.table({"k": pa.array([1, 2], pa.int64()), "x": values}) + base = base.cast(pa.schema([f.with_nullable(False) for f in base.schema])) + source = ArrowTableSource( + base, tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + raw = ArrowTableStream( + source.as_table(columns={"source": True, "system_tags": True}), + tag_columns=["k"], + ) + job = PipelineJob(name="lazy_types", database=InMemoryArrowDatabase()) + with job: + source.select_data_columns(["x"], label="selected") + job.bind(sources={"s": raw}) + out: Any = job.nodes["s"].execute() + assert out.arrow_schema().field("x").type == kind diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py new file mode 100644 index 000000000..7b9ff4193 --- /dev/null +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -0,0 +1,645 @@ +"""ITL-1347 stage 2: a node's output stream equals the stream built from its rows. + +Every job node's ``execute`` now returns its output stream, which the sync orchestrator +hands to every successor. Sources build it from their Arrow table and operators from +their result's Arrow table, with no rows made (the row-built form F, +``StaticOutputOperatorPod._row_built_form``). The governing rule of the spec +(``docs/dev/specs/itl-1347-job-table-transport.md``) is that nothing a run shows may +change. So each output stream must equal, in identity and byte for byte, the stream the +orchestrator built before stage 2 from the same node's rows +(``_materialize_upstream(rows, node)``): + +- L2 (sources): rows are the source node's ``iter_data()``; +- L1 (operators): rows are the operator's result's ``iter_data()``, or the stored + stream's under ``REPLAY``; +- L0 (function and side-effect nodes): rows are the output stream's own rows; +- L5 (held nodes): a held node's stream equals the one built from its rows; +- L7: every node's declared ``arrow_schema()`` equals the schema of its output. + +The job uses every operator kind over several tag orders, table layouts and tag roles. +These tests are about the hand-off between nodes, so they wrap the nodes' ``execute``. +""" + +from __future__ import annotations + +import subprocess +import sys +import warnings +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod, tap_pod +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.core.nodes.operator_node import OperatorJobNode +from orcapod.core.nodes.source_node import SourceNodeBase +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod, at_edge +from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import ProvisionalHashWarning +from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.pipeline.observer import NoOpObserver +from orcapod.operators import Batch, MergeJoin, Rejoin, SelectDataColumns +from orcapod.side_effects import SideEffectJobNode +from orcapod.system_constants import constants +from orcapod.types import CacheMode +from tests.test_core.operators.several_items import ( + MAIN, + P, + Q, + Arrangement, + arrangements, + make_source, +) + +ALL_COLUMNS = { + "meta": True, + "source": True, + "system_tags": True, + "context": True, + "content_hash": True, +} + + +@function_pod(output_keys="d1_doubled") +def doubled(d1: int) -> int: + return 2 * d1 + + +@tap_pod +def noted(d1_doubled: int, ctx: Any) -> None: + return None + + +def build_job(arrangement: Arrangement, database: Any = None) -> Any: + """A job in which every operator kind, a function node and a side effect run.""" + main = make_source(MAIN, arrangement) + partner_p = make_source(P) + partner_q = make_source(Q) + job = PipelineJob( + name="stream_transport", database=database or InMemoryArrowDatabase() + ) + with job: + joined = main.join(partner_p, label="joined") + mapped = joined.map_data({"p1": "p1_renamed"}, label="mapped") + no_nulls = mapped.drop_nulls(["d2"], label="no_nulls") + no_nulls.select_data_columns(["d1", "p1_renamed"], label="after_no_nulls") + main.group_by(["t1"], label="grouped").select_data_columns( + ["d1"], label="after_grouped" + ) + main.select_data_columns(["d1"]).batch(batch_size=2, label="batched") + tagged = main.add_tags(k=1, label="tagged") + twice = doubled.pod(tagged.select_data_columns(["d1"]), label="doubled") + noted_stream: Any = noted + noted_stream(twice, label="noted") + main.semi_join(partner_q, label="semi").select_data_columns( + ["d3"], label="after_semi" + ) + MergeJoin()( + main.select_data_columns(["d1"]), + partner_p.map_data({"p1": "d1"}).select_data_columns(["d1"]), + ).select_data_columns(["d1"], label="after_merged") + Rejoin()( + main.select_data_columns(["d1"]), main.select_data_columns(["d3"]) + ).select_data_columns(["d1"], label="after_rejoined") + main.polars_filter(d1=999, label="nothing").select_data_columns( + ["d1"], label="after_nothing" + ) + return job + + +def _identity(stream: Any) -> tuple[Any, ...]: + return ( + type(stream), + stream.producer, + tuple(id(u) for u in stream.upstreams), + stream.pipeline_hash(), + stream.content_hash(), + stream.keys(), + stream.output_schema(), + stream.data_context_key, + ) + + +def assert_same_stream(got: Any, expected: Any) -> None: + """Equal identity, and equal tables byte for byte (every column group). + + ``got`` is taken as a successor receives it (``at_edge``: an output held as its rows + is built there). + """ + got = at_edge(got) + expected = at_edge(expected) + assert _identity(got) == _identity(expected) + got_table = got.as_table(columns=ALL_COLUMNS).combine_chunks() + expected_table = expected.as_table(columns=ALL_COLUMNS).combine_chunks() + assert got_table.schema.equals(expected_table.schema, check_metadata=True) + assert got_table.equals(expected_table, check_metadata=True) + + +def _rebuilt(rows: list[Any], node: Any) -> Any: + return StaticOutputOperatorPod._materialize_upstream(rows, node) # pyright: ignore[reportPrivateUsage] # the path before stage 2 + + +@pytest.fixture +def outputs(monkeypatch: pytest.MonkeyPatch) -> Iterator[dict[str, Any]]: + """Wrap every node kind's ``execute``; check each output against the row path.""" + seen: dict[str, Any] = {} + + source_execute = SourceNodeBase.execute + + def source(self: Any, **kwargs: Any) -> Any: + out = source_execute(self, **kwargs) + assert_same_stream(out, _rebuilt(list(self.iter_data()), self)) # L2 + seen[self.label] = out + return out + + operator_execute = OperatorJobNode.execute + + def operator(self: Any, *inputs: Any, **kwargs: Any) -> Any: + cached = self.get_cached_output() + if cached is not None: + rows = list(cached.iter_data()) + else: + rows = list(self._operator.process(*inputs).iter_data()) # pyright: ignore[reportPrivateUsage] # the operator's own result, as before stage 2 + out = operator_execute(self, *inputs, **kwargs) + assert_same_stream(out, _rebuilt(rows, self)) # L1 + seen[self.label] = out + return out + + def by_construction(original: Any) -> Any: + def execute(self: Any, *args: Any, **kwargs: Any) -> Any: + out = original(self, *args, **kwargs) + assert_same_stream(out, _rebuilt(list(out.iter_data()), self)) # L0 + seen[self.label] = out + return out + + return execute + + monkeypatch.setattr(SourceNodeBase, "execute", source) + monkeypatch.setattr(OperatorJobNode, "execute", operator) + monkeypatch.setattr( + FunctionJobNode, "execute", by_construction(FunctionJobNode.execute) + ) + monkeypatch.setattr( + SideEffectJobNode, "execute", by_construction(SideEffectJobNode.execute) + ) + yield seen + + +def _run(job: Any) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job.run() + + +@pytest.mark.parametrize("arrangement", arrangements(MAIN), ids=lambda a: a.id) +def test_every_output_stream_equals_the_row_rebuild( + arrangement: Arrangement, outputs: dict[str, Any] +) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangement) + _run(job) + assert {"joined", "nothing", "doubled", "noted", "semi", "batched"} <= set(outputs) + + +def test_a_replayed_operator_output_equals_the_row_rebuild( + outputs: dict[str, Any], +) -> None: + """REPLAY hands on the stored rows' stream, equal to the one built from them.""" + store = InMemoryArrowDatabase() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangements(MAIN)[0], store) + node = job.nodes["joined"] + node.attach_databases( + pipeline_database=store.at("replay"), cache_mode=CacheMode.LOG + ) + _run(job) + node.attach_databases( + pipeline_database=store.at("replay"), cache_mode=CacheMode.REPLAY + ) + node.clear_cache() + outputs.clear() + _run(job) + assert "joined" in outputs + + +def test_a_held_node_hands_on_the_stream_built_from_its_rows( + outputs: dict[str, Any], +) -> None: + """L5: a second run holds every node but one; held streams feed it as before.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangements(MAIN)[0]) + _run(job) + job.nodes["noted"].clear_cache() + outputs.clear() + _run(job) + # Only the cleared side effect ran; its input came from the held function node. + assert set(outputs) == {"noted"} + + +def _without_exceptions(schema: pa.Schema) -> list[tuple[str, Any, bool, Any]]: + """Fields in order as (name, type, nullable, metadata), the spec's exceptions applied. + + Decided by the values of a complete table, not by the description: a system-tag or + source-info field's flag (stated nullable) and a source-info field's type (left out). + A ``null`` column is ``large_string`` in rows (ITL-1319). Column order counts on the + sync path (Codex on PR #485). + """ + prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + return [ + ( + field.name, + None + if field.name.startswith(constants.SOURCE_PREFIX) + else pa.large_string() + if pa.types.is_null(field.type) + else field.type, + True if field.name.startswith(prefixes) else field.nullable, + field.metadata, + ) + for field in schema + ] + + +def _tag_schema_out_of_key_order(arrangement: Arrangement) -> bool: + """Whether the source's tag schema lists its tags in another order than its keys. + + ITL-1365: ``ArrowTableStream`` builds its tag schema in the table's layout order, + while its keys and rows follow the declared tag order; an operator predicts its + keys from that schema, so its ``arrow_schema()`` lists the tags in the layout + order and its rows do not. + """ + source = make_source(MAIN, arrangement) + return tuple(source.output_schema()[0]) != tuple(source.keys()[0]) + + +def _l7_arrangements() -> list[Any]: + return [ + pytest.param( + arrangement, + id=arrangement.id, + marks=pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="ITL-1365: a tag schema in layout order, keys in declared order", + ), + ) + if _tag_schema_out_of_key_order(arrangement) + else pytest.param(arrangement, id=arrangement.id) + for arrangement in arrangements(MAIN)[::4] + ] + + +@pytest.mark.parametrize("arrangement", _l7_arrangements()) +def test_declared_arrow_schema_equals_the_output( + arrangement: Arrangement, outputs: dict[str, Any] +) -> None: + """L7: ``arrow_schema()`` of every node equals the schema of its output stream.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangement) + _run(job) + for label, stream in outputs.items(): + node = job.nodes[label] + output = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + assert _without_exceptions(node.arrow_schema()) == _without_exceptions( + output.schema + ), label + assert node.arrow_types_declared, label + + +def test_a_loaded_job_describes_its_nodes( + tmp_path: Path, outputs: dict[str, Any] +) -> None: + """L7 for a loaded job: each loaded node's ``arrow_schema()`` equals its output. + + A loaded node describes itself from the Arrow type texts its saved file holds + (ITL-640). The job is run and saved in another process, so that the loaded job + holds no run of this process. + """ + script = ( + "import sys, warnings\n" + "from pathlib import Path\n" + "from orcapod.databases import DeltaTableDatabase\n" + "from tests.test_core.operators.several_items import MAIN, arrangements\n" + "from tests.test_pipeline.test_stream_transport_equivalence import build_job\n" + "warnings.simplefilter('ignore')\n" + "root = Path(sys.argv[1])\n" + "job = build_job(arrangements(MAIN)[0], DeltaTableDatabase(root / 'store'))\n" + "job.run()\n" + "job.save(root / 'job.json')\n" + ) + repository = Path(__file__).resolve().parents[2] + subprocess.run( + [sys.executable, "-c", script, str(tmp_path)], check=True, cwd=repository + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + loaded = PipelineJob.load(tmp_path / "job.json") + # In-memory sources are not saved: bind them again. + loaded.bind( + sources={ + "s": make_source(MAIN, arrangements(MAIN)[0]), + "p": make_source(P), + "q": make_source(Q), + } + ) + loaded.run(load_only=True) + assert {"joined", "doubled", "noted", "semi", "batched"} <= set(outputs) + for label, stream in outputs.items(): + node = loaded.nodes[label] + output = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + assert _without_exceptions(node.arrow_schema()) == _without_exceptions( + output.schema + ), label + assert node.arrow_types_declared, label + + +def _poller(fetched_order: tuple[str, ...]) -> Any: + """A ``PollingSource`` declaring tags ``k, j`` and data ``b, a``. + + It fetches a table with its columns in ``fetched_order``: a valid source whose + declared order is not its rows' (Codex on PR #485). + """ + from orcapod.core.sources import PollingSource + from tests.test_hashing.test_logical_type_forms import ( + _TableImpl, # pyright: ignore[reportPrivateUsage] # the one test polling implementation + ) + + columns = { + "k": pa.array(["1", "2"], pa.large_string()), + "j": pa.array(["x", "y"], pa.large_string()), + "a": pa.array([1, 2], pa.int64()), + "b": pa.array([3, 4], pa.int64()), + } + declared = pa.schema( + [pa.field(name, columns[name].type, False) for name in ("k", "j", "b", "a")] + ) + fetched = pa.table({name: columns[name] for name in fetched_order}) + fetched = fetched.cast(pa.schema([f.with_nullable(False) for f in fetched.schema])) + return PollingSource( + _TableImpl(fetched, declared), + tag_columns=["k", "j"], + record_id_columns=["k", "j"], + source_id="poller", + ) + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +@pytest.mark.parametrize( + "fetched_order", + [("j", "k", "a", "b"), ("k", "j", "b", "a"), ("k", "b", "j", "a")], + ids="-".join, +) +def test_a_poller_fetching_in_another_order_hands_on_its_rows( + fetched_order: tuple[str, ...], outputs: dict[str, Any] +) -> None: + """L2 for a poller whose fetched column order differs from its declared order. + + The source node's output equals its rows rebuilt (checked by ``outputs``), and the + operator after it keeps and stores its columns in the rows' order, as on ``main``. + """ + # Built before the job captures: importing the polling implementation's module + # inside ``with job`` would capture the sources that module builds. + poller = _poller(fetched_order) + database = InMemoryArrowDatabase() + job = PipelineJob(name="poller_order", database=database) + with job: + SelectDataColumns(["a", "b"])(poller, label="selected") + job.nodes["selected"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + _run(job) + node = job.nodes["selected"] + rows_order = [ + *job.nodes["selected"].keys()[0], + *(name for name in fetched_order if name in ("a", "b")), + ] + source_order = [f"{constants.SOURCE_PREFIX}{n}" for n in rows_order[2:]] + kept = node.as_table(columns={"source": True}).column_names + assert kept == [*rows_order, *source_order] + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + assert [name for name in stored.column_names if not name.startswith("__")] == [ + *rows_order, + *source_order, + ] + assert "poller" in outputs + + +@function_pod(output_keys="z") +def plus_one(d1_doubled: int) -> int: + return d1_doubled + 1 + + +class _ClearsOnRunStart(NoOpObserver): + """Clears ``node`` when the run starts and counts ``label``'s data starts.""" + + def __init__(self, node: Any, label: str) -> None: + self._node = node + self._label = label + self.data_starts = 0 + + def contextualize(self, *identity_path: str) -> _ClearsOnRunStart: + return self + + def on_run_start(self, run_id: str, pipeline_uri: str = "") -> None: + self._node.clear_cache() + + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: + if node_label == self._label: + self.data_starts += 1 + + +def test_an_async_held_node_sends_the_rows_the_plan_took() -> None: + """The async run sends a held node's rows as planned, not as read again later. + + An observer clears the held node when the run starts; the rows the plan took still + feed the node after it, as on ``main`` (Codex on PR #485). + """ + from orcapod.sources import DictSource + + job = PipelineJob(name="held_snapshot", database=InMemoryArrowDatabase()) + with job: + source = DictSource( + [{"k": i, "d1": i} for i in range(3)], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + plus_one.pod(doubled.pod(source, label="twice"), label="plus") + job.run() + job.nodes["plus"].clear_cache() + observer = _ClearsOnRunStart(job.nodes["twice"], "plus") + summary = job.run(orchestrator=AsyncPipelineOrchestrator(), observer=observer) + assert summary.nodes["twice"].held == 3 + assert observer.data_starts == 3 + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +def test_describing_a_poller_that_has_not_polled_reads_nothing() -> None: + """L7: ``arrow_schema()`` of a poller that has not polled never fetches. + + It answers from the declared schema, the same every time, with each data column's + source info, and ``arrow_types_declared`` stays false (Codex on PR #485). + """ + from orcapod.core.sources import PollingSource + from orcapod.types import Schema + from tests.test_hashing.test_logical_type_forms import ( + _TableImpl, # pyright: ignore[reportPrivateUsage] # the one test polling implementation + ) + + fetches: list[int] = [] + + class Counting(_TableImpl): + async def fetch(self, cursor: Any = None) -> Any: + fetches.append(1) + return await super().fetch(cursor) + + def schema(self) -> Any: + return Schema({"k": str, "a": int, "b": int}) + + table = pa.table( + { + "k": pa.array(["1"], pa.large_string()), + "a": pa.array([1]), + "b": pa.array([2]), + } + ) + poller = PollingSource( + Counting(table, table.schema), + tag_columns=["k"], + record_id_columns=["k"], + source_id="unpolled", + ) + first = poller.arrow_schema() + second = poller.arrow_schema() + assert fetches == [] + assert first.equals(second, check_metadata=True) + assert [n for n in first.names if n.startswith(constants.SOURCE_PREFIX)] == [ + "_source_a", + "_source_b", + ] + assert not poller.arrow_types_declared + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="ITL-1365: a tag schema in layout order, keys in declared order", +) +def test_an_operator_stream_declares_its_tags_in_its_rows_order() -> None: + """A plain operator stream's ``arrow_schema()`` lists its tags as its rows do. + + Tags declared ``b, a`` over a table laid out ``a, b`` (Codex on PR #485). + """ + from orcapod.core.sources import ArrowTableSource + + table = pa.table( + { + "a": pa.array([1, 2]), + "b": pa.array([3, 4]), + "w": pa.array([5, 6]), + "x": pa.array([7, 8]), + } + ) + source = ArrowTableSource( + table, tag_columns=["b", "a"], tag_only_columns=True, source_id="s" + ) + stream = SelectDataColumns(["x"])(source) + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # the rows' order + assert stream.arrow_schema().names[:2] == built.column_names[:2] + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +def test_a_poller_that_fetched_describes_its_rows_order() -> None: + """L7: after a fetch in another order than declared, the description follows the rows. + + A poller declaring ``k, j, b, a`` that fetched ``j, k, a, b`` lists its data as its + rows do (Codex on PR #485). + """ + poller = _poller(("j", "k", "a", "b")) + rows = list(poller.iter_data()) + built, _, _ = StaticOutputOperatorPod._rows_to_table(rows) # pyright: ignore[reportPrivateUsage] # the rows' order + assert poller.arrow_types_declared + assert _without_exceptions(poller.arrow_schema()) == _without_exceptions( + built.schema + ) + + +def test_a_value_decided_source_info_depth_is_a_named_exception() -> None: + """L7: ``Batch`` over null list tokens; the description and the rows agree but for it. + + The rows give ``[None, None]`` one list level (``large_list``); the + description states the declared token type. A source-info type is decided by the + values of a complete table and is one of the description's named exceptions. + """ + from orcapod.core.streams import ArrowTableStream + from orcapod.sources import DictSource + + table = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ).as_table(columns={"source": True, "system_tags": True}) + position = table.schema.get_field_index("_source_x") + strings = pa.large_list(pa.large_string()) + raw = ArrowTableStream( + table.set_column( + position, + pa.field("_source_x", strings, nullable=True), + pa.array([None, None], strings), + ), + tag_columns=["k"], + ) + batched = Batch(batch_size=2)(raw) + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(batched.iter_data())) # pyright: ignore[reportPrivateUsage] # the rows + declared = batched.arrow_schema() + assert declared.field("_source_x").type != built.schema.field("_source_x").type + assert _without_exceptions(declared) == _without_exceptions(built.schema) + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +def test_describing_an_undeclared_poller_that_has_not_polled_reads_nothing() -> None: + """L7: a poller with no declared schema is described with no column, and not polled. + + Its columns are known only from rows; the description never fetches, its modified + time does not move and ``arrow_types_declared`` stays false (Codex on PR #485). + """ + from orcapod.core.sources import PollingSource + from tests.test_hashing.test_logical_type_forms import ( + _TableImpl, # pyright: ignore[reportPrivateUsage] # the one test polling implementation + ) + + fetches: list[int] = [] + + class Undeclared(_TableImpl): + async def fetch(self, cursor: Any = None) -> Any: + fetches.append(1) + return await super().fetch(cursor) + + def schema(self) -> Any: + return None + + table = pa.table( + {"k": pa.array(["1"], pa.large_string()), "a": pa.array([1], pa.int64())} + ) + poller = PollingSource( + Undeclared(table, table.schema), + tag_columns=["k"], + record_id_columns=["k"], + source_id="undeclared", + ) + modified = poller.last_modified + assert poller.arrow_schema() == pa.schema([]) + assert poller.arrow_schema() == pa.schema([]) + assert fetches == [] + assert poller.last_modified == modified + assert not poller.arrow_types_declared diff --git a/tests/test_pipeline/test_sync_orchestrator.py b/tests/test_pipeline/test_sync_orchestrator.py index 4f334c709..ffd2c7907 100644 --- a/tests/test_pipeline/test_sync_orchestrator.py +++ b/tests/test_pipeline/test_sync_orchestrator.py @@ -12,6 +12,7 @@ from orcapod.core.sources import ArrowTableSource from orcapod.databases import InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.pipeline.job import PipelineJob @@ -337,7 +338,7 @@ def test_materialized_stream_has_same_pipeline_hash(self): ) buf = list(node.iter_data()) - stream = SyncPipelineOrchestrator._materialize_as_stream(buf, node) + stream = StaticOutputOperatorPod._materialize_upstream(buf, node) assert stream.pipeline_hash() == node.pipeline_hash() def test_materialized_stream_has_same_content_hash(self): @@ -356,7 +357,7 @@ def test_materialized_stream_has_same_content_hash(self): op_node.run() buf = list(op_node.iter_data()) - stream = SyncPipelineOrchestrator._materialize_as_stream(buf, op_node) + stream = StaticOutputOperatorPod._materialize_upstream(buf, op_node) assert stream.content_hash() == op_node.content_hash() def test_materialized_stream_preserves_system_tags(self): @@ -371,7 +372,7 @@ def test_materialized_stream_preserves_system_tags(self): op_node.run() buf = list(op_node.iter_data()) - stream = SyncPipelineOrchestrator._materialize_as_stream(buf, op_node) + stream = StaticOutputOperatorPod._materialize_upstream(buf, op_node) expected_tag_schema = op_node.output_schema(columns={"system_tags": True})[0] actual_tag_schema = stream.output_schema(columns={"system_tags": True})[0] diff --git a/tests/test_pipeline/test_system_tag_run_stability.py b/tests/test_pipeline/test_system_tag_run_stability.py index 48c50565c..19a757caf 100644 --- a/tests/test_pipeline/test_system_tag_run_stability.py +++ b/tests/test_pipeline/test_system_tag_run_stability.py @@ -27,7 +27,6 @@ from orcapod.core.sources.arrow_table_source import ArrowTableSource from orcapod.databases import DeltaTableDatabase from orcapod.pipeline.job import PipelineJob -from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.side_effects import SideEffectPod, sink_pod Key = tuple[tuple[str, Any], ...] @@ -148,8 +147,8 @@ def test_operator_materialize_to_stream(self) -> None: rows = stream.as_table().to_pylist() assert rows == [{"a": 1, "b": 2, "v": 10}, {"a": 3, "b": 4, "v": 20}] - def test_orchestrator_materialize_as_stream(self) -> None: - """The orchestrator materializer emits rows in the first row's column order.""" + def test_materialize_upstream_keeps_first_row_column_order(self) -> None: + """The upstream materializer emits rows in the first row's column order.""" rows = _rows_with_swapped_tag_order() # The rebuilt stream takes the upstream's data context (ITL-1080) and, for an # upstream with no producer, its pipeline hash (ITL-1094): here a plain @@ -162,7 +161,10 @@ def test_orchestrator_materialize_as_stream(self) -> None: rows ).pipeline_hash, ) - stream = SyncPipelineOrchestrator._materialize_as_stream(rows, upstream) + stream = StaticOutputOperatorPod._materialize_upstream( + rows, + upstream, # pyright: ignore[reportArgumentType] # a stand-in upstream: the attributes the materializer reads + ) rows = stream.as_table().to_pylist() assert rows == [{"a": 1, "b": 2, "v": 10}, {"a": 3, "b": 4, "v": 20}] diff --git a/tests/test_pipeline/test_tag_table_source_info.py b/tests/test_pipeline/test_tag_table_source_info.py index 094b66702..048b4d47d 100644 --- a/tests/test_pipeline/test_tag_table_source_info.py +++ b/tests/test_pipeline/test_tag_table_source_info.py @@ -32,12 +32,13 @@ from orcapod.core.function_pod import FunctionPod from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.operators import SelectDataColumns -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from tests.test_core.operators.test_materialize_source_info import ( + _broadcast_row_zero, # pyright: ignore[reportPrivateUsage] # the one re-creation of the pre-fix broadcast +) from orcapod.core.sources import ArrowTableSource from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.pipeline.job import PipelineJob -from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.system_constants import PIPELINE_DB_SCHEMA_VERSION @@ -160,24 +161,6 @@ def _output_source_info_tokens(job: PipelineJob, label: str, column: str) -> lis return [data.source_info()[column] for _, data in rows] -def _broadcast_row_zero(monkeypatch: pytest.MonkeyPatch) -> None: - """Make every materialization stamp row 0's source info, as before ITL-845.""" - original = StaticOutputOperatorPod._rows_to_table # pyright: ignore[reportPrivateUsage] # re-creating the pre-fix behaviour - - def broadcasting( - rows: Sequence[tuple[TagProtocol, DataProtocol]], - ) -> tuple[pa.Table, tuple[str, ...], tuple[str, ...]]: - """Stamp row 0's source info on every row, then build the table.""" - row_zero = rows[0][1].source_info() - return original( - [(tag, data.with_source_info(**row_zero)) for tag, data in rows] - ) - - monkeypatch.setattr( - StaticOutputOperatorPod, "_rows_to_table", staticmethod(broadcasting) - ) - - @pytest.mark.parametrize("orchestrator", ["sync", "async"]) class TestFreshRunStoresPerRowSourceInfo: def test_source_into_function(self, orchestrator: str):