diff --git a/.zed/rules b/.zed/rules index bbd720618..cfef12e6a 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1308,17 +1308,19 @@ data. The rules: refers to its stream (stream.open_channel()), an output channel to the stream it produces, and OutputChannel.result() closes it into that stream. The conversions are in one place, core/operators/static_output_pod.py (stream_from_batches, transport_schema, and F, - _row_built_form); never build a stream from record batches elsewhere. - channel_to_stream(channel) is the one conversion from an input channel to a stream: it reads - the channel to its end (one pass, every read error raised before an operator runs) and - rebuilds a fixed snapshot through stream_from_batches; only an unread channel whose stream - _output_stream built (ROW_BUILT_OUTPUT, set there only) gives that stream as it is. An - operator's record-batch form (async_execute_batches, renamed async_execute when wired) - applies its one static_process body: per record batch when the class declares ROW_BY_ROW = - True (each output row comes from one input row), otherwise as a barrier over the whole input - (channel_to_stream); Batch with a size has its own form, grouping rows by arrival. A new - operator whose output rows each come from one input row declares ROW_BY_ROW; write no other - per-operator batch code. + _row_built_form); never build a stream from record batches elsewhere. channel.to_stream() is + the one conversion from an input channel to a stream (a plain method that reserves the + channel when called and returns the conversion to await; it imports the builder inside its + body, since the operators sit above the streams): it reads the channel to its end (one pass, + every read error raised before an operator runs) and rebuilds a fixed snapshot through + stream_from_batches; only an unread channel opened on a stream _output_stream built + (ROW_BUILT_OUTPUT, set there only) gives that stream as it is. An operator's record-batch + form (async_execute_batches, renamed async_execute when wired) applies its one + static_process body: per record batch when the class declares ROW_BY_ROW = True (each output + row comes from one input row), otherwise as a barrier over the whole input (to_stream()); + Batch with a size has its own form, grouping rows by arrival. A new operator whose output + rows each come from one input row declares ROW_BY_ROW; write no other per-operator batch + code. - The type converter keys synthesized struct classes by the large-normalized struct, so struct and struct are one Python type (a workaround, TODO(ITL-841)). diff --git a/CLAUDE.md b/CLAUDE.md index 0c6d59591..2a0616434 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1356,16 +1356,18 @@ data. The rules: and `OutputChannel.result()` closes it into that stream. The conversions are in one place, `core/operators/static_output_pod.py` (`stream_from_batches`, `transport_schema`, and F, `_row_built_form`); never build a stream from record batches elsewhere. - `channel_to_stream(channel)` is the one conversion from an input channel to a stream: it - reads the channel to its end (one pass, every read error raised before an operator runs) and - rebuilds a fixed snapshot through `stream_from_batches`; only an unread channel whose stream + `channel.to_stream()` is the one conversion from an input channel to a stream (a plain + method that reserves the channel when called and returns the conversion to await; it imports + the builder inside its body, since the operators sit above the streams): it reads the + channel to its end (one pass, every read error raised before an operator runs) and rebuilds + a fixed snapshot through `stream_from_batches`; only an unread channel opened on a stream `_output_stream` built (`ROW_BUILT_OUTPUT`, set there only) gives that stream as it is. An operator's record-batch form (`async_execute_batches`, renamed `async_execute` when wired) applies its one `static_process` body: per record batch when the class declares `ROW_BY_ROW = True` (each output row comes from one input row), otherwise as a barrier over the whole - input (`channel_to_stream`); `Batch` with a size has its own form, grouping rows by arrival. - A new operator whose output rows each come from one input row declares `ROW_BY_ROW`; write - no other per-operator batch code. + input (`to_stream()`); `Batch` with a size has its own form, grouping rows by arrival. A new + operator whose output rows each come from one input row declares `ROW_BY_ROW`; write no + other per-operator batch code. - The type converter keys synthesized struct classes by the large-normalized struct, so `struct` and `struct` are one Python type (a workaround, `TODO(ITL-841)`). diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 62b990060..f930515f4 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -3,7 +3,7 @@ import asyncio import logging from abc import abstractmethod -from collections.abc import Collection, Coroutine, Iterator, Sequence +from collections.abc import Collection, Iterator, Sequence from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, ClassVar, cast @@ -557,7 +557,7 @@ def _output_stream( node, ) # The one place a stream is marked as a complete, immutable output in the - # row-built form (ITL-1347): ``channel_to_stream`` may give it as it is. + # row-built form (ITL-1347): ``InputChannel.to_stream`` may give it as it is. setattr(stream, ROW_BUILT_OUTPUT, True) return stream @@ -905,7 +905,7 @@ async def async_execute_batches( A row-by-row operator (``ROW_BY_ROW``) is applied to each record batch as it arrives and sends that batch's result at once. Every other operator reads - all of its inputs first (``channel_to_stream``) and then runs exactly + all of its inputs first (``InputChannel.to_stream``) and then runs exactly the sync call, so an input with no rows gives the typed zero-row result of the sync path, with no row to send. @@ -1020,7 +1020,7 @@ async def _streams_of(inputs: Sequence[RecordBatchInput]) -> list[StreamProtocol tasks: list[asyncio.Future[StreamProtocol]] = [] try: for channel in inputs: - tasks.append(asyncio.ensure_future(channel_to_stream(channel))) + tasks.append(asyncio.ensure_future(channel.to_stream())) return list(await asyncio.gather(*tasks)) except BaseException: # Every conversion already started is cancelled and awaited: none is left @@ -1080,65 +1080,10 @@ def transport_schema(stream: StreamProtocol) -> pa.Schema | None: 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 ``channel_to_stream`` may give it without reading. +would rebuild exactly it, and ``InputChannel.to_stream`` may give it without reading. """ -def channel_to_stream( - channel: RecordBatchInput, -) -> Coroutine[Any, Any, StreamProtocol]: - """Return what an input channel delivers, as a stream: the one such conversion. - - It reads the channel to its end (one pass; every error of the read, such as an - unbound source's or a failed producer's, is raised here, before any operator runs) - and builds a fixed snapshot of what was delivered through the one settlement path - (``stream_from_batches``). The only shortcut: a channel opened on a complete - stream that ``_output_stream`` built (``ROW_BUILT_OUTPUT``), not read yet, gives - that stream, which is exactly what its batches would rebuild; the channel is then - closed. A reader of an output channel always collects, whatever its description. - - The channel is reserved when this function is called, before the returned - coroutine is awaited, so nothing can read it in between; the task that runs the - coroutine takes the channel over, and any other task's read is refused. If the - coroutine never starts (its task is cancelled first, or it is never awaited), - the reservation's claim is freed with it and the channel is closed, so no - producer waits on it. - - Args: - channel: The input channel, not read yet. - - Returns: - The conversion to await: a complete, re-readable stream of the channel's - input. - - Raises: - RuntimeError: If a read of the channel was already called (a batch received, - its end reached, or another consumer still waiting): a stream of part of - an input is never made, and a channel is never read again. - ChannelClosed: If the channel was closed, before or during the read. - UpstreamFailedError: If the producer failed or was cancelled. - """ - claim = channel.reserve() # at call time: nothing can read it before the await - return _channel_to_stream(channel, claim) - - -async def _channel_to_stream( - channel: RecordBatchInput, claim: object -) -> StreamProtocol: - """Read a reserved channel and return its input as a stream (``channel_to_stream``). - - Args: - channel: The channel ``channel_to_stream`` reserved. - claim: Its claim, which the task running this conversion takes over. - """ - channel.reserve(claim) - opened_on = channel.opened_on - if opened_on is not None and getattr(opened_on, ROW_BUILT_OUTPUT, False): - await channel.close() - return opened_on - return stream_from_batches(channel.stream, await channel.collect()) - - def stream_from_batches( stream: StreamProtocol, batches: Sequence[pa.RecordBatch] ) -> StreamProtocol: @@ -1146,7 +1091,7 @@ def stream_from_batches( The one place a stream is made from Arrow record batches: what an output channel gives once closed (``OutputChannel.result``), what an input channel delivered - (``channel_to_stream``), and the record batches a row-by-row operator is + (``InputChannel.to_stream``), and the record batches a row-by-row operator is applied to. The batches are put under one another in the order given, and the table is handed on as a node hands its rows to its successors (``_output_stream``): in the row-built form, each system-tag and source-info field diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py index 86dfe2947..f617b1409 100644 --- a/src/orcapod/core/streams/record_batch_input.py +++ b/src/orcapod/core/streams/record_batch_input.py @@ -17,7 +17,7 @@ import asyncio import weakref -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Coroutine from typing import TYPE_CHECKING, Any, Protocol from orcapod.channels import ChannelClosed @@ -59,7 +59,7 @@ class InputChannel: delivers is its ``stream``, known before the first batch: the producing node, or the stream it was opened from. A channel has no identity of its own and is read once; to read again, go back to a stream (the one it was opened from, or the one - ``channel_to_stream`` makes of what it delivered). + ``to_stream`` makes of what it delivered). Made by ``stream.open_channel()`` or by ``OutputChannel.open_reader()``, never directly. @@ -282,6 +282,61 @@ def _closed_early(self) -> ChannelClosed: + "producer completed; it has no complete input to give." ) + def to_stream(self) -> Coroutine[Any, Any, StreamProtocol]: + """Return what the channel delivers, as a stream: the one such conversion. + + It reads the channel to its end (one pass; every error of the read, such as + an unbound source's or a failed producer's, is raised here, before any + operator runs) and builds a fixed snapshot of what was delivered through the + one settlement path (``stream_from_batches``). The only shortcut: a channel + opened on a complete stream that ``_output_stream`` built + (``ROW_BUILT_OUTPUT``), not read yet, gives that stream, which is exactly what + its batches would rebuild; the channel is then closed. A reader of an output + channel always collects, whatever its description. + + A plain method that returns the conversion to await: the channel is reserved + when it is called, before the conversion is awaited, so nothing can read it + in between; the task that runs the conversion takes the channel over, and + any other task's read is refused. If the conversion never starts (its task + is cancelled first, or it is never awaited), the reservation's claim is freed + with it and the channel is closed, so no producer waits on it. + + Returns: + The conversion to await: a complete, re-readable stream of the channel's + input. + + Raises: + RuntimeError: If a read of the channel was already called (a batch + received, its end reached, or another consumer still waiting): a + stream of part of an input is never made, and a channel is never read + again. + ChannelClosed: If the channel was closed, before or during the read. + UpstreamFailedError: If the producer failed or was cancelled. + """ + claim = self.reserve() # at call time: nothing can read it before the await + return self._to_stream(claim) + + async def _to_stream(self, claim: object) -> StreamProtocol: + """Read the reserved channel and return its input as a stream (``to_stream``). + + Args: + claim: The reservation's claim, which the task running this conversion + takes over. + """ + # Imported here: the operators sit above the streams, and this module is + # imported by core/streams/base.py (a module-level import would be circular). + from orcapod.core.operators.static_output_pod import ( + ROW_BUILT_OUTPUT, + stream_from_batches, + ) + + self.reserve(claim) + opened_on = self.opened_on + if opened_on is not None and getattr(opened_on, ROW_BUILT_OUTPUT, False): + await self.close() + return opened_on + return stream_from_batches(self._stream, await self.collect()) + async def collect(self) -> list[pa.RecordBatch]: """Read to the end and return every remaining record batch, in arrival order. diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 2ee788b67..7cb868e90 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -2,6 +2,7 @@ from collections.abc import ( AsyncIterator, + Coroutine, Collection, Iterable, Iterator, @@ -188,8 +189,8 @@ def open_channel(self) -> RecordBatchInput: The channel delivers the stream's rows as Arrow record batches, read once and in order; its description is this stream. Several channels may be opened on - one stream, each with its own position (``channel_to_stream`` makes a stream of - what a channel delivers). + one stream, each with its own position (``to_stream()`` makes a stream of what + a channel delivers). Returns: The input channel. @@ -648,6 +649,22 @@ def reserve(self, claim: object | None = None) -> object: """ ... + def to_stream(self) -> Coroutine[Any, Any, StreamProtocol]: + """Return what the channel delivers, as a stream: the one such conversion. + + A plain method returning the conversion to await; it reserves the channel + when called. The conversion reads the channel to its end, raises every read + error before an operator runs, and builds a fixed snapshot through the one + settlement path; only an unread channel opened on a stream ``_output_stream`` + built gives that stream as it is. + + Raises: + RuntimeError: If a read of the channel was already called. + ChannelClosed: If the channel was closed. + UpstreamFailedError: If the producer failed or was cancelled. + """ + ... + async def close(self) -> None: """Stop reading. The producer no longer waits for this reader.""" ... diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index e12bc7d59..16d16b44d 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -5,7 +5,7 @@ complete stream (``stream.open_channel()``) or from an output channel (``OutputChannel.open_reader``); an output channel, once closed, gives its rows back as an ordinary stream (``result()``), and so does an input channel that is read to its end -(``channel_to_stream``). One test per rule of the design's table "The hard semantics". +(``to_stream()``). One test per rule of the design's table "The hard semantics". The oracle of every table is ``R``: the table today's code builds from a stream's rows (``StaticOutputOperatorPod._rows_to_table``). @@ -36,7 +36,6 @@ from orcapod.core.operators.static_output_pod import ( ROW_BUILT_OUTPUT, StaticOutputOperatorPod, - channel_to_stream, stream_from_batches, transport_schema, ) @@ -118,7 +117,7 @@ async def read() -> list[pa.RecordBatch]: def test_a_channel_opened_on_a_stream_delivers_its_rows_and_refers_to_it() -> None: """The record batches are the stream's rows in the row-built form; the description - is the stream, and ``channel_to_stream`` rebuilds what the channel delivered, with + is the stream, and ``to_stream()`` rebuilds what the channel delivered, with the stream's identity.""" stream = source() channel = stream.open_channel() @@ -129,7 +128,7 @@ def test_a_channel_opened_on_a_stream_delivers_its_rows_and_refers_to_it() -> No assert as_protocol.stream is stream batches = run(stream.open_channel().collect) assert same(pa.Table.from_batches(batches), R(stream)) - delivered = run(lambda: channel_to_stream(channel)) + delivered = run(lambda: channel.to_stream()) assert same(delivered.as_table(columns=ALL), R(stream)) assert delivered.keys() == stream.keys() assert delivered.data_context_key == stream.data_context_key @@ -140,14 +139,14 @@ def test_a_channel_opened_on_a_stream_delivers_its_rows_and_refers_to_it() -> No def test_a_source_node_opens_a_channel_on_its_rows() -> None: """A source node is a stream too. A job's source node delivers its source's rows in - the row-built form, which ``channel_to_stream`` rebuilds. An unbound slot opens a + the row-built form, which ``to_stream()`` rebuilds. An unbound slot opens a channel (opening reads nothing), and its first read raises.""" stream = source() node = SourceJobNode.from_stream(stream, name="events") assert isinstance(node, StreamProtocol) batches = run(node.open_channel().collect) assert same(pa.Table.from_batches(batches), R(node)) - rebuilt = run(lambda: channel_to_stream(node.open_channel())) + rebuilt = run(lambda: node.open_channel().to_stream()) assert same(rebuilt.as_table(columns=ALL), R(node)) slot = SourceNode.from_stream(stream, name="events") @@ -254,7 +253,7 @@ async def read() -> tuple[list[pa.RecordBatch], Any]: for batch in batches: await output.send(batch) # the node's description takes them await output.close() - return batches, await channel_to_stream(node.open_channel()) + return batches, await node.open_channel().to_stream() batches, rebuilt = run(read) assert same(pa.Table.from_batches(batches), R(expected)) @@ -275,7 +274,7 @@ def test_a_rebind_before_the_first_read_is_read_whole() -> None: def test_a_source_nodes_conversion_keeps_the_delivered_column_order() -> None: """Plain tags declared ``k, j`` over physical columns ``x, j, k, y``: the stream - ``channel_to_stream`` makes keeps the columns in the order they were delivered + ``to_stream()`` makes keeps the columns in the order they were delivered (the node's rows), though the node describes itself in the slot's order.""" stream = ArrowTableSource( pa.table( @@ -295,7 +294,7 @@ def test_a_source_nodes_conversion_keeps_the_delivered_column_order() -> None: async def read() -> tuple[list[str], list[str]]: batches = await node.open_channel().collect() - rebuilt = await channel_to_stream(node.open_channel()) + rebuilt = await node.open_channel().to_stream() return batches[0].schema.names, rebuilt.as_table(columns=ALL).column_names delivered, rebuilt = run(read) @@ -349,26 +348,26 @@ async def flagged_stream() -> Any: for batch in batches: await output.send(batch) await output.close() - return await channel_to_stream(output.open_reader()) + return await output.open_reader().to_stream() flagged = run(flagged_stream) assert getattr(flagged, ROW_BUILT_OUTPUT, False) async def read() -> None: direct = flagged.open_channel() - assert await channel_to_stream(direct) is flagged + assert await direct.to_stream() is flagged other = OutputChannel(flagged) reader = other.open_reader() await other.send(batches[0]) await other.close() - rebuilt = await channel_to_stream(reader) + rebuilt = await reader.to_stream() assert rebuilt is not flagged assert rebuilt.as_table().num_rows == 1 failed = OutputChannel(flagged) failing = failed.open_reader() failed.fail(OSError("disk gone")) with pytest.raises(UpstreamFailedError): - _ = await channel_to_stream(failing) + _ = await failing.to_stream() op = SemiJoin() semi_output = OutputChannel(op(stream, flagged)) broken = OutputChannel(flagged) @@ -397,7 +396,7 @@ async def read() -> int: await asyncio.sleep(0) assert not reader.unread with pytest.raises(RuntimeError, match="read already|another consumer"): - _ = await channel_to_stream(reader) + _ = await reader.to_stream() with pytest.raises(RuntimeError, match="another consumer"): _ = await reader.receive() await output.send(batch) @@ -484,7 +483,7 @@ async def owner() -> int: @pytest.mark.parametrize("retain", [True, False], ids=["retained", "bounded"]) def test_a_conversion_reserves_the_reader_when_it_is_created(retain: bool) -> None: - """``pending = channel_to_stream(reader)`` reserves at once: a receive before + """``pending = reader.to_stream()`` reserves at once: a receive before ``await pending`` is refused, and the conversion gets every batch.""" stream = source(2) batches = batches_of(stream, 1) @@ -495,7 +494,7 @@ async def read() -> int: for batch in batches: await output.send(batch) await output.close() - pending = channel_to_stream(reader) + pending = reader.to_stream() with pytest.raises(RuntimeError, match="held for a conversion"): _ = await reader.receive() return (await pending).as_table().num_rows @@ -595,7 +594,7 @@ async def read() -> None: with pytest.raises(RuntimeError, match="StopAsyncIteration"): _ = await InputChannel(stream, _StoppingFeed(first)).collect() with pytest.raises(RuntimeError, match="StopAsyncIteration"): - _ = await channel_to_stream(InputChannel(stream, _StoppingFeed(first))) + _ = await InputChannel(stream, _StoppingFeed(first)).to_stream() run(read) @@ -628,7 +627,7 @@ async def read() -> None: @pytest.mark.parametrize("never", ["cancelled", "dropped"]) def test_a_conversion_that_never_starts_releases_its_reader(never: str) -> None: - """``channel_to_stream`` reserves at call time. If its conversion never starts (its + """``to_stream()`` reserves at call time. If its conversion never starts (its task is cancelled before the first step, or it is dropped unawaited), the reservation is released: the reader is closed and a bounded producer no longer waits on it.""" @@ -639,12 +638,12 @@ async def read() -> None: output = OutputChannel(stream, retain=False, buffer_size=1) reader = output.open_reader() if never == "cancelled": - task = asyncio.ensure_future(channel_to_stream(reader)) + task = asyncio.ensure_future(reader.to_stream()) _ = task.cancel() _ = await asyncio.gather(task, return_exceptions=True) del task else: - pending = channel_to_stream(reader) + pending = reader.to_stream() pending.close() # what dropping an unawaited coroutine does del pending gc.collect() @@ -680,7 +679,7 @@ async def read() -> None: def test_a_closed_reader_cannot_be_converted() -> None: - """A reader closed before any read: ``channel_to_stream`` raises ``ChannelClosed``, + """A reader closed before any read: ``to_stream()`` raises ``ChannelClosed``, as documented, not the error of a channel already read.""" stream = source(1) @@ -688,7 +687,7 @@ async def read() -> None: reader = OutputChannel(stream).open_reader() await reader.close() with pytest.raises(ChannelClosed, match="closed before its producer"): - _ = await channel_to_stream(reader) + _ = await reader.to_stream() run(read) @@ -705,7 +704,7 @@ async def fetch(self, cursor: Any = None) -> Any: def test_a_channel_closed_inside_the_read_is_a_read_error() -> None: """A ``ChannelClosed`` raised by the feed's own read (the source's) is not the end - of the input: iteration, ``collect`` and ``channel_to_stream`` raise it, and a + of the input: iteration, ``collect`` and ``to_stream()`` raise it, and a barrier fails before its body.""" declared = Schema({"id": int, "val": int}) @@ -722,7 +721,7 @@ async def read() -> None: _ = await polling().open_channel().collect() channel = polling().open_channel() with pytest.raises(ChannelClosed, match="underlying input"): - _ = await channel_to_stream(channel) + _ = await channel.to_stream() assert not channel.unread left = source() right = polling() @@ -765,7 +764,7 @@ async def read() -> bool: def test_an_unbound_input_fails_a_barrier_before_it_runs() -> None: """``SemiJoin`` with no shared tag never reads its right input on the sync path, - but ``channel_to_stream`` reads every input first: an unbound right input (a slot, + but ``to_stream()`` reads every input first: an unbound right input (a slot, or a ``SourceProxy``) raises what reading it raises, before the operator runs.""" left = source() other = ArrowTableSource( @@ -816,14 +815,14 @@ async def before_run() -> Any: async def after_run() -> None: assert await channel.collect() == [] # single pass: nothing more with pytest.raises(RuntimeError, match="read already"): - _ = await channel_to_stream(channel) + _ = await channel.to_stream() run(after_run) def test_a_polling_source_is_read_once_through_a_channel() -> None: """A fresh ``PollingSource``: opening a channel fetches nothing; reading it fetches - once and the stream ``channel_to_stream`` gives is a fixed snapshot, read again + once and the stream ``to_stream()`` gives is a fixed snapshot, read again with no further fetch, also through ``collect``.""" fake = FakeDynamicSource(batches=[_batch(i, 10 * i) for i in range(1, 6)]) polling = PollingSource( @@ -834,7 +833,7 @@ async def read() -> None: channel = polling.open_channel() other = polling.open_channel() assert len(fake.fetch_cursors) == 0 # opening reads nothing - snapshot = await channel_to_stream(channel) + snapshot = await channel.to_stream() fetched = len(fake.fetch_cursors) assert fetched == 1 # exactly one fetch for the channel's first read assert len(await other.collect()) >= 1 @@ -909,8 +908,8 @@ async def read() -> tuple[int, int]: assert run(read) == (1, 0) -def test_channel_to_stream_is_everything_or_nothing() -> None: - """``channel_to_stream`` on a channel already read is refused: never part of an +def test_to_stream_is_everything_or_nothing() -> None: + """``to_stream()`` on a channel already read is refused: never part of an input, and a channel is never read again.""" batches = batches_of(source(), 2) @@ -923,7 +922,7 @@ async def read() -> None: channel = output.open_reader() _ = await channel.receive() with pytest.raises(RuntimeError, match="read already"): - _ = await channel_to_stream(channel) + _ = await channel.to_stream() run(read) @@ -963,7 +962,7 @@ async def write() -> OutputChannel: def test_the_identity_of_a_result_with_and_without_a_producer() -> None: - """``result()`` and ``channel_to_stream`` take the describing stream's identity: its + """``result()`` and ``to_stream()`` take the describing stream's identity: its producer and upstreams when it has a producer, its pipeline hash when it has none.""" root = source() produced = SelectDataColumns(["subject", "trial", "amplitude"])(root) @@ -973,7 +972,7 @@ async def both(stream: Any, batches: list[pa.RecordBatch]) -> tuple[Any, Any]: for batch in batches: await output.send(batch) await output.close() - return output.result(), await channel_to_stream(output.open_reader()) + return output.result(), await output.open_reader().to_stream() for stream in (root, produced): batches = batches_of(stream, 3) @@ -986,7 +985,7 @@ async def both(stream: Any, batches: list[pa.RecordBatch]) -> tuple[Any, Any]: def test_a_close_with_no_batch_is_the_typed_zero_row_stream() -> None: - """Zero rows: ``result()`` and ``channel_to_stream`` are typed by the description, never + """Zero rows: ``result()`` and ``to_stream()`` are typed by the description, never by rows, with the columns of a run with rows.""" stream = SelectDataColumns(["subject", "trial", "amplitude", "trace"])(source()) with_rows = R(stream) @@ -996,7 +995,7 @@ async def empty() -> tuple[Any, Any]: reader = output.open_reader() await output.close() await output.close() # a second close does nothing - return output.result(), await channel_to_stream(reader) + return output.result(), await reader.to_stream() for made in run(empty): table = made.as_table(columns=ALL) @@ -1238,20 +1237,18 @@ async def write() -> tuple[type[object], list[int]]: assert rows == [1] -def test_channel_to_stream_of_a_channel_closed_before_its_end_raises() -> None: - """A reader closed while ``channel_to_stream`` (or ``collect()``) reads never makes part +def test_to_stream_of_a_channel_closed_before_its_end_raises() -> None: + """A reader closed while ``to_stream()`` (or ``collect()``) reads never makes part of an input into a stream.""" stream = source(2) first, second = batches_of(stream, 1) async def write() -> None: - for read in ("channel_to_stream", "collect"): + for read in ("to_stream", "collect"): output = OutputChannel(stream, retain=False, buffer_size=4) reader = output.open_reader() reading = asyncio.ensure_future( - channel_to_stream(reader) - if read == "channel_to_stream" - else reader.collect() + reader.to_stream() if read == "to_stream" else reader.collect() ) await output.send(first) await asyncio.sleep(0) @@ -1755,7 +1752,7 @@ async def waiting_consumer() -> Any: blocked = asyncio.ensure_future(waiting_consumer()) await first_read.wait() - whole = asyncio.ensure_future(channel_to_stream(barrier)) + whole = asyncio.ensure_future(barrier.to_stream()) await asyncio.sleep(0) output.fail(boom) output.fail(RuntimeError("a second failure changes nothing")) @@ -1790,7 +1787,7 @@ async def write() -> int: await output.send(batch) await output.close() output.fail(OSError("too late")) - return (await channel_to_stream(output.open_reader())).as_table().num_rows + return (await output.open_reader().to_stream()).as_table().num_rows assert run(write) == 7 @@ -1899,7 +1896,7 @@ async def inputs() -> list[RecordBatchInput]: def test_stream_from_batches_is_the_one_conversion() -> None: - """``result()`` and ``channel_to_stream`` are ``stream_from_batches``: its table equals the + """``result()`` and ``to_stream()`` are ``stream_from_batches``: its table equals the rows' table for every way the batches are cut, and no batch gives zero rows.""" stream = source() for rows in (1, 2, 5, 7): diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 71e6b7cad..6615b8867 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -4,7 +4,7 @@ (``async_execute_batches``) reads input channels opened from streams and writes an output channel, which closes into a stream. An operator whose output rows each come from one input row is applied to every record batch as it arrives; every other -operator reads all of its inputs first (``channel_to_stream``) and then runs the +operator reads all of its inputs first (``to_stream()``) and then runs the sync call; ``Batch`` batches consecutive arrivals. For every case of the async/sync matrix (``test_async_sync_equivalence.CASES``) the @@ -398,7 +398,7 @@ def test_a_barrier_operator_sees_its_input_as_a_job_gives_it(label: str) -> None """The record-batch form is held to what a job's sync path gives an operator: the upstream rebuilt from its rows (``_materialize_upstream``: ``null`` as ``large_string``, the columns in row order), not the raw stream it came from, in - every layout: ``channel_to_stream`` rebuilds what the channel delivered. A + every layout: ``to_stream()`` rebuilds what the channel delivered. A predicate that reads a ``null`` column's type or the column order follows that form (documented behaviour, e5); in a job neither case reaches an operator: a source refuses a ``null`` column, and a job refuses an expression that selects