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
20 changes: 19 additions & 1 deletion src/orcapod/core/operators/static_output_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -1735,14 +1735,32 @@ def _typed_zero_row_table(self) -> pa.Table | None:
table = typed_zero_row_table(upstream)
if table is None:
return None
context = StaticOutputOperatorPod._upstream_context(upstream)
if upstream.producer is None:
# An upstream with no producer (a raw stream, a source) states its own
# pipeline hash, which a stream rebuilt from its zero-row table would
# not (a raw stream's meta columns enter its hash, and its zero-row
# table has none): the system-tag names then follow the upstream's
# hash, as on the sync path (``_as_upstream_stream``'s rule).
inputs.append(
_RowsOfStream(
table,
tag_columns=upstream.keys()[0],
pipeline_hash=upstream.pipeline_hash(),
data_tags=stream_data_tags(upstream),
upstreams=upstream.upstreams,
data_context=context,
)
)
continue
inputs.append(
ArrowTableStream(
table,
tag_columns=upstream.keys()[0],
data_tags=stream_data_tags(upstream),
producer=upstream.producer,
upstreams=upstream.upstreams,
data_context=StaticOutputOperatorPod._upstream_context(upstream),
data_context=context,
)
)
pod = cast(StaticOutputOperatorPod, self._pod)
Expand Down
33 changes: 27 additions & 6 deletions src/orcapod/core/record_batch_channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,8 @@ def __init__(
# Each source-info column's token type as the batches accepted so far settle it
# (``settle_token_types``): a later batch must settle with it.
self._token_types: dict[str, pa.DataType] = {}
# The column order of the channel's batches: the first batch with rows'.
self._order: list[str] | None = None
self._changed = asyncio.Event()

@property
Expand Down Expand Up @@ -185,8 +187,19 @@ def _raise_if_ended(self) -> None:
if self._closed:
raise ChannelClosed("Cannot send to a closed channel")

def _check_schema(self, batch: pa.RecordBatch) -> None:
"""Raise unless ``batch`` has the schema of this channel's record batches."""
def _check_schema(self, batch: pa.RecordBatch) -> pa.RecordBatch:
"""Check ``batch`` against the channel's description; return it in the
channel's column order.

The columns are compared by name, not by position: a result's column order
may follow its input's arrangement where the description follows another
(an order-only difference, which no stored table depends on). The first batch
with rows fixes the channel's column order, and a later batch is put into it,
so that the batches can be put under one another.

Raises:
ValueError: If the batch's columns are not the stream's.
"""
names = batch.schema.names
if len(set(names)) != len(names):
repeated = sorted({name for name in names if names.count(name) > 1})
Expand Down Expand Up @@ -220,6 +233,12 @@ def _check_schema(self, batch: pa.RecordBatch) -> None:
token_types = settle_token_types(batch, self._token_types)
self._schema = schema
self._token_types = token_types
if batch.num_rows:
if self._order is None:
self._order = names
elif names != self._order:
batch = batch.select(self._order)
return batch

async def send(self, batch: pa.RecordBatch) -> None:
"""Send one Arrow record batch of the stream's transport columns.
Expand All @@ -242,7 +261,7 @@ async def send(self, batch: pa.RecordBatch) -> None:
ValueError: If the batch's schema is not the stream's.
"""
self._raise_if_ended()
self._check_schema(batch)
batch = self._check_schema(batch)
if not batch.num_rows:
return
self._sent += 1
Expand Down Expand Up @@ -389,7 +408,8 @@ def _named(stream: Any) -> str: # pyright: ignore[reportExplicitAny] # any str
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``.

The batch must have the description's columns in the same order, each with exactly
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
``null`` type of the description (anywhere in a column's type) is carried as
Expand All @@ -401,10 +421,11 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None:
or ``large_list`` of a token type).
"""
sent = batch.schema
if declared.names != sent.names:
if sorted(declared.names) != sorted(sent.names):
return f"it has {sent.names}, the stream has {declared.names}"
provenance = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX)
for index, (expected, column) in enumerate(zip(declared, sent)):
for index, column in enumerate(sent):
expected = declared.field(column.name)
carried = arrow_utils.normalize_to_large_types(expected.type)
if column.name.startswith(constants.SOURCE_PREFIX):
if not _is_token_type(column.type):
Expand Down
119 changes: 119 additions & 0 deletions tests/test_channels/test_record_batch_channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -1062,6 +1062,125 @@ async def write() -> None:
run(write)


def _in_order(batch: pa.RecordBatch, names: Sequence[str]) -> pa.RecordBatch:
return batch.select(list(names))


@pytest.mark.parametrize("retain", [True, False], ids=["retained", "bounded"])
@pytest.mark.parametrize("declared", [True, False], ids=["declared", "undeclared"])
def test_the_first_batch_fixes_the_column_order(retain: bool, declared: bool) -> None:
"""Columns are compared by name: a batch whose columns are the stream's in another
order is taken (a column order is not a result). The first batch with rows fixes
the channel's order, and every later batch is put into it, never the other way
round."""
table = source().as_table(columns=ALL)
stream = (
source()
if declared
else _UntypedStream(
table, tag_columns=["subject", "trial"], data_tags=["trial"]
)
)
assert stream.arrow_types_declared is declared
first, second, third = batches_of(stream, 3)
names = first.schema.names
reversed_names = list(reversed(names))
shuffled = names[1::2] + names[::2]
assert len({tuple(names), tuple(reversed_names), tuple(shuffled)}) == 3
sent = [
_in_order(first, reversed_names),
second, # the description's order
_in_order(third, shuffled),
]

def names_of(batch: pa.RecordBatch) -> list[str]:
return batch.schema.names

async def through_reader() -> tuple[list[list[str]], Any]:
output = OutputChannel(stream, retain=retain, buffer_size=4)
reader = output.open_reader()
received: list[list[str]] = []
for batch in sent:
await output.send(batch)
received.append(names_of(await reader.receive()))
await output.close()
return received, output.result() if retain else None

received, result = run(through_reader)
assert received == [reversed_names] * 3
if result is not None:
rows = result.as_table(columns=ALL)
assert rows.num_rows == 7
assert sorted(rows.column_names) == sorted(names)

async def in_description_order() -> Any:
output = OutputChannel(stream)
for batch in (first, second, third):
await output.send(batch)
await output.close()
return output.result()

expected = run(in_description_order).as_table(columns=ALL)
assert same(rows.select(expected.column_names), expected)


@pytest.mark.parametrize("declared", [True, False], ids=["declared", "undeclared"])
def test_a_reordered_batch_must_still_have_the_streams_columns(declared: bool) -> None:
"""Order aside, the check is unchanged: names match exactly (case counts), and each
column's type and nullability are the description's (or the first batch's, without
Arrow types). A refused batch fixes no order."""
table = source().as_table(columns=ALL)
stream = (
source()
if declared
else _UntypedStream(
table, tag_columns=["subject", "trial"], data_tags=["trial"]
)
)
first, second = batches_of(stream, 4)
reversed_names = list(reversed(first.schema.names))

def reordered(batch: pa.RecordBatch) -> pa.RecordBatch:
return _in_order(batch, reversed_names)

recased = reordered(second).rename_columns(
["Note" if name == "note" else name for name in reversed_names]
)
retyped = reordered(second)
retyped = retyped.set_column(
retyped.schema.get_field_index("amplitude"),
"amplitude",
retyped.column("amplitude").cast(pa.float64()),
)
reflagged = reordered(second)
reflagged = pa.RecordBatch.from_arrays(
reflagged.columns,
schema=pa.schema(
[
f.with_nullable(not f.nullable) if f.name == "trial" else f
for f in reflagged.schema
]
),
)

async def write() -> list[str]:
output = OutputChannel(stream)
reader = output.open_reader()
await output.send(first) # fixes the description's order
for wrong, said in (
(recased, "'Note'"),
(retyped, "column 'amplitude' is double"),
(reflagged, "column 'trial' is (not )?nullable"),
):
with pytest.raises(ValueError, match=said):
await output.send(wrong)
await output.send(reordered(second))
_ = await reader.receive()
return (await reader.receive()).schema.names

assert run(write) == first.schema.names


def test_what_a_description_does_not_say_is_accepted() -> None:
"""A ``null`` column travels as ``large_string``, and a source-info field's
nullability is set over the complete table: neither is a mismatch."""
Expand Down
Loading
Loading