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
4 changes: 2 additions & 2 deletions src/orcapod/core/operators/batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from orcapod.core.operators.static_output_pod import (
close_inputs,
concatenate_batches,
finish_operator,
)
from orcapod.core.data_tags import stream_data_tags
from orcapod.core.streams import ArrowTableStream
Expand Down Expand Up @@ -319,12 +320,11 @@ async def async_execute_batches(
# whether they make a last one.
if rows:
await self._send_processed(waiting, channel.stream, output)
await output.close()
except BaseException as error:
output.fail(error)
await close_inputs(inputs, error)
raise
await close_inputs(inputs)
await finish_operator(inputs, output)

def to_config(self) -> dict[str, Any]:
"""Serialize this Batch operator to a config dict.
Expand Down
118 changes: 100 additions & 18 deletions src/orcapod/core/operators/static_output_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, cast

import pyarrow as pa
import pyarrow.compute as pc

from orcapod.protocols.core_protocols.streams import (
RecordBatchInput,
Expand Down Expand Up @@ -1055,9 +1056,10 @@ async def async_execute_batches(
came from. A predicate that reads a ``null`` column's type or the column order
follows that form (documented behaviour, e5).

The output is closed when the operator is done. If it fails or is cancelled,
the output fails instead, so no reader takes it for complete; every input is
closed in either case.
When the operator is done its inputs are closed, then its output
(``finish_operator``), so a failing close fails the output. If the operator
fails or is cancelled, the output fails instead, so no reader takes it for
complete; every input is closed in either case.

Args:
inputs: One input channel per input stream, in the operator's order.
Expand All @@ -1071,12 +1073,11 @@ async def async_execute_batches(
else:
streams = await _streams_of(inputs)
await self._send_result(self.static_process(*streams), output)
await output.close()
except BaseException as error:
output.fail(error)
await close_inputs(inputs, error)
raise
await close_inputs(inputs)
await finish_operator(inputs, output)

async def _send_processed(
self,
Expand Down Expand Up @@ -1114,6 +1115,32 @@ async def _send_result(result: StreamProtocol, output: RecordBatchOutput) -> Non
await output.send(batch)


async def finish_operator(
inputs: Sequence[RecordBatchInput], output: RecordBatchOutput
) -> None:
"""End an operator that has sent its result: close its inputs, then its output.

The inputs are closed first, so a failing close fails the output instead of
completing it: readers see the normal end only when the operator ended cleanly.

Args:
inputs: The operator's input channels.
output: Its output channel.

Raises:
Exception: The first error of an input's close, or the output's close; the
output then fails with it.
"""
try:
await close_inputs(inputs)
await output.close()
except BaseException as error:
# A failing close of an input, or of the output itself: no reader takes the
# output for complete.
output.fail(error)
raise


async def close_inputs(
inputs: Sequence[RecordBatchInput], error: BaseException | None = None
) -> None:
Expand Down Expand Up @@ -1295,29 +1322,84 @@ def settle_token_types(
if len(kinds) > 1:
raise SourceInfoTypesDisagree(field.name)
(kind,) = kinds
_ = _tokens_as(column, kind, field.name) # representable, or refused
_ = _named_tokens_as(column, kind, field.name) # representable, or refused
settled[field.name] = kind
return settled


def _tokens_as(
column: pa.Array[Any],
kind: pa.DataType,
name: str, # pyright: ignore[reportExplicitAny] # any column
) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # any column
"""``column``'s tokens as an array of ``kind``: the same array when it has that type.
def tokens_as(column: pa.Array[Any], kind: pa.DataType) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # any column
"""``column``'s source-info tokens as an array of ``kind``, every value kept.

The same array when it has that type. A token type that one batch's values give
(``arrow_utils.source_info_arrow_type``) can be shallower than another's (a null
or an empty list fixes fewer list levels); converting keeps every token, and a
token that ``kind`` cannot hold is refused, never changed.

Args:
column: Source-info tokens.
kind: A token type (``large_string``, or ``large_list`` of a token type).

Returns:
The tokens as ``kind``.

Raises:
RowBuiltFormUnavailable: If a token cannot be represented as ``kind``.
"""
return _tokens_into(column, kind)


def _tokens_into(column: pa.Array[Any], kind: pa.DataType) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # any column
"""``tokens_as``, level by level, never reading a value as another shape.

A level whose values are all null (or that has none) takes ``kind`` as it is; two
list levels convert their values; any other difference is refused. A value is
never re-read in another type (pyarrow reads a string as a list of characters).

Raises:
RowBuiltFormUnavailable: If a token cannot be represented as ``kind``.
"""
if column.type == kind:
return column
if column.null_count == len(column):
return pa.nulls(len(column), kind) # pyright: ignore[reportCallIssue, reportArgumentType] # pyarrow takes any type; the stubs say an extension type
lists = (pa.ListType, pa.LargeListType)
if isinstance(column.type, lists) and isinstance(kind, lists):
# The slice's own lists: its values, and offsets from its lists' lengths (a
# null list holds none), so a sliced array converts as its rows say.
values = _tokens_into(pc.list_flatten(column), kind.value_type) # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType]
lengths = pc.fill_null(pc.list_value_length(column), 0) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType, reportArgumentType] # pyarrow takes a Python fill value
offset_type = pa.int64() if isinstance(kind, pa.LargeListType) else pa.int32()
offsets = pa.concat_arrays(
[
pa.array([0], offset_type),
pc.cumulative_sum(lengths).cast(offset_type), # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType]
]
)
build = (
pa.LargeListArray.from_arrays
if isinstance(kind, pa.LargeListType)
else pa.ListArray.from_arrays
)
return build(offsets, values, type=kind, mask=column.is_null()) # pyright: ignore[reportUnknownVariableType, reportCallIssue, reportArgumentType] # the offsets' width follows ``kind``
raise RowBuiltFormUnavailable(
f"a token of type {column.type} cannot be represented as {kind}"
)


