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: 4 additions & 0 deletions changelog.d/ITL-1333.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Fixed

- Sources reject Arrow fields that carry a logical type annotation on plain storage,
including nested fields. The error names the column and its logical type.
6 changes: 6 additions & 0 deletions docs/concepts/logical-type-identifiers.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ Two columns with the same identifier hold values in the same layout, hashed by t
rule. Orcapod treats the identifier as opaque. It never interprets the metadata; it only
stores it, hashes it and compares it byte for byte.

When you supply Arrow data to a source, logical columns must use their live Arrow
extension types. A plain storage field with an extension annotation is refused, including
inside a list, struct or map. Pass the column as its logical type, or remove the extension
annotation if the column is meant to hold plain data. Orcapod continues to decode its own
stored results when reading caches and derived sources.

## Where the identifier goes

- **Stored with the column.** The name and metadata are written as the column's
Expand Down
17 changes: 11 additions & 6 deletions docs/concepts/sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,20 +228,22 @@ nullable item. Use matching nested flags when joining sources or binding a slot.

The inner field's `nullable` flag is part of a list column's type. Orcapod preserves the
inner field's name and metadata in the source's Arrow schema. When hashing the schema,
Orcapod ignores the item name and ordinary metadata. An Arrow extension identifier,
stored in `ARROW:extension:*` metadata, contributes to the hash.
Orcapod ignores the item name and ordinary metadata. An Arrow extension identifier
contributes to the schema hash. If a plain storage field carries that identifier only in
`ARROW:extension:*` metadata, the source refuses it, including on a list item.

Streaming joins compare the types of incoming user columns without considering list item
names or metadata. They check source-info columns more strictly. When validating a
materialized operator result against its declared schema before caching it, Orcapod also
checks the item names and metadata of the fields it validates.

This example compares the original source's pipeline hash with the hash after each schema
change.
This example compares pipeline hashes for ordinary list item changes and shows what happens
when a stored logical type reaches the source.

```python
import pyarrow as pa

from orcapod.errors import InputValidationError
from orcapod.sources import ArrowTableSource


Expand All @@ -261,8 +263,11 @@ print("Required item:", original == list_source(nullable=False).pipeline_hash())
# Required item: False

uuid_metadata = {"ARROW:extension:name": "arrow.uuid", "ARROW:extension:metadata": ""}
print("UUID extension:", original == list_source(metadata=uuid_metadata).pipeline_hash())
# UUID extension: False
try:
list_source(metadata=uuid_metadata)
except InputValidationError as exc:
print(exc)
# Source column(s) 'values'.'item' ('arrow.uuid' (b'')) carry logical types in stored form. Pass each column as its logical Arrow extension type, or drop the annotation if the column is meant as plain data.
```

When `DictSource` or `ListSource` builds a source from Python values, it checks the
Expand Down
18 changes: 18 additions & 0 deletions docs/dev/design_issues/ITL-1333-BL17.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
## `src/orcapod/core/sources/`

### BL17 — A source read a stored logical column as plain data
**Status:** resolved
**Severity:** high
**Issue:** ITL-1333

An Arrow source could read a Path column as text when the Arrow field carried the type
identifier in metadata. A live extension array with the same values had the same pipeline
and content hashes but gave downstream functions Path objects.

**Fix:** Refuse external Arrow fields that carry logical annotations on their storage type,
including nested fields in pandas Arrow-backed columns. For native PyArrow inputs, including
struct arrays and chunked struct arrays, use the original fields before a C round-trip can
change their types. For third-party Arrow C exporters, use the field type and metadata
after importing into PyArrow. The existing decoding of
Orcapod-owned stored records retains its behavior. Resolving stored logical types at
external source boundaries is planned separately.
6 changes: 3 additions & 3 deletions docs/reference/hashing.md
Original file line number Diff line number Diff line change
Expand Up @@ -1958,9 +1958,9 @@ The same walker gives the form of every other place a schema is compared or save
type at the top of a column becomes the live type, which is what a source holds and what
gives the column its Python type. Arrow cannot build an empty table with an extension type
inside a list, struct or map, so an identifier nested in a plain container is never made
live: it stays in the storage form, and the slot, a source of the same table and the
slot made from that source have one Python schema, one Arrow schema and one pipeline
hash.
live. Blueprint slots, saved schemas and raw Arrow streams can still carry the stored
identifier. Sources, including a polling implementation's Arrow declaration, require
incoming logical fields to be live extension types.

