diff --git a/.zed/rules b/.zed/rules index 63e52b65f..909cc51d5 100644 --- a/.zed/rules +++ b/.zed/rules @@ -999,6 +999,11 @@ of its identity (GroupBy's member_order), never the input's column order. ### Column naming conventions +All column names beginning with `_` are reserved for Orcapod (ITL-1165). Sources refuse +raw input with these names and tell callers to rename the columns or drop them first. +Sources, raw Arrow streams, operators and function pods validate user column names +with `schema_utils.require_names_not_system`. + __ prefix — System metadata (ColumnConfig meta) _source_ prefix — Source info provenance (ColumnConfig source) _input_source_ prefix — Source-info provenance of an input data column as stored by a diff --git a/CLAUDE.md b/CLAUDE.md index 8b45e6619..8c6ad7207 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1022,6 +1022,11 @@ of its identity (GroupBy's `member_order`), never the input's column order. ### Column naming conventions +All column names beginning with `_` are reserved for Orcapod (ITL-1165). Sources refuse +raw input with these names and tell callers to rename the columns or drop them first. +Sources, raw Arrow streams, operators and function pods validate user column names +with `schema_utils.require_names_not_system`. + | Prefix | Meaning | Example | Controlled by | |--------|---------|---------|---------------| | `__` | System metadata | `__data_id`, `__pod_version` | `ColumnConfig(meta=True)` | diff --git a/changelog.d/ITL-1165.md b/changelog.d/ITL-1165.md new file mode 100644 index 000000000..f44970878 --- /dev/null +++ b/changelog.d/ITL-1165.md @@ -0,0 +1,25 @@ +### Breaking changes and migration + +- Names beginning with `_` are reserved for Orcapod. This applies to user tags and + data columns in sources, declared schemas and raw Arrow streams, function pod + outputs, operator outputs and renames, and derived tag copies. Loading a saved + configuration with a reserved user column name raises an error. Rename these + columns and update downstream references before saving a new configuration. + Use `stream.as_table()` to export user-facing columns for a new source. + +### Fixed + +- `Pick` and `Index` reject reserved `out` names at construction, so their output + columns stay visible in stream tables. +- Manual function result cache writes refuse reserved user output keys. A cache + lookup that finds a stored result with a reserved output key fails the job run. + Replay and provenance reads also refuse to reconstruct such rows. +- Operator caches and cached sources refuse stored user columns in the reserved + namespace before presenting their rows. +- Raw Arrow and polling sources report reserved column names before validating + their Arrow types. +- `DataFrameSource` checks the column names of input frames and of the frame inferred + from Python data. `PollingSource` checks the inferred columns of Python batches. + List sources check user names in each callback result before requesting more tags. + Dictionary sources check declared names before reading and each row from a custom + collection before asking for the next. diff --git a/docs/concepts/provenance.md b/docs/concepts/provenance.md index 3db253ff3..88705ed0c 100644 --- a/docs/concepts/provenance.md +++ b/docs/concepts/provenance.md @@ -153,12 +153,9 @@ columns (`stream.as_table(columns={"source": True})`). not valid: the missing inner list would have to be a list, `[[], ["a"]]` or `[[null], ["a"]]`. -Orcapod's sources, operators and functions always keep these rules. They matter when you -build a table with `_source_*` columns by hand and hand it to `ArrowTableStream`: a list -token over a value that is not a list, a list of another kind (a fixed-size list of tokens -needs a fixed-size list of values of the same size), more list levels in the token than in -the value, a token that is not text, or a missing list of tokens at any level is refused with -`InputValidationError`, which names the token column, its data column and both types. +Use the `source_info` argument when supplying your own tokens to `ArrowTableStream`. +Orcapod checks that the token types and nesting match the data columns. An +`InputValidationError` identifies the token column, its data column and both types. One case reaches ordinary pipelines. A `Batch` of single values and a source that already holds lists of them have the same values but different tokens: a list of tokens (one per diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index b5006822e..64012062f 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -20,6 +20,10 @@ dependencies -- it sits at the root of the computational graph. Key properties: ### Concrete source types +Names beginning with `_` are reserved for Orcapod. Rename or drop any such columns +before passing data or a schema to a source. If you have the original stream, +`stream.as_table()` gives you the user-facing columns for a new source. + All sources follow the same pattern: convert input data to a PyArrow Table, then pass it through `SourceStreamBuilder` which handles enrichment (provenance columns, system tags, hashing) and produces the final immutable stream. @@ -379,6 +383,9 @@ categorical column) is not a dictionary column: it is a library value, stored an (see [Arrays and other library values](arrays.md)), and is accepted. Supporting dictionary-encoded columns themselves is future work (ITL-1277). +`DataFrameSource` uses Polars to infer the columns of Python inputs and checks the +resulting column names for reserved names. + ### A bare list of key/value structs is a dict A `dict[K, V]` column is stored as a list of structs with the two fields `key` and `value`, diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index b6c5b891c..ac7626e55 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -336,6 +336,13 @@ shortcut) to control which column groups are included. | `content_hash` | Content hash column | `_content_hash` | | `sort_by_tags` | Sort rows by tag columns | (ordering only) | +Every column name beginning with `_` is reserved for Orcapod. Use another name for +user tags, data columns, operator outputs and function pod output keys. Underscores +after the first character are allowed. + +When reading a table back as a source, drop its system columns first. If you still +have the original stream, `stream.as_table()` gives you its user-facing columns. + Pass config as a dict or a `ColumnConfig` object: ```python diff --git a/docs/dev/design_issues/ITL-1165-RN1.md b/docs/dev/design_issues/ITL-1165-RN1.md index a71fd0d3a..9727988e6 100644 --- a/docs/dev/design_issues/ITL-1165-RN1.md +++ b/docs/dev/design_issues/ITL-1165-RN1.md @@ -1,7 +1,7 @@ ## Cross-cutting ### RN1 — Reserved `_` column names: sources silently drop them, `Pick` / `Index` accept them as new names -**Status:** open +**Status:** resolved **Severity:** medium **Issue:** ITL-1165 @@ -25,3 +25,20 @@ November 16, 2026 while fixing ITL-1160, probed on that branch): To decide: which names are reserved; then a source refuses such a column with an error naming it instead of dropping it, and `Pick` / `Index` refuse a reserved `out` name through the same helper as the mappers. + +**Fix:** Reserve all leading-underscore column names for Orcapod. Raw source readers +report the offending columns and how to remove or rename them. The same rule covers +new operator names and function pod output keys, including user data returned by custom +functions before caching or emission and user keys read from stored results. Operator +caches and cached sources check user columns before exposing rows, including when an +operator's records feed a derived source. +Manual function result cache writes also check output keys, and an invalid cached +result fails the run as a stored-table read error. +`DataFrameSource` checks the names on incoming frames and on the frame Polars infers +from Python inputs. Polling checks the columns Polars infers from Python batches. List +sources validate callback user tags before asking for further tags. DictSource checks +declared schemas before consuming rows and each row of a custom collection before advancing +it. A saved operator schema +identifies legacy user names even when a mixed table alone cannot distinguish them +from system tags. +SpiralDB validates the pinned snapshot's column names for historical reads. diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index a123466a4..74f9ac24a 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -41,6 +41,7 @@ ) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol +from orcapod.utils.schema_utils import require_names_not_system from orcapod.semantic_types._schema_conversion import arrow_schema_for_types @@ -205,6 +206,11 @@ def lookup_cached_data(self, data: DataProtocol) -> DataProtocol | None: cached = self._cache.lookup(data, data_context_key=self.data_context_key) if cached is None: return None + return self._cache_hit_output(cached) + + def _cache_hit_output(self, cached: DataProtocol) -> DataProtocol: + """Validate a stored output before passing it to the caller.""" + require_names_not_system(cached.keys()) return cached.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: False}) def process_data( @@ -234,10 +240,9 @@ def process_data( A ``(tag, output_data)`` tuple; output_data is ``None`` if the inner function filters the data out. """ - cached = self._cache.lookup(data, data_context_key=self.data_context_key) + cached = self.lookup_cached_data(data) if cached is not None: module_logger.info("Pod-level cache hit") - cached = cached.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: False}) return tag, cached tag, output = self._function_pod.process_data( @@ -267,7 +272,7 @@ def process_data( module_logger.info( "A result for this input was stored meanwhile; using it" ) - output = stored.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: False}) + output = self._cache_hit_output(stored) else: output = output.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: True}) return tag, output @@ -338,7 +343,7 @@ async def _async_compute_and_store( module_logger.info( "A result for this input was stored meanwhile; using it" ) - output = stored.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: False}) + output = self._cache_hit_output(stored) else: output = output.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: True}) return tag, output diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index bd21a2871..28600be21 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -892,6 +892,9 @@ def __init__( output_keys = [output_keys] # A copy taken once: a later change to the caller's list changes nothing. output_keys = tuple(output_keys) + # Refuse reserved names at definition time, before inspecting the return + # annotation or executing the function. + schema_utils.require_names_not_system(output_keys) self._output_keys = output_keys if function_name is None: if hasattr(self._function, "__name__"): @@ -1441,11 +1444,17 @@ def from_config(cls, config: dict[str, Any]) -> "PythonDataFunction": import importlib inner = config.get("config", config) + keys = inner.get("output_keys") or () + if isinstance(keys, str): + keys = (keys,) + schema_utils.require_names_not_system( + (*keys, *inner.get("output_data_schema", {})) + ) module = importlib.import_module(inner["module_path"]) func = getattr(module, inner["callable_name"]) return cls( function=func, - output_keys=inner.get("output_keys"), + output_keys=keys, version=inner.get("version", "v0.0"), ) @@ -1693,7 +1702,8 @@ def call( Raises: InputValidationError: If ``data`` is of another data context than this function's; the wrapped function has not been called then, whatever - ``skip_cache_lookup`` and ``skip_cache_insert`` are. + ``skip_cache_lookup`` and ``skip_cache_insert`` are. Also raised if + the wrapped function returns a data column with a reserved name. """ # Checked before anything else: with ``skip_cache_lookup`` the lookup, which # checks it too, does not run, and the function must not be called. @@ -1711,6 +1721,7 @@ def call( self._cache.check_before_side_effect(self.data_context_key) output_data = self._data_function.call(data, logger=logger, **kwargs) if output_data is not None: + schema_utils.require_names_not_system(output_data.keys()) if not skip_cache_insert: var_dg, exec_dg = self._build_metadata_datagrams() self._cache.store( @@ -1738,7 +1749,8 @@ async def async_call( Raises: InputValidationError: If ``data`` is of another data context than this - function's; the wrapped function has not been called then. + function's; the wrapped function has not been called then. Also raised + if the wrapped function returns a data column with a reserved name. """ # Checked before anything else: with ``skip_cache_lookup`` the lookup, which # checks it too, does not run, and the function must not be called. @@ -1758,6 +1770,7 @@ async def async_call( data, logger=logger, **kwargs ) if output_data is not None: + schema_utils.require_names_not_system(output_data.keys()) if not skip_cache_insert: var_dg, exec_dg = self._build_metadata_datagrams() self._cache.store( @@ -1790,7 +1803,12 @@ def record_data( output_data: DataProtocol, skip_duplicates: bool = False, ) -> DataProtocol: - """Record the output data against the input data in the result store.""" + """Record the output data against the input data in the result store. + + Raises: + InputValidationError: If an output column has a reserved name. + """ + schema_utils.require_names_not_system(output_data.keys()) var_dg, exec_dg = self._build_metadata_datagrams() self._cache.store( input_data, diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 1b784a7e2..1c4dd7087 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -136,12 +136,8 @@ def __init__( config: OrcapodConfig | None = None, ctx_arg_name: str | None = None, ) -> None: - output_names = data_function.output_data_schema.keys() - try: - schema_utils.require_names_not_meta(output_names) - schema_utils.require_names_not_system(output_names) - except InputValidationError as exc: - raise InputValidationError(f"Invalid function output: {exc}") from exc + output_schema = data_function.output_data_schema + schema_utils.require_names_not_system(output_schema.keys()) super().__init__( label=label, @@ -165,7 +161,7 @@ def __init__( # Register types for schema validation, excluding ctx (not a data column). self.data_context.type_converter.ensure_types_registered_for_schemas( self.input_data_schema, - data_function.output_data_schema, + output_schema, ) if self._ctx_arg_name is not None: warn_provisional_pod(CONTEXT_FUNCTION_POD) @@ -408,13 +404,19 @@ def process_data( Returns: A ``(tag, output_data)`` tuple; ``output_data`` is ``None`` if the function filters the data out. + + Raises: + InputValidationError: If a returned data column uses a reserved name. """ extra: dict[str, Any] = {} if self._ctx_arg_name is not None: extra[self._ctx_arg_name] = self._build_invocation_context( tag, data, run_id=run_id ) - return tag, self.data_function.call(data, logger=logger, **extra) + output = self.data_function.call(data, logger=logger, **extra) + if output is not None: + schema_utils.require_names_not_system(output.keys()) + return tag, output async def async_process_data( self, @@ -439,13 +441,19 @@ async def async_process_data( Returns: A ``(tag, output_data)`` tuple; ``output_data`` is ``None`` if the function filters the data out. + + Raises: + InputValidationError: If a returned data column uses a reserved name. """ extra: dict[str, Any] = {} if self._ctx_arg_name is not None: extra[self._ctx_arg_name] = self._build_invocation_context( tag, data, run_id=run_id ) - return tag, await self.data_function.async_call(data, logger=logger, **extra) + output = await self.data_function.async_call(data, logger=logger, **extra) + if output is not None: + schema_utils.require_names_not_system(output.keys()) + return tag, output def add_post_run_hook(self, hook: PostRunHook) -> None: """Register a post-run hook on this pod. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 09b106439..3518b8450 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -33,6 +33,7 @@ import pyarrow as pa from orcapod import contexts +from orcapod.core.result_cache import read_stored_result_table from orcapod.core.output_bindings import ( OutputBindings, capture_output_bindings, @@ -3722,8 +3723,8 @@ def _stored_provenance( ) for database, path in places: database.refresh_table(path) - stored = database.get_all_records( - path, record_id_column=constants.DATA_RECORD_ID + stored = read_stored_result_table( + database, path, record_id_column=constants.DATA_RECORD_ID ) if stored is not None: if path[-3:-2] == (PYTHON_FUNCTION.type_id,): @@ -3828,7 +3829,8 @@ def _fetch_joined_records( eph_results: pa.Table | None = None persistent_df = pl.DataFrame() if persistent_taginfo_df.height > 0: - results = self._cached_function_pod.result_database.get_all_records( + results = read_stored_result_table( + self._cached_function_pod.result_database, record_path, record_id_column=constants.DATA_RECORD_ID, ) @@ -3859,11 +3861,10 @@ def _fetch_joined_records( if ephemeral_taginfo_df.height > 0: eph_frame: pl.DataFrame | None = None if self._ephemeral_cached_pod is not None: - eph_results = ( - self._ephemeral_cached_pod.result_database.get_all_records( - self._ephemeral_cached_pod.record_path, - record_id_column=constants.DATA_RECORD_ID, - ) + eph_results = read_stored_result_table( + self._ephemeral_cached_pod.result_database, + self._ephemeral_cached_pod.record_path, + record_id_column=constants.DATA_RECORD_ID, ) if eph_results is not None: eph_results = keep_rows_of_data_context(eph_results, context_key).drop( diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index bbdb1794c..91e5f7b25 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -106,7 +106,7 @@ from orcapod.system_constants import OPERATOR_DB_SCHEMA_VERSION, constants import orcapod.core.row_ids as row_ids from orcapod.types import CacheMode, ColumnConfig, ContentHash, Schema -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, schema_utils logger = logging.getLogger(__name__) @@ -1661,6 +1661,29 @@ def _read_current_context_records(self) -> "pa.Table | None": ) if records is None: return None + try: + saved = self._descriptor.get("output_schema") if self._loaded else None + if saved is not None: + # A descriptor distinguishes a legacy user name from a system tag. + schema_utils.require_names_not_system( + set(saved.get("tag", {})) | set(saved.get("data", {})) + ) + schema_utils.require_stored_stream_column_names( + records.column_names, + ( + self.HASH_COLUMN_NAME, + constants.NODE_CONTENT_HASH_COL, + constants.DATA_CONTEXT_COL, + *_STORED_ONLY_COLUMNS, + ), + ) + except InputValidationError as exc: + location = "/".join( + self._pipeline_database.base_path + self._stored_table_path + ) + raise InputValidationError( + f"{exc} Stored stream table: {location}" + ) from exc self._check_stored_data_tags(records.schema) stored_rows = records.num_rows records = keep_rows_of_data_context(records, self.data_context_key) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b07f4ad06..c15a541d6 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -71,6 +71,7 @@ arrow_schema_identity, compute_schema_hash, declared_arrow_schema, + require_names_not_system, ) if TYPE_CHECKING: @@ -560,6 +561,15 @@ def __init__( *, _inherited_types: bool = False, ) -> None: + tag_names = ( + tag_schema.names if isinstance(tag_schema, pa.Schema) else tag_schema.keys() + ) + data_names = ( + data_schema.names + if isinstance(data_schema, pa.Schema) + else data_schema.keys() + ) + require_names_not_system((*tag_names, *data_names)) super().__init__(label=label, data_context=data_context, config=config) if isinstance(tag_schema, pa.Schema) or isinstance(data_schema, pa.Schema): # A slot declared in Arrow holds exactly those types (ITL-640). diff --git a/src/orcapod/core/operators/add_tags.py b/src/orcapod/core/operators/add_tags.py index aa2f350bd..a93ad27b8 100644 --- a/src/orcapod/core/operators/add_tags.py +++ b/src/orcapod/core/operators/add_tags.py @@ -134,7 +134,6 @@ def __init__(self, tags: Mapping[str, TagConstant], **kwargs: Any): raise TypeError(f"add_tags: tag names must be strings, got {not_strings!r}") if "" in tags: raise ValueError("add_tags: a tag name must not be empty") - schema_utils.require_names_not_meta(list(tags)) schema_utils.require_names_not_system(list(tags)) schema_utils.require_names_without_separator(list(tags)) # In name order: the order the tags are given in is not kept (ITL-1269). diff --git a/src/orcapod/core/operators/index.py b/src/orcapod/core/operators/index.py index 6d38f4a63..cc37bb91c 100644 --- a/src/orcapod/core/operators/index.py +++ b/src/orcapod/core/operators/index.py @@ -64,10 +64,7 @@ def __init__( ) -> None: self.column = column self.i = i - # A data column never gets a meta column's name (ITL-1080): refused here, - # as ``MapData`` refuses it, so no path can produce one and drop it. if out is not None: - schema_utils.require_names_not_meta([out]) schema_utils.require_names_not_system([out]) schema_utils.require_names_without_separator([out]) self.out = out diff --git a/src/orcapod/core/operators/mappers.py b/src/orcapod/core/operators/mappers.py index 6b76fea6f..d2a78ac97 100644 --- a/src/orcapod/core/operators/mappers.py +++ b/src/orcapod/core/operators/mappers.py @@ -105,7 +105,6 @@ def __init__( ): # A data column never gets a meta column's name (ITL-1080): refused here, # so no path (sync, async or the prediction) can produce one. - schema_utils.require_names_not_meta(name_map.values()) schema_utils.require_names_not_system(name_map.values()) schema_utils.require_names_without_separator(name_map.values()) self.name_map = dict(name_map) @@ -383,7 +382,6 @@ def __init__( ): # A tag never gets a meta column's name (ITL-1080): refused here, so no # path (sync, async or the prediction) can produce one. - schema_utils.require_names_not_meta(name_map.values()) schema_utils.require_names_not_system(name_map.values()) schema_utils.require_names_without_separator(name_map.values()) self.name_map = dict(name_map) @@ -678,7 +676,6 @@ def __init__( ): # No column gets a meta column's name (ITL-1080): refused here, so no # path (sync, async or the prediction) can produce one. - schema_utils.require_names_not_meta(name_map.values()) schema_utils.require_names_not_system(name_map.values()) schema_utils.require_names_without_separator(name_map.values()) self.name_map = dict(name_map) diff --git a/src/orcapod/core/operators/pick.py b/src/orcapod/core/operators/pick.py index f36c87c0b..ed39e4d79 100644 --- a/src/orcapod/core/operators/pick.py +++ b/src/orcapod/core/operators/pick.py @@ -66,10 +66,7 @@ def __init__( ) -> None: self.column = column self.key = key - # A data column never gets a meta column's name (ITL-1080): refused here, - # as ``MapData`` refuses it, so no path can produce one and drop it. if out is not None: - schema_utils.require_names_not_meta([out]) schema_utils.require_names_not_system([out]) schema_utils.require_names_without_separator([out]) self.out = out diff --git a/src/orcapod/core/operators/tag_by.py b/src/orcapod/core/operators/tag_by.py index 0481a133b..e195c8340 100644 --- a/src/orcapod/core/operators/tag_by.py +++ b/src/orcapod/core/operators/tag_by.py @@ -81,7 +81,6 @@ class TagBy(UnaryOperator): def __init__(self, columns: str | Iterable[str], **kwargs: Any) -> None: names = _tag_by_names(columns) - schema_utils.require_names_not_meta(names) schema_utils.require_names_not_system(names) schema_utils.require_names_without_separator(names) self.columns: tuple[str, ...] = names diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index af91c96c6..7fe9ba2a0 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -38,6 +38,8 @@ constants, ) +from orcapod.utils.schema_utils import require_names_not_system + if TYPE_CHECKING: from orcapod.protocols.core_protocols.datagrams import DatagramProtocol @@ -200,6 +202,46 @@ def _with_declared_token_columns( return outputs +def read_stored_result_table( + database: ArrowDatabaseProtocol, + path: tuple[str, ...], + *, + record_id_column: str | None = None, +) -> pa.Table | None: + """Read a raw result table and refuse reserved user names before decoding.""" + table = database.get_all_records(path, record_id_column=record_id_column) + if table is not None: + try: + _check_result_table(table, record_id_column) + except InputValidationError as exc: + location = "/".join(database.base_path + path) + raise InputValidationError( + f"{exc} Stored result table: {location}" + ) from exc + return table + + +def _check_result_table(table: pa.Table, record_id_column: str | None) -> None: + """Refuse reserved output names using the result table's own column roles.""" + names = set(table.column_names) + bookkeeping = {column.name for column in COMMON_RESULT_COLUMNS} + if record_id_column is not None: + bookkeeping.add(record_id_column) + bookkeeping.update( + name + for name in names + if name.startswith( + (constants.PF_VARIATION_PREFIX, constants.PF_EXECUTION_PREFIX) + ) + ) + source_info = { + f"{constants.SOURCE_PREFIX}{name}" + for name in names + if not name.startswith(constants.DATAGRAM_PREFIX) + } + require_names_not_system(names - bookkeeping - source_info) + + def context_result_path( uri: tuple[str, ...], context_parameter: str | None ) -> tuple[str, ...]: @@ -424,6 +466,12 @@ def lookup( if result_table is None or result_table.num_rows == 0: return None + try: + _check_result_table(result_table, RECORD_ID_COL) + except InputValidationError as exc: + path = self._result_database.base_path + self._versioned_record_path + raise OrcapodDatabaseReadError("/".join(path), path) from exc + if result_table.num_rows > 1: logger.info( "Cache conflict resolution: %d records for constraints %s, " @@ -655,8 +703,10 @@ def get_all_records( self._account_for_stale_tables(data_context_key) record_id_column = constants.DATA_RECORD_ID if include_system_columns else None - result_table = self._result_database.get_all_records( - self._versioned_record_path, record_id_column=record_id_column + result_table = read_stored_result_table( + self._result_database, + self._versioned_record_path, + record_id_column=record_id_column, ) if result_table is None: return None diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index d3703d5d5..c7b946db4 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -9,12 +9,12 @@ from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, + require_source_column_names, require_supported_nullable_types, ) from orcapod.utils import arrow_utils from orcapod.utils.schema_utils import ( _normalize_column_list, - require_names_not_system_tags, ) if TYPE_CHECKING: @@ -26,9 +26,11 @@ class ArrowTableSource(RootSource): """A source backed by an in-memory PyArrow Table. - Uses ``SourceStreamBuilder`` to strip system columns, add per-row - source-info provenance columns and a system tag column encoding the - schema hash, then wraps the result in an ``ArrowTableStream``. + ``SourceStreamBuilder`` refuses reserved column names beginning with ``_``. + Rename your own columns or drop system columns before building the source. + The builder adds per-row source-info provenance columns and a system tag + column encoding the schema hash, then wraps the result in an + ``ArrowTableStream``. Nullable handling ----------------- @@ -111,7 +113,7 @@ def __init__( super().__init__(**kwargs) tag_columns = _normalize_column_list(tag_columns) - require_names_not_system_tags(table.column_names) + require_source_column_names(table.column_names) if infer_nullable: require_supported_nullable_types(table.schema) logger.debug( diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 66edd6cd5..c475f372e 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -679,6 +679,16 @@ def _read_cached_records_with_hashes(self) -> "pa.Table | None": records = self._read_cache_table() if records is None: return None + try: + schema_utils.require_stored_stream_column_names( + records.column_names, + (self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL), + ) + except InputValidationError as exc: + location = "/".join(self._cache_database.base_path + self.cache_path) + raise InputValidationError( + f"{exc} Stored stream table: {location}" + ) from exc 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: diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index acbdfe788..5292c493e 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -1,6 +1,7 @@ from __future__ import annotations import functools +import io import math import os import re @@ -17,6 +18,7 @@ from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, SourceStreamResult, + require_source_column_names, normalize_record_id_columns, require_live_logical_types, require_supported_nullable_types, @@ -24,13 +26,61 @@ from orcapod.utils import arrow_utils from orcapod.utils.schema_utils import ( _normalize_column_list, - require_names_not_system_tags, ) _INFINITY = re.compile(r"\s*[+-]?inf(inity)?\s*", re.IGNORECASE) """The texts pyarrow's CSV reader reads as an infinity: ``inf`` or ``infinity``, any case, with an optional sign and surrounding spaces.""" +_CSV_UNQUOTED = re.compile(r"[^,\r\n]*") +_CSV_QUOTED = re.compile(r'(?:[^"]++|"")*+') + + +def _csv_header_names(text: io.TextIOBase) -> list[str]: + """Read the first nonempty CSV record without a field size limit.""" + line = next((line for line in text if line not in ("\n", "\r", "\r\n")), "") + if not line: + return [] + + names: list[str] = [] + pos = 0 + while True: + quoted: list[str] = [] + if line[pos : pos + 1] == '"': + pos += 1 + while True: + field = _CSV_QUOTED.match(line, pos) + assert field is not None + quoted.append(field[0]) + pos = field.end() + if pos < len(line): + pos += 1 # Closing quote. Doubled quotes belong to the field. + break + line = text.readline() + if not line: + return names # Leave the unfinished field for Arrow to diagnose. + pos = 0 + + field = _CSV_UNQUOTED.match(line, pos) + assert field is not None + names.append("".join(quoted).replace('""', '"') + field[0]) + pos = field.end() + if line[pos : pos + 1] != ",": + return names + pos += 1 + + +def _require_csv_header_names(stream: pa.NativeFile) -> None: + """Check the first nonempty CSV record before Arrow parses any values.""" + with io.TextIOWrapper( + stream, # pyright: ignore[reportArgumentType] # NativeFile implements the buffer methods TextIOWrapper uses. + encoding="utf-8-sig", + errors="surrogateescape", + newline="", + ) as text: + names = _csv_header_names(text) + require_source_column_names(names) + def _storage_type(declared: pa.DataType) -> pa.DataType: """Return a type's storage type: itself, or a logical type's storage.""" @@ -159,6 +209,10 @@ def _read_declared(path: str, schema: pa.Schema) -> pa.Table: import pyarrow.compute as pc import pyarrow.csv as pa_csv + # Check the same snapshot the typed parser will receive. + with pa.input_stream(path) as stream: + data = stream.read() + _require_csv_header_names(pa.BufferReader(data)) reader_types: dict[str, pa.DataType] = {} for field in schema: try: @@ -168,8 +222,6 @@ def _read_declared(path: str, schema: pa.Schema) -> pa.Table: raise text_like = [f.name for f in schema if _is_text_like(f.type)] # One snapshot of the file, and one set of read and parse options, for every parse. - with pa.input_stream(path) as stream: - data = stream.read() read_options = pa_csv.ReadOptions() parse_options = pa_csv.ParseOptions() # pyarrow's default null markers, which the reader applies to other columns. @@ -199,7 +251,7 @@ def as_text(columns: list[str], include: list[str]) -> pa_csv.ConvertOptions: table = parse(as_text(text_like, [])) # text-like columns only: one parse else: table = parse(pa_csv.ConvertOptions(column_types=reader_types)) - require_names_not_system_tags(table.column_names) + require_source_column_names(table.column_names) if table.column_names != schema.names: raise ValueError( f"the file's columns {table.column_names} are not the schema's fields " @@ -345,11 +397,12 @@ def _read_table(self) -> pa.Table: import pyarrow.csv as pa_csv if self._schema is None: + _require_csv_header_names(pa.input_stream(self._access_path)) table: pa.Table = pa_csv.read_csv(self._access_path) - require_names_not_system_tags(table.column_names) + require_source_column_names(table.column_names) require_supported_nullable_types(table.schema) return table.cast(arrow_utils.infer_schema_nullable(table)) - require_names_not_system_tags(self._schema.names) + require_source_column_names(self._schema.names) require_supported_nullable_types(self._schema) require_live_logical_types(self._schema) try: @@ -480,7 +533,9 @@ def saved_schema(cls, config: dict[str, Any]) -> pa.Schema | None: from orcapod.pipeline.serialization import deserialize_arrow_schema try: - return deserialize_arrow_schema(config["schema"]) + schema = deserialize_arrow_schema(config["schema"]) + require_source_column_names(schema.names) + return schema except ValueError as exc: exc.add_note(f"saved CSVSource config over {config.get('file_path')!r}") raise diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 9e8fb9809..b573a847d 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -13,14 +13,12 @@ SourceStreamBuilder, normalize_record_id_columns, read_arrow_frame_input, + require_source_column_names, require_live_logical_types, require_supported_nullable_types, ) -from orcapod.utils import arrow_utils, polars_data_utils -from orcapod.utils.schema_utils import ( - _normalize_column_list, - require_names_not_system_tags, -) +from orcapod.utils import arrow_utils +from orcapod.utils.schema_utils import _normalize_column_list from orcapod.semantic_types._schema_conversion import arrow_table_for_rows @@ -31,10 +29,12 @@ class DataFrameSource(RootSource): - """A source backed by a Polars DataFrame (or any Polars-compatible data). + """A source backed by a Polars DataFrame or other Polars-compatible data. The DataFrame is converted to an Arrow table and enriched by ``SourceStreamBuilder`` (source-info, schema-hash, system tags). + Column names beginning with an underscore are reserved. For Python row + inputs, the check applies to the columns inferred by Polars. Data-tags (ITL-1023): every declared tag column is a data-tag by default, also a data column of the same name. ``tag_only_columns`` (keyword-only) names the @@ -70,6 +70,8 @@ def __init__( ) -> None: super().__init__(source_id=source_id, **kwargs) + if schema is not None: + require_source_column_names(schema.names) input_schema = arrow_input_schema = None if (arrow_frame := read_arrow_frame_input(data)) is not None: arrow_input, input_schema = arrow_frame @@ -81,8 +83,7 @@ def __init__( ) else: df = pl.DataFrame(data) - - require_names_not_system_tags(df.columns) + require_source_column_names(df.columns) # Convert any Object-dtype columns to Arrow-compatible types. object_columns = [c for c in df.columns if df[c].dtype == pl.Object] @@ -97,11 +98,7 @@ def __init__( tag_columns = _normalize_column_list(tag_columns) - 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) + require_source_column_names(tag_columns) missing = set(tag_columns) - set(df.columns) if missing: @@ -112,7 +109,6 @@ def __init__( require_live_logical_types(arrow_table.schema) if schema is not None: require_supported_nullable_types(schema) - require_names_not_system_tags(schema.names) require_live_logical_types(schema) arrow_table = arrow_table.cast(schema) elif arrow_input_schema is not None: diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 20ec3123e..98c556701 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -26,6 +26,7 @@ from orcapod.core.sources.reload import keep_nullable_columns, same_rows from orcapod.core.sources.source_ids import location_source_name from orcapod.core.sources.stream_builder import ( + require_source_column_names, SourceStreamBuilder, SourceStreamResult, normalize_record_id_columns, @@ -35,7 +36,6 @@ from orcapod.utils import arrow_utils from orcapod.utils.schema_utils import ( _normalize_column_list, - require_names_not_system_tags, ) if TYPE_CHECKING: @@ -223,15 +223,16 @@ def _read_table( """ if self._table_name not in connector.get_table_names(): raise ValueError(f"Table {self._table_name!r} not found in database.") - batches = list(connector.iter_batches(self._query)) + col_infos = connector.get_column_info(self._table_name) + require_source_column_names([info.name for info in col_infos]) + batches: list[pa.RecordBatch] = [] + for batch in connector.iter_batches(self._query): + require_source_column_names(batch.schema.names) + batches.append(batch) if not batches: raise ValueError(f"Table {self._table_name!r} is empty.") table: pa.Table = pa.Table.from_batches(batches) - require_names_not_system_tags(table.column_names) require_live_logical_types(table.schema) - # 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) if col_infos: db_nullable = {ci.name: ci.nullable for ci in col_infos} db_schema = pa.schema( diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 590fc0a1e..464805d10 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -13,6 +13,7 @@ from orcapod.core.sources.reload import same_rows from orcapod.core.sources.source_ids import location_source_name from orcapod.core.sources.stream_builder import ( + require_source_column_names, SourceStreamBuilder, SourceStreamResult, normalize_record_id_columns, @@ -23,7 +24,6 @@ from orcapod.utils.lazy_module import LazyModule from orcapod.utils.schema_utils import ( _normalize_column_list, - require_names_not_system_tags, ) if TYPE_CHECKING: @@ -106,12 +106,15 @@ def __init__( def _read_table(self) -> "pa.Table": """Read the table at the Delta version ``self._delta_table`` is loaded at.""" + require_source_column_names( + [field.name for field in self._delta_table.schema().fields], + ) # The Delta log stores field-level nullable flags; to_pyarrow_dataset() # preserves them exactly — no inference needed. table = delta_to_pyarrow_dataset( self._delta_table, as_large_types=True ).to_table() - require_names_not_system_tags(table.column_names) + require_source_column_names(table.column_names) return table def _build(self, table: "pa.Table") -> SourceStreamResult: diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 614f4fd55..656521b2a 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -81,6 +81,7 @@ def validate_tags_as_data( name is already a column, is used twice, or starts with the prefix reserved for system columns. """ + schema_utils.require_names_not_system(tags_as_data.values()) seen: set[str] = set() for tag, name in tags_as_data.items(): if tag not in tag_keys: @@ -99,11 +100,6 @@ def validate_tags_as_data( f"tags_as_data: the name {name!r} is given to more than one tag. " "Each copy needs its own name." ) - if name.startswith(constants.DATAGRAM_PREFIX): - raise InputValidationError( - f"tags_as_data: cannot copy tag {tag!r} to {name!r}: names starting " - f"with {constants.DATAGRAM_PREFIX!r} are reserved for system columns." - ) seen.add(name) @@ -447,6 +443,12 @@ def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: ), } + @classmethod + def check_saved_config(cls, config: dict[str, Any]) -> None: + """Validate saved tag-copy names before resolving the origin.""" + if targets := config.get("tags_as_data"): + schema_utils.require_names_not_system(targets.values()) + @classmethod def from_config( cls, config: dict[str, Any], db_registry: Any = None @@ -476,6 +478,7 @@ def from_config( if provisional is not None: warn_provisional_source(provisional) cls.require_saved_source_id(config) + cls.check_saved_config(config) if config.get("origin") is None: raise NotImplementedError( @@ -772,10 +775,8 @@ def _derive_from( table: Rows of the origin. tags_as_data: Maps a tag column of the origin to the name of its copy. """ + table = arrow_utils.drop_system_columns(table) require_supported_nullable_types(table.schema) - table = arrow_utils.drop_columns_with_prefix( - table, (constants.SYSTEM_TAG_PREFIX,) - ) for tag, name in tags_as_data.items(): # The copy is the tag's own Arrow column under a renamed field, so its # type, nullability and field metadata are the tag's exactly. diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index 6ff048353..421c10aa6 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -14,6 +14,7 @@ from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, + require_source_column_names, require_live_logical_types, require_supported_nullable_types, ) @@ -21,7 +22,6 @@ from orcapod.utils import arrow_utils from orcapod.utils.schema_utils import ( _normalize_column_list, - require_names_not_system_tags, ) from orcapod.utils.tensor_conversions import warn_source_tensor_conversions @@ -71,37 +71,32 @@ def __init__( **kwargs: Any, ) -> None: super().__init__(source_id=source_id, **kwargs) - if not isinstance(data_schema, pa.Schema) and data_schema is not None: - require_python_schema_without_narrow_float_keys( - data_schema, self.data_context.type_converter - ) tag_columns = _normalize_column_list(tag_columns) - # Read the first input row before its origin is erased by dict(row). - float32_columns = ( - () - if isinstance(data_schema, pa.Schema) - else float32_column_names(data_schema) - ) - if float32_columns: - rows = [] - remaining = iter(data) - for first in remaining: - rows.append(dict(first)) - rows.extend(map(dict, remaining)) - warn_first_python_float(rows[0], float32_columns, first) - break - else: - rows = [dict(row) for row in data] - - for row in rows: - require_names_not_system_tags(row.keys()) if data_schema is not None: - require_names_not_system_tags( + names = ( data_schema.names if isinstance(data_schema, pa.Schema) - else tuple(data_schema) + else data_schema.keys() + ) + require_source_column_names(names) + if not isinstance(data_schema, pa.Schema) and data_schema is not None: + require_python_schema_without_narrow_float_keys( + data_schema, self.data_context.type_converter ) + # Retain the first mapping's origin if dict(row) would erase it. + first_row = None + if type(data) in (list, tuple) and all(type(row) is dict for row in data): + # All keys are already available without advancing a user iterator. + require_source_column_names({name for row in data for name in row}) + rows = [dict(row) for row in data] + else: + rows = [] + for row in data: + require_source_column_names(row.keys()) + if not rows: + first_row = row + rows.append(dict(row)) # Accept either a Python SchemaLike (Mapping[str, type]) or a # pa.Schema directly via data_schema; route to the converter accordingly. @@ -114,6 +109,9 @@ def __init__( arrow_schema=data_schema, ) else: + float32_columns = float32_column_names(data_schema) + if float32_columns and rows: + warn_first_python_float(rows[0], float32_columns, first_row) arrow_table = arrow_table_for_rows( self.data_context.type_converter, rows, diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index 1d345bc84..30a27e85c 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -1,7 +1,7 @@ from __future__ import annotations from collections.abc import Callable, Collection -from typing import TYPE_CHECKING, Any, ClassVar, cast +from typing import TYPE_CHECKING, Any, ClassVar import pyarrow as pa @@ -13,6 +13,7 @@ from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, + require_source_column_names, ) from orcapod.protocols.core_protocols import TagProtocol from orcapod.types import SchemaLike @@ -94,6 +95,12 @@ def __init__( data_schema, self.data_context.type_converter ) + declared_names = {name} + if expected_tag_keys is not None: + declared_names.update(expected_tag_keys) + if data_schema is not None: + declared_names.update(data_schema.keys()) + require_source_column_names(declared_names) self.name = name self._elements = list(data) @@ -114,24 +121,15 @@ def __init__( else float32_column_names(data_schema) ) rows: list[dict[str, Any]] = [] - elements = enumerate(self._elements) first_tag = None - if float32_columns and self._elements: - idx, element = next(elements) - first_tag = tag_function(element, idx) - row = dict( - cast(TagProtocol, first_tag).as_dict() - if hasattr(first_tag, "as_dict") - else first_tag - ) - row[name] = element - rows.append(row) - - for idx, element in elements: + for idx, element in enumerate(self._elements): tag_fields = tag_function(element, idx) + if idx == 0 and float32_columns: + first_tag = tag_fields if hasattr(tag_fields, "as_dict"): tag_fields = tag_fields.as_dict() row = dict(tag_fields) + require_source_column_names(row.keys()) row[name] = element rows.append(row) diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 81a84cb32..fcd15779a 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -28,6 +28,7 @@ from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, + require_source_column_names, read_arrow_frame_input, require_live_logical_types, require_supported_nullable_types, @@ -51,7 +52,7 @@ from orcapod.logical_types.canonical_form import declaration_form_schema from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, Cursor, PollingConfig, Schema -from orcapod.utils import arrow_utils, schema_utils +from orcapod.utils import arrow_utils from orcapod.utils.arrow_utils import system_tag_column_names from orcapod.semantic_types.narrow_float_keys import ( require_python_schema_without_narrow_float_keys, @@ -345,7 +346,7 @@ def __init__( if isinstance(unified_schema, pa.Schema) else tuple(unified_schema.keys()) ) - schema_utils.require_names_not_system_tags(names) + require_source_column_names(names) if isinstance(unified_schema, pa.Schema): require_supported_nullable_types(unified_schema) require_live_logical_types(unified_schema) @@ -942,6 +943,8 @@ def _build_stream_from_df( skipped so that a spurious all-non-nullable schema is never recorded. """ + require_source_column_names(df.columns) + # Handle Object-dtype columns (same pattern as DataFrameSource) object_columns = [c for c in df.columns if df[c].dtype == pl.Object] if object_columns: @@ -950,15 +953,13 @@ def _build_stream_from_df( ) df = df.with_columns([pl.from_arrow(c) for c in sub_table]) - schema_utils.require_names_not_system_tags(df.columns) - raw = df.to_arrow() - require_supported_nullable_types(raw.schema) + arrow_table = df.to_arrow() + require_supported_nullable_types(arrow_table.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 + input_schema = arrow_table.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. if self._canonical_arrow_schema is None: diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index d2bf49437..ca1f243e2 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -66,6 +66,7 @@ key_column_type_allowed, normalize_record_id_columns, require_live_logical_types, + require_source_column_names, require_supported_nullable_types, row_identifiers, ) @@ -84,10 +85,7 @@ from orcapod.types import ColumnConfig, ColumnRef, Condition from orcapod.types.condition import check_float_equalities, check_restriction from orcapod.utils import arrow_utils -from orcapod.utils.schema_utils import ( - _normalize_column_list, - require_names_not_system_tags, -) +from orcapod.utils.schema_utils import _normalize_column_list if TYPE_CHECKING: from orcapod import contexts @@ -406,7 +404,7 @@ def __init__( # The version every read scans is prepared now (its schema and schema # record), also a given older one, so a read makes no metadata call. schema = table.arrow_schema(asof=asof) - require_names_not_system_tags(schema.names) + require_source_column_names(schema.names) require_supported_nullable_types(schema) # One version for every read of this source object. A given version is # used as it is; a table that was never written has no version to pin. @@ -794,7 +792,7 @@ def _pinned_table(self) -> SpiralDBTable: again, other columns (build the source again to read it), or a schema record that cannot be read (``TableSchemaError``). InputValidationError: If the latest check refused the table for a column - in the system-tag namespace. + in the reserved namespace. """ self._connector() # the source is open, and in the process that made it refusal = self._refusal @@ -884,7 +882,7 @@ def check_for_new_data(self) -> bool: sources first: a table this check refuses (dropped and created again, other columns, a schema record that cannot be read) is refused by every read of this source too, before it scans, until a later check accepts the table. A - column in the system-tag namespace is refused and held the same way. + column in the reserved namespace is refused and held the same way. A source built with ``asof`` is checked too (the table id, and its own version's schema record), and its pin never moves. A missing table is refused the same way. ``has_newer_version`` tells whether a newer version exists @@ -898,8 +896,7 @@ def check_for_new_data(self) -> bool: or its columns changed: build the source again to read it. TableSchemaError: If the table's row in the dataset's schema table cannot be read, or disagrees with the table. - InputValidationError: If the table now has a column in the system-tag - namespace. + InputValidationError: If the table now has a reserved column name. """ require_same_process(self._pid) # before a lock inherited by a fork with self._check_lock: @@ -920,8 +917,7 @@ def _check_table(self) -> bool: ValueError: If the table was dropped and created again, or its columns changed. TableSchemaError: If its schema record cannot be read. - InputValidationError: If the table now has a column in the system-tag - namespace. + InputValidationError: If the table now has a reserved column name. """ # One lookup per check (ITL-1350): a table dropped and created again since # is found by this lookup, and its schema and version come from it. @@ -930,7 +926,7 @@ def _check_table(self) -> bool: # handle reads it afresh) and compared, as reads used to do before ITL-1774. given = self._given_asof raw_schema = table.arrow_schema(asof=given) - require_names_not_system_tags(raw_schema.names) + require_source_column_names(raw_schema.names) schema = arrow_utils.drop_system_columns(raw_schema.empty_table()).schema if not schema.equals(self._table_schema, check_metadata=True): raise ValueError( @@ -1061,7 +1057,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_names_not_system_tags(raw.column_names) + require_source_column_names(raw.column_names) require_supported_nullable_types(raw.schema) require_live_logical_types(raw.schema) rows = arrow_utils.drop_system_columns(raw) diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 7fc19f16b..74e104683 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -1,7 +1,7 @@ """Compositional builder for enriching raw Arrow tables into source streams. Extracts the enrichment pipeline that was previously embedded in -``ArrowTableSource.__init__``: dropping system columns, validating tags, +``ArrowTableSource.__init__``: validating input columns and tags, computing schema/table hashes, adding source-info provenance, adding system tag columns, and wrapping the result in an ``ArrowTableStream``. """ @@ -37,7 +37,7 @@ from orcapod.system_constants import constants from orcapod.types import ContentHash from orcapod.utils import arrow_utils, schema_utils -from orcapod.utils.schema_utils import compute_schema_hash +from orcapod.utils.schema_utils import ReservedColumnNameError, compute_schema_hash if TYPE_CHECKING: from polars._typing import ( @@ -95,7 +95,7 @@ def read_arrow_frame_input(data: FrameInitTypes) -> tuple[pa.Table, pa.Schema] | import polars as pl if isinstance(data, pd.DataFrame): - schema_utils.require_names_not_system_tags([str(name) for name in data.columns]) + require_source_column_names([str(name) for name in data.columns]) # Arrow-backed dtypes retain nested field metadata. Check them before # Polars reads the frame, while keeping its normal conversion for pandas. require_live_logical_types( @@ -119,7 +119,7 @@ def read_arrow_frame_input(data: FrameInitTypes) -> tuple[pa.Table, pa.Schema] | # Passing the StructType directly to pa.schema would also use C import. input_schema = pa.schema(list(data.type)) if input_schema is not None: - schema_utils.require_names_not_system_tags(input_schema.names) + require_source_column_names(input_schema.names) require_live_logical_types(input_schema) # Like Polars, prefer the array export when both are available. if hasattr(data, "__arrow_c_array__"): @@ -129,11 +129,11 @@ def read_arrow_frame_input(data: FrameInitTypes) -> tuple[pa.Table, pa.Schema] | table = pa.table(cast("ArrowStreamExportable", data)) else: return None + require_source_column_names(table.column_names) if input_schema is None: # C exporters describe live and stored extensions the same way. Validate # the imported field types and any annotations that remain on storage. input_schema = table.schema - schema_utils.require_names_not_system_tags(input_schema.names) require_live_logical_types(input_schema) return table, input_schema @@ -153,6 +153,16 @@ def require_supported_nullable_types(schema: pa.Schema) -> None: ) +def require_source_column_names(names: Collection[str]) -> None: + """Refuse raw source columns in Orcapod's reserved namespace.""" + try: + schema_utils.require_names_not_system(names) + except ReservedColumnNameError as exc: + raise ReservedColumnNameError( + f"{exc} To build the source, rename the reserved columns or drop them first." + ) from exc + + def require_system_tag_without_field_metadata( field: pa.Field[Any], *, stored_cache: bool = False ) -> None: @@ -610,9 +620,9 @@ def build( ``kind_part`` is not given or is not ``_v``, or if the source id it builds is not valid, or if ``hash_in_key_order`` is given with a ``source_name`` or without key columns. - InputValidationError: If an external column carries a stored logical - type, or if a column's type is or contains a dictionary - (ITL-1264, ITL-1277). + InputValidationError: If a raw column has a reserved name, carries + a stored logical type, or has a type that is or contains a + dictionary (ITL-1264, ITL-1277). """ # Whole-argument checks first, before the table is read. key_columns = normalize_record_id_columns(record_id_columns) or () @@ -622,7 +632,11 @@ def build( hash_in_key_order, source_name=source_name, key_columns=key_columns ) tag_columns_tuple = tuple(tag_columns) - schema_utils.require_names_not_system_tags(table.column_names) + require_source_column_names( + (*table.column_names, *tag_columns_tuple, *data_tags) + ) + if input_schema is not None: + require_source_column_names(input_schema.names) require_supported_nullable_types(table.schema) data_tags_tuple = tuple(c for c in tag_columns_tuple if c in data_tags) if unknown := set(data_tags) - set(tag_columns_tuple): @@ -633,10 +647,6 @@ def build( # Tag-only columns: the tags that are not also data. tag_only_tuple = tuple(c for c in tag_columns_tuple if c not in data_tags_tuple) - # A tag never has a meta column's name; the meta columns are dropped next, - # so say so here rather than report the tag as missing (ITL-1080). - schema_utils.require_names_not_meta(tag_columns_tuple) - if not from_origin: require_live_logical_types( table.schema if input_schema is None else input_schema, @@ -644,9 +654,7 @@ def build( # Dictionary-encoded columns are not currently supported (ITL-1264, # ITL-1277). The stream refuses them too; checking first reports the - # dictionary, not a key column error, and before anything is hashed. It runs - # before dropping reserved meta and source-info columns so an unsupported - # column type is reported even in those columns. + # dictionary, not a key column error, and before anything is hashed. if found := schema_utils.dictionary_columns(table.schema): raise schema_utils.dictionary_columns_error( found, tag_columns_tuple, data_tags_tuple @@ -659,9 +667,6 @@ def build( found, tag_columns_tuple, data_tags_tuple ) - # 1. Drop system columns from raw input. - table = arrow_utils.drop_system_columns(table) - # 2. Validate tag_columns. A table with no columns at all (e.g. a # DictSource built from no rows and no schema) gets its own error, since # "tag column not found" would point at the wrong problem. @@ -685,9 +690,8 @@ def build( # 4. Compute schema hash from the tag/data Arrow schemas (ITL-640). # Nullable flags in the incoming table are trusted as-is — callers must # set them correctly before calling build(). - non_sys = arrow_utils.drop_system_columns(table) - tag_schema = non_sys.select(list(tag_columns_tuple)).schema - data_schema = non_sys.drop(list(tag_only_tuple)).schema + tag_schema = table.select(list(tag_columns_tuple)).schema + data_schema = table.drop(list(tag_only_tuple)).schema try: schema_hash = compute_schema_hash( tag_schema, diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 75cf54d8e..02e92d1cd 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -53,7 +53,7 @@ class ArrowTableStream(MaterializedOutput, StreamBase): too) and every operator result presents large types. Width, nullability, field metadata and logical types are kept; large and non-large variants hash identically. - System-tag columns are reserved for Orcapod's provenance. + System columns are reserved for Orcapod. """ # The table's rows are held, not computed: a run() view says "all N rows", as @@ -73,7 +73,7 @@ def __init__( """Wrap ``table`` as a stream. Args: - table: The rows: tag, data and source-info columns. + table: The user tag and data columns. tag_columns: The user tag columns. source_info: Source-info tokens to add, by column. producer: The pod that produced the stream, if any. @@ -92,9 +92,11 @@ def __init__( Also if a source-info token column does not have the shape of its data column, or a token with a list layer is null (``schema_utils.token_layers_fit``, ITL-1491). - Also if a column name is reserved for system tags. + Also if a user column name begins with an underscore. """ - schema_utils.require_names_not_system_tags(table.column_names) + schema_utils.require_names_not_system( + (*table.column_names, *tag_columns, *data_tags, *(source_info or ())) + ) super().__init__(**kwargs) self._initialize( table, tag_columns, source_info, producer, upstreams, data_tags @@ -112,7 +114,7 @@ def _from_derived_table( data_context: str | contexts.DataContext | None = None, label: str | None = None, ) -> Self: - """Wrap a table whose system tags were built by Orcapod.""" + """Wrap a table whose system columns were built by Orcapod.""" stream = cls.__new__(cls) super(ArrowTableStream, stream).__init__(data_context=data_context, label=label) stream._initialize(table, tag_columns, None, producer, upstreams, data_tags) @@ -175,8 +177,6 @@ def _initialize( prefix_info = {constants.SOURCE_PREFIX: source_info} - # A tag never has a meta column's name (ITL-1080). - schema_utils.require_names_not_meta(tag_columns) # determine tag columns first and then exclude any source info self._tag_columns = tuple(c for c in tag_columns if c in table.column_names) self._system_tag_columns = tuple( diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index af96679a0..9c6304cbf 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -20,6 +20,7 @@ from orcapod.pipeline.dag import OrcaDAG from orcapod.protocols import core_protocols as cp from orcapod.utils.lazy_module import LazyModule +from orcapod.utils.schema_utils import ReservedColumnNameError if TYPE_CHECKING: import networkx as nx @@ -538,7 +539,7 @@ def load(cls, path: str | Path) -> "Pipeline": ) operator = resolve_operator_from_config(op_config) - except Warning: + except (ReservedColumnNameError, Warning): # A warning turned into an error (a ProvisionalHashWarning # under an error filter) propagates (ITL-1331). raise diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index af81177ee..909fa27ee 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -71,6 +71,7 @@ commit_best_effort, database_write_path, ) +from orcapod.utils.schema_utils import ReservedColumnNameError if TYPE_CHECKING: from collections.abc import Mapping @@ -2317,7 +2318,7 @@ def load( deepcopy(src_config) ) source = sources_by_config[config_key] - except Warning: + except (ReservedColumnNameError, Warning): # A warning treated as an error propagates (ITL-1331). raise except Exception as exc: diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 1f2394bc9..71d9dc394 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -25,6 +25,7 @@ ) from orcapod.semantic_types._schema_conversion import arrow_schema_for_types +from orcapod.utils.schema_utils import ReservedColumnNameError, require_names_not_system if TYPE_CHECKING: import pyarrow as pa @@ -757,7 +758,7 @@ def resolve_source_from_config( # All sources accept db_registry — always forward it. # Sources that don't embed database references simply ignore it. return cls.from_config(config, db_registry=db_registry) - except Warning: + except (ReservedColumnNameError, Warning): # A warning turned into an error (a ProvisionalHashWarning under an error # filter) propagates; it is not a source that could not be rebuilt (ITL-1331). raise @@ -879,6 +880,8 @@ def _source_proxy_from_config( data_schema_dict = config.get("data_schema", {}) saved_nullable = config.get("nullable") + require_names_not_system((*tag_schema_dict, *data_schema_dict)) + if not content_hash or not pipeline_hash_val: raise ValueError( "Cannot create SourceProxy: missing identity fields. " @@ -1434,6 +1437,9 @@ def deserialize_output_schema( such as an unregistered logical type, or a saved nullable column name is not a saved column. The message names the column and its saved type string. """ + tag_columns = output_schema.get("tag", {}) + data_columns = output_schema.get("data", {}) + require_names_not_system((*tag_columns, *data_columns)) saved_nullable: dict[str, list[str]] | None = output_schema.get("nullable") def restore(columns: dict[str, str], nullable: list[str] | None) -> Schema: @@ -1465,11 +1471,11 @@ def restore(columns: dict[str, str], nullable: list[str] | None) -> Schema: return ( restore( - output_schema.get("tag", {}), + tag_columns, None if saved_nullable is None else saved_nullable["tag"], ), restore( - output_schema.get("data", {}), + data_columns, None if saved_nullable is None else saved_nullable["data"], ), ) diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index a4992e6de..07d5c1c67 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -780,45 +780,6 @@ def require_names_without_separator(names: Collection[str]) -> None: ) -def require_names_not_meta(names: Collection[str]) -> None: - """Raise if a tag or data column name starts with the reserved meta prefix. - - Names starting with the meta prefix (``__``) are meta columns: a datagram - keeps them apart from its tags and data, and no operator carries them - (ITL-1080). A tag or data column given such a name would silently stop being - one on every path that rebuilds rows, so no stream, source or operator may - produce one. - - Args: - names: Tag or data column names. - - Raises: - InputValidationError: If a name starts with the meta prefix. The message - names the column. - """ - from orcapod.system_constants import constants - - for name in sorted(names): - if name.startswith(constants.META_PREFIX): - raise InputValidationError( - f"column name {name!r} starts with {constants.META_PREFIX!r}, which is " - "reserved for meta columns; a tag or data column needs another name." - ) - - -def require_names_not_system_tags(names: Collection[str]) -> None: - """Refuse public input fields in Orcapod's system-tag namespace.""" - from orcapod.system_constants import constants - - prefixes = (constants.SYSTEM_TAG_PREFIX, "_tag::") - for name in sorted(names): - if name.startswith(prefixes): - raise InputValidationError( - f"column name {name!r} is reserved for Orcapod system tags; " - "give the column another name." - ) - - DICTIONARY_COLUMNS_NOT_SUPPORTED = ( "dictionary-encoded columns are not currently supported in Orcapod" ) @@ -1229,41 +1190,56 @@ def schema_hash_rejected_columns_error( ) -def require_names_not_system(names: Collection[str]) -> None: - """Raise if a tag or data column name is one a stream reads as a system column. +class ReservedColumnNameError(InputValidationError): + """A user column is named in Orcapod's reserved namespace.""" + + +def reserved_system_names(names: Iterable[str]) -> set[str]: + """Return the names in Orcapod's reserved column namespace.""" + from orcapod.system_constants import constants + + return {name for name in names if name.startswith(constants.DATAGRAM_PREFIX)} - A stream reads a column whose name starts with the system-tag prefix - (``_tag_``) as a system tag, one that starts with the source-info prefix - (``_source_``) as source info, and the context key column (``_context_key``) - as the data context, so a tag or data column renamed to such a name stops - being one (ITL-1160). Function pipeline tables also reserve a prefix for - input source info. The meta prefix has its own check, - ``require_names_not_meta``. + +def require_names_not_system(names: Collection[str]) -> None: + """Raise if any user column name begins with the reserved underscore. Args: names: Tag or data column names. Raises: - InputValidationError: If a name starts with a reserved prefix or is the - context key column. The message names the column. + InputValidationError: If any name starts with the reserved prefix. The + message names every offending column. + """ + from orcapod.system_constants import constants + + prefix = constants.DATAGRAM_PREFIX + reserved = sorted(reserved_system_names(names)) + if reserved: + columns = ", ".join(repr(name) for name in reserved) + raise ReservedColumnNameError( + f"Column names {columns} start with {prefix!r}. Names beginning with " + f"{prefix!r} are reserved for Orcapod. Use another column name." + ) + + +def require_stored_stream_column_names( + names: Collection[str], bookkeeping: Collection[str] +) -> None: + """Validate the user columns of a stored stream. + + Stored streams carry system tags and source info alongside the user columns. + System tags have their own prefix. Source info names the column it describes. """ from orcapod.system_constants import constants - reserved_prefixes = { - constants.SYSTEM_TAG_PREFIX: "system tags", - "_tag::": "system tags", - constants.SOURCE_PREFIX: "source info", - constants.INPUT_SOURCE_PREFIX: "input source info", + system_columns = { + name + for name in names + if name.startswith(constants.SYSTEM_TAG_PREFIX) + or ( + name.startswith(constants.SOURCE_PREFIX) + and name.removeprefix(constants.SOURCE_PREFIX) in names + ) } - for name in sorted(names): - for prefix, kind in reserved_prefixes.items(): - if name.startswith(prefix): - raise InputValidationError( - f"column name {name!r} starts with {prefix!r}, which is reserved " - f"for {kind}; a tag or data column needs another name." - ) - if name == constants.CONTEXT_KEY: - raise InputValidationError( - f"column name {name!r} is reserved for the data context; a tag or " - "data column needs another name." - ) + require_names_not_system(set(names) - set(bookkeeping) - system_columns) diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 8715910a0..f05abad59 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -1277,7 +1277,7 @@ async def write() -> list[str]: 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.""" - stream = ArrowTableStream( + stream = ArrowTableStream._from_derived_table( pa.table( { "k": pa.array([1, 2, 3], pa.int64()), @@ -2439,7 +2439,7 @@ def test_concrete_channel_refuses_first_batch_with_a_different_token_type( from orcapod.core.operators.static_output_pod import SourceInfoTypesDisagree declared = pa.large_list(pa.field("leaf", TOKEN, metadata={b"kind": b"token"})) - stream = ArrowTableStream( + stream = ArrowTableStream._from_derived_table( pa.table( { "amplitude": pa.array([[1]], pa.large_list(pa.int64())), diff --git a/tests/test_channels/test_record_batch_review_findings.py b/tests/test_channels/test_record_batch_review_findings.py index e92211eda..e0f6fd95f 100644 --- a/tests/test_channels/test_record_batch_review_findings.py +++ b/tests/test_channels/test_record_batch_review_findings.py @@ -385,7 +385,7 @@ def _list_token_stream(token_type: pa.DataType | None = None) -> ArrowTableStrea token_type: The token column's declared type; a plain large list of strings when not given. """ - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.table( { "k": pa.array([1, 2], pa.int64()), @@ -506,7 +506,7 @@ def test_a_token_sent_into_a_null_typed_source_info_column_is_taken() -> None: type is ``null`` is described by its tokens' type, as a row types a token, so a batch with a real token is accepted at send, and the result's column is ``large_string``. This pins the declined behaviour.""" - stream = ArrowTableStream( + stream = ArrowTableStream._from_derived_table( pa.table( { "k": pa.array([1, 2], pa.int64()), @@ -822,7 +822,7 @@ def test_batches_of_one_input_that_declare_two_token_types_are_refused( StreamingSemiJoin, ) - left = ArrowTableStream( + left = ArrowTableStream._from_derived_table( pa.table( { "k": pa.array([1, 2], pa.int64()), @@ -851,7 +851,7 @@ def test_batches_of_one_input_that_declare_two_token_types_are_refused( batches = [shallow, deep] if shallow_first else [deep, shallow] # The sync path: the same rows keep the type their stream declares. tokens = [[], [["b"]]] if shallow_first else [[["a"]], []] - mixed = ArrowTableStream( + mixed = ArrowTableStream._from_derived_table( pa.table( { "k": pa.array([1, 2], pa.int64()), @@ -1008,7 +1008,7 @@ async def run() -> None: def _deep_token_stream(tokens: list[Any], keys: list[int]) -> ArrowTableStream: # pyright: ignore[reportExplicitAny] # tokens of any shape """Tag ``k``, data ``x`` and ``y``, ``x``'s source info declared two list levels deep.""" - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.table( { "k": pa.array(keys, pa.int64()), @@ -1269,7 +1269,7 @@ def test_settled_tokens_against_an_input_with_no_rows_decide_as_the_sync_path( nothing = _deep_token_stream([], []) if kernel == "join": # Join needs disjoint data: the other input under other data names. - nothing = ArrowTableStream( + nothing = ArrowTableStream._from_derived_table( pa.table( { "k": pa.array([], pa.int64()), @@ -1322,7 +1322,7 @@ def _typed_token_stream( ``x`` is a list in every stream, so a list token and a plain string token are both valid over it (the token-shape rule, ITL-1491). """ - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.table( { "k": pa.array(keys, pa.int64()), diff --git a/tests/test_core/data_function/test_result_token_column_type.py b/tests/test_core/data_function/test_result_token_column_type.py index e7158cc78..f96a3d002 100644 --- a/tests/test_core/data_function/test_result_token_column_type.py +++ b/tests/test_core/data_function/test_result_token_column_type.py @@ -110,6 +110,18 @@ def test_the_declared_token_column_is_a_nullable_large_string() -> None: assert RESULT_TOKEN_COLUMN.python_type is str +def test_record_data_refuses_reserved_output_names(tmp_path: Path) -> None: + """A manual cache write leaves no record if it has reserved output keys.""" + function = _function(_database("memory", tmp_path), ("total", "label")) + input_data = Data({"x": 3, "y": 4}) + with pytest.raises(InputValidationError, match="'_bad'.*'_tag_fake'.*reserved"): + function.record_data( + input_data, Data({"total": 7, "label": "3+4", "_bad": 1, "_tag_fake": 2}) + ) + assert _stored_rows(function) == 0 + assert function.get_cached_output_for_data(input_data) is None + + @pytest.mark.parametrize("backend", BACKENDS) @pytest.mark.parametrize("keys", KEY_ORDERS) @pytest.mark.parametrize("tokens", LIST_TOKENS, ids=repr) diff --git a/tests/test_core/data_tags/test_operator_node_storage.py b/tests/test_core/data_tags/test_operator_node_storage.py index f45da98a7..21466eb8f 100644 --- a/tests/test_core/data_tags/test_operator_node_storage.py +++ b/tests/test_core/data_tags/test_operator_node_storage.py @@ -486,7 +486,7 @@ def stream(mixed: bool) -> ArrowTableStream: "_source_x": [] if nested else None, } ) - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.Table.from_pylist(rows, schema=schema), tag_columns=["k"], producer=op_filter, @@ -504,7 +504,7 @@ def as_table(self, **kwargs): def iter_data(self): return self.current.iter_data() - stream_value = Snapshots( + stream_value = Snapshots._from_derived_table( schema.empty_table(), tag_columns=["k"], producer=op_filter, upstreams=(origin,) ) store = make_store(tmp_path) diff --git a/tests/test_core/data_tags/test_select_keeps_data_context.py b/tests/test_core/data_tags/test_select_keeps_data_context.py index 47d64e898..ebbabd5c5 100644 --- a/tests/test_core/data_tags/test_select_keeps_data_context.py +++ b/tests/test_core/data_tags/test_select_keeps_data_context.py @@ -54,7 +54,7 @@ def _stream(context: contexts.DataContext) -> ArrowTableStream: constants.CONTEXT_KEY: pa.array([OTHER, OTHER], pa.large_string()), } ) - return ArrowTableStream( + return ArrowTableStream._from_derived_table( table, tag_columns=["k", "u"], data_tags=["k"], data_context=context ) diff --git a/tests/test_core/datagrams/test_rows_of_table.py b/tests/test_core/datagrams/test_rows_of_table.py index 68d39bd24..3ed97986c 100644 --- a/tests/test_core/datagrams/test_rows_of_table.py +++ b/tests/test_core/datagrams/test_rows_of_table.py @@ -404,9 +404,9 @@ def _grouped() -> Any: return _joined().group_by(["g"]) -def _raw_stream_without_tags() -> Any: - """A raw stream with no tag column, a meta column and a column with no values.""" - return ArrowTableStream( +def _stream_without_tags() -> Any: + """An internal stream with no tags, a meta column and a column with no values.""" + return ArrowTableStream._from_derived_table( pa.table( { "x": pa.array([1, 2, 3], pa.int32()), @@ -436,7 +436,7 @@ def _raw_stream_in_two_chunks() -> Any: "source_in_another_arrangement": _source_in_another_arrangement, "joined": _joined, "grouped": _grouped, - "raw_stream_without_tags": _raw_stream_without_tags, + "stream_without_tags": _stream_without_tags, "raw_stream_in_two_chunks": _raw_stream_in_two_chunks, } @@ -487,13 +487,13 @@ def test_a_streams_rows_are_the_constructors(name: str) -> None: @pytest.mark.parametrize( - "name", [name for name in STREAMS if name != "raw_stream_without_tags"] + "name", [name for name in STREAMS if name != "stream_without_tags"] ) def test_a_streams_rows_rebuild_its_table(name: str) -> None: """The rows' own tables, put side by side, are the stream's table. - Not for the raw stream with a meta column: a row's data holds that column as meta, - the stream as a column like any other. + The constructor comparison covers the metadata case, where each row's data + exposes the column as metadata. """ stream = STREAMS[name]() columns = {"system_tags": True, "source": True} diff --git a/tests/test_core/function_pod/test_cached_function_pod_job.py b/tests/test_core/function_pod/test_cached_function_pod_job.py index 18cda53ab..90704243e 100644 --- a/tests/test_core/function_pod/test_cached_function_pod_job.py +++ b/tests/test_core/function_pod/test_cached_function_pod_job.py @@ -10,17 +10,21 @@ from __future__ import annotations +import asyncio import json from collections.abc import Callable from pathlib import Path from typing import Any +import pyarrow as pa import pytest -from orcapod import PipelineJob +from orcapod import PipelineJob, errors from orcapod.core.cached_function_pod import CachedFunctionPod +from orcapod.core.datagrams import Data, Datagram from orcapod.core.function_pod import FunctionPod from orcapod.core.operators import Join +from orcapod.core.result_cache import ResultCache from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator @@ -182,6 +186,80 @@ def test_row_in_the_pod_cache_is_not_recomputed_by_a_job() -> None: assert counter.calls == [5] +@pytest.mark.parametrize( + "path", + [ + "lookup", + "stream-sync", + "stream-async", + "job-sync", + "job-async", + "late-hit-sync", + "late-hit-async", + ], +) +def test_pod_cache_refuses_reserved_output_keys( + path: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """A stored row written before output validation must fail on every hit path.""" + counter = Counter() + pod = counter.pod() + cache_db = InMemoryArrowDatabase() + cached = CachedFunctionPod(pod, result_database=cache_db) + source = make_source() + cache = ResultCache( + cache_db, pod.uri, pod.data_function.declaration.revision_component + ) + inputs = [data for _, data in source.iter_data()] + for data in inputs: + cache.store( + data, + Data({"total": 5, "_foo": 6, "_tag_fake": 7}), + Datagram({}), + Datagram({}), + data_context_key=pod.data_context_key, + ) + match = "'_foo'.*'_tag_fake'.*reserved" + if path == "lookup": + with pytest.raises(errors.OrcapodDatabaseReadError, match=match): + _ = cached.lookup_cached_data(inputs[0]) + elif path.startswith("job-"): + job = PipelineJob(name="reject_reserved", database=InMemoryArrowDatabase()) + with job: + _ = cached(source, label="add") + with pytest.raises(errors.OrcapodDatabaseReadError, match=match): + _ = job.run(orchestrator=ORCHESTRATORS[path.removeprefix("job-")]()) + records = job.nodes["add"].get_all_records() + assert records is None or records.num_rows == 0 + else: + if path.startswith("late-hit-"): + # Make the first lookup miss. The conditional write will find the row. + lookup = cache_db.get_records_with_column_value + miss = True + + def miss_first_lookup(*args: Any, **kwargs: Any): + nonlocal miss + if miss: + miss = False + return None + return lookup(*args, **kwargs) + + monkeypatch.setattr( + cache_db, "get_records_with_column_value", miss_first_lookup + ) + stream = cached(source) + + async def consume() -> None: + _ = [row async for row in stream.async_iter_data()] + + with pytest.raises(errors.OrcapodDatabaseReadError, match=match): + if path.endswith("-async"): + asyncio.run(consume()) + else: + _ = list(stream.iter_data()) + assert counter.calls == ([2] if path.startswith("late-hit-") else []) + + def test_inputs_are_joined_once() -> None: counter = Counter() cached_pod = CachedFunctionPod( @@ -246,3 +324,50 @@ def test_saved_job_equals_the_uncached_pods_and_loads( {"k": 1, "total": 5}, {"k": 2, "total": 10}, ] + + +@pytest.mark.parametrize("mode", ["ordinary", "load-only", "records", "derived"]) +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_function_job_refuses_reserved_stored_result_keys( + mode: str, orchestrator: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + counter = Counter() + store = DeltaTableDatabase(tmp_path / "store") + job = run_job(counter.pod(), store, orchestrator) + job_path = tmp_path / "job.json" + job.save(job_path) + counter.calls.clear() + read = DeltaTableDatabase.get_all_records + + def read_legacy_result( + database: DeltaTableDatabase, path: tuple[str, ...], *args: Any, **kwargs: Any + ) -> pa.Table | None: + table = read(database, path, *args, **kwargs) + if path[-1] == "rdb_v1" and table is not None: + return table.append_column( + "_foo", pa.array([6] * table.num_rows) + ).append_column("_tag_fake", pa.array([7] * table.num_rows)) + return table + + monkeypatch.setattr(DeltaTableDatabase, "get_all_records", read_legacy_result) + if mode == "load-only": + job = PipelineJob.load(job_path, database=store) + job.bind(sources={"s": make_source()}) + elif mode == "ordinary": + job = PipelineJob(name="j", database=store) + with job: + _ = counter.pod()(make_source(), label="add") + node = job.nodes["add"] + with pytest.raises( + errors.InputValidationError, match="'_foo'.*'_tag_fake'.*reserved.*rdb_v1" + ): + if mode == "records": + _ = node.get_all_records() + elif mode == "derived": + _ = node.as_source().as_table() + else: + _ = job.run( + orchestrator=ORCHESTRATORS[orchestrator](), + load_only=mode == "load-only", + ) + assert counter.calls == [] diff --git a/tests/test_core/function_pod/test_output_conformance.py b/tests/test_core/function_pod/test_output_conformance.py index 8a2d83621..00b7612f7 100644 --- a/tests/test_core/function_pod/test_output_conformance.py +++ b/tests/test_core/function_pod/test_output_conformance.py @@ -35,14 +35,16 @@ import pytest from pydantic import BaseModel +from typing_extensions import override from orcapod import PipelineJob, errors, function_pod -from orcapod.core.data_function import PythonDataFunction +from orcapod.core.data_function import CachedDataFunction, PythonDataFunction from orcapod.core.datagrams import Data from orcapod.core.function_pod import FunctionPod from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline.observer import NoOpObserver +from orcapod.protocols.core_protocols import DataFunctionProtocol, DataProtocol from orcapod.sources import DictSource @@ -306,6 +308,131 @@ class _NamedOutputs(NamedTuple): _POSITIONAL_SEQUENCE = types.GenericAlias(Sequence, (int, int)) +@pytest.mark.parametrize( + ("reserved_keys", "allowed_keys", "return_error"), + [ + pytest.param("_first", "first", errors.OutputTypeError, id="single-output"), + pytest.param( + ("first", "_second"), + _TWO_TEXT, + errors.OutputContainerTypeError, + id="reserved-last", + ), + pytest.param( + ("_second", "first"), + _TWO_TEXT[::-1], + errors.OutputContainerTypeError, + id="reserved-first", + ), + ], +) +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_reserved_output_names_are_refused_before_return_validation( + reserved_keys: str | tuple[str, ...], + allowed_keys: str | tuple[str, ...], + return_error: type[errors.OutputTypeError], + asynchronous: bool, +) -> None: + fn = _multi_output_function( + tuple[str, str], {"first": "a", "second": "b"}, asynchronous=asynchronous + ) + + with pytest.raises(errors.InputValidationError, match="reserved"): + _ = PythonDataFunction(fn, output_keys=reserved_keys) + + data_function = PythonDataFunction(fn, output_keys=allowed_keys) + with pytest.raises(return_error, match="returned dict") as caught: + data = Data({"x": 7, "y": "b"}) + if asynchronous: + _ = asyncio.run(data_function.async_call(data)) + else: + _ = data_function.call(data) + assert type(caught.value) is return_error + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("reverse", [False, True], ids=["original", "reversed"]) +@pytest.mark.parametrize("path", ["standalone", "job", "data-function-cache"]) +def test_public_function_pod_rejects_reserved_returned_data_keys( + asynchronous: bool, reverse: bool, path: str +) -> None: + """A custom function's row can contain keys its declared outputs did not.""" + items = [("out", 4), ("_tag_fake", 5), ("_content_hash", 6), ("_foo", 7)] + if reverse: + items.reverse() + + def declared(x: int, y: int) -> int: + return x + y + + class CustomFunction(PythonDataFunction): + @override + def call(self, data: DataProtocol, **kwargs: object) -> Data: + return Data( + dict(items), + meta_info={"__debug": "diagnostic"}, + source_info={"out": "token"}, + ) + + @override + async def async_call(self, data: DataProtocol, **kwargs: object) -> Data: + return self.call(data, **kwargs) + + source = DictSource( + [{"k": 1, "g": "a", "x": 2, "y": 3}, {"k": 2, "g": "b", "x": 4, "y": 5}], + tag_columns=["g", "k"] if reverse else ["k", "g"], + tag_only_columns=True, + ) + function = cast(object, CustomFunction(declared, output_keys=["out"])) + assert isinstance(function, DataFunctionProtocol) + cache = ( + CachedDataFunction(function, result_database=InMemoryArrowDatabase()) + if path == "data-function-cache" + else None + ) + pod = FunctionPod(cache if cache is not None else function) + message = "'_content_hash'.*'_foo'.*'_tag_fake'.*reserved" + if path == "job": + job = PipelineJob(name="custom_output", database=InMemoryArrowDatabase()) + with job: + _ = pod(source, label="node") + observer = _CrashRecorder() + orchestrator = ( + AsyncPipelineOrchestrator() if asynchronous else SyncPipelineOrchestrator() + ) + with pytest.warns(errors.RowFailuresWarning, match=message): + _ = job.run(orchestrator=orchestrator, observer=observer) + assert len(observer.crashes) == 2 + for error in observer.crashes: + assert isinstance(error, errors.InputValidationError) + assert all(name in str(error) for name, _ in items if name.startswith("_")) + records = job.nodes["node"].get_all_records() + assert records is None or records.num_rows == 0 + else: + stream = pod(source) + + async def collect() -> list[DataProtocol]: + return [output async for _, output in stream.async_iter_data()] + + with pytest.raises(errors.InputValidationError, match=message): + if asynchronous: + _ = asyncio.run(collect()) + else: + _ = list(stream.iter_data()) + if cache is not None: + assert all( + cache.get_cached_output_for_data(data) is None + for _, data in source.iter_data() + ) + # Legal data, metadata and source information still pass through. + items[:] = [("out", 4)] + outputs = ( + asyncio.run(collect()) + if asynchronous + else [output for _, output in stream.iter_data()] + ) + assert [output.as_dict() for output in outputs] == [{"out": 4}, {"out": 4}] + + @pytest.mark.parametrize( ("annotation", "returned", "keys"), [ diff --git a/tests/test_core/nodes/test_source_node.py b/tests/test_core/nodes/test_source_node.py index f5189d7fd..e8a8011fc 100644 --- a/tests/test_core/nodes/test_source_node.py +++ b/tests/test_core/nodes/test_source_node.py @@ -4,10 +4,15 @@ from unittest.mock import MagicMock +import pyarrow as pa import pytest from orcapod.core.nodes.source_node import SourceJobNode -from orcapod.errors import SourceSpecMismatchError, UnboundSourceError +from orcapod.errors import ( + InputValidationError, + SourceSpecMismatchError, + UnboundSourceError, +) from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import ColumnConfig, Schema @@ -22,6 +27,18 @@ def data_schema(): return Schema({"value": float}) +@pytest.mark.parametrize("arrow", [False, True], ids=["python", "arrow"]) +def test_declared_source_node_refuses_reserved_columns(arrow: bool) -> None: + from orcapod.core.nodes.source_node import SourceNode + + tag = pa.schema([("_id", pa.int64())]) if arrow else Schema({"_id": int}) + data = pa.schema([("_value", pa.int64())]) if arrow else Schema({"_value": int}) + with pytest.raises( + InputValidationError, match="'_id'.*'_value'.*reserved for Orcapod" + ): + SourceNode("input", tag_schema=tag, data_schema=data) + + class TestSourceNodeHashStability: """SourceNode must produce stable, deterministic hashes. diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index d97759752..360665f4d 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -930,6 +930,11 @@ def _float_tag_branch(values: Sequence[float], data: str) -> ArrowTableStream: lambda: Index("l8", 0, out="first"), lambda: (source_a(with_data_tags=True),), ), + Case( + "ref_pick", + lambda: Pick("d", "q", out="picked"), + lambda: (source_a(with_data_tags=True),), + ), Case( "ref_drop_nulls_all", lambda: DropNulls(), @@ -2608,13 +2613,13 @@ def _table_with_meta_named_column() -> pa.Table: def test_a_stream_refuses_a_tag_named_with_the_meta_prefix() -> None: - with pytest.raises(InputValidationError, match="'__g'.*reserved for meta"): + with pytest.raises(InputValidationError, match="'__g'.*reserved for Orcapod"): _ = ArrowTableStream(_table_with_meta_named_column(), tag_columns=["k", "__g"]) def test_a_source_refuses_a_tag_named_with_the_meta_prefix() -> None: - """Not "tag column not found": the source would drop the meta column first.""" - with pytest.raises(InputValidationError, match="'__g'.*reserved for meta"): + """The source reports the reserved name even when it was requested as a tag.""" + with pytest.raises(InputValidationError, match="'__g'.*drop them first"): _ = ArrowTableSource( _table_with_meta_named_column(), tag_columns=["k", "__g"], @@ -2625,7 +2630,7 @@ def test_a_source_refuses_a_tag_named_with_the_meta_prefix() -> None: def test_map_tags_refuses_a_meta_named_target() -> None: """Refused when built, so neither path nor the prediction can produce one.""" - with pytest.raises(InputValidationError, match="'__t'.*reserved for meta"): + with pytest.raises(InputValidationError, match="'__t'.*reserved for Orcapod"): _ = MapTags({"ta": "__t"}) @@ -2720,7 +2725,7 @@ def test_map_tags_dropping_every_tag_agrees_on_both_paths() -> None: def test_map_data_refuses_a_meta_named_target() -> None: """A data column never gets a meta column's name: refused when built.""" - with pytest.raises(InputValidationError, match="'__x'.*reserved for meta"): + with pytest.raises(InputValidationError, match="'__x'.*reserved for Orcapod"): _ = MapData({"i8": "__x"}) diff --git a/tests/test_core/operators/test_filter.py b/tests/test_core/operators/test_filter.py index d901a0c98..07a8814be 100644 --- a/tests/test_core/operators/test_filter.py +++ b/tests/test_core/operators/test_filter.py @@ -262,7 +262,7 @@ def test_each_rows_data_context_passes_through(self): ), } ) - stream = ArrowTableStream(table, tag_columns=["k"]) + stream = ArrowTableStream._from_derived_table(table, tag_columns=["k"]) kept = Filter(col("k") >= 2)(stream).as_table(all_info=True) assert kept["_context_key"].to_pylist() == ["held-b", "held-c"] selected = SelectDataColumns(["v", "w"])(stream).as_table(all_info=True) @@ -276,7 +276,7 @@ def test_no_meta_columns(self): "__note": pa.array(["a", "b"], pa.large_string()), } ) - stream = ArrowTableStream(table, tag_columns=["k"]) + stream = ArrowTableStream._from_derived_table(table, tag_columns=["k"]) out = Filter(col("v") > 10)(stream) assert "__note" not in out.as_table(all_info=True).column_names assert "__note" not in out.output_schema(all_info=True)[1] diff --git a/tests/test_core/operators/test_filter_review_findings.py b/tests/test_core/operators/test_filter_review_findings.py index 85533fd39..69d0a7fdd 100644 --- a/tests/test_core/operators/test_filter_review_findings.py +++ b/tests/test_core/operators/test_filter_review_findings.py @@ -71,7 +71,7 @@ def test_each_kept_rows_context_is_its_own(self, condition, kept): ), } ) - stream = ArrowTableStream(table, tag_columns=["k"]) + stream = ArrowTableStream._from_derived_table(table, tag_columns=["k"]) out = Filter(condition)(stream).as_table(columns={"context": True}) assert out["_context_key"].to_pylist() == kept # As every operator that passes rows through keeps it. diff --git a/tests/test_core/operators/test_index_source_token.py b/tests/test_core/operators/test_index_source_token.py index 28f0344cc..689f8f8d7 100644 --- a/tests/test_core/operators/test_index_source_token.py +++ b/tests/test_core/operators/test_index_source_token.py @@ -186,7 +186,7 @@ def test_index_keeps_a_projected_token_type_its_value_cannot_show( "_source_y": pa.array(["kept", "kept"], type=pa.large_string()), } ) - upstream = ArrowTableStream( + upstream = ArrowTableStream._from_derived_table( table.set_column(2, pa.field("x", data_type, nullable=False), values), tag_columns=list(tags), ) diff --git a/tests/test_core/operators/test_join_meta_columns.py b/tests/test_core/operators/test_join_meta_columns.py index 866ffbb15..ba3bcdd78 100644 --- a/tests/test_core/operators/test_join_meta_columns.py +++ b/tests/test_core/operators/test_join_meta_columns.py @@ -174,7 +174,7 @@ def _plain_table_stream(value_column: str, computed: bool) -> ArrowTableStream: f"{META}computed": pa.array([computed, computed], pa.bool_()), } ) - return ArrowTableStream(table, tag_columns=["id"]) + return ArrowTableStream._from_derived_table(table, tag_columns=["id"]) CASES.append( diff --git a/tests/test_core/operators/test_mappers_strict.py b/tests/test_core/operators/test_mappers_strict.py index d2cab25e3..b909dc229 100644 --- a/tests/test_core/operators/test_mappers_strict.py +++ b/tests/test_core/operators/test_mappers_strict.py @@ -376,7 +376,7 @@ def test_map_columns_refuses_leaving_no_data_column() -> None: def test_map_columns_refuses_a_meta_named_target() -> None: - with pytest.raises(InputValidationError, match="'__x'.*reserved for meta"): + with pytest.raises(InputValidationError, match="'__x'.*reserved for Orcapod"): MapColumns({"age": "__x"}) @@ -491,9 +491,8 @@ def test_the_stream_methods_refuse_a_system_column_name( getattr(_source(), method)({old_name: new_name}) -@pytest.mark.parametrize("new_name", ["_age", "_content_hash"]) -def test_other_underscore_names_stay_usable_as_new_names(new_name: str) -> None: - """Only names a stream reads as system columns are refused (see ITL-1160).""" +@pytest.mark.parametrize("new_name", ["age_", "content_hash"]) +def test_underscores_after_the_first_character_are_allowed(new_name: str) -> None: source = _source() for stream, async_op in ( (source.map_data({"age": new_name}), MapData({"age": new_name})), diff --git a/tests/test_core/operators/test_operators.py b/tests/test_core/operators/test_operators.py index 503abfb3c..f774afe92 100644 --- a/tests/test_core/operators/test_operators.py +++ b/tests/test_core/operators/test_operators.py @@ -589,7 +589,7 @@ def _make_stream(self, id_vals, pkt_col, pkt_vals, meta_val): "__computed": pa.array([meta_val] * len(id_vals), type=pa.bool_()), } ) - return ArrowTableStream(table, tag_columns=["id"]) + return ArrowTableStream._from_derived_table(table, tag_columns=["id"]) def test_three_way_join_with_shared_meta_column_succeeds(self): """Three streams each carrying ``__computed`` should join without DuplicateError.""" diff --git a/tests/test_core/operators/test_pick_index.py b/tests/test_core/operators/test_pick_index.py index 1c1c6a1db..71499dd72 100644 --- a/tests/test_core/operators/test_pick_index.py +++ b/tests/test_core/operators/test_pick_index.py @@ -3,16 +3,41 @@ from __future__ import annotations import pytest +from re import escape from orcapod.logical_types.base_logical_type import BaseLogicalType import dataclasses -from orcapod.core.operators import Pick +from orcapod.core.operators import AddTags, MapColumns, MapData, MapTags, Pick, TagBy from orcapod.core.sources import DictSource from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import InputValidationError from orcapod.core.operators import Index +@pytest.mark.parametrize( + "build", + [ + lambda name: Index("items", 0, out=name), + lambda name: Pick("scores", "speed", out=name), + lambda name: MapColumns({"x": name}), + lambda name: MapData({"x": name}), + lambda name: MapTags({"x": name}), + lambda name: AddTags({name: "value"}), + lambda name: TagBy(name), + ], + ids=["index", "pick", "map-columns", "map-data", "map-tags", "add-tags", "tag-by"], +) +@pytest.mark.parametrize( + "name", + ["_", "_foo", "_tag_y", "_tag::y", "_source_y", "_content_hash", "_context_key"], +) +def test_operators_refuse_reserved_column_names(build, name: str) -> None: + with pytest.raises( + InputValidationError, match=rf"{escape(repr(name))}.*reserved for Orcapod" + ): + build(name) + + class ConcreteLogicalType(BaseLogicalType): """Minimal concrete subclass for testing defaults.""" @@ -69,9 +94,9 @@ def test_pick_out_collision_raises(dict_stream): def test_pick_out_with_the_meta_prefix_raises(): - """``__`` is reserved for meta columns, which no operator carries (ITL-1080): an + """``__`` is reserved for Orcapod, which no operator carries (ITL-1080): an ``out`` named with it would be dropped on every path, so it is refused at once.""" - with pytest.raises(InputValidationError, match="reserved for meta columns"): + with pytest.raises(InputValidationError, match="reserved for Orcapod"): Pick("scores", "speed", out="__speed") @@ -244,9 +269,9 @@ def test_index_out_collision_raises(): def test_index_out_with_the_meta_prefix_raises(): - """``__`` is reserved for meta columns, which no operator carries (ITL-1080): an + """``__`` is reserved for Orcapod, which no operator carries (ITL-1080): an ``out`` named with it would be dropped on every path, so it is refused at once.""" - with pytest.raises(InputValidationError, match="reserved for meta columns"): + with pytest.raises(InputValidationError, match="reserved for Orcapod"): Index("items", 0, out="__first") diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index f27924dd1..9368f44b0 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -465,7 +465,7 @@ def test_a_barrier_operator_sees_its_input_as_a_job_gives_it(label: str) -> None def test_batch_takes_nullable_token_fields_across_arrivals() -> None: """``AddTags`` sends nullable token fields in batches with and without nulls.""" - raw = ArrowTableStream( + raw = ArrowTableStream._from_derived_table( pa.table( { "k": pa.array([1, 2, 3, 4], pa.int64()), @@ -556,7 +556,7 @@ def test_a_meta_column_does_not_travel() -> None: """A raw stream with a meta column: neither it nor a source-info column of it is in the record batches or in the stream rebuilt from them, as in the table built from the stream's rows.""" - raw = ArrowTableStream( + raw = ArrowTableStream._from_derived_table( pa.table( { "k": pa.array([1, 2], pa.int64()), @@ -649,7 +649,7 @@ def test_empty_source_info_lists_keep_their_columns_type(layout: str) -> None: lists: the channel's result equals the job's sync path, and both keep the column's two list levels. The pipeline determines a token column's type; it is never taken from the tokens, which here show one level only (ITL-1491).""" - raw = ArrowTableStream( + raw = ArrowTableStream._from_derived_table( pa.table( { "k": pa.array([1, 2], pa.int64()), diff --git a/tests/test_core/operators/test_semijoin_tag_keys.py b/tests/test_core/operators/test_semijoin_tag_keys.py index e5d324b2d..3d0828a97 100644 --- a/tests/test_core/operators/test_semijoin_tag_keys.py +++ b/tests/test_core/operators/test_semijoin_tag_keys.py @@ -271,7 +271,7 @@ def test_filter_without_the_warning() -> None: """Reduce the right input to its tags plus one renamed data column: no warning.""" source = left_source() subset = PolarsFilter(constraints={"id": 2})(left_source()) - keys_only = subset.select_data_columns(["x"]).map_data({"x": "_x"}) + keys_only = subset.select_data_columns(["x"]).map_data({"x": "right_x"}) with warnings.catch_warnings(): warnings.simplefilter("error", SemiJoinIgnoredColumnWarning) result = SemiJoin()(source, keys_only) diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index 89477aac5..47bd84632 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -1132,7 +1132,7 @@ def test_an_empty_run_ends_with_the_types_of_the_sync_result( @pytest.mark.parametrize("row_count", [0, 2]) -@pytest.mark.parametrize("column", ["k", "x", "__unused"]) +@pytest.mark.parametrize("column", ["k", "x", "unused", "__unused"]) @pytest.mark.parametrize( "bad_type", [ @@ -1161,10 +1161,12 @@ def test_a_source_refuses_a_null_typed_column( [arrays[name] for name in order], schema=pa.schema([fields[name] for name in order]), ) - with pytest.raises( - InputValidationError, - match=rf"{column!r}.*declare a supported nullable type", - ): + message = ( + rf"{column!r}.*drop them first" + if column == "__unused" + else rf"{column!r}.*declare a supported nullable type" + ) + with pytest.raises(InputValidationError, match=message): ArrowTableSource( table, tag_columns=["k", "g"], tag_only_columns=True, source_id="s" ) @@ -1180,7 +1182,7 @@ def _tokens_stream( """ token_list = pa.large_list(pa.large_string()) values = pa.large_list(pa.int64()) - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.table( { "k": pa.array([[key] for key in keys], values), @@ -1340,7 +1342,7 @@ def _token_stream(tokens: list[Any], token_type: pa.DataType) -> ArrowTableStrea from tests.token_shapes import data_for, data_type_for data_type = data_type_for(token_type) - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.table( { "k": pa.array([1, 2], pa.int64()), diff --git a/tests/test_core/sources/test_derived_source_tags_as_data.py b/tests/test_core/sources/test_derived_source_tags_as_data.py index f144d72e8..460d4e09c 100644 --- a/tests/test_core/sources/test_derived_source_tags_as_data.py +++ b/tests/test_core/sources/test_derived_source_tags_as_data.py @@ -628,10 +628,15 @@ def test_two_tags_copied_to_one_name(self): ) def test_reserved_name(self): - with pytest.raises(InputValidationError, match="_hidden"): + with pytest.raises( + InputValidationError, match="'_hidden'.*'_private'.*reserved for Orcapod" + ): DerivedSource( _experiment(), - tags_as_data={"session_start_datetime": "_hidden"}, + tags_as_data={ + "session_start_datetime": "_hidden", + "subject_id": "_private", + }, source_id="with_tags_as_data", ) diff --git a/tests/test_core/sources/test_dictionary_columns_refused.py b/tests/test_core/sources/test_dictionary_columns_refused.py index 9fd4c4e21..1d85541cb 100644 --- a/tests/test_core/sources/test_dictionary_columns_refused.py +++ b/tests/test_core/sources/test_dictionary_columns_refused.py @@ -280,20 +280,18 @@ def test_a_raw_stream_refuses_a_dictionary_in_orcapods_own_columns( assert f"- {role} column {column!r} has type dictionary<" in str(info.value) -OWN_COLUMNS = { - "__note": "meta", - "_source_v": "source-info", -} +OWN_COLUMNS = ("__note", "_source_v", "_tag_source_id::abc") -@pytest.mark.parametrize("own", [("__note",), ("_source_v",), tuple(OWN_COLUMNS)]) +@pytest.mark.parametrize( + "own", [("__note",), ("_source_v",), ("_tag_source_id::abc",), OWN_COLUMNS] +) @pytest.mark.parametrize("with_user_column", [False, True], ids=["alone", "beside-v"]) @pytest.mark.parametrize("own_first", [False, True], ids=["user-first", "own-first"]) -def test_a_source_refuses_a_dictionary_in_hand_built_system_columns( +def test_a_source_reports_reserved_names_before_dictionary_types( own: tuple[str, ...], with_user_column: bool, own_first: bool ) -> None: - """The builder checks before it drops system columns (CodeRabbit on PR 455): a - dictionary-free system column is still stripped, a dictionary one is refused.""" + """A reserved raw name is refused before the dictionary diagnostic.""" user: dict[str, pa.Array[Any]] = { "a": pa.array(["x", "y"]), "b": pa.array(["p", "q"]), @@ -309,11 +307,11 @@ def test_a_source_refuses_a_dictionary_in_hand_built_system_columns( ArrowTableSource(table, tag_columns=["a", "b"], tag_only_columns=True) message = str(info.value) for name in own: - assert f"- {OWN_COLUMNS[name]} column {name!r} has type dictionary<" in message - assert ("- data column 'v'" in message) == with_user_column + assert repr(name) in message + assert "drop them first" in message -def test_a_dictionary_free_system_column_is_still_stripped() -> None: +def test_a_dictionary_free_system_column_is_also_refused() -> None: table = pa.table( { "a": ["x", "y"], @@ -322,8 +320,10 @@ def test_a_dictionary_free_system_column_is_still_stripped() -> None: "v": [1, 2], } ) - source = ArrowTableSource(table, tag_columns=["a"], tag_only_columns=True) - assert source.keys() == (("a",), ("v",)) + with pytest.raises( + InputValidationError, match="'__note'.*'_source_v'.*drop them first" + ): + ArrowTableSource(table, tag_columns=["a"], tag_only_columns=True) def test_an_opaque_type_over_a_dictionary_is_refused() -> None: diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index ad702e872..156f6f6b0 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -5,10 +5,13 @@ import asyncio import contextlib import sqlite3 +from array import array +from collections import UserList, deque +from re import escape from collections.abc import Collection, Iterator from dataclasses import dataclass from pathlib import Path -from typing import TYPE_CHECKING, Any, TypedDict +from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple, TypedDict from uuid import UUID import deltalake @@ -18,6 +21,14 @@ import pyarrow as pa import pyarrow.csv as pa_csv import pytest +from pydantic import ( + BaseModel, + ConfigDict, + Field, + SerializerFunctionWrapHandler, + computed_field, + model_serializer, +) from arro3.core import Table as ArroTable import orcapod.sources as public_sources @@ -133,7 +144,7 @@ def _source( path: Path, monkeypatch: pytest.MonkeyPatch, *, - tags: Collection[str] = TAGS, + tag_columns: Collection[str] = TAGS, tag_only_columns: bool | Collection[str] = True, **kwargs: Any, ) -> ( @@ -147,7 +158,7 @@ def _source( ): """Build the named source over the same columns using its regular reader.""" options: _SourceOptions = { - "tag_columns": tags, + "tag_columns": tag_columns, "tag_only_columns": tag_only_columns, "source_id": "rows", } @@ -210,6 +221,622 @@ def _source( return DBTableSource(_Connector(table), "rows", **options, **kwargs) +@pytest.mark.parametrize("kind", SOURCE_KINDS) +@pytest.mark.parametrize("role", ["data", "tag", "data-tag"]) +@pytest.mark.parametrize("first", [False, True]) +def test_raw_sources_refuse_all_reserved_columns( + kind: str, role: str, first: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + table = pa.table( + { + "g": ["a", "b"], + "k": [1, 2], + "x": [3, 4], + "y": [5, 6], + "_foo": ["a", "b"], + "_content_hash": ["c", "d"], + } + ) + if first: + table = table.select(["_content_hash", "g", "_foo", "k", "y", "x"]) + tags = TAGS if role == "data" else (*TAGS, "_foo") + with pytest.raises(InputValidationError, match="drop them first") as info: + _source( + kind, + table, + tmp_path, + monkeypatch, + tag_columns=tags, + tag_only_columns=TAGS if role == "data-tag" else True, + ) + assert "'_foo'" in str(info.value) + assert "'_content_hash'" in str(info.value) + + +@pytest.mark.parametrize("arrow_schema", [False, True], ids=["python", "arrow"]) +def test_dict_source_refuses_reserved_fields_omitted_from_schema( + arrow_schema: bool, +) -> None: + schema = ( + pa.schema( + [ + ("g", pa.string()), + ("k", pa.int64()), + ("x", pa.int64()), + ("y", pa.int64()), + ] + ) + if arrow_schema + else {"g": str, "k": int, "x": int, "y": int} + ) + rows = [ + {"g": "a", "k": 1, "x": 2, "y": 3, "_foo": 4}, + {"g": "b", "k": 2, "x": 3, "y": 4, "_source_x": 5}, + ] + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + DictSource(rows, tag_columns=TAGS, tag_only_columns=True, data_schema=schema) + + +class _UnreadableRows(Collection[dict[str, int]]): + """Fail if the source reads past the row that exposes a reserved name.""" + + def __init__(self, first: dict[str, int] | None = None) -> None: + """Keep an optional first row for the source to inspect.""" + self.first = first + + def __contains__(self, value: object) -> bool: + """Check membership without advancing the iterator.""" + return value == self.first + + def __len__(self) -> int: + """Count the optional first row and the unreadable row.""" + return 2 if self.first is not None else 1 + + def __iter__(self) -> Iterator[dict[str, int]]: + """Yield the known row, then fail on the next read.""" + if self.first is not None: + yield self.first + raise AssertionError("the source read past a reserved name") + + +@pytest.mark.parametrize( + "schema", + [ + None, + {"_raw": int, "_also_raw": int}, + pa.schema([("_raw", pa.int64()), ("_also_raw", pa.int64())]), + ], + ids=["row", "python-schema", "arrow-schema"], +) +def test_dict_source_reports_known_reserved_names_before_reading_further( + schema: dict[str, type] | pa.Schema | None, +) -> None: + first = {"x": 1, "_raw": 2, "_also_raw": 3} if schema is None else None + with pytest.raises( + InputValidationError, match="'_also_raw'.*'_raw'.*rename.*drop them first" + ): + DictSource(_UnreadableRows(first), data_schema=schema) + + +def test_csv_refuses_reserved_declared_columns_before_parsing_values( + tmp_path: Path, +) -> None: + path = tmp_path / "rows.csv" + path.write_text("g,k,x,y,_foo,_source_x\na,1,2,3,invalid,token\n") + schema = pa.schema( + [ + ("g", pa.string()), + ("k", pa.int64()), + ("x", pa.int64()), + ("y", pa.int64()), + ("_foo", pa.int64()), + ("_source_x", pa.string()), + ] + ) + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + CSVSource(str(path), tag_columns=TAGS, tag_only_columns=True, schema=schema) + + +@pytest.mark.parametrize("declared", [True, False], ids=["declared", "inferred"]) +@pytest.mark.parametrize("header_kind", ["short", "long-quoted", "long-unquoted"]) +@pytest.mark.parametrize("refresh", [False, True], ids=["construction", "refresh"]) +def test_csv_refuses_reserved_header_before_parsing_bad_rows( + tmp_path: Path, declared: bool, header_kind: str, refresh: bool +) -> None: + path = tmp_path / "rows.csv" + schema = pa.schema([("k", pa.int64()), ("x", pa.int64())]) if declared else None + + def build() -> CSVSource: + return CSVSource( + str(path), tag_columns=["k"], tag_only_columns=True, schema=schema + ) + + source = None + if refresh: + path.write_text("k,x\n1,2\n3,4\n") + source = build() + # Cross the csv module's default size limit with a quoted field and an escaped quote. + first = ( + '"' + "x" * 131073 + '\r\n,""name"' + if header_kind == "long-quoted" + else "x" * 131073 + if header_kind == "long-unquoted" + else "k" + ) + path.write_text( + f'\ufeff\r\n{first},x,"_foo","_source_x"\r\n1,invalid,token,source,extra\r\n' + ) + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + if source is not None: + source.check_for_new_data() + else: + build() + + +@pytest.mark.parametrize("as_iterator", [False, True], ids=["sequence", "iterator"]) +def test_dataframe_source_uses_inferred_positional_column_names( + as_iterator: bool, +) -> None: + from collections import namedtuple + + row = namedtuple("ReservedRecord", ["k", "_hidden"], rename=True) + rows: list[Any] = [(1, 2), row(3, 4)] + expected = pl.DataFrame(iter(rows) if as_iterator else rows) + source = DataFrameSource(iter(rows) if as_iterator else rows) + assert source.as_table().to_pylist() == expected.to_dicts() + + +def _late_reserved_rows(reverse: bool) -> list[dict[str, int]]: + rows = [{"g": 0, "k": i, "x": i + 1, "y": i + 2} for i in range(1002)] + names = ("_foo", "_source_x") + if reverse: + names = names[::-1] + rows[-2][names[0]] = 3 + rows[-1][names[1]] = 4 + return rows + + +@pytest.mark.parametrize("iterable", [list, iter], ids=["sequence", "iterator"]) +def test_dataframe_source_checks_inferred_column_names(iterable) -> None: + rows = [{"k": 1, "x": 2, "_foo": 3, "_source_x": 4}] + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + DataFrameSource(iterable(rows), tag_columns=["k"], tag_only_columns=True) + + +@pytest.mark.parametrize("iterable", [list, iter], ids=["sequence", "iterator"]) +def test_dataframe_source_preserves_polars_inference_window(iterable) -> None: + rows = _late_reserved_rows(False) + expected = pl.DataFrame(iterable(rows)) + source = DataFrameSource(iterable(rows), tag_columns=TAGS, tag_only_columns=True) + assert source.as_table().to_pylist() == expected.select(*TAGS, "x", "y").to_dicts() + + +def test_dataframe_source_preserves_inference_for_single_pass_rows() -> None: + def rows() -> Iterator[dict[str, int]]: + row = {"g": 0, "k": 0, "x": 1, "y": 2} + for i in range(1002): + row["k"] = i + yield row + + expected = DataFrameSource( + pl.DataFrame(rows()), tag_columns=TAGS, tag_only_columns=True + ) + source = DataFrameSource(rows(), tag_columns=TAGS, tag_only_columns=True) + assert source.as_table().equals(expected.as_table()) + assert source.source_id == expected.source_id + + +@dataclass +class _FrameRow: + k: int + x: int + + +@dataclass +class _EquivalentFrameRow: + k: int + x: int + + +@dataclass +class _NestedFrameValue: + value: int + + +@dataclass +class _NestedFrameRow: + k: int + g: int + x: _NestedFrameValue + y: int + + +@dataclass +class _ReorderedNestedFrameRow: + y: int + x: _NestedFrameValue + g: int + k: int + + +@dataclass +class _TypedFrameRow: + k: int + g: str + x: float + y: int + + +@dataclass +class _ReorderedTypedFrameRow: + y: int + g: str + x: float + k: int + + +class _TypedFrameModel(BaseModel): + k: int + g: str + x: list[int] + y: int + + +class _ReorderedTypedFrameModel(BaseModel): + y: int + g: str + x: list[int] + k: int + + +class _PlainFrameModel(BaseModel): + k: int + x: int + + +class _EquivalentFrameModel(_PlainFrameModel): + pass + + +class _AliasedFrameModel(_PlainFrameModel): + model_config = ConfigDict(serialize_by_alias=True) + x: int = Field(serialization_alias="value") + + +class _ComputedFrameModel(_PlainFrameModel): + @computed_field # type: ignore[prop-decorator] + @property + def total(self) -> int: + raise AssertionError( + "checking the row layout must not evaluate computed fields" + ) + + +class _SerializedFrameModel(BaseModel): + k: int + x: _PlainFrameModel + + @model_serializer(mode="wrap") + def _serialize(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: + fields = handler(self) + if self.k > 100: + fields["_foo"] = 12345 + return fields + + +class _NestedComputedFrameModel(_SerializedFrameModel): + @computed_field # type: ignore[prop-decorator] + @property + def total(self) -> int: + return self.k + self.x.x + + +@pytest.mark.parametrize( + ("row_type", "x_values", "arrow_type"), + [ + (_TypedFrameRow, (2, 4.5), pa.float64()), + (_ReorderedTypedFrameRow, (2, 4.5), pa.float64()), + (_TypedFrameModel, ([], [4, 5]), pa.large_list(pa.int64())), + (_ReorderedTypedFrameModel, ([], [4, 5]), pa.large_list(pa.int64())), + ], + ids=["dataclass", "dataclass-reordered", "pydantic", "pydantic-reordered"], +) +@pytest.mark.parametrize("use_iterator", [False, True], ids=["sequence", "iterator"]) +@pytest.mark.parametrize("tag_order", [TAGS, TAGS[::-1]], ids=["g-k", "k-g"]) +def test_homogeneous_typed_rows_keep_schema_and_identity( + row_type: type, + x_values: tuple[Any, Any], + arrow_type: pa.DataType, + use_iterator: bool, + tag_order: tuple[str, ...], +) -> None: + rows = [ + row_type(k=1, g="a", x=x_values[0], y=3), + row_type(k=2, g="b", x=x_values[1], y=5), + ] + frame = pl.DataFrame(rows) + expected = DataFrameSource(frame, tag_columns=tag_order, tag_only_columns=True) + canonical = DataFrameSource( + frame.select("k", "g", "x", "y"), tag_columns=TAGS, tag_only_columns=True + ) + source = DataFrameSource( + iter(rows) if use_iterator else rows, + tag_columns=tag_order, + tag_only_columns=True, + ) + assert source.as_table().schema.field("x").type == arrow_type + assert source.as_table().schema == expected.as_table().schema + assert source.as_table().equals(expected.as_table()) + assert ( + source.as_table() + .select(["k", "g", "x", "y"]) + .equals(canonical.as_table().select(["k", "g", "x", "y"])) + ) + assert source.source_id == expected.source_id == canonical.source_id + assert source.content_hash() == expected.content_hash() == canonical.content_hash() + assert ( + source.pipeline_hash() == expected.pipeline_hash() == canonical.pipeline_hash() + ) + + +@pytest.mark.parametrize("use_iterator", [False, True], ids=["sequence", "iterator"]) +def test_frame_rows_keep_null_positions_and_match_mapping_fields_by_name( + use_iterator: bool, +) -> None: + rows = [None, {"k": 1, "x": 2}, None, {"x": 4, "k": 3}] + source = DataFrameSource( + iter(rows) if use_iterator else rows, tag_columns=["k"], tag_only_columns=True + ) + assert source.as_table().to_pylist() == [ + {"k": None, "x": None}, + {"k": 1, "x": 2}, + {"k": None, "x": None}, + {"k": 3, "x": 4}, + ] + + +@pytest.mark.parametrize( + "name", + [ + "_", + "_foo", + "_tag_y", + "_tag::y", + "_source_y", + "_content_hash", + "_context_key", + "__meta", + ], +) +def test_list_source_refuses_reserved_value_column(name: str) -> None: + with pytest.raises(InputValidationError, match=escape(repr(name))): + ListSource(name, [10, 20]) + + +@pytest.mark.parametrize("data", [[], [10, 20]], ids=["empty", "projected"]) +def test_list_source_refuses_reserved_value_name_even_without_arrow_field( + data: list[int], +) -> None: + schema = {"element_index": int} if data else None + with pytest.raises(InputValidationError, match="'_foo'.*drop them first"): + ListSource("_foo", data, data_schema=schema) + + +def test_list_source_refuses_reserved_tags_omitted_from_schema() -> None: + def tags(value: int, index: int) -> dict[str, int]: + return {"k": index, "g": value, "_foo": value, "_source_x": value} + + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + ListSource( + "x", + [10, 20], + tag_function=tags, + expected_tag_keys=TAGS, + data_schema={"k": int, "g": int, "x": int}, + ) + + +def test_list_source_refuses_reserved_tags() -> None: + def tags(value: int, index: int) -> dict[str, int]: + return {"k": index, "g": value, "_foo": value, "_content_hash": index} + + with pytest.raises( + InputValidationError, match="'_content_hash'.*'_foo'.*drop them first" + ): + ListSource("value", [10, 20], tag_function=tags) + + +def test_list_source_reports_reserved_dict_tags_before_next_callback() -> None: + def tags(value: int, index: int) -> dict[str, int]: + assert index == 0, "the source called another callback after a reserved name" + return {"_raw": value, "_also_raw": value} + + with pytest.raises( + InputValidationError, match="'_also_raw'.*'_raw'.*rename.*drop them first" + ): + ListSource("value", [10, 20], tag_function=tags) + + +def test_list_source_accepts_a_tag_from_a_source() -> None: + origin = ArrowTableSource( + pa.table({"k": [1], "g": [2], "x": [3], "y": [4]}), + tag_columns=TAGS, + tag_only_columns=True, + ) + tag = next(iter(origin.iter_data()))[0] + source = ListSource("value", [10], tag_function=lambda *_: tag) + assert source.as_table().to_pylist() == [{"g": 2, "k": 1, "value": 10}] + + +def test_rereading_an_orcapod_table_requires_dropping_system_columns() -> None: + source = DictSource( + [ + {"g": "a", "k": 1, "x": 3, "y": 4}, + {"g": "b", "k": 2, "x": 5, "y": 6}, + ], + tag_columns=TAGS, + tag_only_columns=True, + ) + raw = source.as_table(all_info=True) + system_columns = [name for name in raw.column_names if name.startswith("_")] + with pytest.raises(InputValidationError, match="drop them first") as info: + ArrowTableSource(raw, tag_columns=TAGS, tag_only_columns=True) + assert system_columns + assert all(repr(name) in str(info.value) for name in system_columns) + rebuilt = ArrowTableSource( + raw.drop(system_columns), tag_columns=TAGS, tag_only_columns=True + ) + assert rebuilt.as_table().equals(source.as_table()) + + +def test_arrow_source_documents_reserved_column_refusal() -> None: + table = pa.table({"k": [1, 2], "g": ["a", "b"], "x": [3, 4], "_foo": [5, 6]}) + with pytest.raises(InputValidationError, match="'_foo'.*drop them first"): + _ = ArrowTableSource(table, tag_columns=TAGS, tag_only_columns=True) + assert "refuses reserved column names" in (ArrowTableSource.__doc__ or "") + + +def test_database_refuses_reserved_columns_before_reading_rows() -> None: + class SchemaOnlyConnector(_Connector): + def iter_batches(self, query, params=None, batch_size=1000): + pytest.fail("a reserved database column must prevent reading rows") + + table = _table(pa.field("_foo", pa.string()), ["a", "b"]) + with pytest.raises(InputValidationError, match="'_foo'.*drop them first"): + DBTableSource( + SchemaOnlyConnector(table), + "rows", + tag_columns=TAGS, + tag_only_columns=True, + source_id="rows", + ) + + +def test_database_reads_column_metadata_once_per_scan() -> None: + class Connector(_Connector): + metadata_reads = 0 + + def get_column_info(self, table_name: str) -> list[ColumnInfo]: + self.metadata_reads += 1 + return [ + ColumnInfo(info.name, info.arrow_type, nullable=False) + if info.name == "extra" + else info + for info in super().get_column_info(table_name) + ] + + connector = Connector(_table(pa.field("extra", pa.int64()), [3, 4])) + source = DBTableSource( + connector, "rows", tag_columns=TAGS, tag_only_columns=True, source_id="rows" + ) + assert connector.metadata_reads == 1 + assert not source.as_table().schema.field("extra").nullable + assert not source.check_for_new_data() + assert connector.metadata_reads == 2 + assert not source.as_table().schema.field("extra").nullable + + +@pytest.mark.parametrize("metadata", ["absent", "partial"]) +@pytest.mark.parametrize("refresh", [False, True], ids=["construction", "refresh"]) +def test_database_refuses_reserved_batch_names_with_incomplete_metadata( + metadata: str, refresh: bool +) -> None: + class Connector(_Connector): + def get_column_info(self, table_name: str) -> list[ColumnInfo]: + if metadata == "absent": + return [] + return [ + ColumnInfo(field.name, field.type, field.nullable) + for field in list(self.table.schema)[:2] + ] + + def iter_batches( + self, query: str, params: Any = None, batch_size: int = 1000 + ) -> Iterator[pa.RecordBatch]: + yield from self.table.to_batches(max_chunksize=1) + if "_foo" in self.table.column_names: + pytest.fail("a reserved name in a batch must prevent further fetches") + + reserved = _table(pa.field("_foo", pa.string()), ["a", "b"]).append_column( + "_source_x", pa.array(["c", "d"]) + ) + connector = Connector(reserved.drop(["_foo", "_source_x"]) if refresh else reserved) + + def build() -> DBTableSource: + return DBTableSource( + connector, "rows", tag_columns=TAGS, tag_only_columns=True, source_id="rows" + ) + + if refresh: + source = build() + old = source.as_table() + connector.table = reserved + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + source.check_for_new_data() + assert source.as_table().equals(old) + else: + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + build() + + +@pytest.mark.parametrize("refresh", [False, True], ids=["construction", "refresh"]) +def test_delta_refuses_reserved_names_before_scanning( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, refresh: bool +) -> None: + path = tmp_path / "delta" + reserved = _table(pa.field("_foo", pa.string()), ["a", "b"]).append_column( + "_source_x", pa.array(["c", "d"]) + ) + + def fail_scan(*args: Any, **kwargs: Any) -> None: + pytest.fail("the Delta log already declares the reserved columns") + + def build() -> DeltaTableSource: + return DeltaTableSource(path, tag_columns=TAGS, tag_only_columns=True) + + if refresh: + deltalake.write_deltalake(path, reserved.drop(["_foo", "_source_x"])) + source = build() + old = source.as_table() + deltalake.write_deltalake(path, reserved, mode="append", schema_mode="merge") + monkeypatch.setattr(deltalake.DeltaTable, "to_pyarrow_dataset", fail_scan) + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + source.check_for_new_data() + assert source.as_table().equals(old) + else: + deltalake.write_deltalake(path, reserved) + monkeypatch.setattr(deltalake.DeltaTable, "to_pyarrow_dataset", fail_scan) + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + build() + + +def test_source_accepts_underscores_after_the_first_character() -> None: + source = DictSource( + [{"foo_": "a", "a_b": 1, "tag_x": 2, "other": 3}], + tag_columns=["foo_", "a_b"], + tag_only_columns=True, + ) + assert source.keys() == (("foo_", "a_b"), ("tag_x", "other")) + + def _table(field: pa.Field[Any], values: list[Any]) -> pa.Table: """Two tags, two ordinary data columns and two additional columns.""" schema = pa.schema( @@ -401,7 +1028,7 @@ def test_sources_refuse_stored_logical_columns( table, tmp_path, monkeypatch, - tags=tags, + tag_columns=tags, tag_only_columns=TAGS if role == "data-tag" else True, ) message = str(error.value) @@ -589,7 +1216,7 @@ def test_refuses_arrow_null_from_readers( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - column = "unused" if kind == "spiral" else "__unused" + column = "unused" table = _table(pa.field(column, pa.null()), [None, None]) with pytest.raises( InputValidationError, match=rf"{column!r}.*declare a supported nullable type" @@ -678,6 +1305,56 @@ async def close(self) -> None: """There is no connection to close.""" +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("as_frame", [False, True], ids=["rows", "frame"]) +def test_polling_refuses_reserved_frame_names_before_preprocessing( + use_async: bool, as_frame: bool +) -> None: + rows = [{"k": 1, "x": None, "_foo": 3}, {"k": 2, "x": None, "_foo": 4}] + batch = pl.DataFrame(rows) if as_frame else rows + source = PollingSource( + _Poll(None, batch), ["k"], source_id="poll", record_id_columns="k" + ) + + async def read_first() -> None: + async with contextlib.aclosing(source.async_iter_data()) as rows: + await anext(rows) + + with pytest.raises(InputValidationError, match="'_foo'.*drop them first"): + if use_async: + asyncio.run(read_first()) + else: + source.as_table() + + +@pytest.mark.parametrize("declare", [True, False], ids=["schema", "batch"]) +@pytest.mark.parametrize("as_tag", [True, False], ids=["tag", "data"]) +def test_polling_refuses_reserved_schema_and_batch_columns( + declare: bool, as_tag: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + table = _table(pa.field("_foo", pa.string()), ["a", "b"]) + table = table.append_column("_source_x", pa.array(["p", "q"])) + batch = pl.from_arrow(table) + assert isinstance(batch, pl.DataFrame) + tags = (*TAGS, "_foo") if as_tag else TAGS + if declare: + + async def unexpected_fetch(*args: Any, **kwargs: Any) -> None: + pytest.fail("a reserved declared column must prevent polling") + + monkeypatch.setattr(_Poll, "fetch", unexpected_fetch) + with pytest.raises(InputValidationError, match="drop them first") as info: + source = PollingSource( + _Poll(table.schema if declare else None, batch), + tags, + source_id="poll", + record_id_columns="k", + ) + source.check_for_new_data() + assert "'_foo'" in str(info.value) + assert "'_source_x'" in str(info.value) + + @pytest.mark.parametrize("name", ["_tag_application", "_tag::application"]) @pytest.mark.parametrize("arrow", [False, True], ids=["python", "arrow"]) def test_polling_refuses_system_tags_in_the_declared_schema( @@ -694,17 +1371,23 @@ def test_polling_refuses_null_in_declaration_and_batch(values: list[Any]) -> Non table = _table(pa.field("__unused", pa.large_list(pa.null())), values) batch = pl.from_arrow(table) assert isinstance(batch, pl.DataFrame) - with pytest.raises( - InputValidationError, match=r"'__unused'.*declare a supported nullable type" - ): + with pytest.raises(InputValidationError, match=r"'__unused'.*drop them first"): PollingSource( _Poll(table.schema, batch), TAGS, source_id="poll", record_id_columns="k" ) + # A polled batch checks names first, as DataFrameSource does. poll = PollingSource( _Poll(None, batch), TAGS, source_id="poll", record_id_columns="k" ) + with pytest.raises(InputValidationError, match=r"'__unused'.*drop them first"): + poll.check_for_new_data() + legal = pl.from_arrow(_table(pa.field("unused", pa.large_list(pa.null())), values)) + assert isinstance(legal, pl.DataFrame) + poll = PollingSource( + _Poll(None, legal), TAGS, source_id="poll", record_id_columns="k" + ) with pytest.raises( - InputValidationError, match=r"'__unused'.*declare a supported nullable type" + InputValidationError, match=r"'unused'.*declare a supported nullable type" ): poll.check_for_new_data() @@ -867,9 +1550,7 @@ def test_native_arrow_logical_fields( path, other = leaves.schema paths, others = (column.combine_chunks() for column in leaves.columns) offsets = pa.array([0, 1, 2], type=pa.int32()) - # All routes validate system columns before discarding them. Use one to - # exercise the nested guard independently of existing hash and cast limits. - nested_name = f"{constants.META_PREFIX}logical" + nested_name = "logical" if layout == "struct": array = pa.StructArray.from_arrays([paths, others], fields=[path, other]) table = pa.table({nested_name: array}) @@ -891,27 +1572,24 @@ def test_native_arrow_logical_fields( else: table = leaves table = table.append_column("k", pa.array([1, 2])) - if layout != "top-level": - table = table.append_column("payload", pa.array([1, 2])) - name = "path" if layout == "top-level" else "payload" async def read_async(poll: PollingSource[int]) -> object: async with contextlib.aclosing(poll.async_iter_data()) as rows: _, data = await anext(rows) - return data[name] + return data["path"] def read(data: FrameInitTypes) -> object: if route == "arrow": - return next(ArrowTableSource(table).iter_data())[1][name] + return next(ArrowTableSource(table).iter_data())[1]["path"] if route == "dataframe": - return next(DataFrameSource(data).iter_data())[1][name] + return next(DataFrameSource(data).iter_data())[1]["path"] poll = PollingSource( _Poll(None, data), ["k"], source_id="poll", record_id_columns="k" ) if route == "polling-async": return asyncio.run(read_async(poll)) assert poll.check_for_new_data() - return next(poll.iter_data())[1][name] + return next(poll.iter_data())[1]["path"] # A struct exported as an array or a stream can change the field types when # imported through the Arrow C interface. Cover both native representations. @@ -931,9 +1609,17 @@ def read(data: FrameInitTypes) -> object: assert f"{nested_name!r}.'path'" in message else: assert ".'key'" in message and ".'value'" in message - else: + elif layout == "top-level": expected = Path("a") if registered else "a" - assert read(data) == (expected if layout == "top-level" else 1) + assert read(data) == expected + elif route == "arrow": + # Check the guard independently of nested logical-value hashing. + stream_builder.require_live_logical_types(table.schema) + else: + # Frame sources share this guard before converting to Polars. + frame = stream_builder.read_arrow_frame_input(data) + assert frame is not None + assert frame[1].equals(table.schema, check_metadata=True) @pytest.mark.parametrize( @@ -1020,7 +1706,7 @@ def test_cached_source_refuses_an_existing_stored_null_column() -> None: database = InMemoryArrowDatabase() cached = CachedSource(proxy, cache_database=database) raw = source.as_table(columns={"source": True, "system_tags": True}) - raw = raw.append_column("__unused", pa.nulls(2)) + raw = raw.append_column("unused", pa.nulls(2)) raw = raw.append_column(CachedSource.HASH_COLUMN_NAME, pa.array([b"a", b"b"])) database.add_records( cached.cache_path, @@ -1029,7 +1715,7 @@ def test_cached_source_refuses_an_existing_stored_null_column() -> None: flush=True, ) with pytest.raises( - InputValidationError, match=r"'__unused'.*declare a supported nullable type" + InputValidationError, match=r"'unused'.*declare a supported nullable type" ): cached.as_table() @@ -1290,7 +1976,7 @@ def get_all_records( ) with pytest.raises( InputValidationError, - match=r"'__raw_missing'.*declare a supported nullable type", + match=r"'__raw_missing'.*reserved.*odb_v3", ): derived.as_table() @@ -1315,12 +2001,488 @@ def test_spiral_validates_reserved_null_in_an_empty_scan_batch( [pa.array([], f.type) for f in invalid], schema=invalid ) monkeypatch.setattr(handle, "scan_batches", lambda **kwargs: iter([batch])) - with pytest.raises( - InputValidationError, match=r"'__unused'.*declare a supported nullable type" - ): + with pytest.raises(InputValidationError, match=r"'__unused'.*drop them first"): source.as_table() +def test_spiral_validates_reserved_names_at_the_pinned_version(tmp_path: Path) -> None: + """Build validates the pinned schema, regardless of the current schema.""" + rows = pa.table({"k": ["a"], "x": [1]}) + with fake_spiral_sdk.install(tmp_path): + project = fake_spiral_sdk.ExternalProject("project") + external = project.create_table( + "default.rows", key_schema=pa.schema([rows.schema.field("k")]) + ) + external.write(rows) + before = external.last_modified_at() + external.write(pa.table({"k": ["b"], "x": [2], "_extra": [3]})) + after = external.last_modified_at() + + historical = SpiralDBTableSource( + "project", "rows", asof=before, tag_only_columns=True + ) + assert historical.as_table().to_pylist() == [{"k": "a", "x": 1}] + for version in (None, after): + with pytest.raises(InputValidationError, match="'_extra'.*drop them first"): + SpiralDBTableSource( + "project", "rows", asof=version, tag_only_columns=True + ) + + +@pytest.mark.parametrize( + "kind", ["arrow", "arrow-infer", "dict-schema", "frame-schema", "poll-declaration"] +) +def test_raw_reserved_names_precede_arrow_type_validation(kind: str) -> None: + table = pa.table({"k": [1, 2], "x": [3, 4], "_one": [None, None], "_two": [4, 5]}) + with pytest.raises( + InputValidationError, match="'_one'.*'_two'.*rename.*drop them first" + ): + if kind == "poll-declaration": + PollingSource( + _Poll(table.schema, []), ["k"], source_id="poll", record_id_columns="k" + ) + elif kind == "dict-schema": + DictSource( + table.select(["k", "x"]).to_pylist(), + tag_columns=["k"], + data_schema=table.schema, + ) + elif kind == "frame-schema": + DataFrameSource( + pl.from_arrow(table.select(["k", "x"])), ["k"], schema=table.schema + ) + else: + ArrowTableSource(table, ["k"], infer_nullable=kind == "arrow-infer") + + +@pytest.mark.parametrize( + "kind", + [ + "pandas-series", + "pandas-index", + "namedtuple", + "namedtuple-iterator", + "numpy", + "positional", + "positional-iterator", + "scalar", + "scalar-iterator", + "series-iterator", + "mixed-dataclasses", + "mixed-models", + "model-serializer", + "model-dump-override", + "model-computed-column", + ], +) +@pytest.mark.parametrize("path", ["frame", "poll-sync", "poll-async"]) +def test_named_frame_inputs_keep_polars_conversion(kind: str, path: str) -> None: + from collections import namedtuple + + import numpy as np + import pandas as pd + + class DumpOverride(_SerializedFrameModel): + calls: ClassVar[list[int]] = [] + + def model_dump(self, **kwargs: Any) -> dict[str, Any]: + """Record each serialization while preserving the declared fields.""" + self.calls.append(self.k) + return {**super().model_dump(**kwargs), "k": self.k + 10} + + batch: list[Any] + if kind == "pandas-series": + batch = [pd.Series([1, 2], name="k"), pd.Series([3, 4], name="x")] + elif kind == "pandas-index": + batch = [pd.Index([1, 2], name="k"), pd.Index([3, 4], name="x")] + elif kind.startswith("namedtuple"): + row = namedtuple("FrameRecord", ["k", "x"]) + batch = [row(1, 3), row(2, 4)] + elif kind.startswith("positional"): + batch = [(1, 3), (2, 4)] + elif kind.startswith("scalar"): + batch = [1, 2] + elif kind == "series-iterator": + batch = [pl.Series("k", [1, 2]), pl.Series("x", [3, 4])] + elif kind == "mixed-dataclasses": + batch = [_FrameRow(1, 3), _EquivalentFrameRow(2, 4)] + elif kind == "mixed-models": + batch = [_PlainFrameModel(k=1, x=3), _EquivalentFrameModel(k=2, x=4)] + elif kind in {"model-serializer", "model-dump-override", "model-computed-column"}: + model = { + "model-serializer": _SerializedFrameModel, + "model-dump-override": DumpOverride, + "model-computed-column": _NestedComputedFrameModel, + }[kind] + batch = [model(k=i, x=_PlainFrameModel(k=i, x=i + 2)) for i in (1, 2)] + else: + batch = [np.array([1, 2]), np.array([3, 4])] + + use_iterator = kind.endswith("-iterator") + data = iter(batch) if use_iterator else batch + # Both sources passed the original input straight to Polars on main. + frame = pl.DataFrame(iter(batch) if use_iterator else batch) + key = frame.columns[0] + tags = [key] if frame.width > 1 else [] + expected = frame.to_dicts() + expected_dump_calls = DumpOverride.calls.copy() + DumpOverride.calls.clear() + if path == "frame": + source = DataFrameSource(data, tags, tag_only_columns=True) + control = DataFrameSource(frame, tags, tag_only_columns=True) + assert source.as_table().equals(control.as_table(), check_metadata=True) + assert source.source_id == control.source_id + assert source.content_hash() == control.content_hash() + assert source.pipeline_hash() == control.pipeline_hash() + else: + source = PollingSource( + _Poll(None, data), tags, source_id="poll", record_id_columns=key + ) + assert _read_frame_poll(source, path, len(expected)) == expected + assert DumpOverride.calls == expected_dump_calls + + +@pytest.mark.parametrize("iterator", [False, True], ids=["sequence", "iterator"]) +@pytest.mark.parametrize("path", ["frame", "poll-sync", "poll-async"]) +@pytest.mark.parametrize( + "tail", + [ + range(3, 5), + deque([3, 4]), + array("q", [3, 4]), + UserList([3, 4]), + memoryview(bytes([3, 4])), + bytes([3, 4]), + bytearray([3, 4]), + ], + ids=lambda tail: type(tail).__name__, +) +def test_frame_sources_accept_polars_positional_tails( + tail: object, iterator: bool, path: str +) -> None: + """A namedtuple supplies column names for a compatible positional row.""" + + class Reading(NamedTuple): + k: int + x: int + + rows: list[Any] = [Reading(1, 2), tail] + batch = iter(rows) if iterator else rows + if path == "frame": + source = DataFrameSource(batch, ["k"], tag_only_columns=True) + actual = source.as_table().to_pylist() + else: + poll = PollingSource( + _Poll(None, batch), ["k"], source_id="poll", record_id_columns="k" + ) + actual = _read_frame_poll(poll, path, 2) + assert actual == [{"k": 1, "x": 2}, {"k": 3, "x": 4}] + + +@pytest.mark.parametrize("iterator", [False, True], ids=["sequence", "iterator"]) +@pytest.mark.parametrize("alias", ["k", "other"], ids=["overlapping", "distinct"]) +def test_dataframe_source_preserves_flat_model_columns( + alias: str, iterator: bool +) -> None: + class Reading(_PlainFrameModel): + model_config = ConfigDict(serialize_by_alias=True) + x: int = Field(serialization_alias=alias) + + rows = [Reading(k=1, x=2), Reading(k=3, x=4)] + source = DataFrameSource( + iter(rows) if iterator else rows, ["k"], tag_only_columns=True + ) + assert source.as_table().to_pylist() == [{"k": 1, "x": 2}, {"k": 3, "x": 4}] + + +@pytest.mark.parametrize("iterator", [False, True], ids=["sequence", "iterator"]) +@pytest.mark.parametrize( + "mixed_classes", [False, True], ids=["same-class", "mixed-class"] +) +def test_dataframe_source_preserves_polars_numeric_inference( + mixed_classes: bool, iterator: bool +) -> None: + class Reading(NamedTuple): + k: int + x: int | float + + class OtherReading(NamedTuple): + k: int + x: int | float + + second = OtherReading if mixed_classes else Reading + rows = [Reading(1, 9_007_199_254_740_993), second(2, 1.5)] + source = DataFrameSource( + iter(rows) if iterator else rows, ["k"], tag_only_columns=True + ) + table = source.as_table() + assert table.schema.field("x").type == pa.float64() + assert table.to_pylist() == [ + {"k": 1, "x": 9_007_199_254_740_992.0}, + {"k": 2, "x": 1.5}, + ] + + +@pytest.mark.parametrize( + "kind,reverse", + [ + ("tuple", False), + ("list", False), + ("numpy", False), + ("model", False), + ("model", True), + ("nested-dataclass", False), + ("nested-dataclass", True), + ], +) +@pytest.mark.parametrize("iterator", [False, True], ids=["sequence", "iterator"]) +@pytest.mark.parametrize("path", ["frame", "poll-sync", "poll-async"]) +def test_frame_preserves_mixed_rows_with_the_same_columns( + kind: str, reverse: bool, iterator: bool, path: str +) -> None: + from collections import namedtuple + + import numpy as np + + class Model(BaseModel): + k: int + g: int + x: int + y: int + + class ReverseModel(BaseModel): + y: int + x: int + g: int + k: int + + rows: list[Any] + tags = ["k", "g"] + if kind == "model": + rows = [Model(k=1, g=2, x=3, y=4), ReverseModel(k=5, g=6, x=7, y=8)] + expected = [{"k": 1, "g": 2, "x": 3, "y": 4}, {"k": 5, "g": 6, "x": 7, "y": 8}] + elif kind == "nested-dataclass": + rows = [ + _NestedFrameRow(1, 2, _NestedFrameValue(3), 4), + _ReorderedNestedFrameRow(8, _NestedFrameValue(7), 6, 5), + ] + expected = [ + {"k": 1, "g": 2, "x": {"value": 3}, "y": 4}, + {"k": 5, "g": 6, "x": {"value": 7}, "y": 8}, + ] + else: + tags = ["k"] + record = namedtuple("Record", ["k", "x"]) + rows = [ + record(1, 2), + {"tuple": tuple, "list": list, "numpy": np.array}[kind]((3, 4)), + ] + expected = [{"k": 1, "x": 2}, {"k": 3, "x": 4}] + if reverse: + rows.reverse() + expected.reverse() + tags.reverse() + frame = pl.DataFrame(iter(rows) if iterator else rows) + assert frame.to_dicts() == expected + data = iter(rows) if iterator else rows + if path == "frame": + source = DataFrameSource(data, tags, tag_only_columns=True) + control = DataFrameSource(frame, tags, tag_only_columns=True) + table = source.as_table() + assert table.to_pylist() == expected + assert table.equals(control.as_table(), check_metadata=True) + assert source.source_id == control.source_id + assert source.content_hash() == control.content_hash() + assert source.pipeline_hash() == control.pipeline_hash() + else: + poll = PollingSource( + _Poll(None, data), tags, source_id="poll", record_id_columns="k" + ) + assert _read_frame_poll(poll, path, 2) == expected + + +def _read_frame_poll( + poll: PollingSource[int], path: str, count: int +) -> list[dict[str, Any]]: + """Read a sync snapshot or collect and close a bounded async poll.""" + if path == "poll-sync": + return poll.as_table().to_pylist() + + async def read() -> list[dict[str, Any]]: + """Close the stream after collecting the expected rows or timing out.""" + async with contextlib.aclosing(poll.async_iter_data()) as rows: + async with asyncio.timeout(5): + return [ + {**tag.as_dict(), **data.as_dict()} + for tag, data in [await anext(rows) for _ in range(count)] + ] + + return asyncio.run(read()) + + +@pytest.mark.parametrize("path", ["poll-sync", "poll-async"]) +@pytest.mark.parametrize("kind", ["sparse", "computed", "aliased"]) +def test_polling_keeps_polars_column_layout(kind: str, path: str) -> None: + if kind == "sparse": + batch = [{"k": 1, "x": 3}, {"k": 2}] + expected = [{"k": 1, "x": 3}, {"k": 2, "x": None}] + else: + model = _ComputedFrameModel if kind == "computed" else _AliasedFrameModel + batch = [model(k=1, x=3), model(k=2, x=4)] + expected = [{"k": 1, "x": 3}, {"k": 2, "x": 4}] + source = PollingSource( + _Poll(None, batch), ["k"], source_id="poll", record_id_columns="k" + ) + assert _read_frame_poll(source, path, 2) == expected + + +@pytest.mark.parametrize("view", ["operator-replay", "operator-records", "derived"]) +def test_operator_storage_refuses_reserved_user_columns( + view: str, monkeypatch: pytest.MonkeyPatch +) -> None: + source = ArrowTableSource( + _table(pa.field("extra", pa.string(), nullable=False), ["a", "b"]), + tag_columns=TAGS, + tag_only_columns=True, + source_id="rows", + ) + store = InMemoryArrowDatabase() + job = PipelineJob(name="stored", database=store) + with job: + DropNulls(["x", "y"])(source, label="origin") + node = job.nodes["origin"] + assert isinstance(node, OperatorJobNode) + node.attach_databases(pipeline_database=store, cache_mode=CacheMode.LOG) + job.run() + read = store.get_all_records + + def read_legacy_rows(path: tuple[str, ...], *args: Any, **kwargs: Any): + table = read(path, *args, **kwargs) + if table is not None and path[-1] == "odb_v3": + return table.append_column("_foo", pa.array([4] * table.num_rows)) + return table + + monkeypatch.setattr(store, "get_all_records", read_legacy_rows) + with pytest.raises(InputValidationError, match="'_foo'.*reserved.*odb_v3"): + if view == "operator-records": + node.get_all_records() + elif view == "derived": + node.as_source().as_table() + else: + node.attach_databases(pipeline_database=store, cache_mode=CacheMode.REPLAY) + node.run(load_only=True) + + +def test_cached_source_refuses_reserved_stored_user_columns() -> None: + source = ArrowTableSource( + _table(pa.field("extra", pa.string(), nullable=False), ["a", "b"]), + tag_columns=TAGS, + tag_only_columns=True, + source_id="rows", + ) + tag_schema, data_schema = source.output_schema() + proxy = SourceProxy( + source_id=source.source_id, + content_hash_str=source.content_hash().to_string(), + pipeline_hash_str=source.pipeline_hash().to_string(), + tag_schema=tag_schema, + data_schema=data_schema, + ) + store = InMemoryArrowDatabase() + cached = CachedSource(proxy, cache_database=store) + raw = source.as_table(columns={"source": True, "system_tags": True}) + raw = raw.append_column("_foo", pa.array([4, 5])) + raw = raw.append_column(CachedSource.HASH_COLUMN_NAME, pa.array([b"a", b"b"])) + store.add_records( + cached.cache_path, + with_data_context(raw, source.data_context_key), + record_id_column=CachedSource.HASH_COLUMN_NAME, + flush=True, + ) + with pytest.raises(InputValidationError, match="'_foo'.*reserved.*sdb_v2"): + cached.as_table() + + +def test_dataframe_source_checks_declared_names_before_reading_input() -> None: + def unreadable() -> Iterator[dict[str, int]]: + yield from () + raise AssertionError("should reject the declared name before reading rows") + + with pytest.raises(InputValidationError, match="'_schema'.*drop them first"): + DataFrameSource(unreadable(), schema=pa.schema([("_schema", pa.int64())])) + + +@pytest.mark.parametrize("kind", ["pandas", "arrow"]) +@pytest.mark.parametrize("path", ["frame", "poll-sync"]) +def test_frame_checks_raw_names_before_duplicate_column_error( + kind: str, path: str +) -> None: + import pandas as pd + + names = ["x", "x", "_one", "_two"] + batch = ( + pd.DataFrame([[1, 2, 3, 4]], columns=pd.Index(names)) + if kind == "pandas" + else pa.Table.from_arrays([pa.array([i]) for i in range(4)], names=names) + ) + with pytest.raises(InputValidationError, match="'_one'.*'_two'.*drop them first"): + if path == "frame": + DataFrameSource(batch) + else: + PollingSource( + _Poll(None, batch), ["x"], source_id="poll", record_id_columns="x" + ).as_table() + + +def test_stored_column_validators_use_only_column_roles() -> None: + from orcapod.core.result_cache import _check_result_table + from orcapod.utils.schema_utils import require_stored_stream_column_names + + with pytest.raises(InputValidationError, match="'_tag_fake'.*reserved"): + _check_result_table(pa.table({"_tag_fake": [1]}), None) + with pytest.raises(InputValidationError, match="'_foo'.*reserved"): + require_stored_stream_column_names(["_foo"], ()) + + +def test_stored_operator_checks_user_names_from_descriptor() -> None: + source = ArrowTableSource( + pa.table({"k": [1, 2], "x": [3, 4]}), tag_columns=["k"], tag_only_columns=True + ) + store = InMemoryArrowDatabase() + job = PipelineJob(name="stored", database=store) + with job: + DropNulls(["x"])(source, label="origin") + node = job.nodes["origin"] + assert isinstance(node, OperatorJobNode) + node.attach_databases(pipeline_database=store, cache_mode=CacheMode.LOG) + job.run() + + legacy_name = "_tag_legacy" + path = (*node.node_identity_path, "odb_v3") + records = store.get_all_records(path, record_id_column=node.HASH_COLUMN_NAME) + assert records is not None + legacy_records = records.append_column(legacy_name, pa.array([4, 5])) + legacy_store = InMemoryArrowDatabase() + legacy_store.add_records( + path, legacy_records, record_id_column=node.HASH_COLUMN_NAME, flush=True + ) + loaded = OperatorJobNode.from_descriptor( + { + "label": "origin", + "output_schema": {"data": {legacy_name: "int"}}, + "table_scope": "pipeline_hash", + "cache_mode": "log", + "pipeline_path": node.node_identity_path, + }, + operator=None, + input_streams=(), + databases={"pipeline": legacy_store}, + job_content_hash=node.content_hash().to_string(), + ) + with pytest.raises(InputValidationError, match="'_tag_legacy'.*reserved.*odb_v3"): + loaded.get_all_records(all_info=True) + + def test_bound_proxy_keeps_projections_row_order() -> None: """Hidden tags used for validation do not become sort keys for the table.""" source = ArrowTableSource( diff --git a/tests/test_core/sources/test_source_protocol_conformance.py b/tests/test_core/sources/test_source_protocol_conformance.py index a64aed383..ad73668e4 100644 --- a/tests/test_core/sources/test_source_protocol_conformance.py +++ b/tests/test_core/sources/test_source_protocol_conformance.py @@ -16,6 +16,8 @@ import pyarrow as pa import pytest + +from orcapod.errors import InputValidationError import polars as pl from orcapod.core.sources import ( @@ -460,16 +462,12 @@ def test_df_source_missing_tag_column_raises(self): with pytest.raises(ValueError, match="not found"): DataFrameSource(data=df, tag_columns="nonexistent", tag_only_columns=True) - def test_arrow_source_strips_system_columns_from_input(self): - """Source-info columns in the input table are stripped.""" + def test_arrow_source_refuses_system_columns_in_input(self): table = pa.table( { "x": pa.array([1, 2], type=pa.int64()), "_source_x": pa.array(["a", "b"], type=pa.large_string()), } ) - src = ArrowTableSource(table=table, infer_nullable=True) - # system columns should not appear in data keys - tag_keys, data_keys = src.keys() - assert "_source_x" not in tag_keys - assert "_source_x" not in data_keys + with pytest.raises(InputValidationError, match="'_source_x'.*drop them first"): + ArrowTableSource(table=table, infer_nullable=True) diff --git a/tests/test_core/sources/test_sources_comprehensive.py b/tests/test_core/sources/test_sources_comprehensive.py index 234807c15..e163ad8c9 100644 --- a/tests/test_core/sources/test_sources_comprehensive.py +++ b/tests/test_core/sources/test_sources_comprehensive.py @@ -29,6 +29,8 @@ import polars as pl import pytest +from orcapod.errors import InputValidationError + from orcapod.core.sources import ( ArrowTableSource, CSVSource, @@ -293,18 +295,15 @@ def test_string_tag_columns_accepted(self): assert "id" in tag_keys assert "value" in data_keys - def test_system_columns_stripped_from_polars_input(self): - """Source-info columns in a Polars input are stripped.""" + def test_system_columns_refused_in_polars_input(self): df = pl.DataFrame( { "x": [1, 2], "_source_x": ["a", "b"], } ) - src = DataFrameSource(data=df) - tag_keys, data_keys = src.keys() - assert "_source_x" not in tag_keys - assert "_source_x" not in data_keys + with pytest.raises(InputValidationError, match="'_source_x'.*drop them first"): + DataFrameSource(data=df) def test_source_id_in_provenance_tokens(self): df = pl.DataFrame({"id": [1, 2, 3], "value": ["a", "b", "c"]}) diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py index 47ae155ea..7d67e07a9 100644 --- a/tests/test_core/sources/test_spiraldb_lookups.py +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -761,30 +761,26 @@ def slow(self: SpiralDBTableSource) -> bool: assert most == 1 -def test_a_check_refusing_a_reserved_system_tag_column_is_held_by_every_read( - calls: collections.Counter[str], +@pytest.mark.parametrize("reserved", ["_tag_source_id::x", "_extra"]) +def test_a_check_refusing_a_reserved_column_is_held_by_every_read( + calls: collections.Counter[str], reserved: str ) -> None: - """CodeRabbit on #675: a check that refuses because the table now has a column in - the system-tag namespace (an ``InputValidationError``, not a ``ValueError``) is - held like every other refusal: every later read refuses with it, before - scanning, until a check accepts the table again.""" + """A check that refuses a newly added reserved column also blocks later reads.""" source = _source("plain") layout = _ARRANGED["layout"] - reserved = "_tag_source_id::x" table = fake_spiral_sdk.ExternalProject(_PROJECT).table("default.t") widened = _rows(layout, [0, 1, 2]).append_column( pa.field(reserved, pa.large_string()), pa.array(["r"] * 3, pa.large_string()) ) table.write(widened) table.record(widened.schema) - with pytest.raises(InputValidationError, match="reserved for Orcapod system tags"): + with pytest.raises(InputValidationError, match="reserved for Orcapod") as refusal: source.check_for_new_data() calls.clear() for read in _bare_reads(source).values(): - with pytest.raises( - InputValidationError, match="reserved for Orcapod system tags" - ): + with pytest.raises(InputValidationError, match="reserved for Orcapod") as held: read() + assert held.value is refusal.value assert calls == {} diff --git a/tests/test_core/sources/test_stream_builder.py b/tests/test_core/sources/test_stream_builder.py index a5e06a641..9cb538a43 100644 --- a/tests/test_core/sources/test_stream_builder.py +++ b/tests/test_core/sources/test_stream_builder.py @@ -110,7 +110,7 @@ def test_build_with_record_id_column(self, builder): ) assert result.stream.as_table().num_rows == 2 - def test_build_drops_system_columns_from_input(self, builder): + def test_build_refuses_system_columns_in_input(self, builder): table = pa.table( { "id": pa.array([1]), @@ -118,9 +118,10 @@ def test_build_drops_system_columns_from_input(self, builder): "__system_col": pa.array(["sys"]), } ) - result = builder.build(table, tag_columns=["id"], kind_part="arrow_table_v1") - tag_schema, data_schema = result.stream.output_schema() - assert "__system_col" not in data_schema + with pytest.raises( + InputValidationError, match="'__system_col'.*drop them first" + ): + builder.build(table, tag_columns=["id"], kind_part="arrow_table_v1") class TestSourceStreamBuilderRespectsSchema: diff --git a/tests/test_core/streams/test_data_tag_preview.py b/tests/test_core/streams/test_data_tag_preview.py index c733fba64..1d995ccd8 100644 --- a/tests/test_core/streams/test_data_tag_preview.py +++ b/tests/test_core/streams/test_data_tag_preview.py @@ -696,16 +696,18 @@ def test_job_nodes_show_the_marks(orchestrator: str) -> None: @pytest.mark.parametrize("tag_order", [("a", "b"), ("b", "a")], ids=["ab", "ba"]) @pytest.mark.parametrize("layout", list(RAW_LAYOUTS)) -def test_meta_columns_of_a_raw_stream_stay_unmarked( +def test_meta_columns_of_an_internal_stream_stay_unmarked( layout: str, tag_order: tuple[str, str] ) -> None: - """A raw stream lists its meta columns among its data keys; the display leaves + """An internal stream lists its meta columns among its data keys; the display leaves them unmarked and the legend counts them as nothing, while its data columns and its data-tag keep their marks.""" values = {"a": [1, 2], "b": [3, 4], "x": [5, 6], "y": [7, 8]} values |= {"__debug": ["d1", "d2"], "__note": ["n1", "n2"]} table = pa.table({name: values[name] for name in RAW_LAYOUTS[layout]}) - stream = ArrowTableStream(table, tag_columns=list(tag_order), data_tags=["b"]) + stream = ArrowTableStream._from_derived_table( + table, tag_columns=list(tag_order), data_tags=["b"] + ) assert {"__debug", "__note"} <= set(stream.keys()[1]) meta = [c for c in RAW_LAYOUTS[layout] if c.startswith("__")] data = [c for c in RAW_LAYOUTS[layout] if c in ("x", "y")] diff --git a/tests/test_core/streams/test_iter_data_chunk_layouts.py b/tests/test_core/streams/test_iter_data_chunk_layouts.py index 8596897cb..ec3edce98 100644 --- a/tests/test_core/streams/test_iter_data_chunk_layouts.py +++ b/tests/test_core/streams/test_iter_data_chunk_layouts.py @@ -60,7 +60,9 @@ def _chunked_stream( [f"src::{i}" for i in range(n)], source_sizes, pa.large_string() ) table = pa.Table.from_pydict(columns) - return ArrowTableStream(table, tag_columns=["id", "grp"] if with_tags else []) + return ArrowTableStream._from_derived_table( + table, tag_columns=["id", "grp"] if with_tags else [] + ) LAYOUTS = [ @@ -317,7 +319,7 @@ def test_nested_source_info_pairs_with_its_own_row( SOURCE_X: _chunked(tokens, source_sizes, NESTED_SOURCE_TYPE), } ) - stream = ArrowTableStream(table, tag_columns=["id"]) + stream = ArrowTableStream._from_derived_table(table, tag_columns=["id"]) pairs = list(stream.iter_data()) assert len(pairs) == n for row, (tag, data) in enumerate(pairs): @@ -348,7 +350,7 @@ def test_iter_data_keeps_the_source_info_arrow_type() -> None: SOURCE_X: pa.array(tokens, type=source_type), } ) - stream = ArrowTableStream(table, tag_columns=["id"]) + stream = ArrowTableStream._from_derived_table(table, tag_columns=["id"]) rows = list(stream.iter_data()) assert [data.source_info()["x"] for _, data in rows] == tokens for _, data in rows: diff --git a/tests/test_core/streams/test_streams.py b/tests/test_core/streams/test_streams.py index 14b3b137b..509b907dd 100644 --- a/tests/test_core/streams/test_streams.py +++ b/tests/test_core/streams/test_streams.py @@ -12,6 +12,7 @@ from orcapod.core.streams import ArrowTableStream from orcapod.core.streams.base import StreamBase +from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols.pod import PodProtocol from orcapod.protocols.core_protocols.streams import StreamProtocol from orcapod.types import Schema @@ -21,6 +22,22 @@ # --------------------------------------------------------------------------- +@pytest.mark.parametrize("reverse", [False, True]) +def test_raw_stream_refuses_all_reserved_columns(reverse: bool) -> None: + fields = [ + ("tag", [1]), + ("_private", [2]), + ("_source_value", ["token"]), + ("value", [3]), + ] + if reverse: + fields.reverse() + with pytest.raises( + InputValidationError, match="'_private'.*'_source_value'.*reserved for Orcapod" + ): + ArrowTableStream(pa.table(dict(fields)), tag_columns=["tag"]) + + def make_table_stream( tag_columns: list[str] | None = None, n_rows: int = 3, diff --git a/tests/test_core/streams/test_token_shape.py b/tests/test_core/streams/test_token_shape.py index cc6bb080b..b5e96e534 100644 --- a/tests/test_core/streams/test_token_shape.py +++ b/tests/test_core/streams/test_token_shape.py @@ -93,7 +93,7 @@ def _stream( ), ) tags = ["g", "k", "x"] if role == "data_tag" else ["g", "k"] - return ArrowTableStream( + return ArrowTableStream._from_derived_table( table, tag_columns=tags, data_tags=["x"] if role == "data_tag" else [] ) @@ -379,7 +379,9 @@ def test_every_violating_column_is_named_once() -> None: "_source_z": pa.array(["s::0::z", None], STR), } ) - message = _refusal(lambda: ArrowTableStream(table, tag_columns=["k"])) + message = _refusal( + lambda: ArrowTableStream._from_derived_table(table, tag_columns=["k"]) + ) assert message.count("'_source_x'") == 1 and message.count("'_source_y'") == 1 assert "'_source_z'" not in message diff --git a/tests/test_core/test_row_ids.py b/tests/test_core/test_row_ids.py index b81db7b06..53648141c 100644 --- a/tests/test_core/test_row_ids.py +++ b/tests/test_core/test_row_ids.py @@ -522,7 +522,9 @@ def _stream(self, nested: bool) -> Any: ] ), ) - return ArrowTableStream(table, tag_columns=["subject", "session"]) + return ArrowTableStream._from_derived_table( + table, tag_columns=["subject", "session"] + ) def test_an_ordinary_rows_columns_are_those_its_own_table_gives(self) -> None: rows = list(self._stream(nested=False).iter_data()) diff --git a/tests/test_databases/test_delta_merge_reserved_names.py b/tests/test_databases/test_delta_merge_reserved_names.py index 9a44ede26..a137139a3 100644 --- a/tests/test_databases/test_delta_merge_reserved_names.py +++ b/tests/test_databases/test_delta_merge_reserved_names.py @@ -16,6 +16,7 @@ from __future__ import annotations +import asyncio from pathlib import Path from typing import cast @@ -23,6 +24,9 @@ import pyarrow as pa import pytest +from orcapod import function_pod +from orcapod.sources import ArrowTableSource +from orcapod.pipeline import PipelineJob from orcapod.databases import DeltaTableDatabase from orcapod.databases.delta_lake_databases import MERGE_RESERVED_COLUMNS from orcapod.errors import InputValidationError, UnstorableColumnError @@ -115,6 +119,41 @@ def test_a_stored_table_holding_a_reserved_name_takes_no_append( db.flush() # a no-op +@function_pod(output_keys=["v`output"]) +def _unstorable(v: int) -> int: + return v + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +def test_a_job_writing_an_unstorable_name_stops_at_its_first_write( + tmp_path: Path, use_async: bool +) -> None: + source = ArrowTableSource( + pa.Table.from_arrays( + [pa.array([1, 2], pa.int64()), pa.array([1, 2], pa.int64())], + schema=pa.schema( + [ + pa.field("k", pa.int64(), nullable=False), + pa.field("v", pa.int64(), nullable=False), + ] + ), + ), + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + record_id_columns=["k"], + ) + with pytest.raises(UnstorableColumnError, match="backtick"): + database = DeltaTableDatabase(tmp_path) + job = PipelineJob(name="itl1377", database=database) + with job: + _unstorable.pod(source, label="fn") + if use_async: + asyncio.run(job.run_async()) + else: + job.run() + + def test_a_nested_field_with_a_reserved_name_is_kept(tmp_path: Path) -> None: """Only a top-level column collides with the planner's columns.""" db = DeltaTableDatabase(tmp_path) diff --git a/tests/test_hashing/golden/cases.py b/tests/test_hashing/golden/cases.py index 4641aff05..b5de293bd 100644 --- a/tests/test_hashing/golden/cases.py +++ b/tests/test_hashing/golden/cases.py @@ -980,6 +980,8 @@ def _builder_table() -> pa.Table: @case("schema", "source_stream_builder") def schema_source_stream_builder() -> dict[str, Any]: + from orcapod.system_constants import constants + # SourceStreamBuilder is not public API; the issue names it as a pinned call site. from orcapod.core.sources.stream_builder import SourceStreamBuilder @@ -1003,6 +1005,13 @@ def schema_source_stream_builder() -> dict[str, Any]: out[f"{variant}.schema_hash"] = result.schema_hash out[f"{variant}.table_hash"] = result.table_hash.to_string() out[f"{variant}.source_id"] = result.source_id + out[f"{variant}.system_tag_columns"] = [ + name + for name in result.stream.as_table( + columns={"system_tags": True} + ).column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) + ] out.update(_prefixed(variant, stream_summary(result.stream))) return out diff --git a/tests/test_pipeline/test_operator_node_empty_table_types.py b/tests/test_pipeline/test_operator_node_empty_table_types.py index ee30cd8ea..549a9044b 100644 --- a/tests/test_pipeline/test_operator_node_empty_table_types.py +++ b/tests/test_pipeline/test_operator_node_empty_table_types.py @@ -666,7 +666,7 @@ def test_an_input_with_a_meta_data_column_gives_a_zero_row_table() -> None: A raw stream cannot be a job's input (ITL-1126: it has no system-tag pair), so the operator is applied to it directly, outside a job. """ - raw = ArrowTableStream( + raw = ArrowTableStream._from_derived_table( pa.table( { "id": pa.array([1, 2], pa.int8()), diff --git a/tests/test_pipeline/test_provenance_review.py b/tests/test_pipeline/test_provenance_review.py index 9b9959b55..504555197 100644 --- a/tests/test_pipeline/test_provenance_review.py +++ b/tests/test_pipeline/test_provenance_review.py @@ -19,15 +19,19 @@ from __future__ import annotations from pathlib import Path -from typing import Any +from typing import Any, cast import pyarrow as pa import pytest +from typing_extensions import override -from orcapod import PipelineJob, function_pod +from orcapod import FunctionPod, PipelineJob, function_pod +from orcapod.core.data_function import PythonDataFunction from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase -from orcapod.errors import ProvenanceInconsistencyError +from orcapod.errors import InputValidationError, ProvenanceInconsistencyError +from orcapod.protocols.core_protocols import DataFunctionProtocol +from orcapod.types import Schema from orcapod.operators import ( Batch, DropTagColumns, @@ -1005,18 +1009,76 @@ def test_an_inner_list_of_nested_folds_traces_its_members() -> None: ] -@function_pod(output_keys="_total") -def underscored(x: int, y: int) -> int: +@function_pod(output_keys="total") +def total(x: int, y: int) -> int: return x + y -def test_an_underscore_data_column_of_an_empty_run_is_a_data_column() -> None: +@pytest.mark.parametrize("name", ["_total", "_content_hash", "__delta_rs_source"]) +def test_a_function_refuses_a_reserved_output_name_at_definition(name: str) -> None: + with pytest.raises(InputValidationError, match=repr(name)): + function_pod(output_keys=name)(total_for_reserved_output) + + +def total_for_reserved_output(x: int, y: int) -> int: + return x + y + + +def _pair_for_reserved_outputs(x: int, y: int) -> tuple[int, int]: + return x, y + + +@pytest.mark.parametrize( + "outputs", [("_foo", "_content_hash"), ("_content_hash", "_foo")] +) +def test_public_function_pod_validates_custom_declared_outputs( + outputs: tuple[str, str], +) -> None: + class CustomFunction(PythonDataFunction): + @property + @override + def output_data_schema(self) -> Schema: + return Schema(dict.fromkeys(outputs, int)) + + custom = cast( + object, + CustomFunction(_pair_for_reserved_outputs, output_keys=["left", "right"]), + ) + assert isinstance(custom, DataFunctionProtocol) + with pytest.raises(InputValidationError, match="'_content_hash'.*'_foo'"): + _ = FunctionPod(data_function=custom) + + +@pytest.mark.parametrize("missing_callable", [False, True], ids=["importable", "proxy"]) +@pytest.mark.parametrize("saved_form", ["keys", "schema", "both"]) +def test_saved_function_pod_refuses_reserved_outputs( + missing_callable: bool, saved_form: str +) -> None: + config = FunctionPod.from_fn( + _pair_for_reserved_outputs, ["left", "right"] + ).to_config() + function_config = config["data_function"]["config"] + if saved_form in ("keys", "both"): + function_config["output_keys"] = ["_foo", "_content_hash"] + if saved_form in ("schema", "both"): + output_schema = function_config["output_data_schema"] + function_config["output_data_schema"] = { + "_foo": output_schema["left"], + "_content_hash": output_schema["right"], + } + if missing_callable: + function_config["callable_name"] = "unavailable_function" + with pytest.raises(InputValidationError, match="'_content_hash'.*'_foo'"): + FunctionPod.from_config(config, fallback_to_proxy=missing_callable) + + +def test_a_data_column_of_an_empty_run_is_a_data_column() -> None: source = table_source(rows_kgxy(("a", "1", 1, 2)), TWO_BY_TWO, ["k", "g"], "src") job = PipelineJob(name="under", database=InMemoryArrowDatabase()) with job: - underscored.pod(Filter({"x": 999})(source), label="sums") + total.pod(Filter({"x": 999})(source), label="sums") job.run() - empty = job.nodes["sums"].trace({"k": "a", "g": "1"}, "_total") + empty = job.nodes["sums"].trace({"k": "a", "g": "1"}, "total") assert (empty.status, empty.matched) == ("no_match", 0) with pytest.raises(ValueError, match="not a data column"): job.nodes["sums"].trace({"k": "a", "g": "1"}, "k") diff --git a/tests/test_pipeline/test_result_reuse_itl_1503.py b/tests/test_pipeline/test_result_reuse_itl_1503.py index 4714891e2..61e829a4c 100644 --- a/tests/test_pipeline/test_result_reuse_itl_1503.py +++ b/tests/test_pipeline/test_result_reuse_itl_1503.py @@ -38,7 +38,11 @@ from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase -from orcapod.errors import OrcapodDatabaseReadError, TypeIdentityError +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseReadError, + TypeIdentityError, +) from orcapod.pipeline.observer import NoOpObserver from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.system_constants import constants @@ -241,7 +245,16 @@ def test_persistent_hit_in_ephemeral_mode( ) -> None: """The persistent result is used: no call, no write, recorded as persistent.""" counted = _Counted() - source = _input({"a": 1, "b": 2, "c": 3}, marker=marker, arrangement=arrangement) + inputs = {"a": 1, "b": 2, "c": 3} + if marker: + # The raw stream refuses the column before either execution path can run. + with pytest.raises( + InputValidationError, match=rf"{OLD_MARKER!r}.*reserved for Orcapod" + ): + _input(inputs, marker=True, arrangement=arrangement) + return + + source = _input(inputs, arrangement=arrangement) persistent, ephemeral = InMemoryArrowDatabase(), InMemoryArrowDatabase() stored = _seed(persistent, counted, source, {"a", "b", "c"}) @@ -266,10 +279,6 @@ def test_persistent_hit_in_ephemeral_mode( key: {"result_id": stored[key], "is_ephemeral": False, "computed": False} for key in "abc" } - if marker: - # A user tag with the old marker's name is an ordinary tag. - assert all(tag.as_dict()[OLD_MARKER] is True for tag, _ in rows) - assert set(node.keys()[0]) == {"key", "group", OLD_MARKER} @PATHS diff --git a/tests/test_pipeline/test_row_ids_review_2.py b/tests/test_pipeline/test_row_ids_review_2.py index 5fefc8f00..5701c3ec3 100644 --- a/tests/test_pipeline/test_row_ids_review_2.py +++ b/tests/test_pipeline/test_row_ids_review_2.py @@ -566,7 +566,7 @@ def _list_session_table(session: str) -> pa.Table: def _token_stream(kind: str, session: str = "first") -> ArrowTableStream: """The list-valued session rows with a token column ``_source_a`` of the kind.""" tokens = {**TOKEN_KINDS, **NULL_LIST_TOKENS}[kind] - return ArrowTableStream( + return ArrowTableStream._from_derived_table( _list_session_table(session).append_column( pa.field("_source_a", tokens.type), tokens ), diff --git a/tests/test_pipeline/test_row_ids_stored.py b/tests/test_pipeline/test_row_ids_stored.py index 1c6bea959..3fbea15c4 100644 --- a/tests/test_pipeline/test_row_ids_stored.py +++ b/tests/test_pipeline/test_row_ids_stored.py @@ -1039,7 +1039,7 @@ def _typed_token_stream(tokens: str, arrangement: str) -> ArrowTableStream: pa.field(name, array.type, nullable=nullable) for name, (array, nullable) in columns.items() ) - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.Table.from_arrays([array for array, _ in columns.values()], schema=schema), tag_columns=list(tags), ) diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 169991d5d..39ad613ff 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -852,7 +852,9 @@ def stream() -> ArrowTableStream: constants.CONTEXT_KEY: pa.array([OTHER_CONTEXT] * 2, pa.large_string()), } ) - return ArrowTableStream(table, tag_columns=["k"], data_context=other) + return ArrowTableStream._from_derived_table( + table, tag_columns=["k"], data_context=other + ) node = OperatorJobNode(SelectDataColumns(["x"]), [stream()]) output: Any = node.execute(stream()) diff --git a/tests/test_pipeline/test_serialization.py b/tests/test_pipeline/test_serialization.py index 0cc9ac3a0..b3b65a4f1 100644 --- a/tests/test_pipeline/test_serialization.py +++ b/tests/test_pipeline/test_serialization.py @@ -11,9 +11,10 @@ import orcapod from orcapod.config import DEFAULT_CONFIG, DisplayConfig, HashingConfig, OrcapodConfig from orcapod.core.nodes import SourceNode -from orcapod.core.operators import Join +from orcapod.core.operators import Join, MapColumns from orcapod.core.sources import ArrowTableSource from orcapod.databases.in_memory_databases import InMemoryArrowDatabase +from orcapod.errors import InputValidationError from orcapod.pipeline import Pipeline from orcapod.pipeline.job import PipelineJob from orcapod.pipeline.serialization import PIPELINE_FORMAT_VERSION @@ -78,6 +79,47 @@ def schema(*names: str) -> Schema: return build +def test_load_refuses_reserved_user_columns_in_saved_schema(spec_pipeline) -> None: + pipeline, tmp_path = spec_pipeline + path = tmp_path / "pipeline.json" + pipeline.save(path) + saved = json.loads(path.read_text()) + joiner = next(node for node in saved["nodes"].values() if node["label"] == "joiner") + schema = joiner["output_schema"] + schema["data"]["_score"] = schema["data"].pop("score") + schema["tag"]["_key"] = schema["tag"].pop("key") + path.write_text(json.dumps(saved)) + + with pytest.raises( + InputValidationError, match="'_key'.*'_score'.*reserved for Orcapod" + ): + Pipeline.load(path) + + +def test_load_refuses_reserved_targets_in_saved_operator_config(tmp_path) -> None: + source = SourceNode( + name="origin", + tag_schema=Schema({"key": int}), + data_schema=Schema({"value": int}), + ) + pipeline = Pipeline(name="rename") + with pipeline: + MapColumns({"key": "id", "value": "result"})(source, label="renamed") + path = tmp_path / "pipeline.json" + pipeline.save(path) + saved = json.loads(path.read_text()) + rename = next( + node for node in saved["nodes"].values() if node["label"] == "renamed" + ) + rename["operator_config"]["config"]["name_map"] = {"key": "_id", "value": "_result"} + path.write_text(json.dumps(saved)) + + with pytest.raises( + InputValidationError, match="'_id'.*'_result'.*reserved for Orcapod" + ): + Pipeline.load(path) + + def test_saved_pipeline_accepts_old_default_hashing_settings( hashing_settings_pipeline, tmp_path ) -> None: diff --git a/tests/test_pipeline/test_stored_data_context.py b/tests/test_pipeline/test_stored_data_context.py index 08e59d84a..e885031db 100644 --- a/tests/test_pipeline/test_stored_data_context.py +++ b/tests/test_pipeline/test_stored_data_context.py @@ -1242,7 +1242,9 @@ def _other_context_stream(column: str = "x") -> ArrowTableStream: {"k": ["a", "b"], column: [1, 2], "_context_key": [OTHER, OTHER]}, schema=schema, ) - return ArrowTableStream(table, tag_columns=["k"], data_context=OTHER) + return ArrowTableStream._from_derived_table( + table, tag_columns=["k"], data_context=OTHER + ) def _assert_names_both_contexts(error: InputValidationError) -> None: diff --git a/tests/test_pipeline/test_token_types_review_2.py b/tests/test_pipeline/test_token_types_review_2.py index 288c25fdf..de15e8387 100644 --- a/tests/test_pipeline/test_token_types_review_2.py +++ b/tests/test_pipeline/test_token_types_review_2.py @@ -62,7 +62,7 @@ def _keyed( if data_tag: columns["_source_k"] = pa.array(tokens, token_type) names.append("_source_k") - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.table({name: columns[name] for name in names}), tag_columns=list(tags), data_tags=["k"] if data_tag else [], @@ -388,7 +388,7 @@ def stream(data: tuple[str, str], token: str) -> ArrowTableStream: f"_source_{data[1]}": pa.array(["t0", PENDING_LOOKALIKE], STR), } ) - return ArrowTableStream(table, tag_columns=list(order)) + return ArrowTableStream._from_derived_table(table, tag_columns=list(order)) streams = [ stream(("x", "w"), PENDING_LOOKALIKE), diff --git a/tests/test_pipeline/test_token_types_review_3.py b/tests/test_pipeline/test_token_types_review_3.py index 3cdb0f090..a63b06e56 100644 --- a/tests/test_pipeline/test_token_types_review_3.py +++ b/tests/test_pipeline/test_token_types_review_3.py @@ -190,7 +190,7 @@ def test_a_stream_names_its_violating_columns_in_name_order( for name in columns: held[f"_source_{name}"] = pa.array([None, ["a"]], TOKENS) with pytest.raises(InputValidationError) as refused: - _ = ArrowTableStream(pa.table(held), tag_columns=["k"]) + _ = ArrowTableStream._from_derived_table(pa.table(held), tag_columns=["k"]) message = str(refused.value) assert message.index("'_source_x'") < message.index("'_source_y'") @@ -280,7 +280,7 @@ def _shaped( } names = list(columns) if layout == "tags_first" else list(reversed(columns)) data_tag = role == "data_tag" - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.table({name: columns[name] for name in names}), tag_columns=["g", "k", "x"] if data_tag else ["g", "k"], data_tags=["x"] if data_tag else [], @@ -334,6 +334,8 @@ def test_a_table_cut_into_chunks_is_checked_in_every_chunk() -> None: chunked = pa.concat_tables([one.slice(0, 1), one.slice(1, 1)]) assert chunked.column("_source_x").num_chunks == 2 with pytest.raises(InputValidationError, match="list level 1"): - _ = ArrowTableStream(chunked) + _ = ArrowTableStream._from_derived_table(chunked) # The valid first row alone, as a slice of the same table, is a stream. - assert ArrowTableStream(one.slice(0, 1)).as_table().num_rows == 1 + assert ( + ArrowTableStream._from_derived_table(one.slice(0, 1)).as_table().num_rows == 1 + ) diff --git a/tests/test_pipeline/test_token_types_review_4.py b/tests/test_pipeline/test_token_types_review_4.py index eab775577..7ea4a25ea 100644 --- a/tests/test_pipeline/test_token_types_review_4.py +++ b/tests/test_pipeline/test_token_types_review_4.py @@ -187,7 +187,7 @@ def iter_data(self) -> Any: for tag, data in super().iter_data(): yield tag, data.with_source_info(x=pa.scalar(HOLED, type=NESTED)) - stream = Handing(table, tag_columns=["g", "k"]) + stream = Handing._from_derived_table(table, tag_columns=["g", "k"]) with pytest.raises(InputValidationError) as refused: _ = Index("x", 0)(stream).as_table() message = str(refused.value)