def _named_tokens_as(
column: pa.Array[Any], # pyright: ignore[reportExplicitAny] # any column
kind: pa.DataType,
name: str,
) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # any column
"""``tokens_as`` for the source-info column ``name``, whose name a refusal gives.

Raises:
RowBuiltFormUnavailable: If a token cannot be represented as ``kind``.
"""
try:
return pa.array(column.to_pylist(), type=kind)
except (pa.ArrowInvalid, pa.ArrowTypeError, TypeError, ValueError) as error:
raise RowBuiltFormUnavailable(
f"{name}: a token cannot be represented as {kind} ({error})"
) from error
return tokens_as(column, kind)
except RowBuiltFormUnavailable as error:
raise RowBuiltFormUnavailable(f"{name}: {error}") from error


def concatenate_batches(batches: Sequence[pa.RecordBatch]) -> pa.Table | None:
Expand Down Expand Up @@ -1355,7 +1437,7 @@ def concatenate_batches(batches: Sequence[pa.RecordBatch]) -> pa.Table | None:
fields: list[pa.Field[Any]] = [] # pyright: ignore[reportExplicitAny] # any field
for field, column in zip(batch.schema, batch.columns, strict=True):
if field.name in settled:
column = _tokens_as(column, settled[field.name], field.name)
column = _named_tokens_as(column, settled[field.name], field.name)
field = pa.field(field.name, settled[field.name])
if field.name.startswith(prefixes):
field = field.with_nullable(True)
Expand Down
43 changes: 32 additions & 11 deletions src/orcapod/core/operators/streaming_joins.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,11 @@
SemiJoin,
_has_whole_key, # pyright: ignore[reportPrivateUsage] # SemiJoin's one rule
)
from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod
from orcapod.core.operators.static_output_pod import (
RowBuiltFormUnavailable,
StaticOutputOperatorPod,
tokens_as,
)
from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns
from orcapod.protocols.core_protocols import StreamProtocol
from orcapod.system_constants import constants
Expand Down Expand Up @@ -574,18 +578,31 @@ def _as_input_table(self, input_index: int, batch: pa.RecordBatch) -> pa.Table:
+ f"the column(s) {missing} its stream describes"
)
table = pa.Table.from_batches([batch]).select(layout.names)
for field, actual in zip(layout, table.schema):
if field.type != actual.type and (
table.num_rows or not pa.types.is_null(actual.type)
):
raise ValueError(
f"{type(self).__name__}: column {field.name!r} of input "
+ f"{input_index} is {actual.type} in a batch, but "
+ f"{field.type} in its stream"
)
columns = list(table.columns)
for index, (field, actual) in enumerate(zip(layout, table.schema)):
if field.type == actual.type:
continue
if not table.num_rows and pa.types.is_null(actual.type):
continue
if table.num_rows and field.name.startswith(constants.SOURCE_PREFIX):
# A batch's token type follows its own tokens and can be shallower
# than the layout's (a null or an empty list fixes fewer list
# levels): the tokens are converted, every value kept.
try:
columns[index] = pa.chunked_array(
[tokens_as(table.column(index).combine_chunks(), field.type)]
)
continue
except RowBuiltFormUnavailable:
pass
raise ValueError(
f"{type(self).__name__}: column {field.name!r} of input "
+ f"{input_index} is {actual.type} in a batch, but "
+ f"{field.type} in its stream"
)
if not table.num_rows:
return layout.empty_table()
return pa.Table.from_arrays(table.columns, schema=layout)
return pa.Table.from_arrays(columns, schema=layout)