Python declarations produce implicitly nullable nested fields in data context v1.
For example, `list[int]` and `list[int | None]` convert to the same Arrow type
Expand Down
2 changes: 2 additions & 0 deletions src/orcapod/core/sources/csv_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
SourceStreamResult,
require_custom_system_tags,
require_supported_nullable_types,
require_live_logical_types,
)
from orcapod.utils import arrow_utils
from orcapod.utils.schema_utils import _normalize_column_list
Expand Down Expand Up @@ -351,6 +352,7 @@ def _read_table(self) -> pa.Table:
require_supported_nullable_types(table.schema)
return table.cast(arrow_utils.infer_schema_nullable(table))
require_supported_nullable_types(self._schema)
require_live_logical_types(self._schema, exclude=self._system_tag_columns)
try:
return _read_declared(
self._access_path, self._schema, self._system_tag_columns
Expand Down
45 changes: 21 additions & 24 deletions src/orcapod/core/sources/data_frame_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,27 @@
from collections.abc import Collection
from typing import TYPE_CHECKING, Any, ClassVar, cast

import pandas as pd
import polars as pl
import pyarrow as pa

from orcapod.core.sources.base import RootSource
from orcapod.core.data_tags import TagOnlyColumns, source_data_tags
from orcapod.core.sources.stream_builder import SourceStreamBuilder
from orcapod.core.sources.base import RootSource
from orcapod.core.sources.stream_builder import (
normalize_record_id_columns,
SourceStreamBuilder,
declare_native_custom_system_tags,
normalize_record_id_columns,
read_arrow_frame_input,
require_custom_system_tags,
require_custom_system_tags_values,
require_live_logical_types,
require_supported_nullable_types,
)
from orcapod.errors import InputValidationError
from orcapod.utils import arrow_utils, polars_data_utils
from orcapod.utils.schema_utils import _normalize_column_list

if TYPE_CHECKING:
from polars._typing import (
ArrowArrayExportable,
ArrowStreamExportable,
FrameInitTypes,
)
from polars._typing import FrameInitTypes

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -73,18 +70,13 @@ def __init__(
) -> None:
super().__init__(source_id=source_id, **kwargs)

arrow_input_schema = None
# Keep pandas and Polars on their native paths even if they export Arrow.
# For Arrow inputs, materialize once before Polars drops field metadata.
if not isinstance(data, (pd.DataFrame, pl.DataFrame, pl.Series)) and (
hasattr(data, "__arrow_c_stream__") or hasattr(data, "__arrow_c_array__")
):
# Like Polars, prefer the array export when both are available.
if hasattr(data, "__arrow_c_array__"):
batch = pa.record_batch(cast("ArrowArrayExportable", data))
arrow_input = pa.Table.from_batches([batch])
else:
arrow_input = pa.table(cast("ArrowStreamExportable", data))
input_schema = arrow_input_schema = None
if (
arrow_frame := read_arrow_frame_input(
data, system_tag_columns=system_tag_columns
)
) is not None:
arrow_input, input_schema = arrow_frame
if schema is None:
require_custom_system_tags(arrow_input, system_tag_columns)
else:
Expand Down Expand Up @@ -121,23 +113,27 @@ def __init__(

tag_columns = _normalize_column_list(tag_columns)

require_supported_nullable_types(
polars_data_utils.get_system_columns(df).to_arrow().schema
)
system_schema = polars_data_utils.get_system_columns(df).to_arrow().schema
require_supported_nullable_types(system_schema)
if input_schema is None:
require_live_logical_types(system_schema)
df = polars_data_utils.drop_system_columns(df)

missing = set(tag_columns) - set(df.columns)
if missing:
raise ValueError(f"TagProtocol column(s) not found in data: {missing}")

arrow_table = df.to_arrow()
if input_schema is None:
require_live_logical_types(arrow_table.schema, exclude=system_tag_columns)
if schema is not None:
require_supported_nullable_types(schema)
if arrow_input_schema is None:
require_custom_system_tags_values(arrow_table, system_tag_columns)
require_custom_system_tags(
arrow_table, system_tag_columns, schema=schema
)
require_live_logical_types(schema)
arrow_table = arrow_table.cast(schema)
elif arrow_input_schema is not None:
arrow_table = arrow_utils.restore_schema_nullability(
Expand Down Expand Up @@ -165,6 +161,7 @@ def __init__(
record_id_columns=self._key_columns,
hash_in_key_order=hash_in_key_order,
system_tag_columns=system_tag_columns,
input_schema=input_schema if schema is None else schema,
)

self._stream = result.stream
Expand Down
2 changes: 2 additions & 0 deletions src/orcapod/core/sources/db_table_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from orcapod.core.sources.stream_builder import (
require_custom_system_tags,
require_supported_nullable_types,
require_live_logical_types,
normalize_record_id_columns,
SourceStreamBuilder,
SourceStreamResult,
Expand Down Expand Up @@ -229,6 +230,7 @@ def _read_table(
if not batches:
raise ValueError(f"Table {self._table_name!r} is empty.")
table: pa.Table = pa.Table.from_batches(batches)
require_live_logical_types(table.schema, exclude=self._system_tag_columns)
# Apply database-defined nullability: the connector's get_column_info
# returns the authoritative nullable flag per column from the DB schema.
col_infos = connector.get_column_info(self._table_name)
Expand Down
2 changes: 2 additions & 0 deletions src/orcapod/core/sources/delta_table_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from orcapod.core.sources.stream_builder import (
normalize_record_id_columns,
SourceStreamBuilder,
require_live_logical_types,
SourceStreamResult,
)
from orcapod.databases.storage_utils import delta_to_pyarrow_dataset
Expand Down Expand Up @@ -148,6 +149,7 @@ def check_for_new_data(self) -> bool:
return False
table = self._read_table()
if not table.schema.equals(self._table.schema, check_metadata=True):
require_live_logical_types(table.schema)
raise ValueError(
f"Delta table {str(self._delta_table_path)!r} changed its columns at "
f"version {version}: the source was built with {self._table.schema}, "
Expand Down
1 change: 1 addition & 0 deletions src/orcapod/core/sources/derived_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,7 @@ def _derive_from(
source_name=self.source_name,
kind_part=self.kind_part(),
record_id_columns=self._record_id_columns or (),
from_origin=True,
)
return result.stream

Expand Down
2 changes: 2 additions & 0 deletions src/orcapod/core/sources/dict_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
normalize_record_id_columns,
declare_native_custom_system_tags,
require_supported_nullable_types,
require_live_logical_types,
)
from orcapod.types import DataValue, SchemaLike
from orcapod.utils import arrow_utils
Expand Down Expand Up @@ -87,6 +88,7 @@ def __init__(
# pa.Schema directly via data_schema; route to the converter accordingly.
if isinstance(data_schema, pa.Schema):
require_supported_nullable_types(data_schema)
require_live_logical_types(data_schema, exclude=system_tag_columns)
arrow_table = self.data_context.type_converter.python_dicts_to_arrow_table(
rows,
arrow_schema=data_schema,
Expand Down
38 changes: 26 additions & 12 deletions src/orcapod/core/sources/polling_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import threading
from collections.abc import Collection
from math import floor
from typing import Any, ClassVar, Generic, TYPE_CHECKING, TypeVar, cast
from typing import TYPE_CHECKING, Any, ClassVar, Generic, TypeVar, cast

import polars as pl
import pyarrow as pa
Expand All @@ -25,30 +25,32 @@
from orcapod.core.identity_chains import refuse_identity_io
from orcapod.core.sources.base import RootSource
from orcapod.core.sources.source_ids import hash_source_name
from orcapod.logical_types.canonical_form import declaration_form_schema
from orcapod.core.sources.stream_builder import (
SourceStreamBuilder,
normalize_record_id_columns,
read_arrow_frame_input,
require_live_logical_types,
require_supported_nullable_types,
validate_source_table,
)
from orcapod.core.streams.arrow_table_stream import stream_from_derived_table
from orcapod.core.streams.view import (
ViewStatus,
StreamView,
)
from orcapod.core.streams.base import (
check_head_size,
typed_zero_row_table,
)
from orcapod.core.streams.view import (
StreamView,
ViewStatus,
)
from orcapod.errors import (
CursorInvalidatedError,
InputValidationError,
RowIdentifierError,
SchemaInconsistencyError,
)
from orcapod.logical_types.canonical_form import declaration_form_schema
from orcapod.system_constants import constants
from orcapod.types import ContentHash, ColumnConfig, Cursor, PollingConfig, Schema
from orcapod.types import ColumnConfig, ContentHash, Cursor, PollingConfig, Schema
from orcapod.utils import arrow_utils
from orcapod.utils.arrow_utils import system_tag_column_names
from orcapod.utils.schema_utils import (
Expand All @@ -58,11 +60,11 @@
)

if TYPE_CHECKING:
from orcapod.protocols.hashing_protocols import SemanticHasherProtocol
from polars._typing import FrameInitTypes

from orcapod.core.streams.arrow_table_stream import ArrowTableStream
from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol
from orcapod.protocols.hashing_protocols import SemanticHasherProtocol
from orcapod.types import Schema

T = TypeVar("T")
Expand Down Expand Up @@ -335,8 +337,8 @@ def __init__(
unified_schema = self._impl.schema()
if isinstance(unified_schema, pa.Schema):
require_supported_nullable_types(unified_schema)
# Logical types in one form first: a field declared with its identifier
# in ARROW:extension:* metadata is that logical type (ITL-640).
require_live_logical_types(unified_schema)
# Canonicalize the declaration for comparison to batch schemas (ITL-640).
self._declared_arrow = declaration_form_schema(
pa.schema(
[
Expand Down Expand Up @@ -902,16 +904,22 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None:
Returns:
``ArrowTableStream`` if data has rows and columns, ``None`` otherwise.
"""
arrow_frame = read_arrow_frame_input(data)
input_schema = None
if arrow_frame is not None:
data, input_schema = arrow_frame
df = pl.DataFrame(data)
if len(df.columns) == 0:
logger.debug(
"PollingSource %r: fetch returned data with no columns — skipping stream build",
self.source_id,
)
return None
return self._build_stream_from_df(df)
return self._build_stream_from_df(df, input_schema=input_schema)

def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None:
def _build_stream_from_df(
self, df: pl.DataFrame, *, input_schema: pa.Schema | None
) -> ArrowTableStream | None:
"""Build an ``ArrowTableStream`` from a Polars DataFrame.

Returns ``None`` on the infer-once path when the batch has zero rows and
Expand All @@ -929,6 +937,11 @@ def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None:

raw = df.to_arrow()
require_supported_nullable_types(raw.schema)
# An Arrow input has already been checked against its authoritative schema.
# Polars conversion can export a live, unregistered extension as storage.
if input_schema is None:
input_schema = raw.schema
require_live_logical_types(input_schema)
arrow_table = arrow_utils.drop_system_columns(raw)

# Establish canonical schema on first call; apply it on every call.
Expand Down Expand Up @@ -978,6 +991,7 @@ def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None:
source_name=self._source_name,
kind_part=self.kind_part(),
record_id_columns=self._record_id_columns,
input_schema=input_schema,
)
return result.stream

Expand Down
2 changes: 2 additions & 0 deletions src/orcapod/core/sources/spiraldb_table_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
from orcapod.core.sources.stream_builder import (
require_custom_system_tags,
require_supported_nullable_types,
require_live_logical_types,
SourceStreamBuilder,
key_column_type_allowed,
normalize_record_id_columns,
Expand Down Expand Up @@ -937,6 +938,7 @@ def _read_batches(
for start in range(0, max(batch.num_rows, 1), self._batch_rows):
raw = pa.Table.from_batches([batch.slice(start, self._batch_rows)])
require_supported_nullable_types(raw.schema)
require_live_logical_types(raw.schema)
rows = arrow_utils.drop_system_columns(raw)
# Metadata too: field metadata is how a column's logical type is
# recorded, and the schema hash was computed at construction.
Expand Down
Loading
Loading