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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 13 additions & 11 deletions .zed/rules
Original file line number Diff line number Diff line change
Expand Up @@ -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<b: string> and struct<b: large_string> are one Python type (a workaround,
TODO(ITL-841)).
Expand Down
14 changes: 8 additions & 6 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<b: string>` and `struct<b: large_string>` are one Python type (a workaround,
`TODO(ITL-841)`).
Expand Down
67 changes: 6 additions & 61 deletions src/orcapod/core/operators/static_output_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -1080,73 +1080,18 @@ 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:
"""Return the Arrow record batches of ``stream``'s rows as a stream.

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
Expand Down
59 changes: 57 additions & 2 deletions src/orcapod/core/streams/record_batch_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.

Expand Down
21 changes: 19 additions & 2 deletions src/orcapod/protocols/core_protocols/streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from collections.abc import (
AsyncIterator,
Coroutine,
Collection,
Iterable,
Iterator,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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."""
...
Expand Down
Loading
Loading