def _emitted(self, tables: list[pa.Table]) -> list[pa.RecordBatch]:
"""The record batches of the output tables, holding ``output_columns``.
Expand Down Expand Up @@ -787,6 +804,10 @@ def __init__(self, operator: MergeJoin, inputs: Sequence[StreamProtocol]) -> Non
left, right = inputs
left_tags, left_data = left.keys()
right_tags, right_data = right.keys()
# The data columns the batches carry: a raw stream lists its meta columns
# as data, and no operator carries them (they are not in the layouts).
left_data = [n for n in left_data if n in self._layouts[0].names]
right_data = [n for n in right_data if n in self._layouts[1].names]
self._shared_tags = set(left_tags) & set(right_tags)
merged = Join._merged_data_tags( # pyright: ignore[reportPrivateUsage] # Join's one rule
left_tags, stream_data_tags(left), right_tags, stream_data_tags(right)
Expand Down
13 changes: 12 additions & 1 deletion src/orcapod/core/record_batch_channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,8 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None:
The batch must have the description's columns, compared by name (their order is
not compared: the channel keeps one order of its own), each with exactly
the description's type in its large variant (no other representation is taken and
converted: type strictness), the same nullability and the same field metadata. A
converted: type strictness), the same nullability (and no null where the
description's field is not nullable) and the same field metadata. A
``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
Expand Down Expand Up @@ -457,6 +458,10 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None:
f"column {column.name!r} is {flags[column.nullable]}, the stream's is "
+ flags[expected.nullable]
)
if not expected.nullable and batch.column(index).null_count:
# The flag says nothing about the values: a field marked non-nullable
# may still hold nulls, which a reader of the stream never expects.
return f"column {column.name!r} holds nulls, the stream's is not nullable"
if (expected.metadata or None) != (column.metadata or None) or not (
column.type.equals(carried, check_metadata=True)
):
Expand Down Expand Up @@ -491,6 +496,12 @@ def _without_metadata(kind: pa.DataType) -> pa.DataType:
return pa.struct(
[_field_without_metadata(kind.field(i)) for i in range(kind.num_fields)]
) # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType]
if isinstance(kind, pa.MapType):
return pa.map_( # pyright: ignore[reportCallIssue] # pyarrow takes fields for the key and item; the stubs say types
_field_without_metadata(kind.key_field), # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType]
_field_without_metadata(kind.item_field), # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType]
keys_sorted=kind.keys_sorted,
)
return kind


Expand Down
46 changes: 44 additions & 2 deletions src/orcapod/core/streams/record_batch_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from __future__ import annotations

import asyncio
import functools
import weakref
from collections.abc import AsyncIterator, Coroutine
from typing import TYPE_CHECKING, Any, Protocol
Expand Down Expand Up @@ -143,7 +144,7 @@ def reserve(self, claim: object | None = None) -> object:
f"The input channel of {_named(self._stream)} is claimed by "
+ "another consumer."
)
self._owner = _current_task()
self._bind_owner(_current_task())
self._drop_claim() # redeemed: a later reserve(claim) is refused
return claim
if self._started or self._ended or self._owner is not None:
Expand Down Expand Up @@ -184,6 +185,29 @@ def _abandon(self) -> None:
self._ended = True
self._owner = None

def _bind_owner(self, task: asyncio.Task[Any] | None) -> None: # pyright: ignore[reportExplicitAny] # any task
"""Make ``task`` the channel's one consumer.

When the task finishes (or is cancelled) while it still owns the channel,
before the end and without closing it, the channel is closed: its consumer is
gone, and no producer may wait for it.
"""
self._owner = task
if task is not None:
task.add_done_callback(
functools.partial(_owner_finished, weakref.ref(self))
)

def _owner_gone(self, task: asyncio.Task[Any]) -> None: # pyright: ignore[reportExplicitAny] # any task
"""Close the channel if ``task`` still owns it: the consumer finished."""
if self._owner is not task or self._ended:
return
self._closed = True
self._ended = True
self._owner = None
self._drop_claim()
self._feed.close()

def _belong_to_caller(self) -> None:
"""Bind the channel to the calling task on its first read; refuse any other.

Expand All @@ -197,7 +221,7 @@ def _belong_to_caller(self) -> None:
+ "conversion that has not started; no other read is taken."
)
if self._owner is None:
self._owner = task
self._bind_owner(task)
elif self._owner is not task:
raise RuntimeError(
f"The input channel of {_named(self._stream)} belongs to another "
Expand Down Expand Up @@ -368,6 +392,24 @@ class _Claim:
"""


def _owner_finished(
channel_ref: weakref.ref[InputChannel],
task: asyncio.Task[Any], # pyright: ignore[reportExplicitAny] # any task
) -> None:
"""Release a reader whose consumer task finished between reads.

A done callback of the owning task: the channel, if it still exists and the task
still owns it before its end, is closed (``InputChannel._owner_gone``).

Args:
channel_ref: The channel, held weakly.
task: The finished task.
"""
channel = channel_ref()
if channel is not None:
channel._owner_gone(task) # pyright: ignore[reportPrivateUsage] # the task's release


def _release_claim(feed: BatchFeed, channel_ref: weakref.ref[InputChannel]) -> None:
"""Release a reader whose claim was freed before any task took it over.

Expand Down
Loading
Loading