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
9 changes: 7 additions & 2 deletions .zed/rules
Original file line number Diff line number Diff line change
Expand Up @@ -1342,8 +1342,13 @@ data. The rules:
- Every output column takes the large-normalized form of its input type
(arrow_utils.normalize_to_large_types: string to large_string, binary to large_binary, list
to large_list, recursively). Width, nullability and logical (extension) types are never
changed; int8 stays int8, and null stays null (operators and the type converter pass
keep_null=True; only Data maps null to large_string, the function's default).
changed, so `int8` stays `int8`. Sources refuse Arrow type `null` at any depth, including
in reserved raw columns. Declare a supported nullable type for missing values.
A source's custom system-tag names must each identify an existing non-nullable text
column with no null values. When Join sorts tied system tags, an output field is
nullable if any of the corresponding input fields can hold a null.
A raw `ArrowTableStream` still preserves `null` in its table in ITL-1543 part A.
A row built by `Data` still gives an untyped null the `large_string` type.
PolarsFilter is the one operator that still round-trips its columns through Polars; it
casts them back to the normalized input types (arrow_utils.restore_column_types and
restore_schema_nullability). Every other operator takes its values from the input's Arrow
Expand Down
9 changes: 7 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -1390,8 +1390,13 @@ data. The rules:
- Every output column takes the large-normalized form of its input type
(`arrow_utils.normalize_to_large_types`: `string` to `large_string`, `binary` to `large_binary`, `list`
to `large_list`, recursively). Width, nullability and logical (extension) types are never
changed; `int8` stays `int8`, and `null` stays `null` (operators and the type converter pass
`keep_null=True`; only `Data` maps `null` to `large_string`, the function's default).
changed, so `int8` stays `int8`. Sources refuse Arrow type `null` at any depth, including
in reserved raw columns. Declare a supported nullable type for missing values.
A source's custom system-tag names must each identify an existing non-nullable text
column with no null values. When Join sorts tied system tags, an output field is
nullable if any of the corresponding input fields can hold a null.
A raw `ArrowTableStream` still preserves `null` in its table in ITL-1543 part A.
A row built by `Data` still gives an untyped null the `large_string` type.
`PolarsFilter` is the one operator that still round-trips its columns through Polars; it
casts them back to the normalized input types (`arrow_utils.restore_column_types` and
`restore_schema_nullability`). Every other operator takes its values from the input's Arrow
Expand Down
14 changes: 14 additions & 0 deletions changelog.d/ITL-1543.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
### Breaking changes and migration

- Sources reject Arrow `null` fields at any depth, including in reserved columns.
Declare a supported nullable column type for missing values.
- A custom system-tag column on a source must be a non-nullable string column
with no null values. Sources also reject missing names in `system_tag_columns`.
Convert custom tags to text before building the source.

### Fixed

- Join uses the declared fields of inputs tied on pipeline hash to set the
sorted system tags' nullability. The tag is non-nullable when every
corresponding input field is non-nullable. Existing entry IDs, instance IDs,
record IDs and operator hashes for source inputs stay the same.
14 changes: 14 additions & 0 deletions docs/dev/design_issues/ITL-1543-AS2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
## `src/orcapod/core/streams/`

### AS2 — A stream's Arrow table and its rows can disagree about column types
**Status:** in progress
**Severity:** high
**Issue:** ITL-1543

The stream defines the Arrow schema of each row. Today a row can rebuild its
columns in a different form, which makes identity and storage depend on how the
data was read. For example, a Join of streams tied on pipeline hash can declare
its sorted system tags nullable, although its rows have non-nullable system tags.

Part A corrects that Join schema and rejects Arrow Null in sources, including
nested Null. Part B remains open and makes rows use the stream's field definitions.
19 changes: 15 additions & 4 deletions src/orcapod/core/operators/join.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import itertools
import json
from collections.abc import Callable, Collection, Mapping, Sequence
from typing import Any, ClassVar
from typing import Any, ClassVar, get_args

import polars as pl
import pyarrow as pa
Expand Down Expand Up @@ -44,7 +44,7 @@
TagProtocol,
)
from orcapod.system_constants import constants
from orcapod.types import ColumnConfig, ContentHash, DataValue, Schema
from orcapod.types import ColumnConfig, ContentHash, DataType, DataValue, Schema
from orcapod.utils import arrow_utils, schema_utils

# The row-number columns of the frames Polars joins (``_inner_join``); a tag, so a
Expand Down Expand Up @@ -422,7 +422,7 @@ def _predict_system_tag_schema(self, *streams: StreamProtocol) -> Schema:
n_char = self.orcapod_config.hashing.system_tag_n_char
ordered_streams = self.order_input_streams(*streams)

system_tag_fields: dict[str, type] = {}
system_tag_fields: dict[str, DataType] = {}
for idx, stream in enumerate(ordered_streams):
stream_tag_schema, _ = stream.output_schema(columns={"system_tags": True})
for col_name, col_type in stream_tag_schema.items():
Expand All @@ -432,7 +432,18 @@ def _predict_system_tag_schema(self, *streams: StreamProtocol) -> Schema:
f"{stream.pipeline_hash().to_hex(n_char)}:{idx}"
)
system_tag_fields[new_name] = col_type
return Schema(system_tag_fields)
nullable = arrow_utils.sorted_system_tag_nullability(
{
name: kind is type(None) or type(None) in get_args(kind)
for name, kind in system_tag_fields.items()
}
)
return Schema(
{
name: kind | None if nullable[name] else kind
for name, kind in system_tag_fields.items()
}
)

