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
35 changes: 20 additions & 15 deletions .zed/rules
Original file line number Diff line number Diff line change
Expand Up @@ -1299,21 +1299,26 @@ data. The rules:
context from those datagrams (data_context_key). Add new async operators to
tests/test_core/operators/test_async_sync_equivalence.py.
- Record-batch channels (ITL-1347, ITL-1362; not wired into nodes or orchestrators yet):
orcapod.core.record_batch_channels.InputChannel / OutputChannel carry a stream's rows as
Arrow record batches; operators see them only through the protocols RecordBatchInput /
RecordBatchOutput of protocols/core_protocols/record_batch_channels.py, which imports no
concrete core module (keep modules interacting through protocols: basedpyright counts local
and TYPE_CHECKING imports as import cycles). A channel owns no description: an input channel
refers to its stream (channel_from_stream(stream)), 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. 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.
InputChannel (core/streams/record_batch_input.py) and OutputChannel
(core/record_batch_channels.py) carry a stream's rows as Arrow record batches; operators see
them only through the protocols RecordBatchInput / RecordBatchOutput of
protocols/core_protocols/streams.py (beside StreamProtocol), which imports no concrete core
module (keep modules interacting through protocols: basedpyright counts local and
TYPE_CHECKING imports as import cycles). A channel owns no description: an input channel
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.
- 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
35 changes: 20 additions & 15 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -1346,21 +1346,26 @@ data. The rules:
context from those datagrams (`data_context_key`). Add new async operators to
`tests/test_core/operators/test_async_sync_equivalence.py`.
- Record-batch channels (ITL-1347, ITL-1362; not wired into nodes or orchestrators yet):
`orcapod.core.record_batch_channels.InputChannel` / `OutputChannel` carry a stream's rows as
Arrow record batches; operators see them only through the protocols `RecordBatchInput` /
`RecordBatchOutput` of `protocols/core_protocols/record_batch_channels.py`, which imports no
concrete core module (keep modules interacting through protocols: basedpyright counts local
and `TYPE_CHECKING` imports as import cycles). A channel owns no description: an input
channel refers to its stream (`channel_from_stream(stream)`), 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. 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.
`InputChannel` (`core/streams/record_batch_input.py`) and `OutputChannel`
(`core/record_batch_channels.py`) carry a stream's rows as Arrow record batches; operators
see them only through the protocols `RecordBatchInput` / `RecordBatchOutput` of
`protocols/core_protocols/streams.py` (beside `StreamProtocol`), which imports no concrete
core module (keep modules interacting through protocols: basedpyright counts local and
`TYPE_CHECKING` imports as import cycles). A channel owns no description: an input channel
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.
- 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
70 changes: 70 additions & 0 deletions src/orcapod/core/nodes/source_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

from __future__ import annotations

from collections import deque

import contextlib
import dataclasses
import functools
Expand All @@ -27,10 +29,12 @@
from orcapod.core.streams.arrow_table_stream import ArrowTableStream
from orcapod.core.streams.base import (
ZERO_ROW_INPUT_COLUMNS,
row_built_columns,
schema_requires_io,
typed_arrow_schemas,
typed_zero_row_table,
)
from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel
from orcapod.core.streams.view import (
ViewStatus,
StreamView,
Expand All @@ -57,6 +61,9 @@
if TYPE_CHECKING:
from orcapod.channels import WritableChannel
from orcapod.protocols.core_protocols import StreamProtocol
from orcapod.protocols.core_protocols.streams import (
RecordBatchInput,
)
from orcapod.protocols.observability_protocols import ExecutionObserverProtocol

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -412,6 +419,55 @@ def _require_stream_arrow_types(stream: Any, slot: str) -> None:
raise _no_arrow_type_error(slot, missing)


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.
"""

# 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``.

Args:
node: The source node whose output it delivers.
"""
self._node = node
self._batches: deque[pa.RecordBatch] | None = 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
table = row_built_columns(
output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), output.keys()
)
self._batches = deque(
batch
for batch in table.to_batches(max_chunksize=SOURCE_BATCH_ROWS)
if batch.num_rows
)
return self._batches.popleft() if self._batches else None

def close(self) -> None:
"""Stop reading: the batches not read are dropped."""
self._batches = deque()

@property
def opened_on(self) -> StreamProtocol | None:
"""``None``: the node is not the stream its batches rebuild."""
return None


class SourceNodeBase(TraceableBase, ABC):
"""Abstract base for SourceNode and SourceJobNode.

Expand Down Expand Up @@ -1163,6 +1219,20 @@ def run(self) -> StreamView:
display_all_rows=False,
)

def open_channel(self) -> RecordBatchInput:
"""Open an input channel on this node's rows, for async computation (ITL-1347).