def static_process(self, *streams: StreamProtocol) -> StreamProtocol:
"""Join the streams on their shared tag columns.
Expand Down
49 changes: 38 additions & 11 deletions src/orcapod/core/operators/streaming_joins.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,9 @@
batch of pairs gives the sync rows.
- **Field flags.** A batch's flags are the sync result's, except the system-tag and
source-info fields: a complete table decides those by its values (``StaticOutputOperatorPod._flag_by_values``,
the last step of F), so a kernel declares every such field nullable and the stream made
from its batches settles them.
the last step of F). The input layout declares these fields nullable and the stream
made from the batches settles them. Join's sorted system-tag fields are already
declared non-nullable when the kernel emits them.

A kernel holds only what can still match: a side's rows are dropped when the other side
closes (nothing can arrive to match them), and an arriving row is not kept once the
Expand Down Expand Up @@ -130,13 +131,15 @@
_ROW = ("__streaming_left_row", "__streaming_right_row")


def _settled_by_values(schema: pa.Schema) -> pa.Schema:
"""``schema`` with every system-tag and source-info field nullable.
def _settled_by_values(schema: pa.Schema, *, system_tags: bool = True) -> pa.Schema:
"""``schema`` with source-info and, optionally, system-tag fields nullable.

What a kernel declares for the fields a complete table decides by its values
(``StaticOutputOperatorPod._flag_by_values``): one record batch of many cannot.
"""
prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX)
prefixes = (constants.SOURCE_PREFIX,)
if system_tags:
prefixes = (*prefixes, constants.SYSTEM_TAG_PREFIX)
return pa.schema(
[
field.with_nullable(True) if field.name.startswith(prefixes) else field
Expand All @@ -145,14 +148,17 @@ def _settled_by_values(schema: pa.Schema) -> pa.Schema:
)


def _row_built_zero_rows(stream: StreamProtocol) -> tuple[StreamProtocol, bool]:
def _row_built_zero_rows(
stream: StreamProtocol, *, keep_system_tag_flags: bool = False
) -> tuple[StreamProtocol, bool]:
"""``stream`` with no rows, as an input rebuilt from rows of it reads.

The zero-row input (``_materialize_upstream`` with no rows) put through F: what
``_materialize_upstream(rows, stream, zero_rows=True)`` gives, without rows.

Args:
stream: An input stream (its description).
keep_system_tag_flags: Use the input's declared system-tag nullability.

Returns:
The zero-row stream in the row-built form, and whether its Arrow types differ
Expand All @@ -163,6 +169,14 @@ def _row_built_zero_rows(stream: StreamProtocol) -> tuple[StreamProtocol, bool]:
zero = pod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the operators' one form of an input
table = zero.as_table(columns=ZERO_ROW_INPUT_COLUMNS)
row_built = pod._flag_by_values(row_built_columns(table, stream.keys())) # pyright: ignore[reportPrivateUsage] # F's last step
if keep_system_tag_flags:
fields = [
field.with_nullable(table.schema.field(field.name).nullable)
if field.name.startswith(constants.SYSTEM_TAG_PREFIX)
else field
for field in row_built.schema
]
row_built = pa.Table.from_arrays(row_built.columns, schema=pa.schema(fields))
differs = any(
field.type != table.schema.field(field.name).type for field in row_built.schema
)
Expand Down Expand Up @@ -410,6 +424,7 @@ class StreamingJoinKernel(ABC):

# How many inputs the operator takes; ``None`` for one or more.
ARITY: ClassVar[int | None] = None
KEEP_SYSTEM_TAG_FLAGS: ClassVar[bool] = False

def __init__(
self, operator: StaticOutputOperatorPod, inputs: Sequence[StreamProtocol]
Expand All @@ -424,13 +439,21 @@ def __init__(
self.inputs: tuple[StreamProtocol, ...] = tuple(inputs)
# Each input as the sync path reads rows of it, with no rows (the row-built
# form), and whether that differs from how it reads the input with none.
built = [_row_built_zero_rows(stream) for stream in self.inputs]
built = [
_row_built_zero_rows(
stream, keep_system_tag_flags=self.KEEP_SYSTEM_TAG_FLAGS
)
for stream in self.inputs
]
self._zero_rows: tuple[StreamProtocol, ...] = tuple(z for z, _ in built)
self._null_typed: tuple[bool, ...] = tuple(d for _, d in built)
# The schema of every batch of an input, in its row-built layout; the fields a
# complete table decides by values declared nullable.
self._layouts: tuple[pa.Schema, ...] = tuple(
_settled_by_values(stream.as_table(columns=TRANSPORT_COLUMNS).schema)
_settled_by_values(
stream.as_table(columns=TRANSPORT_COLUMNS).schema,
system_tags=not self.KEEP_SYSTEM_TAG_FLAGS,
)
for stream in self._zero_rows
)
self._closed: list[bool] = [False] * len(self.inputs)
Expand Down Expand Up @@ -646,16 +669,18 @@ def _check_settled_token_types(
def _emitted(self, tables: list[pa.Table]) -> list[pa.RecordBatch]:
"""The record batches of the output tables, holding ``output_columns``.

Every system-tag and source-info field is declared nullable: the complete
table's values decide those flags (``StaticOutputOperatorPod._flag_by_values``).
A source-info field is nullable until the complete table settles its flag
(``StaticOutputOperatorPod._flag_by_values``). System tags keep the field
from the kernel so Join's sorted tags retain their non-nullable declaration.
"""
batches: list[pa.RecordBatch] = []
for table in tables:
if table.num_rows:
self._emitted_any = True
table = table.select(list(self.output_columns)).combine_chunks()
table = pa.Table.from_arrays(
table.columns, schema=_settled_by_values(table.schema)
table.columns,
schema=_settled_by_values(table.schema, system_tags=False),
)
batches.extend(table.to_batches())
return batches
Expand All @@ -682,6 +707,8 @@ class StreamingJoin(StreamingJoinKernel):
inputs: Its input streams, in call order.
"""

KEEP_SYSTEM_TAG_FLAGS: ClassVar[bool] = True

def __init__(self, operator: Join, inputs: Sequence[StreamProtocol]) -> None:
super().__init__(operator, inputs)
self._join = operator
Expand Down
2 changes: 2 additions & 0 deletions src/orcapod/core/sources/arrow_table_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from orcapod.core.sources.stream_builder import SourceStreamBuilder
from orcapod.core.sources.stream_builder import (
normalize_record_id_columns,
require_supported_nullable_types,
)
from orcapod.utils import arrow_utils
from orcapod.utils.schema_utils import _normalize_column_list
Expand Down Expand Up @@ -109,6 +110,7 @@ def __init__(
tag_columns = _normalize_column_list(tag_columns)

if infer_nullable:
require_supported_nullable_types(table.schema)
logger.debug(
"infer_nullable=True: deriving nullable flags from data "
"(nullable=True only for columns with null_count > 0)"
Expand Down
23 changes: 20 additions & 3 deletions src/orcapod/core/sources/cached_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from orcapod.config import OrcapodConfig
from orcapod.core.sources.base import RootSource
from orcapod.core.sources.source_ids import parse_source_id
from orcapod.core.sources.stream_builder import require_supported_nullable_types
from orcapod.errors import (
CachedSourceIdMismatchError,
InputValidationError,
Expand Down Expand Up @@ -269,7 +270,10 @@ def source_name(self) -> str:

def _compute_arrow_schemas(self) -> "tuple[pa.Schema, pa.Schema]":
"""The wrapped source's Arrow schemas: the cache stores that source's rows."""
return typed_arrow_schemas(self._source)
schemas = typed_arrow_schemas(self._source)
for schema in schemas:
require_supported_nullable_types(schema)
return schemas

# -------------------------------------------------------------------------
# Cache path — scoped to source's content hash
Expand Down Expand Up @@ -357,7 +361,15 @@ def _live_records(self) -> pa.Table:
refuse_restricted_cache_input(self._source)
require_same_data_context(self._source.data_context_key, self.data_context_key)
live_table = self._source.as_table(
columns={"source": True, "system_tags": True}
columns={"source": True, "system_tags": True, "meta": True}
)
require_supported_nullable_types(live_table.schema)
live_table = live_table.drop(
[
name
for name in live_table.column_names
if name.startswith(constants.META_PREFIX)
]
)

# Compute per-row record hashes for dedup: hash the full row including
Expand Down Expand Up @@ -519,6 +531,7 @@ def _read_cached_records_with_hashes(self) -> "pa.Table | None":
)
if records is None:
return None
require_supported_nullable_types(records.schema)
stored_rows = records.num_rows
records = keep_rows_of_data_context(records, self.data_context_key)
if records.num_rows < stored_rows and not self._skipped_rows_reported:
Expand Down Expand Up @@ -669,6 +682,7 @@ def _empty_table(self) -> pa.Table:
merged.update(data_schema)
type_converter = self.data_context.type_converter
arrow_schema = type_converter.python_schema_to_arrow_schema(merged)
require_supported_nullable_types(arrow_schema)
return pa.Table.from_pylist([], schema=arrow_schema)

@property
Expand Down Expand Up @@ -716,7 +730,10 @@ def _typed_zero_row_table(self) -> "pa.Table | None":

See ``typed_zero_row_table``; neither the cache nor the source is read.
"""
return typed_zero_row_table(self._source)
table = typed_zero_row_table(self._source)
if table is not None:
require_supported_nullable_types(table.schema)
return table

def _schema_requires_io(self, config: ColumnConfig) -> bool:
"""Whether reading the schema with ``config`` would poll: as for the wrapped source."""
Expand Down
15 changes: 12 additions & 3 deletions src/orcapod/core/sources/csv_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
normalize_record_id_columns,
SourceStreamBuilder,
SourceStreamResult,
require_custom_system_tags,
require_supported_nullable_types,
)
from orcapod.utils import arrow_utils
from orcapod.utils.schema_utils import _normalize_column_list
Expand Down Expand Up @@ -119,7 +121,9 @@ def _refuse_overflow(values: pa.ChunkedArray[Any], texts: pa.ChunkedArray[Any])
)


def _read_declared(path: str, schema: pa.Schema) -> pa.Table:
def _read_declared(
path: str, schema: pa.Schema, system_tag_columns: Collection[str]
) -> pa.Table:
"""Read a CSV file with every column parsed as ``schema`` declares it (ITL-1322).

The text of each cell is parsed as its column's declared type; nothing is
Expand Down Expand Up @@ -246,7 +250,8 @@ def as_text(columns: list[str], include: list[str]) -> pa_csv.ConvertOptions:
table = table.set_column(
table.column_names.index(field.name), field.name, value
)
# A null in a non-nullable field raises here, naming the field.
require_custom_system_tags(table, system_tag_columns, schema=schema)
# A null in an ordinary non-nullable field raises here, naming the field.
return table.cast(schema)


Expand Down Expand Up @@ -343,9 +348,13 @@ def _read_table(self) -> pa.Table:

if self._schema is None:
table: pa.Table = pa_csv.read_csv(self._access_path)
require_supported_nullable_types(table.schema)
return table.cast(arrow_utils.infer_schema_nullable(table))
require_supported_nullable_types(self._schema)
try:
return _read_declared(self._access_path, self._schema)
return _read_declared(
self._access_path, self._schema, self._system_tag_columns
)
except ValueError as exc: # pyarrow's ArrowInvalid is a ValueError
# The reader names a column by its position in the file, which is the
# schema's field order (a schema names every column, in order).
Expand Down
8 changes: 8 additions & 0 deletions src/orcapod/core/sources/data_frame_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
from orcapod.core.sources.stream_builder import SourceStreamBuilder
from orcapod.core.sources.stream_builder import (
normalize_record_id_columns,
require_custom_system_tags,
require_supported_nullable_types,
)
from orcapod.utils import arrow_utils, polars_data_utils
from orcapod.utils.schema_utils import _normalize_column_list
Expand Down Expand Up @@ -78,6 +80,9 @@ def __init__(

tag_columns = _normalize_column_list(tag_columns)

require_supported_nullable_types(
polars_data_utils.get_system_columns(df).to_arrow().schema
)
df = polars_data_utils.drop_system_columns(df)

missing = set(tag_columns) - set(df.columns)
Expand All @@ -86,10 +91,13 @@ def __init__(

arrow_table = df.to_arrow()
if schema is not None:
require_supported_nullable_types(schema)
require_custom_system_tags(arrow_table, system_tag_columns, schema=schema)
arrow_table = arrow_table.cast(schema)
else:
# Polars defaults all fields to nullable=True; infer the correct
# flags from the actual data before passing to the builder.
require_supported_nullable_types(arrow_table.schema)
arrow_table = arrow_table.cast(
arrow_utils.infer_schema_nullable(arrow_table)
)
Expand Down
Loading
Loading