The channel carries exactly this node's own ``execute()`` output: its rows,
as the table a job builds from them, in Arrow record batches. Everything
(the binding, the declared form, the column order, the source info) is read
at the first read, from one binding; opening reads nothing. The description
is this node. An unbound node's first read raises what reading it raises.

Returns:
The input channel.
"""
return InputChannel(self, _ExecuteOutputFeed(self))

async def async_iter_data(self):
"""Asynchronous iterator over (tag, data) pairs.

Expand Down
2 changes: 1 addition & 1 deletion src/orcapod/core/operators/batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import pyarrow as pa

from orcapod.core.operators.meta_columns import WithoutMetaWriter
from orcapod.protocols.core_protocols.record_batch_channels import (
from orcapod.protocols.core_protocols.streams import (
RecordBatchInput,
RecordBatchOutput,
)
Expand Down
131 changes: 117 additions & 14 deletions src/orcapod/core/operators/static_output_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
import asyncio
import logging
from abc import abstractmethod
from collections.abc import Collection, Iterator, Sequence
from collections.abc import Collection, Coroutine, Iterator, Sequence
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, ClassVar, cast

import pyarrow as pa

from orcapod.protocols.core_protocols.record_batch_channels import (
from orcapod.protocols.core_protocols.streams import (
RecordBatchInput,
RecordBatchOutput,
)
Expand Down Expand Up @@ -547,14 +547,19 @@ def _output_stream(
The output stream, with ``node``'s identity.
"""
if table.num_rows == 0:
return StaticOutputOperatorPod._materialize_upstream([], 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,
)
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): ``channel_to_stream`` may give it as it is.
setattr(stream, ROW_BUILT_OUTPUT, True)
return stream

@staticmethod
def _flag_source_info_nullability(table: pa.Table) -> pa.Table:
Expand Down Expand Up @@ -900,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 (``InputChannel.to_stream``) and then runs exactly
all of its inputs first (``channel_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 @@ -1012,12 +1017,17 @@ async def _streams_of(inputs: Sequence[RecordBatchInput]) -> list[StreamProtocol
UpstreamFailedError: If an input's producer failed; the other inputs are no
longer read.
"""
tasks = [asyncio.ensure_future(channel.to_stream()) for channel in inputs]
tasks: list[asyncio.Future[StreamProtocol]] = []
try:
for channel in inputs:
tasks.append(asyncio.ensure_future(channel_to_stream(channel)))
return list(await asyncio.gather(*tasks))
except BaseException:
# Every conversion already started is cancelled and awaited: none is left
# running, or raising with nobody to hear it.
for task in tasks:
_ = task.cancel()
_ = await asyncio.gather(*tasks, return_exceptions=True)
raise


Expand Down Expand Up @@ -1065,14 +1075,75 @@ def transport_schema(stream: StreamProtocol) -> pa.Schema | None:
return row_built_provenance(zero_rows.select(names)).schema


ROW_BUILT_OUTPUT = "_orcapod_row_built_output"
"""The attribute that marks a stream ``_output_stream`` built (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 ``channel_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.

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
(``InputChannel.to_stream``), and the record batches a row-by-row operator is
(``channel_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 All @@ -1091,7 +1162,39 @@ def stream_from_batches(
if not batches:
return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator
table = pa.Table.from_batches([with_open_provenance_flags(b) for b in batches])
return StaticOutputOperatorPod._output_stream(table, stream.keys(), stream) # pyright: ignore[reportPrivateUsage] # F and the identity, stage 2's
return StaticOutputOperatorPod._output_stream( # pyright: ignore[reportPrivateUsage] # F and the identity, stage 2's
table, _keys_in_delivered_order(stream.keys(), table.column_names), stream
)


def _keys_in_delivered_order(
keys: tuple[Sequence[str], Sequence[str]], names: Sequence[str]
) -> tuple[list[str], list[str]]:
"""The description's tag and data keys, in the order the delivered rows have them.

The roles come from the description; the order from the batches, so a stream
made from them keeps the columns as they were delivered. They agree for every
stream whose description follows its rows (an operator's or a function's);
a source node whose plain tags are declared in another order than its columns
describes itself in the slot's order (ITL-1365) while its rows are not.

Args:
keys: The describing stream's tag keys and data keys.
names: The delivered table's column names.

Returns:
The tag keys and the data keys, data-tags first in tag order.
"""
tag_keys, data_keys = keys
tags, data = set(tag_keys), set(data_keys)
position = {name: i for i, name in enumerate(names)}
ordered_tags = sorted(tag_keys, key=lambda n: position.get(n, len(names)))
data_tags = [n for n in ordered_tags if n in data]
plain = sorted(
(n for n in data_keys if n not in tags),
key=lambda n: position.get(n, len(names)),
)
return ordered_tags, data_tags + plain


def with_open_provenance_flags(batch: pa.RecordBatch) -> pa.RecordBatch:
Expand Down
Loading
Loading