diff --git a/.zed/rules b/.zed/rules index f618cedcb..f1b3a1991 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1101,30 +1101,139 @@ these preimages anywhere else. in the result store by the input hash, calls nothing and writes no pipeline row (developer, November 26, 2026; FunctionJobNode._empty_data_cache_hit is the one place that holds that choice, to be reconsidered in ITL-1475). -- The instance id reads a row's tokens through `DataProtocol.source_info_table()`: one column - per data column, a data column with no token having a null token. THE INTENDED RULE - (developer, November 27, 2026): the type of every source-info token column is fixed by the - pipeline, like every other column type, and is not meant to be taken from values: each - source and operator determines its output token columns' types from its inputs' types, by - its own rule, in its own module. A data-tag that falls through a function pod is meant to - keep its source-info token with its type unchanged; a column a function returns is never a - pass-through, even with an input's name and value (its token points to the function). - TODAY (ITL-1471), in `source_info_table()`: a null token is a `large_string` null whatever - type its column declares; a non-null token of a row read from an Arrow table (a stream's - row) keeps the type that table declares, with a nullable field; a token given as a Python - value is typed from its value (`arrow_utils.source_info_arrow_type`). STOPGAP, not the - proper solution: today a token's declared type is, in some places, inferred again from its - value (`Data.as_table(columns={"source": True})` and so `_rows_to_table`, the row-built - form, and `with_columns_of`). It can narrow a declared type (example: `[None]` in a token - column a `Batch` declares with two list levels infers one). ITL-1491 removes it. Never - build on the re-typing, and never write "a function passes a column through". A rename - moves a column's token with it; a token held for the destination name before is dropped. A pipeline table keeps one type per token column: a row whose token column - has another type than the rows recorded (a list token beside a string or null token) is - refused, naming the column and both types (_require_one_type_per_token_column), and the write - fails as a database write error. A lookup must never fail on a row its stream holds as valid Arrow. The pipeline row - stores that same table (_add_pipeline_record), never the columns of - as_table(columns={"source": True}): every stored row gives its instance and record id again - from its own columns. +- The Arrow type of every source-info token column is determined by the pipeline, like + every other column type; it is never taken from values (developer, November 27, 2026, + ITL-1491). A source builds plain `large_string` tokens, and each operator determines its + output's token column types from its inputs' types, as it does for every column: the + types are those of its result over its inputs' zero-row tables (`typed_zero_row_table`), + defined where the operator builds its output (a list of tokens by + `arrow_utils.aggregated_list_type`, as for a data list). Never summarize this as a rule + per operator family: the operators differ (one keeps a column's token type, one adds a + list level to some columns and folds others into one token, one removes a level, one + makes a new string token). A row read from an Arrow table carries its typed token + columns, and every route keeps them, sync and async alike: + `Data.as_table(columns={"source": True})` (so the row-built table at the edge between two + nodes, `_rows_to_table`), `Data.schema(columns={"source": True})` (the Python type of that + Arrow type), the row-built form of a whole table (which only normalizes a token column to + large types, like any column, drops the field's own metadata as a row does, and sets its + field flag), every change of a row (a selection, a drop, a rename, added columns), a + function pod's stream outside a job (`_table_from_pairs` takes each row's token columns) + and a function node, which takes the token types from its input's rows. A data-tag that + falls through a function pod keeps its token with its type unchanged + (`Data.with_columns_of`); a column a function returns is never a pass-through, even with + an input's name and value: its token points to the function. Never write "a function + passes a column through", and never type a token from its value where an Arrow type + exists. An operator that derives a token from its input's gives it the derived type: + `Join` writes the token it merges for a data-tag both inputs hold with the type the + inputs declare for that token column, on both paths (through `join._token_array`, which + refuses to write a token that does not fit its column: pyarrow stores a string given for + a list type as its characters); `Index` gives the element's token the token type with one + list layer removed, as an Arrow scalar (`with_source_info` keeps a scalar's type). The + one exception: a token is typed from its value (`arrow_utils.source_info_arrow_type`) + only where it is first created and no Arrow type exists: a `Data` built by hand from + Python values or given a Python value by `with_source_info`, and the string tokens + Orcapod itself creates (a source's, a function output's, `Pick`'s, `Index`'s over a + string token, a placeholder's). +- **A token's shape is its data's shape** (developer, November 27, 2026, ITL-1491). A token + column's type is some list layers on top of `large_string`. Those layers must match + EXACTLY the outer list layers of its data column's type, kind for kind: a `large_list` + layer needs a `large_list` layer, a fixed-size list a fixed-size list of the same size + (compared after large normalization, so a plain `list` is a large list). Under its layers + a token is a string: any other leaf (an integer, a binary, also as a plain scalar token + column) is refused. The data may be deeper than its token + (`large_list>` under a `large_list` token), and a plain + `large_string` token has no layer, so it fits any data. A data column of a logical list + type (the extension type built for a list of a logical element, such as a list of `Path`) + is read as its storage: one large-list layer per list level, which is what `Batch`, + `GroupBy` and `MergeJoin` build over a logical element. A token's list is never null AT ANY + LEVEL (developer, November 27, 2026): a null is allowed only at the innermost level, + where the element is a string (`["a::row_0::x", null]` is valid; `[null, ["a"]]` under + a two-level token type is not); a plain string token may be null. Valid: `large_list` over `large_list`; + `fixed_size_list[2]` over `fixed_size_list[2]`; `large_string` over + anything. Invalid: `large_list` over `int64`; a large list over a + fixed-size list or the reverse; two list levels over one; a null list token; + `large_list` as a token. Only lists are layers today: a token type with a nested + layer of another kind (a struct, a map) is refused, and no code is written for layers + that do not exist yet. A layer's item field (name, nullability, metadata) is NOT compared + between a token and its data, nor between two inputs' declarations of one token column + beyond what `require_shared_arrow_type` compares (ITL-1519 decides a consistent + treatment); never add a refusal for it. The rule is checked where a stream is built from + a table (`ArrowTableStream.__init__`, so every source, operator result, table built from + rows, typed zero-row input and the sync orchestrator's held-rows stream), from the + columns' types and the token column's null count only: no value is read and nothing is + computed. The error lists the violating columns in name order (`token_shape_error` + sorts them). KNOWN LIMIT (ITL-1534): the rule is checked where a stream is built, and + the async orchestrator hands a held node's rows on without building one, so a + hand-built held row with an invalid token shape is refused on sync and accepted on + async (pinned by `test_rows_on_read.py::test_held_rows_that_break_the_token_shape_rule_differ_by_route_itl_1534`). + A check of held rows on the async route was tried in this PR and taken out (developer, + November 27, 2026): never add one back here, ITL-1534 decides it. Whatever is done + there, NEVER hash an Arrow type object or use one as a dict or set key: an extension + type need not be hashable (Orcapod's own `list[Path]` type is not), which made a held + batch of such lists fail on replay + (`test_token_types_review_4.py::test_a_replay_over_logical_lists_reuses_its_rows`). + The type rule is the pure function + `schema_utils.token_layers_fit`; `token_shape_violations` lists the violating columns and + `token_shape_error` words the `InputValidationError`, which names the token column, the + data column and both types. Never loosen it. NOT covered: a record batch sent into an + `OutputChannel` (the channels are not wired into nodes; the stream `result()` builds is + checked; the follow-up is ITL-1526), and a `Data` built by hand outside a stream. The null check reads the + validity of EVERY list level of a list-typed token column (`schema_utils.null_list_level`: + the null count of each level's arrays, no value), and the error says at which level (0 is the + token itself). A typed zero-row table and a plain string token are unaffected. No + source, operator or function builds a violating stream. The operators that need an + inner list keep a guard for input no stream can hold any more (rows built by hand and + sent over a bare row channel, hand-built record batches): `Index` on a null inner list, + and `Join` / `MergeJoin` and the streaming-join kernels merging the tokens of a shared + data-tag (`join.NullTokenListError`, which says what it found, worded for the user by + `join.null_token_list_error`). Each guard has a unit test; never remove one, and never + raise a blank internal exception from one. +- Two inputs that declare one token column with two types are refused, on the sync and the + async path, with `require_shared_arrow_type`'s error naming the column and both types + (developer, November 27, 2026): a column that collides under `MergeJoin`, and the token + column of a data-tag both inputs of a `Join` or a `MergeJoin` hold (compared before + `MergeJoin` renames the second input's column, so the outcome never depends on whether a + row matches). ORDINARY sources reach this: `Batch(1)` over a source of scalars gives list + data with LIST tokens, a source that already holds such lists has STRING tokens, and + joining the two on that data-tag (or merging that column) is refused; the remedy is to + bring both inputs to one form before the join (it is a known limitation in the + changelog; keep refusing; the follow-up is ITL-1522). The decision comes from the declared + types: the sync path reads its inputs' tables; the async `Join` takes each input's first + row as its declaration and compares it with every other input's as it arrives, whether + or not any row matches. An input that sends NO row over a bare row channel + (`Join().async_execute` called directly) declares nothing there, as for the shared-key + type check (a stated limit, never fix it here: ITL-1527); in a job the node knows its inputs' types and both orchestrators refuse. + `MergeJoin` reports its first disagreement in name order (`_output_types` iterates + sorted names, never a set). The async `Join` folds only the tokens of columns it merged + (`merged_so_far`, one set per join, shared by the steps of a staggered chain): a + column's own token that happens to start like the join's internal pending marker is the + user's and is kept, as on the sync path. Record batches of one stream declare one token + type, compared strictly (`settle_token_types`: list kind, depth, and each item field's + name, nullability and metadata), so the order of the batches never decides a type; a + batch that declares another is refused, and a streaming-join kernel holds every batch to + its input stream's token type. A token column may carry metadata on a list's item field, + as its stream declares it. +- The instance id reads a row's tokens through `DataProtocol.source_info_table()`: the typed + columns the row carries, every field nullable; a null token is a `large_string` null, for + the id and for the stored column (developer decision of November 26, 2026). A stream's + rows have a null token only in a `large_string` column (the token-shape rule); the + rewrite of a null in a column declared otherwise matters only for a `Data` built by hand + from a table outside a stream. A rename moves a column's token with it; a token held for + the destination name before is dropped. There is one column per data column: a data + column with no token has a null token, so a row built from values and the same row read + from a table have one instance id whenever the values' own types + (`source_info_arrow_type`) are the table's: always for string and null tokens, and for a + list token that shows every list level of its column. A hand-built row whose list token + shows fewer levels than a table declares for it (`[[]]` in a three-level column) is typed + from that value and is another instance. Ids are a function of the row alone, never of + the order sessions ran in. A pipeline table keeps one type per token column: a row whose + token column has another type than the rows recorded (a list token beside a string or + null token) is refused, naming the column and both types + (`_require_one_type_per_token_column`), and the write fails as a database write error; it + is the safety net for a hand-built row given straight to a node and for an + implementation bug. A lookup must never fail on a row its stream holds as valid Arrow. + The pipeline row stores that same table (`_add_pipeline_record`): every stored row gives + its instance and record id again from its own columns. - A trace resolves a held row by its instance id, on every branch of a function step (over a source and over another node): a function node says which instance it holds each row under (FunctionJobNode.held_instance_ids), and provenance._entries_for keeps the stored records of @@ -1318,6 +1427,7 @@ data. The rules: expands or converts a type implicitly; the only exception is normalization to large variants. Inputs that disagree on a column's type are an error naming the column and both types, on every execution path (sync and async). + Something that used to complete may be changed to a refusal when the behaviour that let it complete was erroneous: a result reached through a bug (a silently changed type, a value that is not what it claims to be) is not protected by "nothing that completes may stop completing". The refusal stands until a proper fix exists, and is often the proper permanent answer. (Developer, November 27, 2026.) Function-output rule (developer, November 12, 2026): the returned value must be an instance of the declared type, or an exact numeric equivalent; a subclass stands in for its base. What is stored for a subclass instance is decided by the logical type of the declared class (developer, November 12, 2026, ITL-871): a plain user class is stored as the base @@ -1345,9 +1455,16 @@ data. The rules: changed, so `int8` stays `int8`. Sources refuse Arrow type `null` at any depth, including in reserved raw columns. Declare a supported nullable type for missing values. A source's custom system-tag names must each identify an existing non-nullable text - column with no null values. When Join sorts tied system tags, an output field is - nullable if any of the corresponding input fields can hold a null. + column with no null values and no Arrow field metadata. Remove field metadata before + building the source. This restriction is a stopgap pending ITL-1561. System-tag fields on + a raw ArrowTableStream keep their metadata. When Join sorts tied system tags, it declares + the rebuilt fields without operand metadata. A rebuilt field is nullable if any of the + corresponding input fields can hold a null. A raw `ArrowTableStream` still preserves `null` in its table in ITL-1543 part A. + A row's system-tag fields come from its stream, including raw streams. Join + uses those declarations on the async row path as well as in its tables. + Source-info token declarations and the row-built gate are tracked separately + under ITL-1557 and the PR 601 follow-up. A row built by `Data` still gives an untyped null the `large_string` type. PolarsFilter is the one operator that still round-trips its columns through Polars; it casts them back to the normalized input types (arrow_utils.restore_column_types and @@ -1806,15 +1923,16 @@ data. The rules: (`arrow_keys.polars_key_frame`, `arrow_keys.sort_key`) and the rows are taken from the table, so no value passes through Polars. A tag type with no rule (a map, an interval, a union, a list view) raises `TypeError` naming the column. -- `Data` source-info values may be `str`, `None`, or `list[...]`, nested to any depth; for a - token supplied as a Python value the Arrow and Python types are derived from the value, with - `None` mapping to `large_string`. That rule has one definition, - `arrow_utils.source_info_arrow_type`. `ArrowTableStream.iter_data` hands each row's source - info to `Data` as Arrow columns, and `source_info_table()` keeps the type the stream - declares for a non-null token. Today a declared type is, in some places, inferred again - from the value, a stopgap ITL-1491 removes (above, "Row ids"). A many→one operator must - emit a list for EVERY row of a list-valued column — mixing in a bare None makes per-row - as_table() schemas diverge and pa.concat_tables fail on the barrier path. +- Data source-info values may be str, None, or list[...], nested to any depth; Arrow/Python + types are derived from the value, with None mapping to large_string. That rule has one + definition, arrow_utils.source_info_arrow_type, and applies only to tokens supplied as + Python values: ArrowTableStream.iter_data hands each row's source info to Data as Arrow + columns, so a type the stream already has is never re-inferred. A + many→one operator must emit a list for **every** row of a list-valued column: a token + has no null list at any level (the token-shape rule, ITL-1491), and a stream that + holds one is refused when it is built. Rows read from a table keep its column type, so + they always make one table; only rows built from Python values, where a bare `None` is + typed `large_string` and a list a list, give per-row `as_table()` schemas that diverge. - Operators that build lists (Batch, GroupBy, MergeJoin) build every list-valued column with arrow_utils.aggregated_list_array (member values in member order, lists from offsets), never from Python values and never pa.list_(field.type). Its type comes from diff --git a/CLAUDE.md b/CLAUDE.md index 538313dd0..d6c7ceb4f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1132,30 +1132,139 @@ are defined in one module, `core/row_ids.py`; never build one of these preimages result in the result store by the input hash, calls nothing and writes no pipeline row (developer, November 26, 2026; `FunctionJobNode._empty_data_cache_hit` is the one place that holds that choice, to be reconsidered in ITL-1475). -- The instance id reads a row's tokens through `DataProtocol.source_info_table()`: one column - per data column, a data column with no token having a null token. THE INTENDED RULE - (developer, November 27, 2026): the type of every source-info token column is fixed by the - pipeline, like every other column type, and is not meant to be taken from values: each - source and operator determines its output token columns' types from its inputs' types, by - its own rule, in its own module. A data-tag that falls through a function pod is meant to - keep its source-info token with its type unchanged; a column a function returns is never a - pass-through, even with an input's name and value (its token points to the function). - TODAY (ITL-1471), in `source_info_table()`: a null token is a `large_string` null whatever - type its column declares; a non-null token of a row read from an Arrow table (a stream's - row) keeps the type that table declares, with a nullable field; a token given as a Python - value is typed from its value (`arrow_utils.source_info_arrow_type`). STOPGAP, not the - proper solution: today a token's declared type is, in some places, inferred again from its - value (`Data.as_table(columns={"source": True})` and so `_rows_to_table`, the row-built - form, and `with_columns_of`). It can narrow a declared type (example: `[None]` in a token - column a `Batch` declares with two list levels infers one). ITL-1491 removes it. Never - build on the re-typing, and never write "a function passes a column through". A rename - moves a column's token with it; a token held for the destination name before is dropped. A pipeline table keeps one type per token - column: a row whose token column has another type than the rows recorded (a list token - beside a string or null token) is refused, naming the column and both types - (`_require_one_type_per_token_column`), and the write fails as a database write error. A lookup must never fail on a row its stream holds as valid Arrow. The - pipeline row stores that same table (`_add_pipeline_record`), never the columns of - `as_table(columns={"source": True})`: every stored row gives its instance and record id - again from its own columns. +- The Arrow type of every source-info token column is determined by the pipeline, like + every other column type; it is never taken from values (developer, November 27, 2026, + ITL-1491). A source builds plain `large_string` tokens, and each operator determines its + output's token column types from its inputs' types, as it does for every column: the + types are those of its result over its inputs' zero-row tables (`typed_zero_row_table`), + defined where the operator builds its output (a list of tokens by + `arrow_utils.aggregated_list_type`, as for a data list). Never summarize this as a rule + per operator family: the operators differ (one keeps a column's token type, one adds a + list level to some columns and folds others into one token, one removes a level, one + makes a new string token). A row read from an Arrow table carries its typed token + columns, and every route keeps them, sync and async alike: + `Data.as_table(columns={"source": True})` (so the row-built table at the edge between two + nodes, `_rows_to_table`), `Data.schema(columns={"source": True})` (the Python type of that + Arrow type), the row-built form of a whole table (which only normalizes a token column to + large types, like any column, drops the field's own metadata as a row does, and sets its + field flag), every change of a row (a selection, a drop, a rename, added columns), a + function pod's stream outside a job (`_table_from_pairs` takes each row's token columns) + and a function node, which takes the token types from its input's rows. A data-tag that + falls through a function pod keeps its token with its type unchanged + (`Data.with_columns_of`); a column a function returns is never a pass-through, even with + an input's name and value: its token points to the function. Never write "a function + passes a column through", and never type a token from its value where an Arrow type + exists. An operator that derives a token from its input's gives it the derived type: + `Join` writes the token it merges for a data-tag both inputs hold with the type the + inputs declare for that token column, on both paths (through `join._token_array`, which + refuses to write a token that does not fit its column: pyarrow stores a string given for + a list type as its characters); `Index` gives the element's token the token type with one + list layer removed, as an Arrow scalar (`with_source_info` keeps a scalar's type). The + one exception: a token is typed from its value (`arrow_utils.source_info_arrow_type`) + only where it is first created and no Arrow type exists: a `Data` built by hand from + Python values or given a Python value by `with_source_info`, and the string tokens + Orcapod itself creates (a source's, a function output's, `Pick`'s, `Index`'s over a + string token, a placeholder's). +- **A token's shape is its data's shape** (developer, November 27, 2026, ITL-1491). A token + column's type is some list layers on top of `large_string`. Those layers must match + EXACTLY the outer list layers of its data column's type, kind for kind: a `large_list` + layer needs a `large_list` layer, a fixed-size list a fixed-size list of the same size + (compared after large normalization, so a plain `list` is a large list). Under its layers + a token is a string: any other leaf (an integer, a binary, also as a plain scalar token + column) is refused. The data may be deeper than its token + (`large_list>` under a `large_list` token), and a plain + `large_string` token has no layer, so it fits any data. A data column of a logical list + type (the extension type built for a list of a logical element, such as a list of `Path`) + is read as its storage: one large-list layer per list level, which is what `Batch`, + `GroupBy` and `MergeJoin` build over a logical element. A token's list is never null AT ANY + LEVEL (developer, November 27, 2026): a null is allowed only at the innermost level, + where the element is a string (`["a::row_0::x", null]` is valid; `[null, ["a"]]` under + a two-level token type is not); a plain string token may be null. Valid: `large_list` over `large_list`; + `fixed_size_list[2]` over `fixed_size_list[2]`; `large_string` over + anything. Invalid: `large_list` over `int64`; a large list over a + fixed-size list or the reverse; two list levels over one; a null list token; + `large_list` as a token. Only lists are layers today: a token type with a nested + layer of another kind (a struct, a map) is refused, and no code is written for layers + that do not exist yet. A layer's item field (name, nullability, metadata) is NOT compared + between a token and its data, nor between two inputs' declarations of one token column + beyond what `require_shared_arrow_type` compares (ITL-1519 decides a consistent + treatment); never add a refusal for it. The rule is checked where a stream is built from + a table (`ArrowTableStream.__init__`, so every source, operator result, table built from + rows, typed zero-row input and the sync orchestrator's held-rows stream), from the + columns' types and the token column's null count only: no value is read and nothing is + computed. The error lists the violating columns in name order (`token_shape_error` + sorts them). KNOWN LIMIT (ITL-1534): the rule is checked where a stream is built, and + the async orchestrator hands a held node's rows on without building one, so a + hand-built held row with an invalid token shape is refused on sync and accepted on + async (pinned by `test_rows_on_read.py::test_held_rows_that_break_the_token_shape_rule_differ_by_route_itl_1534`). + A check of held rows on the async route was tried in this PR and taken out (developer, + November 27, 2026): never add one back here, ITL-1534 decides it. Whatever is done + there, NEVER hash an Arrow type object or use one as a dict or set key: an extension + type need not be hashable (Orcapod's own `list[Path]` type is not), which made a held + batch of such lists fail on replay + (`test_token_types_review_4.py::test_a_replay_over_logical_lists_reuses_its_rows`). + The type rule is the pure function + `schema_utils.token_layers_fit`; `token_shape_violations` lists the violating columns and + `token_shape_error` words the `InputValidationError`, which names the token column, the + data column and both types. Never loosen it. NOT covered: a record batch sent into an + `OutputChannel` (the channels are not wired into nodes; the stream `result()` builds is + checked; the follow-up is ITL-1526), and a `Data` built by hand outside a stream. The null check reads the + validity of EVERY list level of a list-typed token column (`schema_utils.null_list_level`: + the null count of each level's arrays, no value), and the error says at which level (0 is the + token itself). A typed zero-row table and a plain string token are unaffected. No + source, operator or function builds a violating stream. The operators that need an + inner list keep a guard for input no stream can hold any more (rows built by hand and + sent over a bare row channel, hand-built record batches): `Index` on a null inner list, + and `Join` / `MergeJoin` and the streaming-join kernels merging the tokens of a shared + data-tag (`join.NullTokenListError`, which says what it found, worded for the user by + `join.null_token_list_error`). Each guard has a unit test; never remove one, and never + raise a blank internal exception from one. +- Two inputs that declare one token column with two types are refused, on the sync and the + async path, with `require_shared_arrow_type`'s error naming the column and both types + (developer, November 27, 2026): a column that collides under `MergeJoin`, and the token + column of a data-tag both inputs of a `Join` or a `MergeJoin` hold (compared before + `MergeJoin` renames the second input's column, so the outcome never depends on whether a + row matches). ORDINARY sources reach this: `Batch(1)` over a source of scalars gives list + data with LIST tokens, a source that already holds such lists has STRING tokens, and + joining the two on that data-tag (or merging that column) is refused; the remedy is to + bring both inputs to one form before the join (it is a known limitation in the + changelog; keep refusing; the follow-up is ITL-1522). The decision comes from the declared + types: the sync path reads its inputs' tables; the async `Join` takes each input's first + row as its declaration and compares it with every other input's as it arrives, whether + or not any row matches. An input that sends NO row over a bare row channel + (`Join().async_execute` called directly) declares nothing there, as for the shared-key + type check (a stated limit, never fix it here: ITL-1527); in a job the node knows its inputs' types and both orchestrators refuse. + `MergeJoin` reports its first disagreement in name order (`_output_types` iterates + sorted names, never a set). The async `Join` folds only the tokens of columns it merged + (`merged_so_far`, one set per join, shared by the steps of a staggered chain): a + column's own token that happens to start like the join's internal pending marker is the + user's and is kept, as on the sync path. Record batches of one stream declare one token + type, compared strictly (`settle_token_types`: list kind, depth, and each item field's + name, nullability and metadata), so the order of the batches never decides a type; a + batch that declares another is refused, and a streaming-join kernel holds every batch to + its input stream's token type. A token column may carry metadata on a list's item field, + as its stream declares it. +- The instance id reads a row's tokens through `DataProtocol.source_info_table()`: the typed + columns the row carries, every field nullable; a null token is a `large_string` null, for + the id and for the stored column (developer decision of November 26, 2026). A stream's + rows have a null token only in a `large_string` column (the token-shape rule); the + rewrite of a null in a column declared otherwise matters only for a `Data` built by hand + from a table outside a stream. A rename moves a column's token with it; a token held for + the destination name before is dropped. There is one column per data column: a data + column with no token has a null token, so a row built from values and the same row read + from a table have one instance id whenever the values' own types + (`source_info_arrow_type`) are the table's: always for string and null tokens, and for a + list token that shows every list level of its column. A hand-built row whose list token + shows fewer levels than a table declares for it (`[[]]` in a three-level column) is typed + from that value and is another instance. Ids are a function of the row alone, never of + the order sessions ran in. A pipeline table keeps one type per token column: a row whose + token column has another type than the rows recorded (a list token beside a string or + null token) is refused, naming the column and both types + (`_require_one_type_per_token_column`), and the write fails as a database write error; it + is the safety net for a hand-built row given straight to a node and for an + implementation bug. A lookup must never fail on a row its stream holds as valid Arrow. + The pipeline row stores that same table (`_add_pipeline_record`): every stored row gives + its instance and record id again from its own columns. - A trace resolves a held row by its **instance id**, on every branch of a function step (over a source and over another node): a function node says which instance it holds each row under (`FunctionJobNode.held_instance_ids`), and `provenance._entries_for` keeps the @@ -1366,6 +1475,7 @@ data. The rules: expands or converts a type implicitly; the only exception is normalization to large variants. Inputs that disagree on a column's type are an error naming the column and both types, on every execution path (sync and async). + Something that used to complete may be changed to a refusal when the behaviour that let it complete was erroneous: a result reached through a bug (a silently changed type, a value that is not what it claims to be) is not protected by "nothing that completes may stop completing". The refusal stands until a proper fix exists, and is often the proper permanent answer. (Developer, November 27, 2026.) Function-output rule (developer, November 12, 2026): the returned value must be an instance of the declared type, or an exact numeric equivalent; a subclass stands in for its base. What is stored for a subclass instance is decided by the logical type of the declared class (developer, November 12, 2026, ITL-871): a plain user class is stored as the base @@ -1393,9 +1503,16 @@ data. The rules: changed, so `int8` stays `int8`. Sources refuse Arrow type `null` at any depth, including in reserved raw columns. Declare a supported nullable type for missing values. A source's custom system-tag names must each identify an existing non-nullable text - column with no null values. When Join sorts tied system tags, an output field is - nullable if any of the corresponding input fields can hold a null. + column with no null values and no Arrow field metadata. Remove field metadata before + building the source. This restriction is a stopgap pending ITL-1561. System-tag fields on + a raw ArrowTableStream keep their metadata. When Join sorts tied system tags, it declares + the rebuilt fields without operand metadata. A rebuilt field is nullable if any of the + corresponding input fields can hold a null. A raw `ArrowTableStream` still preserves `null` in its table in ITL-1543 part A. + A row's system-tag fields come from its stream, including raw streams. Join + uses those declarations on the async row path as well as in its tables. + Source-info token declarations and the row-built gate are tracked separately + under ITL-1557 and the PR 601 follow-up. A row built by `Data` still gives an untyped null the `large_string` type. `PolarsFilter` is the one operator that still round-trips its columns through Polars; it casts them back to the normalized input types (`arrow_utils.restore_column_types` and @@ -1858,16 +1975,16 @@ data. The rules: (`arrow_keys.polars_key_frame`, `arrow_keys.sort_key`) and the rows are taken from the table, so no value passes through Polars. A tag type with no rule (a map, an interval, a union, a list view) raises `TypeError` naming the column. -- `Data` source-info values may be `str`, `None`, or `list[...]`, nested to any depth; for a - token supplied as a Python value the Arrow and Python types are derived from the value, with - `None` mapping to `large_string`. That rule has one definition, - `arrow_utils.source_info_arrow_type`. `ArrowTableStream.iter_data` hands each row's source - info to `Data` as Arrow columns, and `source_info_table()` keeps the type the stream - declares for a non-null token. Today a declared type is, in some places, inferred again - from the value, a stopgap ITL-1491 removes (above, "Row ids"). A - many→one operator must emit a list for **every** row of a list-valued column — mixing a bare - `None` into some rows makes per-row `as_table()` schemas diverge and `pa.concat_tables` fail - on the barrier path. +- `Data` source-info values may be `str`, `None`, or `list[...]`, nested to any depth; the + Arrow and Python types are derived from the value, with `None` mapping to `large_string`. + That rule has one definition, `arrow_utils.source_info_arrow_type`, and applies only to + tokens supplied as Python values: `ArrowTableStream.iter_data` hands each row's source info + to `Data` as Arrow columns, so a type the stream already has is never re-inferred. A + many→one operator must emit a list for **every** row of a list-valued column: a token + has no null list at any level (the token-shape rule, ITL-1491), and a stream that + holds one is refused when it is built. Rows read from a table keep its column type, so + they always make one table; only rows built from Python values, where a bare `None` is + typed `large_string` and a list a list, give per-row `as_table()` schemas that diverge. - Operators that build lists (`Batch`, `GroupBy`, `MergeJoin`) build every list-valued column with `arrow_utils.aggregated_list_array` (member values in member order, lists from offsets), never from Python values and never `pa.list_(field.type)`. Its type comes from diff --git a/changelog.d/ITL-1491.md b/changelog.d/ITL-1491.md new file mode 100644 index 000000000..73168ff0d --- /dev/null +++ b/changelog.d/ITL-1491.md @@ -0,0 +1,97 @@ +### Breaking changes and migration + +- **A stream whose source-info token does not have the shape of its data is refused.** A + token column's type is some list layers on top of a string, and those layers must be the + outer list layers of its data column: a `large_list` of tokens needs a `large_list` of + values, a fixed-size list a fixed-size list of the same size. Under its layers a token is + a string. The values may be deeper than their tokens, and a plain string token fits any + value. A token's list is never null at any level: a null is allowed only at the innermost + level, where the element is a string (`["a", null]` is valid, `[null, ["a"]]` under a + two-level token type is not); a plain string token may be null. The rule is checked where a stream is built from a table; + a stream that breaks it raises `InputValidationError` naming the token column, its data column and both + types. Sources, operators and functions always build tokens of the right shape, so only a + table built by hand with `_source_*` columns is affected. Such a table used to be accepted + because nothing checked it; downstream, a `Join` over a data-tag with a null list token + silently stored the characters of an internal marker as the merged token, and so did a + `Join` or `MergeJoin` over a list-of-lists token with a null inner list. (ITL-1491) +- **Inputs that declare one token column with two types are refused.** `MergeJoin` (a + colliding data column, or a data-tag both inputs hold) and `Join` (a data-tag both inputs + hold, whose tokens the join merges) raise `InputValidationError` naming the column and + both types, on the sync and the async path, whether or not a key matches. A `Join` over + such a data-tag used to fail with `ValueError: cannot merge the source info of a list + with that of a scalar` when a key matched and to complete when none did; `MergeJoin` + already refused a colliding column. See the known limitation below for the case that + ordinary sources reach. (ITL-1491) + +### Changed + +- **The type of a source-info token column is determined by the pipeline, never by the + tokens' values.** A source builds plain `large_string` tokens, and each operator determines + its output's token types from its inputs' types, as it does for every other column. A row + read from a stream keeps that type where it used to be typed again from its value: in the + table built from rows between two nodes, in a node's output, in a row shown as a table + (`data.as_table(columns={"source": True})`, and the Python type + `data.schema(columns={"source": True})` reports), in the rows an async `Join` merges, in + the element `Index` takes from a list of tokens, in a function pod's stream outside a job, + and in record batches. For the tokens that sources and operators build, nothing changes: + no hash, stored path or stored column type moves. A token is still typed from its value + where it is first created from a Python value and no Arrow type exists + (`Data(..., source_info=...)`, `with_source_info`). (ITL-1491) +- **A hand-built raw stream keeps the token type it declares.** A fixed-size list of tokens + (over a fixed-size list of values) stays a fixed-size list, where it used to become a + `large_list`, and a list of tokens keeps its item field's name, nullability and metadata, + also in an operator cache. (ITL-1491) +- **A data-tag that falls through a function pod keeps its source-info token with its type + unchanged.** The token used to be typed again from its value. A column a function returns + is not affected: its token points to the function. (ITL-1491) + +### Fixed + +- **Rows with a nested source-info token column behave the same on the sync and the async + path.** A row whose token column is nested (a list of tokens, or a list of such lists) + and whose tokens could not be typed again from their values (an empty list, or a null + string inside a list of lists, such as `[[null], []]`) raised an Arrow type error where + the sync path builds a table from rows between two nodes, while the async path recorded + the rows. Both paths now pass such rows on and store them, with the same token types and + the same entry, instance and record ids. (ITL-1491) +- **An async `Join` writes the token of a merged data-tag with the type its inputs + declare.** It rebuilt the merged token from its Python value, so a list token that the + sync path kept as declared became another list type on the async path, and a job run on + one path could not be continued on the other over the same store. (ITL-1491) +- **`Index` gives the element's token the type of the token list's items.** It typed the + token again from its value, so a list item's type could change (a fixed-size list became a + `large_list`). An element that is a null where the remaining token type is a list is + refused with `InputValidationError` naming the column, on both paths. (ITL-1491) +- **A function pod's stream outside a job shows list-valued source-info tokens.** + `pod(stream).as_table(columns={"source": True})` raised `ValueError: Unsupported Python + type` when a data-tag that falls through the function had a list token. (ITL-1491) +- **An async `Join` keeps a token that looks like its internal marker.** A column the join + does not merge keeps its own token on both paths. The async path used to replace a token + that began with the join's internal marker text by a `join_v1:` digest. (ITL-1491) +- **`MergeJoin` reports the same first disagreement in every process.** When several + columns of its two inputs disagree in type, the one first in name order is reported; which + one was reported used to follow the interpreter's hash seed. (ITL-1491) + +### Known limitations + +- **A `Batch` of single values cannot be joined with a source that already holds lists of + them, on that column.** The two have the same values and data type but different + source-info tokens: a list of tokens (one per member) after `Batch`, one plain token per + list in the source. A `Join` where that column is a data-tag of both inputs, or a + `MergeJoin` where it collides, refuses the inputs with `InputValidationError` naming the + token column and both types. Bring both inputs to one form before the join: batch both, + or neither. Whether the two forms should join is ITL-1522. (ITL-1491) +- **A record batch sent into a record-batch channel is not checked against the token-shape + rule.** The stream built from the channel's batches is. The channels are not used by jobs + yet; checking a batch where it is sent is ITL-1526. (ITL-1491) +- **An input that sends no row over a bare row channel declares no token type.** A `Join` + run directly through `async_execute` over row channels (outside a job) compares its + inputs' token types from their first rows, so it cannot refuse an input that sends none; + the sync call and a job on either orchestrator refuse it. Carrying the declared types over + row channels is ITL-1527. (ITL-1491) +- **Rows an async run holds instead of running are not checked against the token-shape + rule.** The rule is checked where a stream is built. The sync orchestrator builds a held + node's rows into a stream, and the async orchestrator hands them on without building one, + so a held row built by hand with an invalid token shape is refused on sync and accepted + on async. Rows that come from a stream were checked when it was built. Making the two + routes agree is ITL-1534. (ITL-1491) diff --git a/changelog.d/ITL-1543.md b/changelog.d/ITL-1543.md index 5c5313a53..f552f242c 100644 --- a/changelog.d/ITL-1543.md +++ b/changelog.d/ITL-1543.md @@ -5,6 +5,10 @@ - A custom system-tag column on a source must be a non-nullable string column with no null values. Sources also reject missing names in `system_tag_columns`. Convert custom tags to text before building the source. +- Sources refuse Arrow field metadata on nominated custom system tags, including + tag copies nominated with `system_tag_columns`. Remove the field metadata before + building the source. Rebuild a source cache if it was written with field + metadata on a system tag. ITL-1561 tracks re-evaluating this restriction. ### Fixed @@ -12,3 +16,10 @@ sorted system tags' nullability. The tag is non-nullable when every corresponding input field is non-nullable. Existing entry IDs, instance IDs, record IDs and operator hashes for source inputs stay the same. +- Rows preserve the stream's Arrow fields for system tags, including width, + nullability, and metadata. Standalone async Join uses those fields as well. + IDs can change for hand-built streams with unusual system-tag fields. +- Standalone async Join uses the same fields as the table and sync rows for + sorted system tags of tied inputs, and leaves custom tags with their operands. + Entry-ID errors for a raw Arrow Null system + tag name the column and ask for a supported nullable type. diff --git a/docs/concepts/provenance.md b/docs/concepts/provenance.md index 8bc650427..e3f0adcf3 100644 --- a/docs/concepts/provenance.md +++ b/docs/concepts/provenance.md @@ -130,6 +130,44 @@ print([(label, run.computed_here) for label, run in trace.function_runs()]) # [('per_animal', True), ('scores', False), ('scores', True)] ``` +## The shape of a token + +A value's token has the shape of the value. You see tokens in the `_source_` +columns (`stream.as_table(columns={"source": True})`). + +- **A plain token fits any value.** A source gives every value one token, a string + (`large_string`), whatever the value is: a number, a text, a list, an array. A function + gives each value it returns one token too. A plain token may be missing (null). +- **A list of tokens needs a list of values.** `Batch`, `GroupBy` and `MergeJoin` put + several rows' values into one list, and their tokens into a list beside it, one token per + member, in the same order: values `[0.8, 0.3]` with tokens + `["scores::...::accuracy", "scores::...::accuracy"]`. After two such steps both are lists + of lists. +- **The values may be deeper than their tokens.** A source column that holds lists has one + plain token per value, so after a `Batch` its values are lists of lists and its tokens a + list of plain tokens. +- **A list of tokens is never missing, at any level; only a token inside the innermost + list may be.** A batch of three rows of which one has no token gives + `["a::row_0::x", null, "a::row_2::x"]`. In a list of lists of tokens, `[null, ["a"]]` is + 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. + +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 +member) in the first, one plain token per list in the second. A `Join` on such a column as +a data-tag, or a `MergeJoin` of it, refuses the two inputs and names the token column and +both types. Bring both inputs to one form before the join: batch both, or neither. +Whether the two forms should join is an open question (ITL-1522). The Arrow types, with a table of what is +accepted and refused, are in +[the hashing reference](../reference/hashing.md#the-shape-of-a-source-info-token-column). + ## When there is nothing to trace An operator or function node shows only the rows of its run in this process (see diff --git a/docs/dev/design_issues/ITL-1543-AS2.md b/docs/dev/design_issues/ITL-1543-AS2.md index 88251de24..463c9c12f 100644 --- a/docs/dev/design_issues/ITL-1543-AS2.md +++ b/docs/dev/design_issues/ITL-1543-AS2.md @@ -11,4 +11,6 @@ data was read. For example, a Join of streams tied on pipeline hash can declare its sorted system tags nullable, although its rows have non-nullable system tags. Part A corrects that Join schema and rejects Arrow Null in sources, including -nested Null. Part B remains open and makes rows use the stream's field definitions. +nested Null. Part B carries a stream's system-tag fields through row and batch +reads, including the standalone async Join. Source-info flag decisions remain +open in ITL-1557, and the existing row-built guard remains pending PR 601. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index e05ee87b3..fc23c7593 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1261,12 +1261,136 @@ preimage = tag.as_table(columns={"system_tags": True}) | Field | Value | |---|---| -| **Inputs** | `__pipeline_entry_id` (the entry id's labelled digest, `pa.large_binary()`), then the `_source_*` columns of the input data in name order (`data.source_info_table()`): one per data column, a data column with no token having a null token, the type of each column today: a null token is a `large_string` null whatever type its column declares; a non-null token of a row read from an Arrow table keeps the type that table declares for it (nullable field); a token given as a Python value has the type its value infers. A token column's type is fixed by the pipeline and is not meant to be taken from values; today a declared type is, in some places, inferred again from the value (`Data.as_table(columns={"source": True})` and so `_rows_to_table`, the row-built form, and `with_columns_of`), a stopgap that ITL-1491 removes. The pipeline row stores this same table (`FunctionJobNode._add_pipeline_record`), so a stored row gives its instance id again from its own columns | +| **Inputs** | `__pipeline_entry_id` (the entry id's labelled digest, `pa.large_binary()`), then the `_source_*` columns of the input data in name order (`data.source_info_table()`): one per data column, a data column with no token having a null token, each with the type the pipeline determines for it (below, "The type of a source-info token column"), a null token being a `large_string` null. A row built from values and the same row read from a table give the same columns when the values' own types are the table's (always for string and null tokens; a list token built by hand that shows fewer list levels than the table declares, such as `[[]]` in a three-level column, is typed from its value and gives another id). So the id is a function of the row alone, never of the order sessions ran in. The pipeline row stores this same table (`FunctionJobNode._add_pipeline_record`), so a stored row gives its instance id again from its own columns | | **Algorithm** | `StarfixArrowHasher.hash_table(preimage)` | | **Output format** | `ContentHash`; stored in `__pipeline_instance_id` as `b"{method}:{digest}"` | | **Uniqueness guarantee** | Unique per `(entry, source-info tokens)`; the in-memory cache key and the lookup column of the pipeline table | | **Known exclusions** | The result id: every result recorded for one instance has this id. | +#### The type of a source-info token column + +The Arrow type of every source-info token column is determined by the pipeline, like every +other column type. It is never taken from values (developer, November 27, 2026, ITL-1491). + +A source builds `large_string` tokens. Each operator determines the token column types of +its output from the types of its inputs, as it determines every other column type: they are +the types of its result over its inputs' zero-row tables, and they are defined where the +operator builds its output (a list of tokens is typed like a list of data values, by +`arrow_utils.aggregated_list_type`). The operators differ, so there is no rule per family +of operators: one keeps a column's token type, another puts the tokens of the rows it +gathers into a list, another takes one element of a token list (one list layer less), and +another makes one new string token from several. At a function pod, a column the function +returns has a `large_string` token that points to the function, and a data-tag that falls +through keeps its token with its type unchanged. + +A row read from a stream carries its typed token columns, and every route keeps them: the +table built from rows at the edge between two nodes (sync), the rows sent on as they are +(async), the whole-table form of a node's output, record batches, a function pod's stream +outside a job, and every change of a row that keeps a token (a selection, a drop, a rename, +added columns). `schema(columns={"source": True})` reports the Python type of that Arrow +type. So a function node reads the same token types from its input on the sync and on the +async path, and a row has one instance id whichever path recorded it first. + +A token is typed from its value only where it is first created and no Arrow type exists: a +row built by hand from Python values (`Data(..., source_info=...)`, `with_source_info` given +a Python value), and the string tokens Orcapod itself creates (a source's, a function +output's, `Pick`'s, a placeholder's), which are `large_string`. + +#### The shape of a source-info token column + +A token column's type is some list layers on top of `large_string`. Those layers must match +exactly the outer list layers of its data column's type (developer, November 27, 2026, +ITL-1491): + +| Token column | Data column | | +|---|---|---| +| `large_string` | any type | valid: a plain string token has no layer | +| `large_list` | `large_list` | valid | +| `large_list` | `large_list>` | valid: the data may be deeper than its token | +| `large_list>` | `large_list>` | valid | +| `fixed_size_list[2]` | `fixed_size_list[2]` | valid: same kind, same size | +| `large_list` | the logical list type of a list of `Path` | valid: a logical list is one large-list layer per list level | +| `large_list` | `int64` | refused: the token has a layer its data lacks | +| `large_list` | `fixed_size_list[2]` | refused: the kinds differ (and the reverse) | +| `fixed_size_list[2]` | `fixed_size_list[3]` | refused: the sizes differ | +| `large_list>` | `large_list` | refused: two layers over one | +| a struct, a map | any type | refused: only lists are layers today | +| `large_list`, `int64`, `large_binary` | any type | refused: under its layers a token is a string | + +- Both types are compared in their large variants, so a plain `list` counts as a large list. +- A token's list is never null at any level: a null is allowed only at the innermost level, + where the element is a string. So `[null, ["a"]]` under a two-level token type is refused, + and the error says at which list level the null list is (level 0 is the token itself). + A null string inside a list is valid at any depth: a `Batch` over three + rows of which one has no recorded provenance gives `["a::row_0::x", null, "a::row_2::x"]`. + A plain string token may be null. +- A layer's item field (its name, nullability and metadata) is not compared between a token + and its data. +- The rule is checked where a stream is built from a table (so for every source, every + operator result and every table built from rows), from the columns' types and the + validity of every list level of a list-typed token column (the null count of each + level's arrays): no value is read. A table with no rows is never refused for a null. A stream that breaks it is refused with + `InputValidationError` naming the token column, the data column and both types + (`schema_utils.token_layers_fit` is the rule). The error lists the violating columns + in name order. +- No source, operator or function builds such a stream: the lists `Batch`, `GroupBy` and + `MergeJoin` build are parallel by origin row, data and tokens alike. Only a table built by + hand can break the rule. + +`Index`, `Join`, `MergeJoin` and the record-batch join kernels need the inner lists of a +token. They keep a guard for a null one, which no stream can hold: it can only reach them +in rows built by hand and sent over a bare row channel, or in hand-built record batches, +and it raises `InputValidationError` naming the column. + +What the check does not cover: + +- The rows of a node an async run holds instead of running. The rule is checked where a + stream is built; the sync orchestrator builds a held node's rows into a stream where a + successor reads them, and the async orchestrator hands them on without building one. So + a held row built by hand with an invalid token shape is refused on the sync route and + accepted on the async route. Rows a run holds come from a stream that was checked when + it was built, so this concerns hand-built rows only. Making the two routes agree is + ITL-1534. +- A record batch sent into a record-batch channel. The channels are not wired into nodes + yet; the stream built from a channel's batches is checked. Checking a batch where it is sent is ITL-1526. +- A `Data` row built by hand outside a stream. + +Where a null token is stored or hashed (the inputs of site 8, above) it is a `large_string` +null; by the rule a stream's rows have a null token only in a `large_string` column. A +pipeline table that already holds a token column with another type refuses the row, naming +the column and both types. + +#### Two declarations of one token column + +Two inputs that declare one token column with two types are refused, on the sync and on the +async path, with the error that names the column and both types: a column that collides +under `MergeJoin`, and the token column of a data-tag that both inputs of a `Join` or a +`MergeJoin` hold, which the operator merges into one token of that declared type. With +streams that satisfy the shape rule this is a list of tokens in one input against a plain +string token in the other, or list items that differ in nullability. + +Ordinary sources can reach this refusal. `Batch(1)` over a source of single values gives +lists with a list of tokens (one token per member). A source that already holds such lists +has one plain token per value. The two have the same data type and two token types, so a +`Join` on that data-tag, or a `MergeJoin` on that column, refuses them. Bring both inputs +to one form before the join: batch both, or neither. Whether the two forms should join is ITL-1522. + +The decision comes from the declared types, not from which rows match. The sync path reads +its inputs' tables. The async `Join` takes each input's first row as its declaration and +compares it with every other input's as it arrives. An input that sends no row over a bare +row channel (`Join().async_execute(...)` called directly, outside a job) declares nothing +there; in a job the node knows its inputs' types, and both orchestrators refuse. Carrying the declared types over row channels is ITL-1527. + +Item fields that differ only in name or metadata between two inputs' declarations are not +refused: both paths give the first input's type (in the join's canonical input order). + +The async `Join` folds only the tokens of the columns it merged. A column's own token is +the user's, whatever it looks like. + +Record batches of one stream declare one token type, compared strictly (list kind, depth, +and each item field's name, nullability and metadata), so the order of the batches never +decides a type. + The placeholder of an ephemeral result that is gone (`EmptyData`) carries tokens too: for each output of the function, a real output's token with the sentinel `EPHEMERAL_RESULT_GONE` (one constant, `row_ids.EPHEMERAL_RESULT_GONE`) where the result id would stand, diff --git a/src/orcapod/core/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index 23acd12ac..f5d74dac2 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -356,6 +356,7 @@ def _rows_of_table( """ if table.num_rows == 0: return + original_table = table table = arrow_utils.normalize_table_to_large_types(table) row_contexts: list[Any | None] | None = None if constants.CONTEXT_KEY in table.column_names and data_context is None: @@ -365,7 +366,9 @@ def _rows_of_table( if apart_prefix is not None: apart = [c for c in data_table.column_names if c.startswith(apart_prefix)] if apart: - apart_table = data_table.select(apart) + apart_table = arrow_utils.normalize_table_to_large_types( + original_table.select(apart), keep_null=True + ) data_table = data_table.drop_columns(apart) # The optional tables that are there, and where each is in a row's tuple. optional = [meta_table, apart_table, beside] diff --git a/src/orcapod/core/datagrams/tag_data.py b/src/orcapod/core/datagrams/tag_data.py index d00efbad3..c51e5c950 100644 --- a/src/orcapod/core/datagrams/tag_data.py +++ b/src/orcapod/core/datagrams/tag_data.py @@ -19,7 +19,7 @@ import logging import uuid from collections.abc import Iterator, Mapping, Sequence -from typing import TYPE_CHECKING, Any, Self +from typing import cast, TYPE_CHECKING, Any, Self import pyarrow as pa @@ -90,6 +90,7 @@ def __init__( data = _pa.Table.from_batches([data]) extracted_sys_tags: dict[str, DataValue] + system_tag_table = None if isinstance(data, _pa.Table): # Arrow path: call super() first, then extract system-tag columns from @@ -107,9 +108,12 @@ def __init__( if c.startswith(constants.SYSTEM_TAG_PREFIX) ] if sys_tag_cols: + system_tag_table = arrow_utils.normalize_table_to_large_types( + data.select(sys_tag_cols), keep_null=True + ) extracted_sys_tags = ( self._data_context.type_converter.arrow_table_to_python_dicts( - self._data_table.select(sys_tag_cols) # type: ignore[union-attr] + system_tag_table )[0] ) self._data_table = self._data_table.drop_columns(sys_tag_cols) # type: ignore[union-attr] @@ -138,7 +142,10 @@ def __init__( **kwargs, ) - self._set_system_tags({**extracted_sys_tags, **(system_tags or {})}) + if system_tag_table is not None and not system_tags: + self._set_system_tag_table(system_tag_table, extracted_sys_tags) + else: + self._set_system_tags({**extracted_sys_tags, **(system_tags or {})}) def _set_system_tags(self, system_tags: dict[str, DataValue]) -> None: """Hold ``system_tags`` as this tag's system tags.""" @@ -147,6 +154,20 @@ def _set_system_tags(self, system_tags: dict[str, DataValue]) -> None: [self._system_tags], default_type=str ) self._system_tags_table: "pa.Table | None" = None + self._system_tags_from_arrow = False + + def _set_system_tag_table( + self, table: "pa.Table", values: dict[str, DataValue] + ) -> None: + """Hold the system-tag fields and values supplied by an Arrow table.""" + self._system_tags_table = table + self._system_tags = values + self._system_tags_python_schema = Schema( + self._data_context.type_converter.arrow_schema_to_python_schema( + table.schema + ) + ) + self._system_tags_from_arrow = True @classmethod def rows_of( @@ -178,13 +199,15 @@ def rows_of( table, data_context, apart_prefix=constants.SYSTEM_TAG_PREFIX ) for tag, system_tag_row, _ in rows: - tag._set_system_tags( - tag._data_context.type_converter.arrow_table_to_python_dicts( - system_tag_row - )[0] - if system_tag_row is not None - else {} - ) + if system_tag_row is None: + tag._set_system_tags({}) + else: + tag._set_system_tag_table( + system_tag_row, + tag._data_context.type_converter.arrow_table_to_python_dicts( + system_tag_row + )[0], + ) yield tag # ------------------------------------------------------------------ @@ -287,7 +310,12 @@ def copy(self, include_cache: bool = True, preserve_id: bool = False) -> Self: new_tag = super().copy(include_cache=include_cache, preserve_id=preserve_id) new_tag._system_tags = dict(self._system_tags) new_tag._system_tags_python_schema = self._system_tags_python_schema - new_tag._system_tags_table = self._system_tags_table if include_cache else None + new_tag._system_tags_from_arrow = self._system_tags_from_arrow + new_tag._system_tags_table = ( + self._system_tags_table + if include_cache or self._system_tags_from_arrow + else None + ) return new_tag @@ -309,12 +337,26 @@ def _source_info_python_type(value: "SourceInfoValue") -> DataType: ``str`` for scalars and unknowns, ``list[...]`` nested to the token's depth for lists. """ - import pyarrow as _pa + return _token_python_type(arrow_utils.source_info_arrow_type(value)) + - arrow_type = arrow_utils.source_info_arrow_type(value) +def _token_python_type(arrow_type: "pa.DataType") -> DataType: + """The Python type of a source-info column of ``arrow_type``. + + Args: + arrow_type: A token column's Arrow type: a string, or a list of any kind + (large, plain or fixed-size) of a token type. + + Returns: + ``str``, under one ``list[...]`` per list level of ``arrow_type``. + """ depth = 0 - while _pa.types.is_large_list(arrow_type): - arrow_type = arrow_type.value_type + while ( + pa.types.is_large_list(arrow_type) + or pa.types.is_list(arrow_type) + or pa.types.is_fixed_size_list(arrow_type) + ): + arrow_type = arrow_type.value_type # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownVariableType] # a list type has a value type depth += 1 python_type: DataType = str for _ in range(depth): @@ -376,8 +418,10 @@ def __init__( self._source_info: dict[str, SourceInfoValue] = self._source_info_of_row( si_table ) - # The table's own source-info columns, when the tokens are all its own. - typed = si_table if not source_info and si_table.num_rows == 1 else None + # The row's source-info columns: the table's own, with their types; a + # token given as a value (``source_info``) is made here, so its column + # is typed from that value (ITL-1491). + typed = si_table if si_table.num_rows == 1 else None else: typed = None # Dict path: extract source-info keys before calling super() @@ -484,6 +528,22 @@ def rows_of( # ------------------------------------------------------------------ def _ensure_source_info_table(self) -> "pa.Table": + """Return the row's source-info columns as ``as_table`` shows them. + + The type of a token column is determined by the pipeline, never taken + from values (developer, November 27, 2026, ITL-1491): a row read from an + Arrow table gives the columns that table has, with their types (a null + token's included) and every field nullable; the arrays are wrapped again, + never cast. Only a row built from Python values, for which no Arrow type + exists, types each token from its value + (``arrow_utils.source_info_arrow_type``). + """ + typed = self._typed_source_info + if self._source_info_table is None and typed is not None: + self._source_info_table = pa.Table.from_arrays( + typed.columns, + schema=pa.schema([pa.field(f.name, f.type) for f in typed.schema]), + ) if self._source_info_table is None: import pyarrow as _pa @@ -577,27 +637,27 @@ def source_info_table(self) -> "pa.Table": """Return the source-info tokens as a one-row table. One ``_source_`` per data column, in their order, every field - nullable; a data column with no token has a null token. What each - column's type is today (ITL-1471): - - - a null token is a ``large_string`` null whatever type its column - declares (a null says nothing a type could tell apart); - - a non-null token of a row read from an Arrow table (a stream's row) - keeps the type that table declares for it: it is not worked out again - from its value, which a nested token column would not survive. A - change of the row keeps the typed column of every token it keeps (a - selection, a drop, a rename, added columns); - - a token given as a Python value (a row built from values, - ``with_source_info``) is typed from its value - (``arrow_utils.source_info_arrow_type``), and so is a token copied - from another row by ``with_columns_of`` (a stopgap, see there). - - A token column's type is not meant to be taken from values: it is - fixed by the pipeline (ITL-1491). - - ``as_table(columns={"source": True})`` differs in two ways: it types - every token from its value, and it has no column for a data column whose - token was never given. + nullable; a data column with no token has a null token. Each column has + one canonical type, a function of the token's value alone (ITL-1471): a + null token is a ``large_string`` null whatever type its column declares + (a null says nothing a type could tell apart), and a non-null token of a + row read from an Arrow table (a stream's row) keeps the type that table + gives it: its type is never worked out again from its value, which a + nested token column would not survive. A change of the row keeps the + typed column of every token it keeps (a selection, a drop, a rename, + added columns, a column taken from another row with its token: + ``with_columns_of``). Only a token created from a Python value, where no + Arrow type exists (a row built from values, ``with_source_info``), is + typed from its value. So a row built from values and the same row read + from a table give the same columns when the values' own types are the + table's (a hand-built list token that shows fewer list levels than the + table declares is typed from its value, and differs). + + ``as_table(columns={"source": True})`` gives the same typed columns + (ITL-1491) and differs in two ways: a null token keeps the type its + column declares, so that the rows of one stream make one table; and a row + built from values has no column for a data column whose token was never + given. Returns: The one-row table; a table with no column when there is no data @@ -608,34 +668,51 @@ def source_info_table(self) -> "pa.Table": names = Datagram.keys(self) if all(name in self._source_info for name in names): return self._ensure_source_info_table() - return self._token_columns({}) + return self._token_columns({}, every_column=True) # The fields of a row's own table: the name and the type, nullable, as # ``_source_info_field`` makes them (a stream's may be non-null). The # arrays are the stream's, wrapped again, never cast. A null token is a - # ``large_string`` null whatever its column declares. - columns = [ - pa.chunked_array([pa.nulls(1, _NULL_TOKEN_TYPE)]) - if column.null_count == len(column) - else column - for column in typed.columns - ] + # ``large_string`` null whatever its column declares, and so is the token + # of a data column the row holds no token column for. + null = pa.chunked_array([pa.nulls(1, _NULL_TOKEN_TYPE)]) + columns: "list[pa.ChunkedArray[Any]]" = [] + column_names: "list[str]" = [] + for name in Datagram.keys(self): + column_name = f"{constants.SOURCE_PREFIX}{name}" + column = ( + typed.column(column_name) if column_name in typed.column_names else null + ) + columns.append(null if column.null_count == len(column) else column) + column_names.append(column_name) return pa.Table.from_arrays( columns, schema=pa.schema( - [pa.field(f.name, c.type) for f, c in zip(typed.schema, columns)] + [ + pa.field(name, column.type) + for name, column in zip(column_names, columns) + ] ), ) - def _token_columns(self, kept: "Mapping[str, pa.ChunkedArray[Any]]") -> "pa.Table": - """Return one token column per data column this row holds, in their order. + def _token_columns( + self, kept: "Mapping[str, pa.ChunkedArray[Any]]", *, every_column: bool = False + ) -> "pa.Table": + """Return this row's token columns, in the order of its data columns. + + A row has a token column for each data column it holds a token for (a + null token included), as ``as_table(columns={"source": True})`` shows + them: a row read from a table for every data column, a row built from + values only for the tokens it was given. Args: kept: The typed column of each token that is kept as it was read, by the name of the data column it now belongs to. + every_column: Give every data column a column, null when the row holds + no token for it (the form of ``source_info_table``). Returns: A one-row table: for a data column in ``kept`` that column, for any - other the row's token typed from its value (null when it has none). + other the row's token typed from its value. """ arrays: "list[pa.ChunkedArray[Any]]" = [] fields: "list[pa.Field[Any]]" = [] @@ -643,6 +720,8 @@ def _token_columns(self, kept: "Mapping[str, pa.ChunkedArray[Any]]") -> "pa.Tabl column_name = f"{constants.SOURCE_PREFIX}{name}" array = kept.get(name) if array is None: + if not every_column and name not in self._source_info: + continue token = self._source_info.get(name) token_type = _source_info_field(column_name, token).type array = pa.chunked_array([pa.array([token], type=token_type)]) @@ -650,40 +729,78 @@ def _token_columns(self, kept: "Mapping[str, pa.ChunkedArray[Any]]") -> "pa.Tabl fields.append(pa.field(column_name, array.type)) return pa.Table.from_arrays(arrays, schema=pa.schema(fields)) - def _keep_typed_tokens(self, changed: Self, origin: "Mapping[str, str]") -> None: - """Give ``changed`` the typed columns of the tokens it keeps from this row. + def _keep_typed_tokens( + self, + changed: Self, + origin: "Mapping[str, str]", + *, + given: "Mapping[str, pa.ChunkedArray[Any]] | None" = None, + ) -> None: + """Build ``changed``'s token columns using the Arrow types it already has. - Does nothing when this row holds no typed columns (it was built from - Python values): its tokens are then typed from their values anyway. + When there are no Arrow token columns on either side, tokens are typed + from their Python values when needed. Args: changed: The row made from this one; its columns and tokens are set. origin: For each data column of ``changed`` whose token is this row's, unchanged: the name the column has in this row. + given: New tokens already represented as Arrow columns, by data + column name. """ typed = self._typed_source_info - if typed is None: + if typed is None and not given: changed._typed_source_info = None return kept = { new: typed.column(f"{constants.SOURCE_PREFIX}{old}") for new, old in origin.items() - if f"{constants.SOURCE_PREFIX}{old}" in typed.column_names + if typed is not None + and f"{constants.SOURCE_PREFIX}{old}" in typed.column_names } + if given: + kept.update(given) changed._typed_source_info = changed._token_columns(kept) - def with_source_info(self, **source_info: "SourceInfoValue") -> Self: - """Create a copy with updated source-information entries.""" + def with_source_info( + self, **source_info: "SourceInfoValue | pa.Scalar[Any]" + ) -> Self: + """Create a copy with updated source-information entries. + + A token given as a Python value is typed from that value: no Arrow type + exists for it. A token whose column type is known (an operator that + derives a token from its input's, as ``Index`` does) is given as an + Arrow scalar of that type, and keeps it (ITL-1491). If both spellings of + a column name are given, the later keyword wins. + + Args: + **source_info: The token of each named data column: a Python value, + or an Arrow scalar that carries the token column's type. + + Returns: + The copy. + """ + updates = { + key.removeprefix(constants.SOURCE_PREFIX): value + for key, value in source_info.items() + } current = dict(self._source_info) - for key, value in source_info.items(): - if key.startswith(constants.SOURCE_PREFIX): - key = key.removeprefix(constants.SOURCE_PREFIX) - current[key] = value + typed_given: "dict[str, pa.ChunkedArray[Any]]" = {} + for key, value in updates.items(): + if isinstance(value, pa.Scalar): + token = cast("SourceInfoValue", value.as_py()) + typed_given[key] = pa.chunked_array( + [pa.array([token], type=value.type)] + ) + else: + token = value + current[key] = token new_p = self.copy(include_cache=False) new_p._source_info = current - replaced = {key.removeprefix(constants.SOURCE_PREFIX) for key in source_info} self._keep_typed_tokens( - new_p, {k: k for k in Datagram.keys(new_p) if k not in replaced} + new_p, + {k: k for k in Datagram.keys(new_p) if k not in updates}, + given=typed_given, ) return new_p @@ -712,10 +829,16 @@ def schema( schema = dict(super().schema(columns=columns, all_info=all_info)) column_config = ColumnConfig.handle_config(columns, all_info=all_info) if column_config.source: + # A token column's Python type follows its Arrow type when the row + # carries one (ITL-1491), so it agrees with ``arrow_schema``; only a + # token given as a value is typed from that value. + typed = self._typed_source_info for key in super().keys(): - schema[f"{constants.SOURCE_PREFIX}{key}"] = _source_info_python_type( - self._source_info.get(key) - ) + name = f"{constants.SOURCE_PREFIX}{key}" + if typed is not None and name in typed.column_names: + schema[name] = _token_python_type(typed.schema.field(name).type) + else: + schema[name] = _source_info_python_type(self._source_info.get(key)) return Schema(schema) def arrow_schema( @@ -859,19 +982,11 @@ def with_columns_of(self, other: "DataProtocol", names: "Sequence[str]") -> Self values a function returned, are not converted again. Used for the columns of data-tags that fall through a function pod. - The intended rule (developer, November 27, 2026): a data-tag that falls - through a function pod keeps its source-info token with its type - unchanged. A column a function returns is never a pass-through, even with - an input's name and value: its token points to the function. The type of - every source-info token column is fixed by the pipeline and is not meant - to be taken from values: each source and operator determines its output - token columns' types from its inputs' types, by its own rule, in its own - module. - - Stopgap, not the proper solution: today this method types the copied - tokens again from their values (``arrow_utils.source_info_arrow_type``), - so a copied token's declared type may not be kept (a ``fixed_size_list`` - token becomes a ``large_list``). ITL-1491 removes it. + A data-tag that falls through a function pod keeps its source-info token + with its type unchanged (developer, November 27, 2026, ITL-1491): the added + columns' token columns are ``other``'s, never typed again from their + values. A column a function returns is never a pass-through, even with an + input's name and value: its token points to the function. Args: other: The data to take the columns from. @@ -908,20 +1023,35 @@ def with_columns_of(self, other: "DataProtocol", names: "Sequence[str]") -> Self new_p._data_arrow_schema = None # The added columns' source info is ``other``'s; an entry this data holds for # one of them (it does not hold the column) does not override it. + # A taken column has a token only when ``other`` shows a token column for + # it, so the row has the token columns of the same row built by hand. + theirs = other.as_table(columns={"source": True}) new_p._source_info = { - **{name: other_info.get(name) for name in names}, + **{ + name: other_info.get(name) + for name in names + if f"{constants.SOURCE_PREFIX}{name}" in theirs.column_names + }, **{k: v for k, v in self._source_info.items() if k not in names}, } new_p._source_info_table = None - # STOPGAP, not the proper solution (developer, November 27, 2026; - # ITL-1491 removes it): the copied columns' typed token columns are not - # kept, so the copied tokens are typed again from their values. A - # data-tag that falls through a function pod is meant to keep its token - # with its type unchanged. This row's own typed columns, when it has - # them, are kept. - self._keep_typed_tokens( - new_p, {k: k for k in Datagram.keys(self) if k not in names} - ) + # The added columns keep the token columns ``other`` carries, with their + # types (the pipeline determines a token column's type; ITL-1491); this + # row's own are its typed columns when it has them, and typed from their + # values otherwise (a function's output, whose tokens are created here). + kept = { + name: theirs.column(f"{constants.SOURCE_PREFIX}{name}") + for name in names + if f"{constants.SOURCE_PREFIX}{name}" in theirs.column_names + } + own = self._typed_source_info + if own is not None: + kept |= { + name.removeprefix(constants.SOURCE_PREFIX): own.column(name) + for name in own.column_names + if name.removeprefix(constants.SOURCE_PREFIX) not in names + } + new_p._typed_source_info = new_p._token_columns(kept) return new_p def copy(self, include_cache: bool = True, preserve_id: bool = True) -> Self: diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index d2ff1fb3e..7f9d45ff9 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -1131,6 +1131,41 @@ def _no_content_hashes() -> pa.Array[Any]: return pa.array([], type=pa.large_string()) +def _token_rows(rows: "Sequence[pa.Table]") -> pa.Table: + """Put the one-row source-info tables of a stream's rows under one another. + + Every column keeps the Arrow type its rows carry. A row that has no column for + a token another row has (a row built from values without that token) gets a + null there. + + Args: + rows: One table of ``_source_*`` columns per row, in row order. + + Returns: + The table of every row's source-info columns, in first-seen column order, + every field nullable. + """ + types: dict[str, pa.DataType] = {} + for row in rows: + for field in row.schema: + _ = types.setdefault(field.name, field.type) + schema = pa.schema([pa.field(name, kind) for name, kind in types.items()]) + return pa.concat_tables( + [ + pa.Table.from_arrays( + [ + row.column(name) + if name in row.column_names + else pa.nulls(row.num_rows, kind) # pyright: ignore[reportCallIssue, reportArgumentType] # pyarrow takes any type; the stubs say an extension type + for name, kind in types.items() + ], + schema=schema, + ) + for row in rows + ] + ) + + class FunctionPodStream(StreamBase): """Recomputable stream wrapping a data function.""" @@ -1544,22 +1579,43 @@ def _table_from_pairs( {**tag_schema, **data_schema}, self.data_context.type_converter ) tag_tables: list[pa.Table] = [] + token_tables: list[pa.Table] = [] all_data = [] data_schema = None # A data-tag that falls through the pod is one column: it is laid # out from the tags, with its exact Arrow type, never converted from its # Python value (ITL-1023). shared: set[str] = set() + source_prefix = constants.SOURCE_PREFIX for tag, data in pairs: if data_schema is None: shared = set(tag.keys()) & set(data.keys()) data_schema = data.arrow_schema(all_info=True) - data_schema = pa.schema(f for f in data_schema if f.name not in shared) + data_schema = pa.schema( + f + for f in data_schema + if f.name not in shared and not f.name.startswith(source_prefix) + ) # Tags are passed through untouched: each row's own Arrow table keeps # the input's tag types, a logical type included (ITL-928). tag_tables.append(tag.as_table(columns={"system_tags": True})) + # So are the source-info tokens: each row's own token columns, with + # the types the row carries, never converted from their Python + # values (ITL-1491). + row_table = data.as_table(columns={"source": True}) + token_tables.append( + row_table.select( + [n for n in row_table.column_names if n.startswith(source_prefix)] + ) + ) row = data.as_dict(all_info=True) - all_data.append({k: v for k, v in row.items() if k not in shared}) + all_data.append( + { + k: v + for k, v in row.items() + if k not in shared and not k.startswith(source_prefix) + } + ) # TODO: re-verify the implemetation of this conversion converter = self.data_context.type_converter @@ -1567,8 +1623,8 @@ def _table_from_pairs( # The data columns have declared types: convert each value as its column's # type, never as the type the value happens to have. A subclass instance # returned for a base-class column is then refused instead of being stored - # as the base without its own fields (ITL-972). Only the remaining columns - # (meta, source info) are typed from their values. + # as the base without its own fields (ITL-972). Only the meta columns are + # typed from their values. python_schema = dict(infer_python_schema_from_pylist_data(all_data)) python_schema.update(self.output_schema()[1]) struct_data = converter.python_dicts_to_struct_dicts( @@ -1578,7 +1634,9 @@ def _table_from_pairs( all_data_as_tables: pa.Table = pa.Table.from_pylist( struct_data, schema=data_schema ) - return arrow_utils.hstack_tables(all_tags_as_tables, all_data_as_tables) + return arrow_utils.hstack_tables( + all_tags_as_tables, all_data_as_tables, _token_rows(token_tables) + ) def as_table( self, diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 43fb63fb2..3d0e1acc6 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3330,11 +3330,14 @@ def _add_pipeline_record( def _require_one_type_per_token_column(self, tokens: "pa.Table") -> None: """Refuse a row whose token column has another type than the rows recorded. - A pipeline table has one Arrow type per column. A token's type is a - function of its value (``Data.source_info_table``: a null is a - ``large_string`` null, a list a list), so rows whose tokens of one column - differ in kind (a list token and a string or null token) cannot share a - table. The types are those of the stored table (read once, by + A pipeline table has one Arrow type per column. A token column's type is + determined by the pipeline (ITL-1491), so in a pipeline built through + sources every row of one table gives a column the same type; this is the + safety net for a hand-built raw stream given straight to a node, and for + an implementation bug. A null token is recorded as a ``large_string`` null + whatever its column declares (``Data.source_info_table``), so a column + that mixes null and list tokens is refused here too. The types are those + of the stored table (read once, by ``_preflight_pipeline_write_schema``) and of the rows this node recorded since. diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index e7a1969f8..e19a8aab0 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -336,8 +336,8 @@ async def async_execute_batches( full = rows - rows % self.batch_size if not full: continue - # Arrived batches may differ in their provenance fields: put them - # under one another as a complete table settles them. + # Arrived batches may differ in their provenance fields' flags: put + # them under one another, under one schema. arrived = concatenate_batches(waiting) assert arrived is not None # they hold rows await self._send_processed( diff --git a/src/orcapod/core/operators/index.py b/src/orcapod/core/operators/index.py index cbb6c2c37..30b97bdfc 100644 --- a/src/orcapod/core/operators/index.py +++ b/src/orcapod/core/operators/index.py @@ -274,6 +274,33 @@ def unary_output_schema( # Per-packet processing # ------------------------------------------------------------------ + @staticmethod + def _element_token_type(token_type: pa.DataType) -> pa.DataType: + """The token type of an element, given the token type of its list. + + One list layer removed (a large or a fixed-size list); a token with no + layer keeps its type (the element's token is then a new string). + + Args: + token_type: The Arrow type of the indexed column's token column. + + Returns: + The Arrow type of the element's token column. + """ + if ( + pa.types.is_large_list(token_type) + or pa.types.is_list(token_type) + or pa.types.is_fixed_size_list(token_type) + ): + return token_type.value_type # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownVariableType] # a list type has a value type + return token_type + + def _token_type(self, data: DataProtocol) -> pa.DataType | None: + """The Arrow type ``data`` carries for the indexed column's token, if any.""" + name = f"{constants.SOURCE_PREFIX}{self.column}" + schema = data.arrow_schema(columns={"source": True}) + return schema.field(name).type if name in schema.names else None + def _process_one( self, tag: TagProtocol, @@ -333,13 +360,34 @@ def _process_one( ) old_src = data.source_info().get(self.column) - new_src: SourceInfoValue + new_src: "SourceInfoValue | pa.Scalar[Any]" if isinstance(old_src, list): # A many->one operator (Batch, GroupBy) left one token per member: the # element's provenance is its own token, one list level removed (the # inner list after two aggregations). ``effective_i`` is in range for # the value, and a token list holds one entry per member. - new_src = old_src[effective_i] if effective_i < len(old_src) else None + element = old_src[effective_i] if effective_i < len(old_src) else None + # The element's token has the type of the token list's items: the + # pipeline determines it, and it is never taken from the value + # (ITL-1491). + new_src = element + token_type = self._token_type(data) + if token_type is not None: + remaining = self._element_token_type(token_type) + if ( + element is None + and remaining != token_type + and (remaining != pa.large_string()) + ): + target = f"{constants.SOURCE_PREFIX}{self.out or self.column}" + raise InputValidationError( + f"Index: element {self.i} of the source-info token of column " + + f"{self.column!r} is null in the row with tag {tag}, and " + + f"the token column {target!r} it would give has type " + + f"{remaining}: a source-info token that has a list layer " + + "is never null." + ) + new_src = pa.scalar(element, type=remaining) else: new_src = f"{old_src}[{self.i}]" if old_src else None @@ -427,11 +475,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: token_name = f"{constants.SOURCE_PREFIX}{self.column}" input_token = input_schema.field(token_name) input_token_type = input_token.type - token_type = ( - input_token_type.value_type - if pa.types.is_large_list(input_token_type) - else input_token_type - ) + token_type = self._element_token_type(input_token_type) token_field = pa.field( f"{constants.SOURCE_PREFIX}{self.out or self.column}", token_type, diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 06cdcfd26..8c643807f 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -2,7 +2,7 @@ import functools import itertools import json -from collections.abc import Callable, Collection, Mapping, Sequence +from collections.abc import Callable, Collection, Sequence from typing import Any, ClassVar, get_args import polars as pl @@ -44,7 +44,7 @@ TagProtocol, ) from orcapod.system_constants import constants -from orcapod.types import ColumnConfig, ContentHash, DataType, DataValue, Schema +from orcapod.types import ColumnConfig, ContentHash, DataType, Schema from orcapod.utils import arrow_utils, schema_utils # The row-number columns of the frames Polars joins (``_inner_join``); a tag, so a @@ -179,6 +179,143 @@ def _fold_members(tokens: Sequence[str | None]) -> str: return arrow_utils.fold_system_tag_values(ordered, label=JOIN_FOLD_LABEL) +class NullTokenListError(ValueError): + """A token list that is to be merged is null where a list of tokens is declared. + + Two inputs' tokens of a merged data-tag are merged position by position. A null + where the token column's type still has a list layer (a null inner list of a + list-of-lists token) has no positions to merge. The caller, which knows the + operator and the column, raises the ``InputValidationError``. + """ + + +def _is_token_list(kind: pa.DataType | None) -> bool: + """Whether ``kind`` is a list of tokens (a large, plain or fixed-size list).""" + return kind is not None and ( + pa.types.is_large_list(kind) + or pa.types.is_list(kind) + or pa.types.is_fixed_size_list(kind) + ) + + +def _merge_typed(left: Any, right: Any, kind: pa.DataType | None) -> Any: + """Merge two inputs' tokens of one merged column, keeping the column's shape. + + ``_merge_pending`` for a token column of type ``kind``: the tokens are merged + position by position down to the strings, where the two members are held + pending. + + Args: + left: The first input's token. + right: The second input's token. + kind: The token column's Arrow type, or ``None`` when no input declares + one (rows built from values): the tokens' own shapes are then used. + + Returns: + The merged token, of the column's shape. + + Raises: + NullTokenListError: If a token is null where ``kind`` is a list. + ValueError: If the two tokens' lists differ in length, or one is a list + and the other is not (``merge_source_info``). + """ + if not _is_token_list(kind): + return _merge_pending(left, right) + if left is None or right is None: + raise NullTokenListError( + f"a null where a list of tokens (type {kind}) is declared: no stream " + + "holds one (a token's list is never null at any level)" + ) + if not (isinstance(left, list) and isinstance(right, list)): + return _merge_pending(left, right) + if len(left) != len(right): + return _merge_pending(left, right) # raises: lists of different lengths + assert kind is not None + item = kind.value_type # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownVariableType] # a list type has a value type + return [_merge_typed(a, b, item) for a, b in zip(left, right)] # pyright: ignore[reportUnknownArgumentType] + + +def null_token_list_error( + operator: str, column: str, kind: pa.DataType +) -> InputValidationError: + """Return the refusal of a merged token that holds a null list of tokens. + + Args: + operator: The operator's name. + column: The token column. + kind: The token column's Arrow type. + + Returns: + The ``InputValidationError`` naming the operator, the column and its type. + """ + return InputValidationError( + f"{operator}: the source-info token column {column!r} (type {kind}) of a " + + "data-tag both inputs hold has a null where a list of tokens is declared. " + + "The tokens of the two inputs are merged position by position, and a null " + + "list has no position to merge. Give that list its tokens (an empty list, " + + "or null tokens inside a list), or keep the column a data-tag of one " + + "input only." + ) + + +def _token_fits(value: Any, kind: pa.DataType) -> bool: + """Whether the token ``value`` can be written as ``kind`` with its shape kept. + + A string is a token of a string type only, and a list of a list type whose + items fit; a null fits any type. pyarrow would read a string given for a list + type as the list of its characters, so the shape is checked before writing. + + Args: + value: A source-info token: a string, ``None`` or a list of tokens. + kind: The Arrow type of the token column. + + Returns: + Whether ``pa.array([value], type=kind)`` holds ``value`` as it is. + """ + if value is None: + return True + if isinstance(value, str): + return pa.types.is_large_string(kind) or pa.types.is_string(kind) + if isinstance(value, list): + if not ( + pa.types.is_large_list(kind) + or pa.types.is_list(kind) + or pa.types.is_fixed_size_list(kind) + ): + return False + return all(_token_fits(item, kind.value_type) for item in value) # pyright: ignore[reportAttributeAccessIssue, reportUnknownArgumentType, reportUnknownMemberType] # a list type has a value type + return False + + +def _token_array(values: Sequence[Any], kind: pa.DataType, name: str) -> Any: + """Return the tokens ``values`` as an array of ``kind``, each with its shape kept. + + The one way the join writes a token it made (a merged token, a fold) into a + column. A stream's tokens have the shape of their column (the token-shape + rule), so every such token fits; a token that does not is never written. + + Args: + values: The tokens, one per row. + kind: The Arrow type of the token column. + name: The token column's name. + + Returns: + The array. + + Raises: + RuntimeError: If a token does not fit ``kind`` (``_token_fits``): pyarrow + would store a string given for a list type as its characters. + """ + for value in values: + if not _token_fits(value, kind): + raise RuntimeError( + f"Join: a merged source-info token of column {name!r} does not have " + + f"the shape of its type {kind}; it is not written. This is a bug in " + + "Orcapod: a stream's tokens always have the shape of their column." + ) + return pa.array(values, type=kind) + + def _fold_pending(value: Any) -> Any: """Replace every pending token position of ``value`` by its merged token.""" if isinstance(value, list): @@ -440,7 +577,7 @@ def _predict_system_tag_schema(self, *streams: StreamProtocol) -> Schema: ) return Schema( { - name: kind | None if nullable[name] else kind + name: kind | None if nullable.get(name, False) else kind for name, kind in system_tag_fields.items() } ) @@ -530,6 +667,15 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: ) require_matchable_key("Join", key, key_type) common_tag_keys.add(_COMMON_JOIN_KEY) + # The token column of a merged data-tag must have one Arrow type in + # both inputs too: the merged token takes it (ITL-1491). + for left_name, right_name in sorted(right_source.items()): + _ = require_shared_arrow_type( + "Join", + left_name, + table.schema.field(left_name).type, + next_table.schema.field(right_name).type, + ) table_ref_schema = table.schema table = _inner_join(table, next_table, list(common_tag_keys)) @@ -540,7 +686,12 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: table, table_ref_schema, next_ref_schema, common_tag_keys ) for left_name, right_name in right_source.items(): - table = self._merge_source_columns(table, left_name, right_name) + try: + table = self._merge_source_columns(table, left_name, right_name) + except NullTokenListError as error: + raise null_token_list_error( + "Join", left_name, table.schema.field(left_name).type + ) from error merged_source |= set(right_source) tag_keys.update(next_tag_keys) @@ -590,17 +741,22 @@ def _merge_source_columns( Returns: The table with ``left_name`` holding both sides' members, pending until the join folds them (``_fold_source_column``). + + Raises: + NullTokenListError: If a token is null where the column's type is a + list of tokens; the caller names the operator and the column. """ field = table.schema.field(left_name) - merged = pa.array( + merged = _token_array( [ - _merge_pending(left, right) + _merge_typed(left, right, field.type) for left, right in zip( table.column(left_name).to_pylist(), table.column(right_name).to_pylist(), ) ], - type=field.type, + field.type, + left_name, ) index = table.schema.get_field_index(left_name) table = table.set_column(index, field, merged) @@ -618,9 +774,10 @@ def _fold_source_column(table: "pa.Table", name: str) -> "pa.Table": The table with one merged token at every token position of ``name``. """ field = table.schema.field(name) - folded = pa.array( + folded = _token_array( [_fold_pending(value) for value in table.column(name).to_pylist()], - type=field.type, + field.type, + name, ) return table.set_column(table.schema.get_field_index(name), field, folded) @@ -769,8 +926,6 @@ async def _streaming_join( suffixes: Per-input system-tag suffixes (positional). """ n = len(inputs) - block_sep = constants.BLOCK_SEPARATOR - if n == 2: # Join in canonical order so the merged tag and data keys follow # the order ``output_schema`` defines, whatever the operand order. @@ -783,7 +938,7 @@ def merge_fn( rt: TagProtocol, rp: DataProtocol, ) -> tuple[TagProtocol, DataProtocol]: - return self._merge_pair_rename(lt, lp, rt, rp, pair_suffixes, block_sep) + return self._merge_pair_rename(lt, lp, rt, rp, pair_suffixes) await self._binary_streaming_join( inputs[left_idx], inputs[right_idx], output, merge_fn @@ -840,10 +995,22 @@ async def _staggered_join( """ from orcapod.channels import Channel - block_sep = constants.BLOCK_SEPARATOR - sys_prefix = constants.SYSTEM_TAG_PREFIX - canon_order = self._canonical_input_order(suffixes) + # The columns the chain's steps merge, folded by its last step only. + merged_so_far: set[str] = set() + # Each input's first row, by canonical position. A row carries its token + # columns' types, so the first row of an input is its declaration: it is + # compared with every other input's as it arrives, whether or not any row + # matches (the sync path compares the inputs' tables before it joins). + first_rows: dict[int, tuple[TagProtocol, DataProtocol]] = {} + + def declare(position: int, tag: TagProtocol, data: DataProtocol) -> None: + for other, (other_tag, other_data) in sorted(first_rows.items()): + if other < position: + self._check_merged_token_types(other_tag, other_data, tag, data) + else: + self._check_merged_token_types(tag, data, other_tag, other_data) + first_rows[position] = (tag, data) async with asyncio.TaskGroup() as tg: # Pre-rename system tags for each input so binary joins @@ -851,15 +1018,14 @@ async def _staggered_join( renamed_readers: list[ ReadableChannel[tuple[TagProtocol, DataProtocol]] ] = [] - for orig_idx in canon_order: + for position, orig_idx in enumerate(canon_order): ch: Channel[tuple[TagProtocol, DataProtocol]] = Channel(buffer_size=64) tg.create_task( self._rename_sys_tags( inputs[orig_idx], ch.writer, suffixes[orig_idx], - block_sep, - sys_prefix, + functools.partial(declare, position), ) ) renamed_readers.append(ch.reader) @@ -881,7 +1047,11 @@ async def _staggered_join( current_reader, renamed_readers[i], target_writer, - functools.partial(self._merge_pair_passthrough, final=is_last), + functools.partial( + self._merge_pair_passthrough, + final=is_last, + merged_so_far=merged_so_far, + ), ) ) @@ -962,6 +1132,15 @@ async def _drain( self._check_shared_key_types( tag, buffers[other][0][0], shared_keys ) + # The same for the token column of a data-tag both sides + # hold, which the join merges (side 0 is the earlier input). + rows = [buffers[other][0], (tag, pkt)] + (first_tag, first), (second_tag, second) = ( + rows if other == 0 else rows[::-1] + ) + self._check_merged_token_types( + first_tag, first, second_tag, second + ) # The same, for a name that is a tag on one side and a data # column on the other (the sync path checks the schemas). try: @@ -1065,27 +1244,26 @@ async def _rename_sys_tags( ch_in: ReadableChannel[tuple[TagProtocol, DataProtocol]], ch_out: WritableChannel[tuple[TagProtocol, DataProtocol]], suffix: str, - block_sep: str, - sys_prefix: str, + on_first_row: Callable[[TagProtocol, DataProtocol], None], ) -> None: """Read rows and rename system-tag keys by appending the per-input suffix. Used as a pre-processing step in ``_staggered_join`` so that downstream binary joins can pass system tags through without modification. The tag's user columns keep their Arrow table. + ``on_first_row`` is given the input's first row before it is passed on. """ try: + first = True async for tag, pkt in ch_in: - sys_tags = tag.system_tags() - if sys_tags: - renamed: dict[str, DataValue] = {} - for k, v in sys_tags.items(): - new_key = ( - f"{k}{block_sep}{suffix}" if k.startswith(sys_prefix) else k - ) - renamed[new_key] = v + if first: + first = False + on_first_row(tag, pkt) + if (system_tags := Join._system_tag_table(tag)) is not None: tag = Join._build_tag( - Join._merge_tag_tables(tag, None), renamed, tag.data_context_key + Join._merge_tag_tables(tag, None), + arrow_utils.append_to_system_tags(system_tags, suffix), + tag.data_context_key, ) await ch_out.send((tag, pkt)) finally: @@ -1156,10 +1334,31 @@ def _merge_tag_tables( ] return pa.Table.from_arrays(columns, schema=pa.schema(list(fields.values()))) + @staticmethod + def _system_tag_table(tag: TagProtocol) -> "pa.Table | None": + """Return the system-tag columns of a row, with their Arrow fields.""" + columns = {"system_tags": True} + names = [ + name + for name in tag.keys(columns=columns) + if name.startswith(constants.SYSTEM_TAG_PREFIX) + ] + return tag.as_table(columns=columns).select(names) if names else None + + @staticmethod + def _join_system_tag_tables( + tables: Sequence["pa.Table | None"], + ) -> "pa.Table | None": + """Join the system-tag tables and sort tied positions.""" + present = [table for table in tables if table is not None] + if not present: + return None + return arrow_utils.sort_system_tag_values(arrow_utils.hstack_tables(*present)) + @staticmethod def _build_tag( table: "pa.Table | None", - system_tags: Mapping[str, DataValue], + system_tags: "pa.Table | None", data_context_key: str, ) -> TagProtocol: """Build a ``Tag`` from a merged Arrow table and its system tags. @@ -1175,8 +1374,13 @@ def _build_tag( from orcapod.core.datagrams import Tag if table is None: - return Tag({}, system_tags=system_tags, data_context=data_context_key) - return Tag(table, system_tags=system_tags, data_context=data_context_key) + return Tag( + system_tags if system_tags is not None else {}, + data_context=data_context_key, + ) + if system_tags is not None: + table = arrow_utils.hstack_tables(table, system_tags) + return Tag(table, data_context=data_context_key) @staticmethod def _merge_data( @@ -1185,6 +1389,7 @@ def _merge_data( right_tag: TagProtocol, right: DataProtocol, final: bool = True, + merged_so_far: set[str] | None = None, ) -> DataProtocol: """Merge two data datagrams as Arrow, left columns first. @@ -1204,6 +1409,9 @@ def _merge_data( final: Whether this row is emitted by the join (the last step of a staggered chain, or a two-input join): then every merged column's pending members are folded into merged tokens. + merged_so_far: The columns the steps of one join have merged so far, + shared by the steps of a staggered chain and added to here; only + these are folded. ``None`` for a join of one step. Returns: The merged data, in the context of ``left``. @@ -1214,6 +1422,8 @@ def _merge_data( """ from orcapod.core.datagrams import Data + if merged_so_far is None: + merged_so_far = set() left_table, right_table = left.as_table(), right.as_table() merged = Join._merged_data_tags( left_tag.keys(), @@ -1226,17 +1436,59 @@ def _merge_data( raise InputValidationError( f"Join: inputs share data columns {sorted(overlap - merged)}." ) - source_info = {**left.source_info(), **right.source_info()} - if merged: - left_info, right_info = left.source_info(), right.source_info() - for name in merged: - source_info[name] = _merge_pending( - left_info.get(name), right_info.get(name) + # Each column's token goes on as the typed column its row carries: the + # pipeline determines a token column's type, and it is never taken from a + # value (ITL-1491). Only a token the join makes is given: the token of a + # merged data-tag, from both sides' tokens, and, when the row is emitted, + # the fold of the members this or an earlier step of the chain left + # pending. Only columns the join merged are folded (``merged_so_far``): a + # column's own token is the user's, whatever it looks like. + declared = Join._declared_token_types(left, right) + left_info, right_info = left.source_info(), right.source_info() + source_info: dict[str, Any] = {} + for name in sorted(merged): + try: + source_info[name] = _merge_typed( + left_info.get(name), right_info.get(name), declared.get(name) ) + except NullTokenListError as error: + raise null_token_list_error( + "Join", f"{constants.SOURCE_PREFIX}{name}", declared[name] + ) from error + merged_so_far.update(merged) if final: + carried = {**left_info, **right_info, **source_info} source_info = { - name: _fold_pending(value) for name, value in source_info.items() + name: _fold_pending(carried[name]) + for name in sorted(merged_so_far) + if name in carried } + made = set(source_info) + tokens = Join._token_columns(left, made) + Join._token_columns(right, made) + # A token the join makes is written with the type its column declares in + # the inputs, as the sync path writes it into the left input's column; it + # is given as a value only when no input declares a type for it (rows + # built from values). + typed_names = [name for name in source_info if name in declared] + if typed_names: + tokens.append( + pa.Table.from_arrays( + [ + _token_array( + [source_info.pop(name)], + declared[name], + f"{constants.SOURCE_PREFIX}{name}", + ) + for name in typed_names + ], + schema=pa.schema( + [ + pa.field(f"{constants.SOURCE_PREFIX}{name}", declared[name]) + for name in typed_names + ] + ), + ) + ) # Column order as ``static_process`` lays it out: the data-tag columns # first, in the merged tag order, then each side's other data columns. tag_order = [*left_tag.keys()] @@ -1248,7 +1500,7 @@ def _merge_data( ] if not with_data_tags: return Data( - arrow_utils.hstack_tables(left_table, right_table), + arrow_utils.hstack_tables(left_table, right_table, *tokens), source_info=source_info, data_context=left.data_context_key, ) @@ -1280,11 +1532,88 @@ def _merge_data( schema=pa.schema(fields), ) return Data( - arrow_utils.hstack_tables(data_tags, left_rest, right_rest), + arrow_utils.hstack_tables(data_tags, left_rest, right_rest, *tokens), source_info=source_info, data_context=left.data_context_key, ) + @staticmethod + def _declared_token_types(*rows: DataProtocol) -> dict[str, pa.DataType]: + """Return the type each row declares for its token columns, by data column. + + Args: + *rows: Rows, in the canonical order of their inputs; the first row that + has a token column for a name gives its type. + + Returns: + The Arrow type of each ``_source_`` column, keyed by ``name``. + """ + declared: dict[str, pa.DataType] = {} + for row in rows: + for field in row.arrow_schema(columns={"source": True}): + if field.name.startswith(constants.SOURCE_PREFIX): + _ = declared.setdefault( + field.name.removeprefix(constants.SOURCE_PREFIX), field.type + ) + return declared + + @staticmethod + def _check_merged_token_types( + first_tag: TagProtocol, + first: DataProtocol, + second_tag: TagProtocol, + second: DataProtocol, + ) -> None: + """Raise if a merged data-tag's token column has two types in two inputs. + + The async counterpart of the check ``static_process`` runs on the input + tables before its join, applied to the first row of each side, so the error + does not depend on whether any key matches. + + Args: + first_tag: A tag from the canonically earlier input. + first: Its data. + second_tag: A tag from the other input. + second: Its data. + + Raises: + InputValidationError: If the large-normalized Arrow types of a merged + data-tag's token column differ (``require_shared_arrow_type``). + """ + merged = Join._merged_data_tags( + first_tag.keys(), + data_tag_names(first_tag.keys(), first.keys()), + second_tag.keys(), + data_tag_names(second_tag.keys(), second.keys()), + ) + left = Join._declared_token_types(first) + right = Join._declared_token_types(second) + for name in sorted(merged & left.keys() & right.keys()): + _ = require_shared_arrow_type( + "Join", f"{constants.SOURCE_PREFIX}{name}", left[name], right[name] + ) + + @staticmethod + def _token_columns(data: DataProtocol, merged: Collection[str]) -> list[pa.Table]: + """Return ``data``'s source-info columns, without those of ``merged`` columns. + + Args: + data: One side's row. + merged: The columns whose token the join makes, given as a value. + + Returns: + A list holding the one-row table of the kept ``_source_*`` columns, with + the types the row carries; an empty list when no column is kept. + """ + table = data.as_table(columns={"source": True}) + kept = [ + name + for name in table.column_names + if name.startswith(constants.SOURCE_PREFIX) + and name.removeprefix(constants.SOURCE_PREFIX) not in merged + ] + return [table.select(kept)] if kept else [] + @staticmethod def _merge_pair_rename( left_tag: TagProtocol, @@ -1292,7 +1621,6 @@ def _merge_pair_rename( right_tag: TagProtocol, right_pkt: DataProtocol, suffixes: list[str], - block_sep: str, ) -> tuple[TagProtocol, DataProtocol]: """Merge a matched pair, renaming system tags with per-side suffixes. @@ -1300,18 +1628,13 @@ def _merge_pair_rename( during the merge (not pre-renamed). The merged row is built from the inputs' Arrow tables, in the left (canonically first) tag's context. """ - sys_prefix = constants.SYSTEM_TAG_PREFIX - - # Rename and merge system tags - merged_sys: dict[str, DataValue] = {} - for i, tag in enumerate((left_tag, right_tag)): - for k, v in tag.system_tags().items(): - new_key = ( - f"{k}{block_sep}{suffixes[i]}" if k.startswith(sys_prefix) else k - ) - merged_sys[new_key] = v - - merged_sys = Join._sort_merged_system_tags(merged_sys) + tables = [ + arrow_utils.append_to_system_tags(table, suffix) + if (table := Join._system_tag_table(tag)) is not None + else None + for tag, suffix in zip((left_tag, right_tag), suffixes, strict=True) + ] + merged_sys = Join._join_system_tag_tables(tables) merged_tag = Join._build_tag( Join._merge_tag_tables(left_tag, right_tag), merged_sys, @@ -1326,88 +1649,33 @@ def _merge_pair_passthrough( right_tag: TagProtocol, right_pkt: DataProtocol, final: bool = True, + merged_so_far: set[str] | None = None, ) -> tuple[TagProtocol, DataProtocol]: """Merge a matched pair, passing system tags through without renaming. Used in the staggered chain where system tags have already been pre-renamed by ``_rename_sys_tags``. The merged row is built from the inputs' Arrow tables, in the left (canonically first) tag's context. - ``final`` is true only for the chain's last step (see ``_merge_data``). + ``final`` is true only for the chain's last step, and ``merged_so_far`` + is the chain's one set of merged columns (see ``_merge_data``). """ - # Combine system tags (already renamed) - merged_sys: dict[str, DataValue] = {} - merged_sys.update(left_tag.system_tags()) - merged_sys.update(right_tag.system_tags()) - - # Sort within same-provenance-path groups for commutativity - merged_sys = Join._sort_merged_system_tags(merged_sys) + merged_sys = Join._join_system_tag_tables( + [Join._system_tag_table(left_tag), Join._system_tag_table(right_tag)] + ) merged_tag = Join._build_tag( Join._merge_tag_tables(left_tag, right_tag), merged_sys, left_tag.data_context_key, ) return merged_tag, Join._merge_data( - left_tag, left_pkt, right_tag, right_pkt, final=final + left_tag, + left_pkt, + right_tag, + right_pkt, + final=final, + merged_so_far=merged_so_far, ) - @staticmethod - def _sort_merged_system_tags(merged_sys: dict) -> dict: - """Sort system tag values within same-provenance-path groups. - - When two joined inputs share a pipeline_hash, their system tag - columns share a provenance path but occupy different canonical - positions. Sorting the paired (source_id, record_id) values - across positions ensures commutativity — mirroring what - ``sort_system_tag_values`` does on Arrow tables in - ``static_process``. - """ - sys_prefix = constants.SYSTEM_TAG_PREFIX - block_sep = constants.BLOCK_SEPARATOR - field_sep = constants.FIELD_SEPARATOR - - # Parse keys → groups[provenance_path][position][field_type] = key - groups: dict[str, dict[str, dict[str, str]]] = {} - for key in merged_sys: - if not key.startswith(sys_prefix): - continue - base, sep, position = key.rpartition(field_sep) - if not sep or not position.isdigit(): - continue - after_prefix = base[len(sys_prefix) :] - field_type, bsep, prov_path = after_prefix.partition(block_sep) - if not bsep: - continue - groups.setdefault(prov_path, {}).setdefault(position, {})[field_type] = key - - sid_field = constants.SYSTEM_TAG_SOURCE_ID_PREFIX[len(sys_prefix) :] - rid_field = constants.SYSTEM_TAG_RECORD_ID_PREFIX[len(sys_prefix) :] - - for _prov_path, positions in groups.items(): - if len(positions) <= 1: - continue - - sorted_pos_keys = sorted(positions.keys(), key=int) - - # Collect (sort_key, {field_type: value}) per position - entries: list[tuple[tuple, dict[str, object]]] = [] - for pos in sorted_pos_keys: - fmap = positions[pos] - sid_val = merged_sys.get(fmap.get(sid_field, "")) - rid_val = merged_sys.get(fmap.get(rid_field, "")) - vals = {ft: merged_sys[k] for ft, k in fmap.items()} - entries.append(((sid_val or "", rid_val or b""), vals)) - - entries.sort(key=lambda e: e[0]) - - # Write sorted values back to the original position keys - for pos, (_, sorted_vals) in zip(sorted_pos_keys, entries): - fmap = positions[pos] - for field_type, key in fmap.items(): - if field_type in sorted_vals: - merged_sys[key] = sorted_vals[field_type] - - return merged_sys - def rows_dropped_text( self, position: int, diff --git a/src/orcapod/core/operators/merge_join.py b/src/orcapod/core/operators/merge_join.py index 88abafc5a..624f00d75 100644 --- a/src/orcapod/core/operators/merge_join.py +++ b/src/orcapod/core/operators/merge_join.py @@ -13,6 +13,8 @@ ) from orcapod.core.operators.join import ( _MERGED_SOURCE_PREFIX, # pyright: ignore[reportPrivateUsage] # one definition, shared with Join + NullTokenListError, + null_token_list_error, _inner_join, # pyright: ignore[reportPrivateUsage] # one definition, shared with Join _COMMON_JOIN_KEY, # pyright: ignore[reportPrivateUsage] # one definition, shared with Join _with_common_key, # pyright: ignore[reportPrivateUsage] # one definition, shared with Join @@ -54,7 +56,9 @@ def _output_types( Column name to its output Arrow type, for every column of either input. """ resolved: dict[str, pa.DataType] = {} - for name in left_types.keys() | right_types.keys(): + # In name order: which disagreement is reported first never follows a set's + # order (and so the hash seed). + for name in sorted(left_types.keys() | right_types.keys()): left_type, right_type = left_types.get(name), right_types.get(name) if left_type is not None and right_type is not None: resolved[name] = require_shared_arrow_type( @@ -424,6 +428,17 @@ def binary_static_process( for name in sorted(merged) if f"{constants.SOURCE_PREFIX}{name}" in right_table.column_names } + # The two tokens become one of the type both inputs declare: compared + # before the second input's column is renamed, so the outcome never + # depends on whether a row matches (ITL-1491). + for left_name in sorted(right_source): + if left_name in left_table.column_names: + _ = require_shared_arrow_type( + "MergeJoin", + left_name, + left_table.schema.field(left_name).type, + right_table.schema.field(left_name).type, + ) if right_source: right_table = right_table.rename_columns( [right_source.get(c, c) for c in right_table.column_names] @@ -494,7 +509,12 @@ def binary_static_process( joined = _inner_join(left_table, right_table, join_keys) joined = joined.drop(_COMMON_JOIN_KEY) for left_name, right_name in right_source.items(): - joined = Join._merge_source_columns(joined, left_name, right_name) # pyright: ignore[reportPrivateUsage] # Join's one rule + try: + joined = Join._merge_source_columns(joined, left_name, right_name) # pyright: ignore[reportPrivateUsage] # Join's one rule + except NullTokenListError as error: + raise null_token_list_error( + "MergeJoin", left_name, joined.schema.field(left_name).type + ) from error joined = Join._fold_source_column(joined, left_name) # pyright: ignore[reportPrivateUsage] # Join's one rule # Use the left stream's type converter — not the default context — so that a diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index cae6813fe..25b1ba4e5 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -16,7 +16,6 @@ from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, cast import pyarrow as pa -import pyarrow.compute as pc from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, @@ -88,9 +87,9 @@ class RowBuiltFormUnavailable(ValueError): class SourceInfoTypesDisagree(RowBuiltFormUnavailable): - """Two rows give one source-info column different types (``_row_built_form``). + """Two record batches of one stream declare one source-info column with two types. - A table built from such rows cannot be concatenated. + A table cannot be built from such batches (``settle_token_types``). """ @@ -516,23 +515,23 @@ def _kept_output( return StaticOutputOperatorPod._zero_rows_in_row_order(result) @staticmethod - def _flag_by_values(table: pa.Table) -> pa.Table: - """Flag each system-tag and source-info field nullable only when it holds a null. + def _flag_by_values(table: pa.Table, *, system_tags: bool = True) -> pa.Table: + """Flag value-based fields nullable only when they hold a null. - The last step of F (``_row_built_form``), which needs the complete table. A table - built from rows takes its system tags and source-info tokens from each row's - values, so those fields are non-nullable unless a value is missing, whatever - flags the table the rows came from had (a join over inputs tied on pipeline hash - declares its system tags nullable). The table built from rows also carries no - schema metadata (``arrow_utils.hstack_tables``), so none is kept. + The row-built form settles source-info flags from the complete table. + Callers that settle both provenance groups use this for transport layouts. + The table built from rows carries no schema metadata. Args: table: A table of user tags, system tags, data and source info. + system_tags: Also settle system-tag flags from values. Returns: The same arrays under the new field flags, with no schema metadata. """ - prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + prefixes = (constants.SOURCE_PREFIX,) + if system_tags: + prefixes = (*prefixes, constants.SYSTEM_TAG_PREFIX) fields = [ field.with_nullable(table.column(i).null_count > 0) if field.name.startswith(prefixes) @@ -542,70 +541,6 @@ def _flag_by_values(table: pa.Table) -> pa.Table: # Same arrays, new field flags: no cast, so no value or type can change. return pa.Table.from_arrays(table.columns, schema=pa.schema(fields)) - @staticmethod - def _type_source_info_by_values(table: pa.Table) -> pa.Table: - """Type each source-info column from its tokens, as the rows of a table built from rows do. - - A step of F (``_row_built_form``) on the complete table, beside - ``_flag_by_values``. A row's ``Data`` types each source-info token from its - value (``arrow_utils.source_info_arrow_type``, the one rule): a string or - ``None`` as ``large_string``, a list as ``large_list`` of its first informative - element's type, so a list of ``None`` or of empty lists shows fewer levels than - its column may declare. The rows' tables are then concatenated, which needs - every row to give a column one type. This step gives each column that type, - built from the same values. A ``large_string`` column is every row's type - already and is left as it is. - - Stopgap, not the proper solution (developer, November 27, 2026): this - step infers a token column's declared type again from its values. A - token column's type is fixed by the pipeline and is not meant to be - taken from values. The inference can narrow a declared type (example: - ``[None]`` in a token column a ``Batch`` declares with two list levels - infers one). ITL-1491 removes it. - - Args: - table: A table of user tags, system tags, data and source info, after the - per-slice steps (``streams.base.row_built_columns``). - - Returns: - The table with each source-info column of the type its tokens give. - - Raises: - SourceInfoTypesDisagree: If two rows give one source-info column different - types, where the rows' tables cannot be concatenated. The caller builds - the rows (``_rows_to_table``), which raises the error a table built from - rows raises. - """ - from orcapod.utils import arrow_utils - - columns = list(table.columns) - fields = list(table.schema) - changed = False - for index, field in enumerate(fields): - if not field.name.startswith(constants.SOURCE_PREFIX): - continue - if pa.types.is_large_string(field.type): - continue - values = table.column(index).to_pylist() - kinds = {arrow_utils.source_info_arrow_type(value) for value in values} - if len(kinds) != 1: - raise SourceInfoTypesDisagree(field.name) - (kind,) = kinds - if kind == field.type: - continue - columns[index] = pa.chunked_array([pa.array(values, type=kind)]) - fields[index] = pa.field(field.name, kind, nullable=field.nullable) - changed = True - if not changed: - return table - return pa.Table.from_arrays( - columns, - schema=pa.schema( - fields, - cast("dict[bytes | str, bytes | str] | None", table.schema.metadata), - ), - ) - @staticmethod def _row_built_form( table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] @@ -615,11 +550,14 @@ def _row_built_form( F in the ITL-1347 spec: the same table, without making the rows. Two steps: - per slice (``streams.base.row_built_columns``), what each row decides on its - own: the columns, their order, their large types, and the provenance fields' - form (no system-tag field metadata, source-info lists of nullable items); - - on the complete table, what depends on the values of every row: each - source-info column's type, from its tokens (``_type_source_info_by_values``), - then the system-tag and source-info field flags (``_flag_by_values``). + own: the columns, their order, the declared system-tag fields, and the + source-info fields in the form the rows give them; + - on the complete table, settle the source-info field flags from the values + of every row (``_flag_by_values``). + + A source-info column keeps its type: the pipeline determines it, and a row + carries the typed column, so neither the rows nor F type a token from its + value (developer, November 27, 2026, ITL-1491). The equality with ``_rows_to_table`` is tested over every operator, source kind, column role and raw-stream provenance shape (ITL-1347, L0-L2). @@ -633,16 +571,14 @@ def _row_built_form( The table ``_rows_to_table`` would build from its rows. Raises: - RowBuiltFormUnavailable: If the whole table cannot be built: the rows' - tokens give a source-info column two types - (``SourceInfoTypesDisagree``), or an Arrow conversion fails. The node - then builds its rows (``_raise_as_rows_do``). + RowBuiltFormUnavailable: If the whole table cannot be built because an + Arrow conversion fails. The node then builds its rows + (``_raise_as_rows_do``). """ try: return StaticOutputOperatorPod._flag_by_values( - StaticOutputOperatorPod._type_source_info_by_values( - row_built_columns(table, keys) - ) + row_built_columns(table, keys), + system_tags=False, ) except RowBuiltFormUnavailable: raise @@ -1140,9 +1076,8 @@ async def async_execute_batches( try: if self.ROW_BY_ROW: (channel,) = inputs - # The input's token types across its batches: a batch whose tokens - # cannot make one table with the earlier ones is refused, as the sync - # path refuses the whole input, never processed alone. + # The input's token types across its batches: a batch that declares + # another type than the earlier ones is refused, never processed alone. settled: dict[str, pa.DataType] = {} async for batch in channel: settled = settle_token_types(batch, settled) @@ -1317,10 +1252,10 @@ def stream_from_batches( (``InputChannel.to_stream``), and the record batches a row-by-row operator is applied to. The batches are put under one another in the order given, and the table is handed on as a node hands its rows to its successors - (``_output_stream``): in the row-built form, each system-tag and source-info field - flagged nullable only when one of its values is null (decided over the complete - table, never per batch), with ``stream``'s identity: its producer, upstreams, - pipeline hash and data context. With no batch it is ``stream``'s zero-row input, + (``_output_stream``): declared system-tag flags are restored and source-info + flags are settled from values over the complete table. The result keeps + ``stream``'s producer, upstreams, pipeline hash and data context. + With no batch it is ``stream``'s zero-row input, typed by its description and never by rows. Args: @@ -1335,6 +1270,20 @@ def stream_from_batches( table = concatenate_batches(batches) if table is None: return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator + declared = typed_zero_row_table(stream) + fields = [] + for field, column in zip(table.schema, table.columns, strict=True): + if field.name.startswith(constants.SYSTEM_TAG_PREFIX): + typed = ( + declared.schema.field(field.name) + if declared is not None and field.name in declared.column_names + else None + ) + field = field.with_nullable( + typed.nullable if typed is not None else column.null_count > 0 + ) + fields.append(field) + table = pa.Table.from_arrays(table.columns, schema=pa.schema(fields)) return StaticOutputOperatorPod._output_stream( # pyright: ignore[reportPrivateUsage] # F and the identity, stage 2's table, _keys_in_delivered_order(stream.keys(), table.column_names), stream ) @@ -1375,11 +1324,13 @@ def settle_token_types( ) -> dict[str, pa.DataType]: """Each source-info column's token type, settled with the batches accepted so far. - A source-info column's type follows its tokens over the complete table, as a row - types each token from its value (``arrow_utils.source_info_arrow_type``, the one - rule ``_type_source_info_by_values`` applies). A batch with no rows has no token - and settles nothing. Every token of the batch must then be representable in its - column's settled type, so that the complete table can be built. + A source-info column's type is the one its batch declares: the pipeline determines + it, and it is never taken from the tokens' values (developer, November 27, 2026, + ITL-1491). Every batch of one stream therefore declares the same type, compared + strictly (list kind, depth, and each item field's name, nullability and + metadata), so that the order of the batches never decides the table's type; a + batch that declares another is refused. A batch with no rows has no token and settles + nothing (its column may be of the ``null`` type of a zero-row form). Args: batch: A record batch of a stream's rows. @@ -1389,122 +1340,33 @@ def settle_token_types( The token types with this batch accepted. Raises: - SourceInfoTypesDisagree: If the batch's tokens give a column two types, or a + SourceInfoTypesDisagree: If the batch declares, for a source-info column, a type other than the accepted batches'. - RowBuiltFormUnavailable: If a token cannot be represented in its column's - settled type. """ - from orcapod.utils import arrow_utils - settled = dict(accepted) if not batch.num_rows: return settled # no token: nothing to learn - for field, column in zip(batch.schema, batch.columns, strict=True): + for field in batch.schema: if not field.name.startswith(constants.SOURCE_PREFIX): continue - kinds: set[pa.DataType] - if pa.types.is_large_string(field.type): - kinds = {pa.large_string()} - else: - kinds = { - arrow_utils.source_info_arrow_type(value) - for value in column.to_pylist() - } - if field.name in settled: - kinds.add(settled[field.name]) - if len(kinds) > 1: + accepted_type = settled.setdefault(field.name, field.type) + # Strictly: the item fields' names, nullability and metadata too. pyarrow's + # ``==`` takes lists with differently named items as equal, and a table + # made of such batches would take the first batch's name. + if not accepted_type.equals(field.type, check_metadata=True): raise SourceInfoTypesDisagree(field.name) - (kind,) = kinds - _ = _named_tokens_as(column, kind, field.name) # representable, or refused - settled[field.name] = kind return settled -def tokens_as(column: pa.Array[Any], kind: pa.DataType) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # any column - """``column``'s source-info tokens as an array of ``kind``, every value kept. - - The same array when it has that type. A token type that one batch's values give - (``arrow_utils.source_info_arrow_type``) can be shallower than another's (a null - or an empty list fixes fewer list levels); converting keeps every token, and a - token that ``kind`` cannot hold is refused, never changed. - - Args: - column: Source-info tokens. - kind: A token type (``large_string``, or ``large_list`` of a token type). - - Returns: - The tokens as ``kind``. - - Raises: - RowBuiltFormUnavailable: If a token cannot be represented as ``kind``. - """ - return _tokens_into(column, kind) - - -def _tokens_into(column: pa.Array[Any], kind: pa.DataType) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # any column - """``tokens_as``, level by level, never reading a value as another shape. - - A level whose values are all null (or that has none) takes ``kind`` as it is; two - list levels convert their values; any other difference is refused. A value is - never re-read in another type (pyarrow reads a string as a list of characters). - - Raises: - RowBuiltFormUnavailable: If a token cannot be represented as ``kind``. - """ - if column.type == kind: - return column - if column.null_count == len(column): - return pa.nulls(len(column), kind) # pyright: ignore[reportCallIssue, reportArgumentType] # pyarrow takes any type; the stubs say an extension type - lists = (pa.ListType, pa.LargeListType) - if isinstance(column.type, lists) and isinstance(kind, lists): - # The slice's own lists: its values, and offsets from its lists' lengths (a - # null list holds none), so a sliced array converts as its rows say. - values = _tokens_into(pc.list_flatten(column), kind.value_type) # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType] - lengths = pc.fill_null(pc.list_value_length(column), 0) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType, reportArgumentType] # pyarrow takes a Python fill value - offset_type = pa.int64() if isinstance(kind, pa.LargeListType) else pa.int32() - offsets = pa.concat_arrays( - [ - pa.array([0], offset_type), - pc.cumulative_sum(lengths).cast(offset_type), # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType] - ] - ) - build = ( - pa.LargeListArray.from_arrays - if isinstance(kind, pa.LargeListType) - else pa.ListArray.from_arrays - ) - return build(offsets, values, type=kind, mask=column.is_null()) # pyright: ignore[reportUnknownVariableType, reportCallIssue, reportArgumentType] # the offsets' width follows ``kind`` - raise RowBuiltFormUnavailable( - f"a token of type {column.type} cannot be represented as {kind}" - ) - - -def _named_tokens_as( - column: pa.Array[Any], # pyright: ignore[reportExplicitAny] # any column - kind: pa.DataType, - name: str, -) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # any column - """``tokens_as`` for the source-info column ``name``, whose name a refusal gives. - - Raises: - RowBuiltFormUnavailable: If a token cannot be represented as ``kind``. - """ - try: - return tokens_as(column, kind) - except RowBuiltFormUnavailable as error: - raise RowBuiltFormUnavailable(f"{name}: {error}") from error - - def concatenate_batches(batches: Sequence[pa.RecordBatch]) -> pa.Table | None: """Put a stream's record batches under one another, or ``None`` with no row. - Batches built from different rows may differ in their provenance fields: a - system-tag or source-info field's nullability, and a source-info column's token - type, follow each batch's own values. Each source-info column is brought to the - type its tokens settle over all the batches (``settle_token_types``), and every - provenance field is flagged nullable, so that the batches have one schema; the - complete table's flags and types are then set by its values (``_row_built_form``). - A batch with no rows is left out. The values are unchanged. + Batches may differ in the top-level flags of system-tag and source-info + fields. These fields are flagged nullable so the batches can share a schema. + ``stream_from_batches`` restores the declared system-tag flags, and + ``_row_built_form`` settles source-info flags from the complete table. Each + source-info column keeps the type declared by every batch + (``settle_token_types``). A batch with no rows is left out. Args: batches: Record batches of one stream's rows, in order. @@ -1513,9 +1375,8 @@ def concatenate_batches(batches: Sequence[pa.RecordBatch]) -> pa.Table | None: The table, or ``None`` when no batch has a row. Raises: - SourceInfoTypesDisagree: If the tokens give a source-info column two types. - RowBuiltFormUnavailable: If a token cannot be represented in its column's - settled type. + SourceInfoTypesDisagree: If two batches declare a source-info column with + two types. """ rows = [batch for batch in batches if batch.num_rows] if not rows: @@ -1529,9 +1390,6 @@ def concatenate_batches(batches: Sequence[pa.RecordBatch]) -> pa.Table | None: columns: list[Any] = [] # pyright: ignore[reportExplicitAny] # any column fields: list[pa.Field[Any]] = [] # pyright: ignore[reportExplicitAny] # any field for field, column in zip(batch.schema, batch.columns, strict=True): - if field.name in settled: - column = _named_tokens_as(column, settled[field.name], field.name) - field = pa.field(field.name, settled[field.name]) if field.name.startswith(prefixes): field = field.with_nullable(True) columns.append(column) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index fae5beed5..bac090655 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -93,8 +93,10 @@ _COMMON_JOIN_KEY, # pyright: ignore[reportPrivateUsage] # Join's one rule _MERGED_SOURCE_PREFIX, # pyright: ignore[reportPrivateUsage] # Join's one rule Join, + NullTokenListError, _matched_pairs, # pyright: ignore[reportPrivateUsage] # Join's one rule _with_common_key, # pyright: ignore[reportPrivateUsage] # Join's one rule + null_token_list_error, ) from orcapod.core.operators.base import require_shared_arrow_type from orcapod.core.operators.key_nullability import key_nullable @@ -112,10 +114,8 @@ _has_whole_key, # pyright: ignore[reportPrivateUsage] # SemiJoin's one rule ) from orcapod.core.operators.static_output_pod import ( - RowBuiltFormUnavailable, StaticOutputOperatorPod, settle_token_types, - tokens_as, ) from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns from orcapod.protocols.core_protocols import StreamProtocol @@ -625,21 +625,17 @@ def _as_input_table(self, input_index: int, batch: pa.RecordBatch) -> pa.Table: table = pa.Table.from_batches([batch]).select(layout.names) columns = list(table.columns) for index, (field, actual) in enumerate(zip(layout, table.schema)): - if field.type == actual.type: + # The pipeline declares token types including nested item fields. + if field.type.equals( + actual.type, + check_metadata=field.name.startswith(constants.SOURCE_PREFIX), + ): continue if not table.num_rows and pa.types.is_null(actual.type): continue - if table.num_rows and field.name.startswith(constants.SOURCE_PREFIX): - # A batch's token type follows its own tokens and can be shallower - # than the layout's (a null or an empty list fixes fewer list - # levels): the tokens are converted, every value kept. - try: - columns[index] = pa.chunked_array( - [tokens_as(table.column(index).combine_chunks(), field.type)] - ) - continue - except RowBuiltFormUnavailable: - pass + # A source-info column is held to its stream's type like any other + # column: the pipeline determines it, and a batch never brings its own + # (ITL-1491). raise ValueError( f"{type(self).__name__}: column {field.name!r} of input " + f"{input_index} is {actual.type} in a batch, but " @@ -771,7 +767,12 @@ def finish( table, left_schema, right_schema, keys ) for left_name, right_name in rename.items(): - table = Join._merge_source_columns(table, left_name, right_name) # pyright: ignore[reportPrivateUsage] # Join's one rule + try: + table = Join._merge_source_columns(table, left_name, right_name) # pyright: ignore[reportPrivateUsage] # Join's one rule + except NullTokenListError as error: + raise null_token_list_error( + "Join", left_name, table.schema.field(left_name).type + ) from error if not final: return table for name in sorted(self._merged_source): @@ -982,7 +983,12 @@ def _finish( left_names = set(left_schema.names) suffixed = (set(right_schema.names) & left_names) - self._shared_tags for left_name, right_name in self._rename.items(): - joined = Join._merge_source_columns(joined, left_name, right_name) # pyright: ignore[reportPrivateUsage] # Join's one rule + try: + joined = Join._merge_source_columns(joined, left_name, right_name) # pyright: ignore[reportPrivateUsage] # Join's one rule + except NullTokenListError as error: + raise null_token_list_error( + "MergeJoin", left_name, joined.schema.field(left_name).type + ) from error joined = Join._fold_source_column(joined, left_name) # pyright: ignore[reportPrivateUsage] # Join's one rule for name in sorted(self._colliding): source_name = f"{constants.SOURCE_PREFIX}{name}" diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 3e94bbe12..876b5e677 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -150,8 +150,8 @@ def __init__( # batch's when the stream cannot say its Arrow types without rows. self._schema: pa.Schema | None = None self._schema_known = False - # Each source-info column's token type as the batches accepted so far settle it - # (``settle_token_types``): a later batch must settle with it. + # Each source-info column's token type as the batches accepted so far declare + # it (``settle_token_types``): a later batch must declare the same. self._token_types: dict[str, pa.DataType] = {} # The column order of the channel's batches: the first batch with rows'. self._order: list[str] | None = None @@ -405,6 +405,19 @@ def _named(stream: Any) -> str: # pyright: ignore[reportExplicitAny] # any str return repr(label) if label else repr(stream) +def _is_token_type(kind: pa.DataType) -> bool: + """Whether ``kind`` is a source-info token type: ``large_string``, or a list of one. + + The list may be a large list (what ``Batch``, ``GroupBy`` and ``MergeJoin`` + build) or a fixed-size list (a hand-built stream's, kept as declared: ITL-1491). + """ + if pa.types.is_large_string(kind): + return True + if isinstance(kind, (pa.LargeListType, pa.FixedSizeListType)): + return _is_token_type(kind.value_type) # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType] + return False + + def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: """Say how a record batch's columns differ from a channel's, or ``None``. @@ -414,26 +427,30 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: converted: type strictness), the same nullability (and no null where the description's field is not nullable) and the same field metadata. A ``null`` type of the description (anywhere in a column's type) is carried as - ``large_string``, as a row's datagram stores it, and only null values are taken - there. Whether a system-tag or source-info field is nullable is not compared: it - follows the values of the complete table (``_flag_by_values``). Nor is a - source-info column's type, which follows its tokens over the complete table - (``_type_source_info_by_values``): it must only be a token type (``large_string``, - or ``large_list`` of a token type). + ``large_string`` outside system tags, and only null values are taken there. + System-tag field metadata must match the description. Batches may differ in + their top-level provenance flags. The complete stream uses the declared system-tag + flags and settles source-info flags from values. A source-info column's type + is the one the batch declares, since a stream bound to a slot may declare + another token type than the slot's description. It must be a token type + (``_is_token_type``), and every batch of the channel must declare it exactly + (``settle_token_types``), including nested item field metadata. """ sent = batch.schema if sorted(declared.names) != sorted(sent.names): return f"it has {sent.names}, the stream has {declared.names}" - provenance = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) for index, column in enumerate(sent): expected = declared.field(column.name) - carried = arrow_utils.normalize_to_large_types(expected.type) + system_tag = column.name.startswith(constants.SYSTEM_TAG_PREFIX) + carried = arrow_utils.normalize_to_large_types( + expected.type, keep_null=system_tag + ) if column.name.startswith(constants.SOURCE_PREFIX): if not _is_token_type(column.type): return f"column {column.name!r} is {column.type}, not a token type" - if column.metadata or not column.type.equals( - _without_metadata(column.type), check_metadata=True - ): + # A row builds the field anew, so the field itself has no metadata; its + # type is the stream's, the metadata of a list's item field included. + if column.metadata: return f"column {column.name!r} carries field metadata" continue if column.type != carried: @@ -445,12 +462,15 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: f"column {column.name!r} holds values where the stream's type " + f"{expected.type} holds only nulls" ) - if column.name.startswith(provenance): - # A row builds these from its values: no field metadata at any depth. - if column.metadata or not column.type.equals( - _without_metadata(column.type), check_metadata=True + if system_tag: + if (expected.metadata or None) != (column.metadata or None) or not ( + column.type.equals(carried, check_metadata=True) ): - return f"column {column.name!r} carries field metadata" + return f"column {column.name!r} carries field metadata that differs from its stream" + if not expected.nullable and batch.column(index).null_count: + return ( + f"column {column.name!r} holds nulls, the stream's is not nullable" + ) continue if expected.nullable != column.nullable: flags = {True: "nullable", False: "not nullable"} @@ -562,18 +582,6 @@ def _map_entries(array: pa.MapArray) -> tuple[pa.Array[Any], pa.Array[Any]]: # return array.keys.take(taken), array.items.take(taken) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType] -def _is_token_type(kind: pa.DataType) -> bool: - """Whether ``kind`` is a source-info token type: ``large_string``, or a list of one. - - The types ``arrow_utils.source_info_arrow_type`` gives a token. - """ - if pa.types.is_large_string(kind): - return True - if isinstance(kind, pa.LargeListType): - return _is_token_type(kind.value_type) # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType] - return False - - def _without_metadata(kind: pa.DataType) -> pa.DataType: """``kind`` with the field metadata of every nested field removed.""" if isinstance(kind, pa.LargeListType): diff --git a/src/orcapod/core/row_ids.py b/src/orcapod/core/row_ids.py index ecdaf05aa..d854c74d1 100644 --- a/src/orcapod/core/row_ids.py +++ b/src/orcapod/core/row_ids.py @@ -34,6 +34,7 @@ import pyarrow as pa from orcapod.system_constants import constants +from orcapod.utils.arrow_utils import contains_null_type if TYPE_CHECKING: from orcapod.protocols.core_protocols import DataProtocol, TagProtocol @@ -89,7 +90,23 @@ def entry_id( Returns: The entry id. """ - return hasher.hash_table(entry_id_preimage(tag, data)) + preimage = entry_id_preimage(tag, data) + try: + return hasher.hash_table(preimage) + except ValueError as exc: + raw_null_tags = [ + repr(field.name) + for field in preimage.schema + if field.name.startswith(constants.SYSTEM_TAG_PREFIX) + and contains_null_type(field.type) + ] + if raw_null_tags: + names = ", ".join(raw_null_tags) + raise ValueError( + f"{exc}. Declare a supported nullable type for the raw Arrow Null " + f"system-tag column(s) {names}." + ) from exc + raise def instance_id_preimage(entry: "ContentHash", data: "DataProtocol") -> "pa.Table": diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 15501c76c..a7ac3bdb2 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -14,7 +14,10 @@ from orcapod.config import OrcapodConfig from orcapod.core.sources.base import RootSource from orcapod.core.sources.source_ids import parse_source_id -from orcapod.core.sources.stream_builder import require_supported_nullable_types +from orcapod.core.sources.stream_builder import ( + require_supported_nullable_types, + validate_source_table, +) from orcapod.errors import ( CachedSourceIdMismatchError, InputValidationError, @@ -363,7 +366,7 @@ def _live_records(self) -> pa.Table: live_table = self._source.as_table( columns={"source": True, "system_tags": True, "meta": True} ) - require_supported_nullable_types(live_table.schema) + validate_source_table(live_table) live_table = live_table.drop( [ name @@ -423,9 +426,7 @@ def _source_modified_time(self) -> datetime | None: def _cached_record_hashes(self) -> set[bytes]: """The record hashes of the rows cached under the current data context.""" self._account_for_stale_tables() - records = self._cache_database.get_all_records( - self.cache_path, record_id_column=self.HASH_COLUMN_NAME - ) + records = self._read_cache_table() if records is None: return set() records = keep_rows_of_data_context(records, self.data_context_key) @@ -495,6 +496,17 @@ def check_for_new_data(self) -> bool: self._update_modified_time() return True + def _read_cache_table(self) -> pa.Table | None: + """Read and validate the physical cache before using any of its columns.""" + records = self._cache_database.get_all_records( + self.cache_path, record_id_column=self.HASH_COLUMN_NAME + ) + return ( + None + if records is None + else validate_source_table(records, stored_cache=True) + ) + def _read_cached_records(self) -> "pa.Table | None": """Read the cached rows written under the current data context. @@ -526,12 +538,9 @@ def _read_cached_records_with_hashes(self) -> "pa.Table | None": InputValidationError: If a cached column reads back as another Arrow type. """ self._account_for_stale_tables() - records = self._cache_database.get_all_records( - self.cache_path, record_id_column=self.HASH_COLUMN_NAME - ) + records = self._read_cache_table() if records is None: return None - require_supported_nullable_types(records.schema) stored_rows = records.num_rows records = keep_rows_of_data_context(records, self.data_context_key) if records.num_rows < stored_rows and not self._skipped_rows_reported: @@ -559,9 +568,7 @@ def _require_rows_of_this_source(self) -> None: """ if self._source_ids_checked: return - records = self._cache_database.get_all_records( - self.cache_path, record_id_column=self.HASH_COLUMN_NAME - ) + records = self._read_cache_table() if records is None: return self._require_source_ids( @@ -731,9 +738,7 @@ def _typed_zero_row_table(self) -> "pa.Table | None": See ``typed_zero_row_table``; neither the cache nor the source is read. """ table = typed_zero_row_table(self._source) - if table is not None: - require_supported_nullable_types(table.schema) - return table + return None if table is None else validate_source_table(table) def _schema_requires_io(self, config: ColumnConfig) -> bool: """Whether reading the schema with ``config`` would poll: as for the wrapped source.""" diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 54a563f88..dd6b0a51a 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -2,8 +2,9 @@ import logging from collections.abc import Collection -from typing import TYPE_CHECKING, Any, ClassVar +from typing import TYPE_CHECKING, Any, ClassVar, cast +import pandas as pd import polars as pl import pyarrow as pa @@ -14,12 +15,17 @@ normalize_record_id_columns, require_custom_system_tags, require_supported_nullable_types, + require_system_tag_without_field_metadata, ) from orcapod.utils import arrow_utils, polars_data_utils from orcapod.utils.schema_utils import _normalize_column_list if TYPE_CHECKING: - from polars._typing import FrameInitTypes + from polars._typing import ( + ArrowArrayExportable, + ArrowStreamExportable, + FrameInitTypes, + ) logger = logging.getLogger(__name__) @@ -65,7 +71,27 @@ def __init__( ) -> None: super().__init__(source_id=source_id, **kwargs) - df = pl.DataFrame(data) + # Keep pandas and Polars on their native paths even if they export Arrow. + # For Arrow inputs, materialize once before Polars drops field metadata. + if not isinstance(data, (pd.DataFrame, pl.DataFrame, pl.Series)) and ( + hasattr(data, "__arrow_c_stream__") or hasattr(data, "__arrow_c_array__") + ): + # Like Polars, prefer the array export when both are available. + if hasattr(data, "__arrow_c_array__"): + batch = pa.record_batch(cast("ArrowArrayExportable", data)) + arrow_input = pa.Table.from_batches([batch]) + else: + arrow_input = pa.table(cast("ArrowStreamExportable", data)) + for field in arrow_input.schema: + if field.name in system_tag_columns: + require_system_tag_without_field_metadata(field) + # Polars rechunks native tables but preserves chunks on exporter inputs. + df = cast( + pl.DataFrame, + pl.from_arrow(arrow_input, rechunk=isinstance(data, pa.Table)), + ) + else: + df = pl.DataFrame(data) # Convert any Object-dtype columns to Arrow-compatible types. object_columns = [c for c in df.columns if df[c].dtype == pl.Object] diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 55f0c82b7..cf3cb6b97 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -166,6 +166,7 @@ def __init__( # _query allows subclasses (e.g. SQLiteTableSource) to inject a custom # SELECT (e.g. SELECT rowid, * FROM "t") without duplicating the rest of init. self._query = _query if _query is not None else f'SELECT * FROM "{table_name}"' + self._system_tag_columns: Collection[str] = system_tag_columns table = self._read_table(connector) # The rows as read, columns and types included: a check compares a new read # with them, and refuses a table whose columns changed. @@ -173,7 +174,6 @@ def __init__( # Step 4: Enrich via SourceStreamBuilder (same pipeline as all other RootSources) self._tag_columns: Collection[str] = resolved_tag_columns - self._system_tag_columns: Collection[str] = system_tag_columns # Every declared tag is a data-tag unless kept tag-only (ITL-1023); a # rebuild after a check (ITL-1102) applies the same choice. data_tags = source_data_tags(self._tag_columns, tag_only_columns) @@ -235,7 +235,16 @@ def _read_table( db_nullable = {ci.name: ci.nullable for ci in col_infos} db_schema = pa.schema( [ - pa.field(f.name, f.type, nullable=db_nullable.get(f.name, True)) + # Keep nominated metadata visible to source validation. Other + # fields retain the database-backed schema used for hashing. + pa.field( + f.name, + f.type, + nullable=db_nullable.get(f.name, True), + metadata=f.metadata or None + if f.name in self._system_tag_columns + else None, + ) for f in table.schema ] ) diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index aeef4bfd5..a9bf44561 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -20,6 +20,7 @@ from orcapod.core.sources.source_ids import hash_source_name from orcapod.core.sources.stream_builder import ( require_supported_nullable_types, + validate_source_table, SourceStreamBuilder, normalize_record_id_columns, ) @@ -809,9 +810,8 @@ def _stream_over(self, table: "pa.Table") -> ArrowTableStream: """Return this source's stream over the origin rows ``table``.""" if self._tags_as_data is not None: return self._derive_from(table, self._tags_as_data) - require_supported_nullable_types(table.schema) return ArrowTableStream( - table, + validate_source_table(table), tag_columns=self._origin.keys()[0], data_tags=self._data_tags(), ) diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 3b4f65398..17a3bc733 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -29,6 +29,7 @@ SourceStreamBuilder, normalize_record_id_columns, require_supported_nullable_types, + validate_source_table, ) from orcapod.core.streams.view import ( ViewStatus, @@ -561,8 +562,9 @@ def _typed_zero_row_table(self) -> pa.Table | None: table = typed_zero_row_table(batch) if table is None: return None - require_supported_nullable_types(table.schema) - zero_rows = ArrowTableStream(table=table, tag_columns=self._tag_columns) + zero_rows = ArrowTableStream( + table=validate_source_table(table), tag_columns=self._tag_columns + ) result = zero_rows if result is None else self._combine(result, zero_rows) return typed_zero_row_table(result) @@ -1084,8 +1086,9 @@ def _combine( ], promote_options="default", ) - require_supported_nullable_types(combined.schema) - return ArrowTableStream(table=combined, tag_columns=self._tag_columns) + return ArrowTableStream( + table=validate_source_table(combined), tag_columns=self._tag_columns + ) def _mark_new_rows(self, committed: ArrowTableStream | None) -> bool: """Move the modified time to now if the batch just committed holds rows. diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 83eb6238d..143a044fb 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -17,6 +17,7 @@ from orcapod.core.sources.base import RootSource from orcapod.core.sources.source_ids import parse_source_id +from orcapod.core.sources.stream_builder import validate_source_table from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -259,10 +260,18 @@ def _typed_zero_row_table(self) -> pa.Table | None: See ``typed_zero_row_table``. An unbound proxy knows only its stored Python schema (a known limitation, ITL-912). """ - return typed_zero_row_table(self._delegate) + table = typed_zero_row_table(self._delegate) + return None if table is None else validate_source_table(table) def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: - return self._require_delegate().iter_data() + delegate = self._require_delegate() + + def checked_rows() -> Iterator[tuple[TagProtocol, DataProtocol]]: + for tag, data in delegate.iter_data(): + validate_source_table(tag.as_table(columns={"system_tags": True})) + yield tag, data + + return checked_rows() def as_table( self, @@ -270,7 +279,9 @@ def as_table( columns: ColumnConfig | dict[str, Any] | None = None, all_info: bool = False, ) -> pa.Table: - return self._require_delegate().as_table(columns=columns, all_info=all_info) + return validate_source_table( + self._require_delegate().as_table(columns=columns, all_info=all_info) + ) def head( self, @@ -281,9 +292,9 @@ def head( ) -> StreamView: """Return the bound source's head, or no rows when no live source is bound.""" if self._delegate is not None: - return head_of( - self._delegate.head(n, columns=columns, all_info=all_info), self - ) + view = self._delegate.head(n, columns=columns, all_info=all_info) + validate_source_table(view.table) + return head_of(view, self) check_head_size(n) config = ColumnConfig.handle_config(columns, all_info=all_info) return self._head_without_rows( diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 22736f37f..a5ccebceb 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -36,24 +36,12 @@ from orcapod.protocols.hashing_protocols import ArrowHasherProtocol -def _contains_null_type(arrow_type: pa.DataType) -> bool: - """Return whether an Arrow type contains the Null type at any depth.""" - if isinstance(arrow_type, pa.BaseExtensionType): - return _contains_null_type(arrow_type.storage_type) - if pa.types.is_dictionary(arrow_type): - return _contains_null_type(arrow_type.value_type) - return pa.types.is_null(arrow_type) or any( - _contains_null_type(arrow_type.field(i).type) - for i in range(arrow_type.num_fields) - ) - - def require_supported_nullable_types(schema: pa.Schema) -> None: """Refuse source columns containing the Arrow Null type, even with zero rows.""" columns = sorted( (field.name, str(field.type)) for field in schema - if _contains_null_type(field.type) + if arrow_utils.contains_null_type(field.type) ) if columns: names = ", ".join(f"{name!r} ({arrow_type})" for name, arrow_type in columns) @@ -63,22 +51,67 @@ def require_supported_nullable_types(schema: pa.Schema) -> None: ) +def require_system_tag_without_field_metadata( + field: pa.Field[Any], *, stored_cache: bool = False +) -> None: + """Refuse field metadata on a system tag before it can reach source rows.""" + # Stopgap (ITL-1561): re-evaluate what metadata a system-tag field may carry. + # Extension metadata reaches the row hash now that rows use stream fields. + if not field.metadata: + return + if stored_cache: + raise InputValidationError( + f"System-tag column {field.name!r}: the source cache was written with " + "Arrow field metadata on a system tag. Rebuild the cache." + ) + raise InputValidationError( + f"Custom system-tag column {field.name!r} has Arrow field metadata. " + "Remove the field metadata before building the source." + ) + + +def validate_source_table(table: pa.Table, *, stored_cache: bool = False) -> pa.Table: + """Validate an enriched table presented by a source without the source builder. + + Args: + table: Source fields and values, with system tags already named as such. + stored_cache: Report the rebuild remedy for a persisted source cache. + + Returns: + The same table, with fields and values unchanged. + """ + require_supported_nullable_types(table.schema) + require_custom_system_tags( + table, + [ + name + for name in table.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) + ], + stored_cache=stored_cache, + ) + return table + + def require_custom_system_tags( table: pa.Table, names: Collection[str], *, schema: pa.Schema | None = None, + stored_cache: bool = False, ) -> None: - """Validate custom system-tag names, types, field flags and values. + """Validate custom system-tag declarations and values. Args: table: The source's Arrow columns. names: The columns nominated as system tags. schema: The declared fields if the reader has yet to apply them. + stored_cache: Report the rebuild remedy for a persisted source cache. Raises: ValueError: If a nominated column is missing from the source table. - InputValidationError: If a nominated column is not non-nullable text. + InputValidationError: If a nominated column has field metadata, can + hold nulls or is not text. """ if not names: return @@ -91,6 +124,11 @@ def require_custom_system_tags( ) for name in names: field = fields.field(name) + require_system_tag_without_field_metadata(field, stored_cache=stored_cache) + if schema is not None: + require_system_tag_without_field_metadata( + table.schema.field(name), stored_cache=stored_cache + ) has_nulls = table.column(name).null_count > 0 if ( field.nullable diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index df49eaff6..87a52c9b9 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -79,6 +79,9 @@ def __init__( InputValidationError: If a column's type is, or contains, a dictionary: dictionary-encoded columns are not currently supported (ITL-1264, ITL-1277). + 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). """ super().__init__(**kwargs) @@ -184,6 +187,14 @@ def __init__( self._table = table self._source_info_table = prefix_tables[constants.SOURCE_PREFIX] self._data_context_table = data_context_table + # A token's list layers are its data's outer list layers, and a token with + # a layer is never null (developer, November 27, 2026, ITL-1491). Every + # source, operator result and table built from rows becomes a stream here, + # so this is the one check: types and validity only, no value read. + if found := schema_utils.token_shape_violations( + self._table, self._source_info_table, self._data_columns + ): + raise schema_utils.token_shape_error(found) if len(self._data_columns) == 0: raise ValueError( diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 9f8b731f7..a762542b4 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -85,14 +85,10 @@ def reads_as_its_class(obj: object, cls: type) -> bool: def system_tags_as_rows_give(table: pa.Table) -> bool: - """Whether every system-tag column is what the row rebuild gives: non-null text. + """Whether the optimized row-building path may use these system tags. - ``main`` rebuilt a node's table from its rows, whose system tags are typed from - their values: a ``large_string`` field, non-nullable, with no field metadata (the - only kind library code makes). A whole table is its rows only when its system tags - are already so, in their values as in their fields: a narrow integer, a nullable - field, a null value (also in a field declared non-nullable) or field metadata (an - Arrow extension's, which a tag drops) is decided by the rows (ITL-1347). + The optimized path still uses the ITL-1347 gate for non-nullable text + without field metadata. The row path now carries declared system-tag fields. Args: table: The table. @@ -272,13 +268,10 @@ def row_built_columns( column of ``table``. 3. Normalized to the large types without keeping ``null``: each row's datagram stores a ``null`` column as ``large_string`` (``Datagram._init_from_table``). - 4. The system-tag and source-info fields as a row builds them from its values - (``row_built_provenance``): no field metadata, and a source-info list of the - form its tokens give. + 4. Keep the declared system-tag fields. Strip top-level metadata from + source-info fields while preserving their types (``row_built_provenance``). - Whether a system-tag or source-info field is nullable depends on its values over - the complete table (``StaticOutputOperatorPod._flag_by_values``), so it is not - decided here. + Source-info field nullability is settled over the complete table. Args: table: A table of user tags, system tags, data and source info. @@ -288,73 +281,43 @@ def row_built_columns( Returns: The same values, selected and ordered, in their large types. """ - return row_built_provenance( - arrow_utils.normalize_table_to_large_types( - table.select(row_built_names(table.column_names, keys)) - ) - ) - - -def _source_info_value_type(kind: pa.DataType) -> pa.DataType: - """The Arrow type a row gives a source-info column of type ``kind``. - - A row's ``Data`` types its tokens from their Python values - (``arrow_utils.source_info_arrow_type``): a string as ``large_string``, a list as - ``large_list`` of its element's type, with the item field named ``item`` and - nullable. A type of any other kind is left as it is. - """ - if ( - pa.types.is_list(kind) - or pa.types.is_large_list(kind) - or pa.types.is_fixed_size_list(kind) - ): - return pa.large_list(_source_info_value_type(kind.value_type)) # pyright: ignore[reportAttributeAccessIssue, reportUnknownArgumentType, reportUnknownMemberType] # a list type has a value type - if ( - pa.types.is_string(kind) - or pa.types.is_large_string(kind) - or pa.types.is_null(kind) - ): - return pa.large_string() - return kind + selected = table.select(row_built_names(table.column_names, keys)) + normalized = arrow_utils.normalize_table_to_large_types(selected) + for index, field in enumerate(selected.schema): + if field.name.startswith(constants.SYSTEM_TAG_PREFIX) and ( + field.type != normalized.schema.field(index).type + ): + normalized = normalized.set_column(index, field, selected.column(index)) + return row_built_provenance(normalized) def row_built_provenance(table: pa.Table) -> pa.Table: - """Give ``table``'s system-tag and source-info fields the form a row builds. + """Give ``table``'s source-info fields the form a row builds. - A row rebuilds its system tags and its source info from their values, so their - fields carry no field metadata, and a source-info column has the type its tokens - give (``_source_info_value_type``): a list's item field named ``item`` and - nullable at every depth. The values are unchanged: a type that differs only in - its item fields is cast. The fields' nullability is left as it is - (``StaticOutputOperatorPod._flag_by_values`` decides it). Other fields are not - touched. + A row rebuilds the top-level token field without metadata. The column + keeps its declared type, including nested item fields and their metadata + (ITL-1491). Source-info field nullability is settled separately by + ``StaticOutputOperatorPod._flag_by_values``. Args: table: A table of user tags, system tags, data and source info. Returns: - The same values under the rebuilt fields. + The same columns under the rebuilt fields. """ - fields: list[pa.Field[pa.DataType]] = [] - columns: list[Any] = [] - changed = False - for field, column in zip(table.schema, table.columns, strict=True): - if field.name.startswith(constants.SOURCE_PREFIX): - kind = _source_info_value_type(field.type) - if kind != field.type: - column = column.cast(kind) - new_field = pa.field(field.name, kind, nullable=field.nullable) - elif field.name.startswith(constants.SYSTEM_TAG_PREFIX): - new_field = field.remove_metadata() - else: - new_field = field - changed = changed or not new_field.equals(field, check_metadata=True) - fields.append(new_field) - columns.append(column) - if not changed: + fields = [ + field.remove_metadata() + if field.name.startswith(constants.SOURCE_PREFIX) + else field + for field in table.schema + ] + if all( + new.equals(old, check_metadata=True) + for new, old in zip(fields, table.schema, strict=True) + ): return table return pa.Table.from_arrays( - columns, + table.columns, schema=pa.schema( fields, cast("dict[bytes | str, bytes | str] | None", table.schema.metadata) ), @@ -443,11 +406,11 @@ def stream_arrow_schema( converted by its data context (``arrow_types_declared`` is then false), and one whose schema is known only by polling (nothing declared, nothing polled: ``schema_requires_io``) answers with no column. Each - system-tag and source-info field is stated nullable: a table decides its flag from - its values (F's last step). A source-info field's type is stated as the declared - token type; a complete table decides it from its tokens - (``StaticOutputOperatorPod._type_source_info_by_values``), so consumers must not - rely on it. A ``null`` column keeps the zero-row ``null`` type; rows + source-info field is stated nullable: a table decides its flag from + its values (F's last step). System-tag fields keep their declared flags and + metadata. A source-info field's type is the declared token type, which its + rows keep (ITL-1491). Outside system tags, a ``null`` column keeps the + zero-row ``null`` type; rows carry ``large_string`` (ITL-1319). ITL-1307 later reads it from ``Schema`` instead, here. @@ -508,9 +471,8 @@ def stream_arrow_schema( keys = given_keys if given_keys is not None else keys_of_rows(table, typed.keys()) names = row_built_names(table.column_names, keys) schema = row_built_provenance(table.select(names)).schema - prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) for index, field in enumerate(schema): - if field.name.startswith(prefixes): + if field.name.startswith(constants.SOURCE_PREFIX): schema = schema.set(index, field.with_nullable(True)) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized return schema @@ -563,13 +525,10 @@ async def next(self) -> pa.RecordBatch | None: def _row_built_table(self) -> pa.Table: """The stream's table in the row-built form: its one read. - The table first: reading it is the stream's one read (an unpolled source polls - here), and its keys are then known without another. Its system tags must be - what rows give (``system_tags_as_rows_give``: non-null text, no field - metadata); otherwise, as on the eager routes of a job, the table is the one - its rows build (``main``'s row path), so a narrow or nullable system tag is - retyped as a row retypes it. Only a stream that holds such a column (a raw - ``ArrowTableStream``) is read that way, and its reads have no effect. + The table first: reading it is the stream's one read (an unpolled source + polls here), and its keys are then known without another. The existing + system-tag gate sends other fields through the row path, which carries + their declared system-tag fields. """ table = self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) if not system_tags_as_rows_give(table): diff --git a/src/orcapod/protocols/core_protocols/datagrams.py b/src/orcapod/protocols/core_protocols/datagrams.py index eb19f07ee..0aea62b4c 100644 --- a/src/orcapod/protocols/core_protocols/datagrams.py +++ b/src/orcapod/protocols/core_protocols/datagrams.py @@ -695,7 +695,7 @@ def source_info_table(self) -> "pa.Table": def with_source_info( self, - **source_info: SourceInfoValue, + **source_info: "SourceInfoValue | pa.Scalar[Any]", ) -> Self: """ Create a new data with updated source information. @@ -704,7 +704,9 @@ def with_source_info( tracking data provenance and lineage through the computational graph. Args: - **source_info: Source metadata as keyword arguments. + **source_info: The token of each named data column: a Python value, + typed from that value, or an Arrow scalar that carries the token + column's type, which is kept. Returns: A new data instance with updated source information. diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index c49d1f429..ea33a5623 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -1248,6 +1248,18 @@ def make_schema_non_nullable(schema: "pa.Schema") -> "pa.Schema": ) +def contains_null_type(arrow_type: "pa.DataType") -> bool: + """Return whether an Arrow type contains the Null type at any depth.""" + if isinstance(arrow_type, pa.BaseExtensionType): + return contains_null_type(arrow_type.storage_type) + if pa.types.is_dictionary(arrow_type): + return contains_null_type(arrow_type.value_type) + return pa.types.is_null(arrow_type) or any( + contains_null_type(arrow_type.field(i).type) + for i in range(arrow_type.num_fields) + ) + + def infer_schema_nullable(table: "pa.Table") -> "pa.Schema": """Return a schema where each field's nullable flag is inferred from actual data. @@ -1682,9 +1694,9 @@ def _system_tag_position_groups( def sorted_system_tag_nullability( nullable_by_name: Mapping[str, bool], ) -> dict[str, bool]: - """Give each movable system-tag field the nullability of all its inputs.""" - nullable = dict(nullable_by_name) - for positions in _system_tag_position_groups(nullable).values(): + """Return nullability for the source/record fields rebuilt by a tied sort.""" + nullable: dict[str, bool] = {} + for positions in _system_tag_position_groups(nullable_by_name.keys()).values(): if len(positions) <= 1: continue for prefix in ( @@ -1700,6 +1712,11 @@ def sorted_system_tag_nullability( return nullable +def sorted_system_tag_field(field: "pa.Field[Any]", nullable: bool) -> "pa.Field[Any]": + """Declare a tied field without metadata from any one operand.""" + return field.with_nullable(nullable).remove_metadata() + + def sort_system_tag_values(table: "pa.Table") -> "pa.Table": """Sort paired system tag values for columns that share the same provenance path. @@ -1789,8 +1806,8 @@ def sort_system_tag_values(table: "pa.Table") -> "pa.Table": ): if name is not None: index = table.schema.get_field_index(name) - field = pa.field( - name, table.schema.field(index).type, nullable=nullable[name] + field = sorted_system_tag_field( + table.schema.field(index), nullable[name] ) table = table.set_column( index, field, pa.array(values, type=field.type) diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index f0322d3f2..dfd675641 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -14,6 +14,11 @@ logger = logging.getLogger(__name__) +TokenShapeViolation = tuple[str, str, pa.DataType, pa.DataType, int | None] +"""A token column that breaks the token-shape rule: the token column, its data +column, both types as the rule reads them, and the list level of a null list +(0 is the token itself), or ``None`` when the token's type does not fit the data's.""" + def verify_data_schema(data: dict, schema: SchemaLike) -> bool: """Verify that the dictionary's types match the expected types in the schema.""" @@ -834,6 +839,180 @@ def dictionary_columns( return found +def _list_layer(arrow_type: "pa.DataType") -> "tuple[str, int] | None": + """Return the list layer ``arrow_type`` has on the outside, or ``None``. + + A plain and a large list are one kind (the large variant: every stream is in + its large variants); a fixed-size list is another kind for each size. + + Args: + arrow_type: An Arrow type. + + Returns: + ``("large_list", 0)``, ``("fixed_size_list", )``, or ``None`` when + the type is not a list. + """ + if pa.types.is_large_list(arrow_type) or pa.types.is_list(arrow_type): + return ("large_list", 0) + if pa.types.is_fixed_size_list(arrow_type): + return ("fixed_size_list", arrow_type.list_size) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownVariableType] # a fixed-size list type has a size + return None + + +def token_layers_fit(token_type: "pa.DataType", data_type: "pa.DataType") -> bool: + """Whether a source-info token type's layers are its data type's outer layers. + + The token-shape rule (developer, November 27, 2026, ITL-1491). A token + column's type is some list layers on top of a plain token. Those layers must + match exactly the outer list layers of the data column's type: a large list + needs a large list, a fixed-size list a fixed-size list of the same size + (a plain ``list`` counts as a large list). The data may be deeper than its + token, and a token with no layer fits any data. A data type that is a + logical type is read as its storage, so the logical list built for a list of + a logical element counts as one large-list layer per list level. + + Only lists are layers today, and under its layers a token is a string: a + token type with a layer of another kind (a struct, a map, a union, a list + view) or with another leaf (an integer, a binary) is refused whatever the + data. A layer's item field (its name, nullability and metadata) is not + compared. + + Args: + token_type: The Arrow type of the ``_source_`` column. + data_type: The Arrow type of the data column ````. + + Returns: + Whether the token type fits the data type. + """ + token, data = token_type, data_type + while True: + layer = _list_layer(token) + if layer is None: + # The leaf: a string. A stream's token columns are large-normalized; + # the other spellings are the same token. + return ( + pa.types.is_large_string(token) + or pa.types.is_string(token) + or pa.types.is_string_view(token) + ) + while isinstance(data, pa.ExtensionType): + data = data.storage_type + if _list_layer(data) != layer: + return False + token, data = token.value_type, data.value_type # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownVariableType] # a list type has a value type + + +TOKEN_SHAPE_RULE = ( + "A source-info token column must have the shape of its data column: its type is " + "list layers over a string (large_string), each list layer needs the same list " + "layer in the data's type (a large list, or a fixed-size list of the same size), " + "and a token's list is never null at any level: a null is allowed only at the " + "innermost level, where the element is a string" +) +"""The token-shape rule, as the refusal of a stream that breaks it begins.""" + + +def null_list_level(column: "pa.ChunkedArray[Any] | pa.Array[Any]") -> int | None: + """Return the outermost list level at which a token column holds a null list. + + A token's list is never null at any level (developer, November 27, 2026, + ITL-1491): a null is allowed only at the innermost level, where the element is + a string. Level 0 is the token itself, level 1 the lists inside it, and so on. + Only validity is read, level by level (the null count of each level's arrays); + no value is read. A column with no rows, and a plain string column, have none. + + Args: + column: A ``_source_`` column. + + Returns: + The level, or ``None`` when no list of the column is null. + """ + arrays: "list[pa.Array[Any]]" = ( + list(column.chunks) if isinstance(column, pa.ChunkedArray) else [column] + ) + level = 0 + while arrays and _list_layer(arrays[0].type) is not None: + if any(array.null_count for array in arrays): + return level + arrays = [array.flatten() for array in arrays] # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownVariableType] # a list array + level += 1 + return None + + +def token_shape_violations( + data: "pa.Table", tokens: "pa.Table", data_columns: Collection[str] +) -> "list[TokenShapeViolation]": + """Return the source-info columns of a table that break the token-shape rule. + + The shape is read from the columns' types and the nulls from the validity of + every list level of a list-typed token column (``null_list_level``); no value + is read. A plain string token column is never looked at further, + and a data column with no token column is skipped. + + Args: + data: The table of tag and data columns. + tokens: The table of ``_source_`` columns (it may be ``data``). + data_columns: The data columns (data-tags included). + + Returns: + One entry per violating column, in the order of ``data_columns`` + (``TokenShapeViolation``). + """ + from orcapod.system_constants import constants + + found: "list[TokenShapeViolation]" = [] + token_names = set(tokens.column_names) + for name in data_columns: + token_name = f"{constants.SOURCE_PREFIX}{name}" + if token_name not in token_names: + continue + token_type = tokens.schema.field(token_name).type + if pa.types.is_large_string(token_type): + continue + data_type = data.schema.field(name).type + if not token_layers_fit(token_type, data_type): + found.append((token_name, name, token_type, data_type, None)) + elif (level := null_list_level(tokens.column(token_name))) is not None: + found.append((token_name, name, token_type, data_type, level)) + return found + + +def token_shape_error( + found: "Sequence[TokenShapeViolation]", +) -> InputValidationError: + """Return the error refusing the source-info columns ``found``. + + Args: + found: The columns, as ``token_shape_violations`` returns them. + + Returns: + An ``InputValidationError`` naming each token column, its data column and + both types, and what is wrong with it, in the order of the token columns' + names (a set of names is held sorted). + """ + lines = [ + f" - token column {token_name!r} has type {token_type} and its data column " + f"{name!r} has type {data_type}: " + + ( + "the token's type is not list layers over a string that are the " + "data's outer list layers" + if level is None + else "it holds a null token" + if level == 0 + else f"it holds a null list of tokens at list level {level} (level 0 " + "is the token itself)" + ) + for token_name, name, token_type, data_type, level in sorted( + found, key=lambda entry: entry[0] + ) + ] + return InputValidationError( + f"{TOKEN_SHAPE_RULE}:\n" + + "\n".join(lines) + + "\nA plain string token (large_string) fits any data and may be null." + ) + + def dictionary_columns_error( found: "Sequence[tuple[str, pa.DataType, pa.DataType]]", tag_columns: Collection[str], diff --git a/tests/test_channels/test_native_async_operators.py b/tests/test_channels/test_native_async_operators.py index 82c774af7..058ab42c9 100644 --- a/tests/test_channels/test_native_async_operators.py +++ b/tests/test_channels/test_native_async_operators.py @@ -43,6 +43,7 @@ from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants from orcapod.types import ContentHash +from orcapod.utils.arrow_utils import sort_system_tag_values # --------------------------------------------------------------------------- @@ -2231,8 +2232,8 @@ async def test_three_way_system_tags_match_sync(self): assert sync_sys == async_sys -class TestSortMergedSystemTags: - """Unit tests for Join._sort_merged_system_tags.""" +class TestSortSystemTagValues: + """Unit tests for the sorter shared by both Join paths.""" def test_sorts_same_provenance_path_by_value(self): """System tag values at different positions within the same provenance @@ -2245,7 +2246,9 @@ def test_sorts_same_provenance_path_by_value(self): "_tag_source_id::abc123:1": "a_source", "_tag_record_id::abc123:1": "a_record", } - result = Join._sort_merged_system_tags(merged_sys) + result = sort_system_tag_values(pa.Table.from_pylist([merged_sys])).to_pylist()[ + 0 + ] # After sorting, position 0 should have the smaller values assert result["_tag_source_id::abc123:0"] == "a_source" @@ -2259,7 +2262,9 @@ def test_single_position_unchanged(self): "_tag_source_id::abc123:0": "only_source", "_tag_record_id::abc123:0": "only_record", } - result = Join._sort_merged_system_tags(merged_sys) + result = sort_system_tag_values(pa.Table.from_pylist([merged_sys])).to_pylist()[ + 0 + ] assert result == merged_sys def test_non_system_tag_keys_ignored(self): @@ -2269,7 +2274,9 @@ def test_non_system_tag_keys_ignored(self): "_tag_source_id::abc123:0": "src0", "_tag_record_id::abc123:0": "rec0", } - result = Join._sort_merged_system_tags(merged_sys) + result = sort_system_tag_values(pa.Table.from_pylist([merged_sys])).to_pylist()[ + 0 + ] assert result["regular_key"] == "value" diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index d4416e6db..9cf5d8d96 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -41,7 +41,6 @@ ) from orcapod.core.operators.static_output_pod import ( ROW_BUILT_OUTPUT, - RowBuiltFormUnavailable, StaticOutputOperatorPod, stream_from_batches, ) @@ -69,6 +68,61 @@ TIMEOUT = 5.0 +def test_raw_system_tag_fields_survive_a_record_batch_channel() -> None: + """A channel carries a stream's system-tag Arrow fields through to its rows.""" + system = pa.schema( + [ + pa.field("_tag_rank", pa.int8(), False, metadata={b"purpose": b"rank"}), + pa.field("_tag_label", pa.large_string(), True), + ] + ) + schema = pa.schema( + [ + pa.field("subject", pa.large_string(), False), + pa.field("trial", pa.int16(), False), + pa.field("x", pa.int8(), False), + pa.field("y", pa.int8(), False), + *system, + ] + ) + table = pa.Table.from_arrays( + [ + pa.array(values, field.type) + for values, field in zip( + (["a", "b"], [1, 2], [3, 4], [5, 6], [7, 8], ["a", None]), + schema, + strict=True, + ) + ], + schema=schema, + ) + stream = ArrowTableStream(table, tag_columns=("subject", "trial")) + + async def forward() -> StreamProtocol: + output = OutputChannel(stream) + async for batch in stream.open_channel(): + assert batch.select(system.names).schema.equals(system, check_metadata=True) + await output.send(batch) + await output.close() + return output.result() + + assert pa.schema([stream.arrow_schema().field(n) for n in system.names]).equals( + system, check_metadata=True + ) + rebuilt = run(forward) + assert ( + rebuilt.as_table(columns=ALL) + .select(system.names) + .schema.equals(system, check_metadata=True) + ) + for tag, _ in rebuilt.iter_data(): + assert ( + tag.as_table(columns=ALL) + .select(system.names) + .schema.equals(system, check_metadata=True) + ) + + def run(make: Callable[[], Awaitable[T]]) -> T: """Run a coroutine to its end; a channel that never wakes fails the test.""" @@ -99,6 +153,35 @@ def source(n: int = 7, source_id: str = "events") -> ArrowTableSource: ) +def shaped_source(kind: pa.DataType, n: int = 2) -> ArrowTableSource: + """``source(n)`` whose ``amplitude`` has the list layers of the token type ``kind``. + + A token's list layers are its data's outer list layers (the token-shape rule, + ITL-1491), so a test that carries ``_source_amplitude`` as ``kind`` sends it as + this stream. + """ + from tests.token_shapes import data_type_for, nested_value + + data_type = data_type_for(kind, pa.float32()) + return ArrowTableSource( + pa.table( + { + "subject": pa.array([f"m{i % 3}" for i in range(n)], pa.string()), + "trial": pa.array(range(n), pa.int16()), + "amplitude": pa.array( + [nested_value(0.5 * i, data_type) for i in range(n)], data_type + ), + "note": pa.array( + [None if i % 4 == 1 else f"n{i}" for i in range(n)], pa.string() + ), + } + ), + tag_columns=["subject", "trial"], + tag_only_columns=(), + source_id="shaped", + ) + + def R(stream: Any) -> pa.Table: """The table today's code builds from ``stream``'s rows.""" return StaticOutputOperatorPod._rows_to_table(list(stream.iter_data()))[0] @@ -2094,7 +2177,7 @@ async def write() -> None: def test_a_batch_whose_tokens_cannot_settle_with_accepted_ones_is_refused() -> None: """A second batch with list tokens where the first had string tokens is refused at - send, with the error the complete table would raise (Codex on PR #485, round 5).""" + send: two batches of one stream declare one token type (Codex on PR #485, round 5).""" from orcapod.core.operators.static_output_pod import SourceInfoTypesDisagree stream = source() @@ -2144,23 +2227,47 @@ def _with_amplitude_tokens( ) -SETTLING_CASES: dict[ +NON_NULL_TOKENS = pa.large_list(pa.field("item", TOKEN, nullable=False)) +FIXED_TOKENS = pa.list_(TOKEN, 1) + +# Batches that declare one token type are assembled with that type, whatever their +# tokens show (ITL-1491: the pipeline determines a token column's type). +ONE_TYPE_CASES: dict[ str, tuple[list[tuple[int, list[Any], pa.DataType]], pa.DataType, list[Any]] ] = { - # An empty token list carried two levels deep, then a token list: both settle as - # one level of tokens. - "list_depth": ([(0, [[]], TOKEN_LISTS), (1, [["b"]], TOKENS)], TOKENS, [[], ["b"]]), - # A null token carried as a list, then a string token: both settle as strings. - "null_then_string": ([(0, [None], TOKENS), (1, ["b"], TOKEN)], TOKEN, [None, "b"]), - # Lists that differ only in their item field's nullability. - "item_nullability": ( - [ - (0, [["a"]], pa.large_list(pa.field("item", TOKEN, nullable=False))), - (1, [["b"]], TOKENS), - ], + # An empty token list (which shows one list level), then a token list. + "empty_list_two_levels": ( + [(0, [[]], TOKEN_LISTS), (1, [[["b"]]], TOKEN_LISTS)], + TOKEN_LISTS, + [[], [["b"]]], + ), + # A null token inside a list, then a list token. + "null_element_then_list": ( + [(0, [[None]], TOKENS), (1, [["b"]], TOKENS)], TOKENS, + [[None], ["b"]], + ), + # Lists whose item field is declared non-nullable keep it. + "non_null_items": ( + [(0, [["a"]], NON_NULL_TOKENS), (1, [["b"]], NON_NULL_TOKENS)], + NON_NULL_TOKENS, + [["a"], ["b"]], + ), + # A hand-built fixed-size list stays one. + "fixed_size_list": ( + [(0, [["a"]], FIXED_TOKENS), (1, [["b"]], FIXED_TOKENS)], + FIXED_TOKENS, [["a"], ["b"]], ), + # A token no value could type ([[], [[]]] three levels deep) is taken as declared. + "three_levels": ( + [ + (0, [[[], [[]]]], pa.large_list(TOKEN_LISTS)), + (1, [[[["b"]]]], pa.large_list(TOKEN_LISTS)), + ], + pa.large_list(TOKEN_LISTS), + [[[], [[]]], [[["b"]]]], + ), # A batch with no rows has no token and fixes no type. "zero_rows_first": ( [(0, [], TOKEN), (0, [["a"]], TOKENS), (1, [["b"]], TOKENS)], @@ -2170,13 +2277,13 @@ def _with_amplitude_tokens( } -@pytest.mark.parametrize("case", list(SETTLING_CASES)) +@pytest.mark.parametrize("case", list(ONE_TYPE_CASES)) def test_batches_send_accepts_are_assembled(case: str) -> None: """What ``send`` accepts can be assembled: ``result()`` and ``to_stream()`` build - the complete table, each source-info column of the type its tokens settle.""" - stream = source(2) + the complete table, each source-info column of the type its batches declare.""" + parts, declared, tokens = ONE_TYPE_CASES[case] + stream = shaped_source(declared) (batch,) = batches_of(stream) - parts, settled, tokens = SETTLING_CASES[case] async def write() -> tuple[Any, Any]: output = OutputChannel(stream) @@ -2189,31 +2296,50 @@ async def write() -> tuple[Any, Any]: result, converted = run(write) for assembled in (result, converted): table = assembled.as_table(columns=ALL) - assert table.schema.field("_source_amplitude").type == settled + assert table.schema.field("_source_amplitude").type == declared assert table.column("_source_amplitude").to_pylist() == tokens -def test_a_token_that_cannot_be_represented_is_refused_at_send() -> None: - """A token that has no place in its column's settled type (``[[], [[]]]`` carried - three levels deep) is refused at send; the channel takes valid batches after it.""" - stream = source(2) +# Batches that declare two token types: before ITL-1491 the first three "settled" to +# one type worked out from the tokens; a token column's type is now the declared one. +TWO_TYPE_CASES: dict[str, list[tuple[int, list[Any], pa.DataType]]] = { + "list_depth": [(0, [[]], TOKEN_LISTS), (1, [["b"]], TOKENS)], + "list_then_string": [(0, [["a"]], TOKENS), (1, ["b"], TOKEN)], + "item_nullability": [(0, [["a"]], NON_NULL_TOKENS), (1, [["b"]], TOKENS)], + "fixed_then_large": [(0, [["a"]], FIXED_TOKENS), (1, [["b"]], TOKENS)], +} + + +@pytest.mark.parametrize("order", ["as_listed", "reversed"]) +@pytest.mark.parametrize("case", list(TWO_TYPE_CASES)) +def test_a_batch_that_declares_another_token_type_is_refused_at_send( + case: str, order: str +) -> None: + """A batch whose source-info column declares another type than the batches + accepted so far is refused at send, whatever its tokens are; the channel takes a + batch of the accepted type after it, and assembles what it accepted.""" + from orcapod.core.operators.static_output_pod import SourceInfoTypesDisagree + + (_, first_values, first), (_, other_values, other) = ( + TWO_TYPE_CASES[case] + if order == "as_listed" + else list(reversed(TWO_TYPE_CASES[case])) + ) + stream = shaped_source(first) (batch,) = batches_of(stream) - deep = pa.large_list(TOKEN_LISTS) - async def write() -> list[Any]: + async def write() -> Any: output = OutputChannel(stream) - with pytest.raises(RowBuiltFormUnavailable, match="cannot be represented"): - await output.send(_with_amplitude_tokens(batch, 0, [[[], [[]]]], deep)) - await output.send(_with_amplitude_tokens(batch, 0, [["a"]], TOKENS)) + await output.send(_with_amplitude_tokens(batch, 0, first_values, first)) + with pytest.raises(SourceInfoTypesDisagree, match="_source_amplitude"): + await output.send(_with_amplitude_tokens(batch, 1, other_values, other)) + await output.send(_with_amplitude_tokens(batch, 1, first_values, first)) await output.close() - return ( - output.result() - .as_table(columns=ALL) - .column("_source_amplitude") - .to_pylist() - ) + return output.result().as_table(columns=ALL) - assert run(write) == [["a"]] + table = run(write) + assert table.schema.field("_source_amplitude").type == first + assert table.column("_source_amplitude").to_pylist() == [*first_values] * 2 def test_a_duplicate_system_tag_column_is_refused_on_a_declared_stream() -> None: @@ -2230,11 +2356,11 @@ async def write() -> None: run(write) -def test_batch_puts_arrivals_with_differing_token_types_together() -> None: - """``Batch(2)`` over arrivals whose source-info tokens are carried in two types (an - empty list two levels deep, then a token list): it groups them, as a complete table - settles them.""" - stream = source(2) +def test_batch_puts_arrivals_whose_tokens_show_two_depths_together() -> None: + """``Batch(2)`` over arrivals whose source-info tokens show two depths (an empty + list, then a list of token lists), both declared two levels deep: it groups them + under one more list level of the declared type (ITL-1491).""" + stream = shaped_source(TOKEN_LISTS) (batch,) = batches_of(stream) op = Batch(batch_size=2) @@ -2242,7 +2368,7 @@ async def go() -> Any: feed = OutputChannel(stream) reader = feed.open_reader() await feed.send(_with_amplitude_tokens(batch, 0, [[]], TOKEN_LISTS)) - await feed.send(_with_amplitude_tokens(batch, 1, [["b"]], TOKENS)) + await feed.send(_with_amplitude_tokens(batch, 1, [[["b"]]], TOKEN_LISTS)) await feed.close() output = OutputChannel(op(stream)) await op.async_execute_batches([reader], output) @@ -2250,7 +2376,8 @@ async def go() -> Any: table = run(go).as_table(columns=ALL) assert table.num_rows == 1 - assert table.column("_source_amplitude").to_pylist() == [[[], ["b"]]] + assert table.schema.field("_source_amplitude").type == pa.large_list(TOKEN_LISTS) + assert table.column("_source_amplitude").to_pylist() == [[[], [["b"]]]] def test_a_source_nodes_channel_gives_its_output_stream_as_it_is() -> None: diff --git a/tests/test_channels/test_record_batch_review_findings.py b/tests/test_channels/test_record_batch_review_findings.py index 2a2902143..4cffa453d 100644 --- a/tests/test_channels/test_record_batch_review_findings.py +++ b/tests/test_channels/test_record_batch_review_findings.py @@ -384,7 +384,8 @@ def _list_token_stream() -> ArrowTableStream: pa.table( { "k": pa.array([1, 2], pa.int64()), - "x": pa.array([1.5, 2.5], pa.float64()), + # A list token needs list data (the token-shape rule, ITL-1491). + "x": pa.array([[1.5], [2.5]], pa.large_list(pa.float64())), "_source_x": pa.array( [["s::r0::x"], ["s::r1::x"]], pa.large_list(pa.large_string()) ), @@ -394,26 +395,19 @@ def _list_token_stream() -> ArrowTableStream: ) -@pytest.mark.parametrize("where", ["top_level", "list_item"]) -def test_a_source_info_field_carries_no_metadata(where: str) -> None: +def test_a_source_info_field_carries_no_metadata_of_its_own() -> None: """Codex on PR 483, round 2, finding 3: a source-info field carries no field - metadata, at its own level or on a list item, as a row builds it.""" - stream = source() if where == "top_level" else _list_token_stream() + metadata at its own level, as a row builds it.""" + stream = source() (batch,) = batches_of(stream) index = next( i for i, n in enumerate(batch.schema.names) if n.startswith("_source_") ) field = batch.schema.field(index) - if where == "top_level": - tagged = pa.RecordBatch.from_arrays( - batch.columns, - schema=batch.schema.set(index, field.with_metadata({"m": "1"})), - ) - else: - tagged_type = _with_metadata_inside(field.type) - tagged = batch.set_column( - index, field.with_type(tagged_type), batch.column(index).cast(tagged_type) - ) + tagged = pa.RecordBatch.from_arrays( + batch.columns, + schema=batch.schema.set(index, field.with_metadata({"m": "1"})), + ) async def write() -> None: output = OutputChannel(stream) @@ -424,6 +418,40 @@ async def write() -> None: asyncio.run(write()) +def test_a_token_columns_item_metadata_is_part_of_its_declared_type() -> None: + """Restated for ITL-1491 (review of PR #601, P2-4): metadata on a token list's + item field is part of the column's type, which a row keeps as its stream + declares it, so a batch that carries it is taken (it used to be refused as + "carrying field metadata", when a row rebuilt its token type from the value). + Batches of one stream declare one token type, compared strictly: after it, a + batch without the metadata is refused, and another with it is taken.""" + from orcapod.core.operators.static_output_pod import SourceInfoTypesDisagree + + stream = _list_token_stream() + (batch,) = batches_of(stream) + index = next( + i for i, n in enumerate(batch.schema.names) if n.startswith("_source_") + ) + field = batch.schema.field(index) + tagged_type = _with_metadata_inside(field.type) + tagged = batch.set_column( + index, field.with_type(tagged_type), batch.column(index).cast(tagged_type) + ) + + async def write() -> pa.Table: + output = OutputChannel(stream) + await output.send(tagged.slice(0, 1)) + with pytest.raises(SourceInfoTypesDisagree, match=field.name): + await output.send(batch.slice(1, 1)) + await output.send(tagged.slice(1, 1)) + await output.close() + return output.result().as_table(columns={"source": True}) + + result = asyncio.run(write()) + assert result.schema.field(field.name).type.equals(tagged_type, check_metadata=True) + assert result.num_rows == 2 + + # --- A null-typed source-info column (Codex on PR 483, round 2, finding 5: declined) -- @@ -733,16 +761,15 @@ def _token_batch( "shallow_first", [True, False], ids=["shallow_first", "deep_first"] ) @pytest.mark.parametrize("kernel", ["join", "merge_join", "semi_join"]) -def test_tokens_that_cannot_make_one_input_table_are_refused( +def test_batches_of_one_input_that_declare_two_token_types_are_refused( kernel: str, shallow_first: bool ) -> None: - """Codex on PR 510: one batch of an input whose source-info tokens are empty - lists (one list level) and another whose tokens hold strings two levels deep - cannot make one table: the sync path refuses the input when it rebuilds it, - before any match. A kernel refuses the second batch, also when no row would - match, instead of finishing with no row.""" + """Codex on PR 510, restated for ITL-1491: the pipeline determines a token + column's type, so every batch of one input declares the same one. A batch that + declares another (one list level where the other declares two) is refused, also + when no row would match, instead of finishing with no row. The sync path reads + the same rows with the type their stream declares, whatever the tokens show.""" from orcapod.core.operators import Join, MergeJoin, SemiJoin - from orcapod.core.operators.static_output_pod import SourceInfoTypesDisagree from orcapod.core.operators.streaming_joins import ( StreamingJoin, StreamingMergeJoin, @@ -753,7 +780,10 @@ def test_tokens_that_cannot_make_one_input_table_are_refused( pa.table( { "k": pa.array([1, 2], pa.int64()), - "x": pa.array([10, 20], pa.int64()), + # ``x`` has its token's two list layers (the token-shape rule). + "x": pa.array( + [[[10]], [[20]]], pa.large_list(pa.large_list(pa.int64())) + ), "_source_x": pa.array([[["a"]], [["b"]]], DEEP_TOKENS), } ), @@ -773,24 +803,33 @@ def test_tokens_that_cannot_make_one_input_table_are_refused( shallow = _token_batch(left, [[], []], SHALLOW_TOKENS).slice(0, 1) deep = _token_batch(left, [[["a"]], [["b"]]], DEEP_TOKENS).slice(1, 1) batches = [shallow, deep] if shallow_first else [deep, shallow] - # The sync path: the same rows, rebuilt from rows before any match, refuse. + # The sync path: the same rows keep the type their stream declares. tokens = [[], [["b"]]] if shallow_first else [[["a"]], []] mixed = ArrowTableStream( pa.table( { "k": pa.array([1, 2], pa.int64()), - "x": pa.array([10, 20], pa.int64()), + "x": pa.array( + [[[10]], [[20]]], pa.large_list(pa.large_list(pa.int64())) + ), "_source_x": pa.array(tokens, DEEP_TOKENS), } ), tag_columns=["k"], ) - with pytest.raises((pa.ArrowInvalid, ValueError)): - _ = _token_batch(mixed, tokens, DEEP_TOKENS) + rebuilt = _token_batch(mixed, tokens, DEEP_TOKENS) + assert rebuilt.schema.field("_source_x").type == DEEP_TOKENS + assert rebuilt.column("_source_x").to_pylist() == tokens + # The batch that declares another type than its stream is refused when it + # arrives, first or second (a ``SourceInfoTypesDisagree`` is a ``ValueError``); + # the stream's own batch is taken. instance = make() - _ = instance.push(0, batches[0]) - with pytest.raises(SourceInfoTypesDisagree): - _ = instance.push(0, batches[1]) + for batch in batches: + if batch is shallow: + with pytest.raises(ValueError, match="_source_x"): + _ = instance.push(0, batch) + else: + _ = instance.push(0, batch) # The refused batch changed nothing: the input still closes, with no row. assert instance.close(0) == [] @@ -866,7 +905,10 @@ def _deep_token_stream(tokens: list[Any], keys: list[int]) -> ArrowTableStream: pa.table( { "k": pa.array(keys, pa.int64()), - "x": pa.array([10 * k for k in keys], pa.int64()), + # ``x`` has its token's two list layers (the token-shape rule). + "x": pa.array( + [[[10 * k]] for k in keys], pa.large_list(pa.large_list(pa.int64())) + ), "y": pa.array([k + 0.5 for k in keys], pa.float64()), "_source_x": pa.array(tokens, DEEP_TOKENS), } @@ -879,21 +921,20 @@ def _deep_token_stream(tokens: list[Any], keys: list[int]) -> ArrowTableStream: "matching", [True, False], ids=["keys_match", "no_key_matches"] ) @pytest.mark.parametrize("shallow", ["left", "right"]) -def test_merge_join_inputs_whose_tokens_settle_to_two_types_are_refused( +def test_merge_join_inputs_whose_tokens_show_two_depths_are_joined( shallow: str, matching: bool ) -> None: - """CodeRabbit on PR 510 (major): both inputs declare ``_source_x`` two list levels - deep, but one delivers ``[]`` (one level, as its rows type it) and the other - ``[["b"]]``. The sync path rebuilds each input from its rows and ``MergeJoin`` - refuses the two types of one column; the kernel compares the inputs' settled token - types and refuses too, with the same error, whether or not a key matches.""" + """CodeRabbit on PR 510, restated for ITL-1491: both inputs declare ``_source_x`` + two list levels deep; one delivers ``[]`` (which shows one level) and the other + ``[["b"]]``. A token column's type is the one its stream declares, never taken + from the tokens, so the two inputs have one type: the sync path joins them, and + the kernel gives the same rows, whether or not a key matches.""" from orcapod.core.operators import MergeJoin + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.operators.streaming_joins import ( TRANSPORT_COLUMNS, StreamingMergeJoin, ) - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - from orcapod.errors import InputValidationError right_keys = [1, 2] if matching else [7, 8] empty = _deep_token_stream([[], []], [1, 2]) @@ -905,21 +946,32 @@ def rebuilt(stream: ArrowTableStream) -> Any: # pyright: ignore[reportExplicitA list(stream.iter_data()), stream ) - with pytest.raises(InputValidationError) as sync_error: - _ = MergeJoin().static_process(rebuilt(left), rebuilt(right)) + sync = MergeJoin().static_process(rebuilt(left), rebuilt(right)) + expected = sync.as_table(columns=TRANSPORT_COLUMNS) + assert expected.num_rows == (2 if matching else 0) kernel = StreamingMergeJoin(MergeJoin(), (left, right)) batches = [ rebuilt(s).as_table(columns=TRANSPORT_COLUMNS).combine_chunks().to_batches()[0] for s in (left, right) ] - assert kernel.push(0, batches[0]) == [] - with pytest.raises(InputValidationError) as kernel_error: - _ = kernel.push(1, batches[1]) - assert str(kernel_error.value) == str(sync_error.value) + for batch in batches: + assert batch.schema.field("_source_x").type == DEEP_TOKENS + out = kernel.push(0, batches[0]) + kernel.push(1, batches[1]) + out += kernel.close(0) + kernel.close(1) + assert sum(batch.num_rows for batch in out) == expected.num_rows + if matching: + got = pa.Table.from_batches(out).select(expected.column_names) + assert ( + got.schema.field("_source_x").type + == expected.schema.field("_source_x").type + ) + assert sorted(got.to_pylist(), key=lambda row: row["k"]) == sorted( + expected.to_pylist(), key=lambda row: row["k"] + ) def test_merge_join_inputs_whose_tokens_settle_to_one_type_are_joined() -> None: - """CodeRabbit on PR 510: both inputs settle to one list level: they join.""" + """CodeRabbit on PR 510: both inputs hold only empty token lists: they join.""" from orcapod.core.operators import MergeJoin from orcapod.core.operators.streaming_joins import ( TRANSPORT_COLUMNS, @@ -1034,29 +1086,30 @@ def opened_on(self) -> Any: # pyright: ignore[reportExplicitAny] return None -def test_batches_whose_tokens_cannot_make_one_input_table_fail_the_operator() -> None: - """CodeRabbit on PR 510: a row-by-row operator processes batches as they arrive; - a later batch whose source-info tokens cannot make one table with the earlier - ones (``[]``, then ``[["b"]]``) is refused, as the sync path refuses the whole - input, and the output fails instead of completing with part of the rows. The - operator drops the column, so its own output (whose send check settles token - types too) would not see the conflict.""" +def test_batches_that_declare_two_token_types_fail_the_operator() -> None: + """CodeRabbit on PR 510, restated for ITL-1491: a row-by-row operator processes + batches as they arrive; a later batch that declares another source-info token + type than the earlier ones (one list level, then two) is refused, and the output + fails instead of completing with part of the rows. The operator drops the + column, so its own output (whose send check compares token types too) would not + see the conflict. The sync path reads such rows with their stream's one type.""" from orcapod.core.operators import SelectDataColumns from orcapod.core.operators.static_output_pod import SourceInfoTypesDisagree from orcapod.core.streams.record_batch_input import InputChannel - stream = _deep_token_stream([[], [["b"]]], [1, 2]) # its rows: sync refuses + stream = _deep_token_stream([[], [["b"]]], [1, 2]) # its rows: one declared type clean = _deep_token_stream([[["a"]], [["b"]]], [1, 2]) # one schema, buildable shallow = _token_batch(clean, [[], []], SHALLOW_TOKENS).slice(0, 1) deep = _token_batch(clean, [[["a"]], [["b"]]], DEEP_TOKENS).slice(1, 1) op = SelectDataColumns(["y"]) from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - with pytest.raises((pa.ArrowInvalid, ValueError)): - # A job's sync path rebuilds the input from its rows first, and refuses. - _ = StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # the job's sync form - list(stream.iter_data()), stream - ) + # A job's sync path rebuilds the input from its rows, with the stream's type. + rebuilt = StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # the job's sync form + list(stream.iter_data()), stream + ).as_table(columns={"source": True}) + assert rebuilt.schema.field("_source_x").type == DEEP_TOKENS + assert rebuilt.column("_source_x").to_pylist() == [[], [["b"]]] async def go() -> OutputChannel: output = OutputChannel(op(clean)) @@ -1080,12 +1133,12 @@ async def go() -> OutputChannel: def test_settled_tokens_against_an_input_with_no_rows_decide_as_the_sync_path( kernel: str, empty: int, tokens: str ) -> None: - """CodeRabbit on PR 520: one input delivers no rows, the other's tokens settle - ``_source_x`` to one list level (``[]``) or to the two its type declares. The - sync path reads the empty input in its zero-row form (declared two levels) and - the other by its rows; ``MergeJoin`` refuses two types of one column. The kernel - decides as the sync path does when the last input closes: the same error, or the - same rows.""" + """CodeRabbit on PR 520: one input delivers no rows, the other's tokens are empty + lists (``[]``, which show one list level) or fill the two levels its type + declares. The sync path reads the empty input in its zero-row form and the other + by its rows, both with the declared two levels (ITL-1491: a token column's type + is never taken from the tokens), so no kernel refuses. The kernel decides as the + sync path does when the last input closes: the same rows.""" from orcapod.core.operators import Join, MergeJoin, SemiJoin from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.operators.streaming_joins import ( @@ -1105,7 +1158,7 @@ def test_settled_tokens_against_an_input_with_no_rows_decide_as_the_sync_path( pa.table( { "k": pa.array([], pa.int64()), - "w": pa.array([], pa.int64()), + "w": pa.array([], pa.large_list(pa.large_list(pa.int64()))), "_source_w": pa.array([], DEEP_TOKENS), } ), @@ -1138,3 +1191,69 @@ def rebuilt(stream: ArrowTableStream) -> Any: # pyright: ignore[reportExplicitA except Exception as error: # noqa: BLE001 # the refusal is the outcome compared result = (type(error).__name__, str(error)) assert result == sync + assert isinstance(sync, int) + + +# --- Review of PR 601: genuinely different declared token types (ITL-1491) ------------ + + +def _typed_token_stream( + tokens: list[Any], # pyright: ignore[reportExplicitAny] # tokens of any shape + keys: list[int], + kind: pa.DataType, +) -> ArrowTableStream: + """Tags ``k`` and ``g``, data ``x`` (a list) and ``y``; ``x``'s token declared ``kind``. + + ``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( + pa.table( + { + "k": pa.array(keys, pa.int64()), + "g": pa.array([f"g{k}" for k in keys], pa.large_string()), + "x": pa.array([[10 * k] for k in keys], pa.large_list(pa.int64())), + "y": pa.array([k + 0.5 for k in keys], pa.float64()), + "_source_x": pa.array(tokens, kind), + } + ), + tag_columns=["k", "g"], + ) + + +@pytest.mark.parametrize( + "layout", ["keys_match", "no_key_matches", "left_empty", "right_empty"] +) +@pytest.mark.parametrize("listed", ["left", "right"]) +def test_merge_join_inputs_that_declare_two_token_types_are_refused( + listed: str, layout: str +) -> None: + """Review of PR 601: the two inputs DECLARE ``_source_x`` with two types (a list + of tokens in one, a plain string token in the other; both fit the list-valued + ``x``), on matching keys, on keys that never match and with an input that has no + rows. The sync path refuses the two types of one column; the kernel refuses + too, with the same error, when it is built over the inputs, before any batch.""" + from orcapod.core.operators import MergeJoin + from orcapod.core.operators.streaming_joins import StreamingMergeJoin + from orcapod.errors import InputValidationError + + keys = { + "keys_match": ([1, 2], [1, 2]), + "no_key_matches": ([1, 2], [7, 8]), + "left_empty": ([], [1, 2]), + "right_empty": ([1, 2], []), + }[layout] + string = pa.large_string() + kinds = (SHALLOW_TOKENS, string) if listed == "left" else (string, SHALLOW_TOKENS) + left, right = ( + _typed_token_stream( + [["a"] if kind == SHALLOW_TOKENS else "a" for _ in side], side, kind + ) + for side, kind in zip(keys, kinds) + ) + with pytest.raises(InputValidationError) as sync_error: + _ = MergeJoin().static_process(left, right) + assert "'_source_x'" in str(sync_error.value) + with pytest.raises(InputValidationError) as kernel_error: + _ = StreamingMergeJoin(MergeJoin(), (left, right)) + assert str(kernel_error.value) == str(sync_error.value) diff --git a/tests/test_core/datagrams/test_lazy_conversion.py b/tests/test_core/datagrams/test_lazy_conversion.py index 2673b6138..71902bb56 100644 --- a/tests/test_core/datagrams/test_lazy_conversion.py +++ b/tests/test_core/datagrams/test_lazy_conversion.py @@ -310,7 +310,7 @@ def test_copy_before_schema_is_computed_reports_correct_schema(self, include_cac class TestTagLazySystemTagsTable: - """_system_tags_table is built only when system_tags are explicitly requested.""" + """Dictionary tags build their table lazily and Arrow tags keep their fields.""" def test_dict_backed_starts_with_no_system_tags_table(self): t = Tag({"a": 1, f"{SYS}run": "run1"}) @@ -326,8 +326,9 @@ def test_arrow_backed_system_tag_columns_extracted_from_data_table(self): assert sys_col not in t._data_table.column_names # Captured in the system_tags dict assert t._system_tags[sys_col] == "run1" - # Table not yet built - assert t._system_tags_table is None + # Arrow-backed tags retain their declared fields at construction. + assert t._system_tags_table is not None + assert t._system_tags_table.equals(tbl.select([sys_col]), check_metadata=True) def test_system_tags_table_not_built_without_system_tags_flag(self): t = Tag({"a": 1, f"{SYS}run": "run1"}) diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index 1a6a54096..a6116253e 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -15,6 +15,7 @@ import asyncio import decimal +import itertools import re from collections.abc import Callable, Sequence from dataclasses import dataclass @@ -28,6 +29,7 @@ from orcapod.contexts import get_default_context, get_default_type_converter from orcapod.core.cached_function_pod import CachedFunctionPod from orcapod.core.data_function import PythonDataFunction +from orcapod.core.datagrams import Tag from orcapod.core.function_pod import FunctionPod from orcapod.core.operators import ( AddTags, @@ -1013,6 +1015,191 @@ def test_async_rows_equal_sync_rows(case: Case) -> None: ) +@pytest.mark.parametrize("reverse_columns", [False, True]) +@pytest.mark.parametrize("metadata", ["none", "same", "different"]) +def test_standalone_async_join_rows_keep_declared_system_tag_fields( + reverse_columns: bool, + metadata: str, +) -> None: + source_id = "_tag_source_id::seed" + record_id = "_tag_record_id::seed" + schema = pa.schema( + [ + pa.field("k", pa.int64(), False), + pa.field("g", pa.large_string(), False), + pa.field(source_id, pa.large_string(), False), + pa.field(record_id, pa.large_string(), True), + ] + ) + inputs = [] + empty_inputs = [] + for source, records in (("a", [None, "q"]), ("b", ["r", "t"]), ("c", ["s", "u"])): + field_metadata: dict[bytes | str, bytes | str] | None = ( + None + if metadata == "none" + else {b"owner": b"a" if metadata == "same" else source.encode()} + ) + fields = pa.schema( + [ + field.with_metadata(field_metadata) + if field_metadata is not None and field.name in (source_id, record_id) + else field + for field in schema + ] + ) + table = pa.Table.from_pylist( + [ + {"k": i, "g": group, source_id: source, record_id: record} + for i, (group, record) in enumerate( + zip(("x", "y"), records, strict=True) + ) + ], + schema=fields, + ) + if reverse_columns: + table = table.select(list(reversed(schema.names))) + inputs.append( + ArrowTableStream(table, tag_columns=("k", "g"), data_tags=("k", "g")) + ) + empty_inputs.append( + ArrowTableStream( + table.slice(0, 0), tag_columns=("k", "g"), data_tags=("k", "g") + ) + ) + assert len({stream.pipeline_hash() for stream in inputs}) == 1 + columns = {"system_tags": True} + for positions in itertools.permutations(range(len(inputs))): + ordered = [inputs[i] for i in positions] + empty = [empty_inputs[i] for i in positions] + join = Join() + stream = join(*ordered) + table = stream.as_table(columns=columns) + empty_table = join(*empty).as_table(columns=columns) + assert empty_table.num_rows == 0 + assert empty_table.schema.equals(table.schema, check_metadata=True) + tags, _ = join.output_schema(*ordered, columns=columns) + tag_names = [name for name in tags if name.startswith("_tag_")] + assert len(tag_names) == 6 + for name in tag_names: + field = table.schema.field(name) + assert field.metadata is None + assert field.nullable == name.startswith(record_id) + assert tags[name] == (str | None if field.nullable else str) + for rows in (list(stream.iter_data()), async_rows(join, *ordered)): + assert len(rows) == table.num_rows == 2 + for tag, data in rows: + tag_table = tag.as_table(columns=columns) + assert tag_table.schema.equals( + table.select(tag_table.column_names).schema, check_metadata=True + ) + data_table = data.as_table() + assert data_table.schema.equals( + table.select(data_table.column_names).schema, check_metadata=True + ) + + +@pytest.mark.parametrize("reverse_columns", [False, True]) +def test_tied_join_keeps_custom_system_tags_with_their_operand( + reverse_columns: bool, +) -> None: + source_id, record_id, custom = ( + "_tag_source_id::seed", + "_tag_record_id::seed", + "_tag_rev::seed", + ) + inputs = {} + for name in "abc": + schema = pa.schema( + [ + pa.field("k", pa.int64(), False), + pa.field("g", pa.large_string(), False), + pa.field(source_id, pa.large_string(), False), + pa.field(record_id, pa.large_string(), False), + pa.field( + custom, pa.large_string(), name == "a", {b"owner": name.encode()} + ), + ] + ) + table = pa.Table.from_pylist( + [ + { + "k": i, + "g": group, + source_id: name, + record_id: record, + custom: f"{name}{i}", + } + for i, (group, record) in enumerate((("x", "p"), ("y", "q")), start=1) + ], + schema=schema, + ) + if reverse_columns: + table = table.select(list(reversed(table.column_names))) + inputs[name] = ArrowTableStream( + table, tag_columns=["k", "g"], data_tags=["k", "g"] + ) + assert len({stream.pipeline_hash() for stream in inputs.values()}) == 1 + columns = {"system_tags": True} + for order in itertools.permutations(inputs): + operands = [inputs[name] for name in order] + join = Join() + stream = join(*operands) + expected = stream.as_table(columns=columns) + prediction, _ = join.output_schema(*operands, columns=columns) + names = sorted( + name for name in expected.column_names if name.startswith(custom) + ) + for name, owner in zip(names, order, strict=True): + assert expected[name].to_pylist() == [f"{owner}1", f"{owner}2"] + assert prediction[name] == (str | None if owner == "a" else str) + for rows in (list(stream.iter_data()), async_rows(join, *operands)): + assert len(rows) == expected.num_rows + actual = pa.concat_tables( + [tag.as_table(columns=columns).select(names) for tag, _ in rows] + ) + target = expected.select(names) + assert actual.equals(target, check_metadata=True) + assert actual.schema.equals(target.schema, check_metadata=True) + + +@pytest.mark.parametrize("reverse_columns", [False, True]) +def test_raw_stream_rows_keep_system_tag_width_flags_and_metadata( + reverse_columns: bool, +) -> None: + schema = pa.schema( + [ + pa.field("k", pa.int64(), False), + pa.field("g", pa.large_string(), False), + pa.field("x", pa.int16(), False), + pa.field("y", pa.large_string(), True), + pa.field("_tag_rank", pa.int8(), False, metadata={b"purpose": b"rank"}), + pa.field("_tag_label", pa.large_string(), True), + ] + ) + table = pa.Table.from_pylist( + [ + {"k": 1, "g": "a", "x": 4, "y": "x", "_tag_rank": 7, "_tag_label": "a"}, + {"k": 2, "g": "b", "x": 5, "y": None, "_tag_rank": 8, "_tag_label": None}, + ], + schema=schema, + ) + if reverse_columns: + table = table.select(list(reversed(schema.names))) + stream = ArrowTableStream(table, tag_columns=("k", "g")) + columns = {"system_tags": True} + for tag, data in stream.iter_data(): + assert isinstance(tag, Tag) + for row in (tag, tag.copy(include_cache=False)): + got = row.as_table(columns=columns) + assert got.schema.equals( + table.select(got.column_names).schema, check_metadata=True + ) + got_data = data.as_table() + assert got_data.schema.equals( + table.select(got_data.column_names).schema, check_metadata=True + ) + + # ── inputs that are not root sources (ITL-906) ────────────────────────────── @@ -2412,3 +2599,169 @@ def test_strict_selection_naming_a_meta_column_raises_alike( ) as async_error: _ = async_rows(make_op(), source) assert str(async_error.value) == str(sync_error.value) + + +# ── source-info token columns keep the pipeline's type (ITL-1491) ─────────── + +_TOKENS = pa.large_list(pa.large_string()) +_TOKEN_LISTS = pa.large_list(_TOKENS) +_FIXED_TOKENS = pa.list_(pa.large_string(), 2) +# Per layout: the token column of ``a`` and of ``b``, each with values that show +# fewer list levels than the column has, a null inside a list, or a type no value +# gives. A token with a list layer is never null itself, and its data column has +# the same list layers (the token-shape rule): ``_token_stream`` shapes the data. +_TOKEN_LAYOUTS: dict[str, dict[str, tuple[list[Any], pa.DataType]]] = { + "one_level": { + "a": ([[None], [], ["s::0::a", None]], _TOKENS), + "b": ([[], ["u", "v"], [None, None]], _TOKENS), + }, + "two_levels": { + "a": ([[[None]], [[]], [["a"], []]], _TOKEN_LISTS), + "b": ([[[]], [[None], []], [[None, "c"]]], _TOKEN_LISTS), + }, + "fixed_size_and_strings": { + "a": ([["p", "q"], ["r", "s"], ["t", "u"]], _FIXED_TOKENS), + "b": (["s::0::b", None, "s::2::b"], pa.large_string()), + }, +} +_TOKEN_TAG_ORDERS = {"g_then_k": ("g", "k"), "k_then_g": ("k", "g")} + + +def _token_stream( + layout: str, + tags: Sequence[str], + data: Sequence[str] = ("a", "b"), + source_id: str = "t", +) -> ArrowTableStream: + """Three rows, two tags and two data columns, with the layout's token columns. + + The stream is a source's table (so it has the source's system tags) whose + ``_source_*`` columns are replaced; ``data`` renames the two data columns. + """ + from tests.token_shapes import with_token_column + + first, second = data + columns = { + "g": pa.array(["m", "m", "n"], pa.large_string()), + "k": pa.array([1, 2, 1], pa.int64()), + first: pa.array([10, 20, 30], pa.int64()), + second: pa.array([0.5, 1.5, 2.5], pa.float64()), + } + names = [*tags, first, second] + source = ArrowTableSource( + pa.table({name: columns[name] for name in names}), + tag_columns=list(tags), + tag_only_columns=True, + source_id=source_id, + ) + table = source.as_table(columns={"source": True, "system_tags": True}) + for name, (values, kind) in zip(data, _TOKEN_LAYOUTS[layout].values()): + table = with_token_column(table, name, values, kind) + return ArrowTableStream(table, tag_columns=list(tags)) + + +def _listed(kind: pa.DataType, levels: int) -> pa.DataType: + """``kind`` under ``levels`` more list levels.""" + for _ in range(levels): + kind = pa.large_list(kind) + return kind + + +# The operator, its inputs' data names, and the list levels it adds to a token column. +_TOKEN_OPERATORS: dict[ + str, tuple[Callable[[], StaticOutputOperatorPod], tuple[tuple[str, str], ...], int] +] = { + "select": (lambda: SelectDataColumns(["b", "a"]), (("a", "b"),), 0), + "map_data": (lambda: MapData({"a": "a", "b": "b"}), (("a", "b"),), 0), + "join": (Join, (("a", "b"), ("c", "d")), 0), + "semi_join": (SemiJoin, (("a", "b"), ("c", "d")), 0), + "batch": (lambda: Batch(batch_size=2), (("a", "b"),), 1), + "group_by": (lambda: GroupBy(by=["g"]), (("a", "b"),), 1), + "merge_join": (MergeJoin, (("a", "b"), ("a", "b")), 1), +} + + +@pytest.mark.parametrize("tags", list(_TOKEN_TAG_ORDERS)) +@pytest.mark.parametrize("layout", list(_TOKEN_LAYOUTS)) +@pytest.mark.parametrize("operator", list(_TOKEN_OPERATORS)) +def test_token_columns_keep_the_pipelines_type_on_both_paths( + operator: str, layout: str, tags: str +) -> None: + """A token column's type is the pipeline's on the sync and on the async path. + + The inputs' token columns are lists whose values show fewer levels than the + column has, hold nulls, or are fixed-size lists: no value gives their type. Each + operator here determines the output's token type from its input's: unchanged + (select, map, ``Join`` and ``SemiJoin`` over plain tags) or one list level more + (``Batch``, a non-key column under ``GroupBy``, a colliding column under + ``MergeJoin``). The async path yields the sync path's rows, types, hashes and + source info (ITL-1491: the async ``Join`` and the table built from rows typed + each token again from its value, so a null token lost its column's type). + """ + make_op, inputs, levels = _TOKEN_OPERATORS[operator] + order = _TOKEN_TAG_ORDERS[tags] + + def sources() -> tuple[StreamProtocol, ...]: + return tuple( + _token_stream(layout, order, data, source_id=f"t{index}") + for index, data in enumerate(inputs) + ) + + expected = sync_rows(make_op(), *sources()) + actual = async_rows(make_op(), *sources()) + assert expected + assert_equivalent(expected, actual) + assert_same_provenance(expected, actual) + declared = { + name: kind + for data in inputs[: 1 if operator == "semi_join" else None] + for name, (_, kind) in zip(data, _TOKEN_LAYOUTS[layout].values()) + } + for rows in (expected, actual): + for _, data in rows: + in_transit = data.as_table(columns={"source": True}) + for_the_id = data.source_info_table() + for name, kind in declared.items(): + column = f"_source_{name}" + wanted = _listed(kind, levels) + # In transit a token keeps its column's type, a null token too. + assert in_transit.schema.field(column).type == wanted + # For the instance id a null token is a ``large_string`` null. + token = for_the_id.column(column) + assert token.type == (pa.large_string() if token.null_count else wanted) + assert token.to_pylist() == in_transit.column(column).to_pylist() + + +@pytest.mark.parametrize("layout", list(_TOKEN_LAYOUTS)) +@pytest.mark.parametrize("operator", list(_TOKEN_OPERATORS)) +def test_tag_order_changes_no_token_of_a_row(operator: str, layout: str) -> None: + """The two tag orders give the same tokens and token types, row for row.""" + make_op, inputs, _ = _TOKEN_OPERATORS[operator] + seen = [] + for order in _TOKEN_TAG_ORDERS.values(): + rows = async_rows( + make_op(), + *( + _token_stream(layout, order, data, source_id=f"t{index}") + for index, data in enumerate(inputs) + ), + ) + seen.append( + sorted( + ( + repr(sorted(tag.as_dict().items(), key=repr)), + repr( + sorted( + (f.name, str(f.type), repr(c.to_pylist())) + for f, c in zip( + data.as_table(columns={"source": True}).schema, + data.as_table(columns={"source": True}).columns, + ) + if f.name.startswith("_source_") + ) + ), + ) + for tag, data in rows + ) + ) + assert seen[0] == seen[1] diff --git a/tests/test_core/operators/test_index_source_token.py b/tests/test_core/operators/test_index_source_token.py index 5e4a6267c..9f35c8255 100644 --- a/tests/test_core/operators/test_index_source_token.py +++ b/tests/test_core/operators/test_index_source_token.py @@ -11,11 +11,14 @@ from typing import Any import pyarrow as pa +import pytest from orcapod.channels import Channel from orcapod.core.operators import Batch, GroupBy, Index from orcapod.core.sources import ArrowTableSource -from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.core.streams import ArrowTableStream +from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol +from tests.token_shapes import data_for, data_type_for SRC = "src" @@ -157,3 +160,62 @@ def test_zero_row_result_has_every_token_type_of_a_non_empty_one() -> None: empty_schema = empty.as_table(columns={"source": True}).schema full_schema = non_empty.as_table(columns={"source": True}).schema assert empty_schema == full_schema + + +@pytest.mark.parametrize("route", ["sync", "async"]) +@pytest.mark.parametrize("out", [None, "first"]) +@pytest.mark.parametrize("tags", [("k", "g"), ("g", "k")]) +def test_index_keeps_a_projected_token_type_its_value_cannot_show( + route: str, out: str | None, tags: tuple[str, str] +) -> None: + """An element of a four-level token may show only two of its three levels.""" + token = [[], [[]]] + element_type = pa.large_list(pa.large_list(pa.large_list(pa.large_string()))) + input_type = pa.large_list(element_type) + data_type = data_type_for(input_type) + values = pa.array( + [data_for([token], value, data_type) for value in (10, 20)], type=data_type + ) + table = pa.table( + { + "k": [1, 2], + "g": ["a", "b"], + "x": values, + "y": [3, 4], + "_source_x": pa.array([[token], [token]], type=input_type), + "_source_y": pa.array(["kept", "kept"], type=pa.large_string()), + } + ) + upstream = ArrowTableStream( + table.set_column(2, pa.field("x", data_type, nullable=False), values), + tag_columns=list(tags), + ) + op = Index("x", 0, out=out) + + async def run() -> list[tuple[TagProtocol, DataProtocol]]: + op.validate_inputs(upstream) + source: Channel[tuple[TagProtocol, DataProtocol]] = Channel(buffer_size=2) + result: Channel[tuple[TagProtocol, DataProtocol]] = Channel(buffer_size=2) + for row in upstream.iter_data(): + await source.writer.send(row) + await source.writer.close() + await op.async_execute( + [source.reader], + result.writer, + input_pipeline_hashes=[upstream.pipeline_hash()], + ) + return await result.reader.collect() + + rows = list(op(upstream).iter_data()) if route == "sync" else asyncio.run(run()) + assert len(rows) == 2 + for _, data in rows: + table = data.as_table(columns={"source": True}) + name = f"_source_{out or 'x'}" + assert table.column(name).to_pylist() == [token] + assert table.schema.field(name).type.equals(element_type, check_metadata=True) + assert table.column("_source_y").to_pylist() == ["kept"] + if out is not None: + assert table.column("_source_x").to_pylist() == [[token]] + assert table.schema.field("_source_x").type.equals( + input_type, check_metadata=True + ) diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index f6762c14d..960bf4e6a 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -511,7 +511,8 @@ def test_the_provenance_columns_have_the_row_built_schema() -> None: [ pa.field("k", pa.int64()), pa.field(SYSTEM_TAG, pa.large_string(), metadata={"m": "1"}), - pa.field("x", pa.int64()), + # A list token needs list data (the token-shape rule, ITL-1491). + pa.field("x", pa.large_list(pa.int64())), pa.field("z", pa.int64()), pa.field("y", pa.int64()), pa.field( @@ -525,7 +526,7 @@ def test_the_provenance_columns_have_the_row_built_schema() -> None: [ pa.array([1, 2], pa.int64()), pa.array(["s", "s"], pa.large_string()), - pa.array([1, 2], pa.int64()), + pa.array([[1], [2]], pa.large_list(pa.int64())), pa.array([3, 4], pa.int64()), pa.array([5, 6], pa.int64()), pa.array([["a"], ["b"]], schema.field("_source_x").type), @@ -633,16 +634,17 @@ def _schema_outcome(make: Callable[[], StreamProtocol]) -> tuple[str, Any]: @pytest.mark.parametrize("layout", ["one_batch", "one_row_per_batch"]) -def test_empty_source_info_lists_are_typed_from_their_tokens(layout: str) -> None: +def test_empty_source_info_lists_keep_their_columns_type(layout: str) -> None: """A raw stream whose source-info column is a nested list type holding only empty - lists: the channel's result equals the job's sync path, both typing the tokens from - their values over the complete table (``_type_source_info_by_values``), as the rows - do: one list level, not the column's two.""" + 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( pa.table( { "k": pa.array([1, 2], pa.int64()), - "x": pa.array([1, 2], pa.int64()), + # ``x`` has its token's two list layers (the token-shape rule). + "x": pa.array([[], []], pa.large_list(pa.large_list(pa.int64()))), "z": pa.array([3, 4], pa.int64()), "_source_x": pa.array( [[], []], pa.large_list(pa.large_list(pa.large_string())) @@ -657,16 +659,13 @@ def test_empty_source_info_lists_are_typed_from_their_tokens(layout: str) -> Non rebuilt = job_sync.as_table(columns=ALL) assert got.to_pylist() == rebuilt.to_pylist() assert got.schema.equals(rebuilt.schema) - assert got.schema.field("_source_x").type == pa.large_list(pa.large_string()) + assert got.schema.field("_source_x").type == pa.large_list( + pa.large_list(pa.large_string()) + ) -def test_a_system_tag_with_a_null_is_refused_by_the_job_sync_path() -> None: - """Pins a stream no job can run: a raw stream whose system-tag column holds a string - and a null. The job's sync path refuses it (the rows' system-tag fields differ in - their flags), and so does the channel, which builds such a stream from - its rows (CodeRabbit on PR #510); a job never sees such a stream, - because a source with a nullable system tag cannot be bound to a slot - (``SourceSpecMismatchError``).""" +def test_a_raw_nullable_system_tag_keeps_its_field_in_a_job_and_channel() -> None: + """The stream's nullable string field applies to rows with and without a value.""" raw = ArrowTableStream( pa.table( { @@ -678,12 +677,11 @@ def test_a_system_tag_with_a_null_is_refused_by_the_job_sync_path() -> None: ), tag_columns=["k"], ) - assert _schema_outcome(lambda: _job_sync(SelectDataColumns(["x"]), raw)) == ( - "refused", - "ArrowInvalid", - ) - with pytest.raises(pa.ArrowInvalid): - run_on_channels(SelectDataColumns(["x"]), [raw], None) + expected = raw.as_table(columns=ALL).select([SYSTEM_TAG]) + sync = _job_sync(SelectDataColumns(["x"]), raw) + channel = run_on_channels(SelectDataColumns(["x"]), [raw], None) + for result in (sync, channel): + assert_same_table(result.as_table(columns=ALL).select([SYSTEM_TAG]), expected) # --- Ending the output and closing the inputs ------------------------------------------------ diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py index c511d1b5c..709c7a654 100644 --- a/tests/test_core/operators/test_row_built_form.py +++ b/tests/test_core/operators/test_row_built_form.py @@ -28,7 +28,6 @@ from orcapod import PipelineJob from orcapod.core.operators import Batch, DropNulls, SelectDataColumns from orcapod.core.operators.static_output_pod import ( - SourceInfoTypesDisagree, StaticOutputOperatorPod, ) from orcapod.databases import InMemoryArrowDatabase @@ -36,7 +35,9 @@ from orcapod.types import CacheMode from orcapod.core.streams import ArrowTableStream from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns +from orcapod.errors import InputValidationError from orcapod.system_constants import constants +from tests.token_shapes import data_type_for, nested_value, with_token_column from tests.test_core.operators.test_async_sync_equivalence import ( AFTER_OPERATOR_CASES, CASES, @@ -154,7 +155,8 @@ def _raw_stream() -> ArrowTableStream: "k": pa.array([1, 2], pa.int64()), "j": pa.array(["a", "b"], pa.large_string()), system_tag: pa.array(["s1", "s2"], pa.large_string()), - "x": pa.array([1.0, float("nan")]), + # A list token needs list data (the token-shape rule, ITL-1491). + "x": pa.array([[1.0, float("nan")], [2.0]], pa.large_list(pa.float64())), "z": pa.array([3, None], pa.int8()), "__note": pa.array(["a", "b"]), "_source_x": pa.array([["a", "b"], ["c"]], pa.large_list(member)), @@ -200,33 +202,50 @@ def test_row_built_form_of_a_raw_stream(make: Any) -> None: assert_same_values(formed, built) -def _source_table() -> pa.Table: - """A source's table with its system tags and source info (one tag, one data).""" - from orcapod.sources import DictSource +def _source(kind: pa.DataType | None = None) -> Any: + """A source with one tag and one data column, ``x``. - source = DictSource( - [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + Args: + kind: A token type whose list layers ``x`` is given (the token-shape rule, + ITL-1491: a list token needs list data); ``None`` for a plain integer. + """ + from orcapod.sources import ArrowTableSource + + data_type = data_type_for(kind or pa.large_string()) + schema = pa.schema( + [ + pa.field("k", pa.int64(), nullable=False), + pa.field("x", data_type, nullable=False), + ] + ) + return ArrowTableSource( + pa.Table.from_arrays( + [ + pa.array([1, 2], pa.int64()), + pa.array([nested_value(v, data_type) for v in (1, 2)], data_type), + ], + schema=schema, + ), tag_columns=["k"], tag_only_columns=True, source_id="s", ) - return source.as_table(columns={"source": True, "system_tags": True}) + + +def _source_table() -> pa.Table: + """A source's table with its system tags and source info (one tag, one data).""" + return _source().as_table(columns={"source": True, "system_tags": True}) def _with_source_x(values: list[Any], kind: pa.DataType) -> ArrowTableStream: """A source's rows as a raw stream, ``_source_x`` replaced by ``values`` of ``kind``. - It keeps the source's system-tag pair, so a job slot accepts it (Codex on PR #485). + ``x`` gets the list layers of ``kind``, each row's value at every token position + (the token-shape rule, ITL-1491). The stream keeps the source's system-tag pair, + so a job slot accepts it (Codex on PR #485). """ - table = _source_table() - position = table.schema.get_field_index("_source_x") return ArrowTableStream( - table.set_column( - position, - pa.field("_source_x", kind, nullable=True), - pa.array(values, kind), - ), - tag_columns=["k"], + with_token_column(_source_table(), "x", values, kind), tag_columns=["k"] ) @@ -238,9 +257,9 @@ def _with_source_x(values: list[Any], kind: pa.DataType) -> ArrowTableStream: "make", [ pytest.param(lambda: _with_source_x([[], []], _NESTED), id="empty-lists"), - pytest.param(lambda: _with_source_x([None, None], _STRINGS), id="null-lists"), + pytest.param(lambda: _with_source_x([[], []], _STRINGS), id="empty-strings"), pytest.param( - lambda: _with_source_x([[None], [None]], _NESTED), id="lists-of-null" + lambda: _with_source_x([[[None]], [[None]]], _NESTED), id="lists-of-null" ), pytest.param( lambda: Batch(batch_size=1)( @@ -249,42 +268,79 @@ def _with_source_x(values: list[Any], kind: pa.DataType) -> ArrowTableStream: id="batch-1-of-null-tokens", ), pytest.param( - lambda: Batch(batch_size=2)(_with_source_x([None, None], _STRINGS)), - id="batch-2-of-null-lists", + lambda: Batch(batch_size=2)( + _with_source_x([None, None], pa.large_string()) + ), + id="batch-2-of-null-tokens", ), pytest.param(lambda: _with_source_x([None, None], pa.null()), id="null-type"), ], ) -def test_source_info_types_follow_the_tokens(make: Any) -> None: - """F types each source-info column from its tokens, as the rows do. +def test_source_info_types_are_the_streams(make: Any) -> None: + """F keeps each source-info column's type, as the rows do (ITL-1491). - A list of ``None`` or of empty lists shows fewer levels than its column declares; - the rows type it from the tokens (``arrow_utils.source_info_arrow_type``), and so - does F, over the whole table. + A list of ``None`` or of empty lists shows fewer levels than its column declares. + The pipeline determines the column's type; neither the rows nor F take it from + the tokens: both give the stream's type (a ``null`` column as ``large_string``, + as every datagram stores it). """ stream = make() built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle + table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test - stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + table, stream.keys() ) assert formed.column_names == built.column_names assert formed.schema.equals(built.schema, check_metadata=True) assert_same_values(formed, built) + declared = table.schema.field("_source_x").type + assert formed.schema.field("_source_x").type == ( + pa.large_string() if pa.types.is_null(declared) else declared + ) -def test_tokens_of_two_types_raise_as_the_rows_do() -> None: - """A list token on one row and ``None`` on another: no table holds both rows. - - The rows' tables cannot be concatenated (``ArrowInvalid``); F says so - (``SourceInfoTypesDisagree``), and a node then builds the rows, which raise. +@pytest.mark.parametrize( + ("values", "kind"), + [ + pytest.param([["s"], []], _STRINGS, id="list-beside-empty"), + pytest.param([[[None]], [["s"]]], _NESTED, id="null-inside-beside-nested"), + pytest.param([[], [["s"]]], _NESTED, id="empty-beside-nested"), + pytest.param( + [[[], [[]]], [[["t"]]]], pa.large_list(_NESTED), id="three-levels" + ), + pytest.param( + [["a", "b"], ["c", "d"]], pa.list_(pa.large_string(), 2), id="fixed-size" + ), + pytest.param( + [["a"], ["b"]], + pa.large_list(pa.field("member", pa.large_string(), nullable=False)), + id="named-non-null-item", + ), + ], +) +def test_tokens_no_value_could_type_alike_make_one_table( + values: list[Any], kind: pa.DataType +) -> None: + """Rows whose tokens show two shapes, or a type no value gives, make one table. + + Before ITL-1491 each row typed its token from its value, so a token that shows + fewer levels than its column (an empty list, a null inside a list) could not be + concatenated with a full one (``ArrowInvalid``), and F said so + (``SourceInfoTypesDisagree``). The rows and F now keep the stream's type: a + fixed-size list stays one, and a list's item field keeps its name and + nullability. (A null list token is not a valid token: the test below.) """ - stream = _with_source_x([["s"], None], _STRINGS) - with pytest.raises(pa.ArrowInvalid, match="Schema at index 1 was different"): - StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle - with pytest.raises(SourceInfoTypesDisagree, match="_source_x"): - StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test - stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() - ) + stream = _with_source_x(values, kind) + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle + formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + ) + for table in (built, formed): + field = table.schema.field("_source_x") + assert field.type.equals(kind, check_metadata=True) + assert field.nullable == (None in values) + assert table.column("_source_x").to_pylist() == values + assert formed.schema.equals(built.schema, check_metadata=True) class _NodeEvents(NoOpObserver): @@ -305,16 +361,14 @@ def on_node_end(self, node_label: str, node_hash: str) -> None: self.events.append(("end", node_label)) -def _batched_job(database: InMemoryArrowDatabase) -> PipelineJob: - """``source -> select x -> Batch(2)``, the batch node in ``LOG`` mode.""" - from orcapod.sources import DictSource +def _batched_job( + database: InMemoryArrowDatabase, kind: pa.DataType | None = None +) -> PipelineJob: + """``source -> select x -> Batch(2)``, the batch node in ``LOG`` mode. - source = DictSource( - [{"k": 1, "x": 1}, {"k": 2, "x": 2}], - tag_columns=["k"], - tag_only_columns=True, - source_id="s", - ) + ``x`` has the list layers of the token type ``kind`` its slot is to be bound with. + """ + source = _source(kind) job = PipelineJob(name="source_info_types", database=database) with job: Batch(batch_size=2)(source.select_data_columns(["x"]), label="batched") @@ -324,36 +378,91 @@ def _batched_job(database: InMemoryArrowDatabase) -> PipelineJob: return job -def test_a_job_keeps_and_stores_the_token_type_the_rows_give() -> None: - """A bound raw source with null list tokens, through ``Batch(2)`` in ``LOG`` mode. +@pytest.mark.parametrize( + ("values", "kind"), + [ + pytest.param([None, None], _STRINGS, id="null-lists"), + pytest.param([["s"], None], _STRINGS, id="list-beside-null"), + pytest.param([None, [["s"]]], _NESTED, id="null-beside-nested"), + pytest.param( + [None, ["a", "b"]], pa.list_(pa.large_string(), 2), id="null-fixed" + ), + ], +) +def test_a_null_list_token_is_refused_when_the_stream_is_built( + values: list[Any], kind: pa.DataType +) -> None: + """A token that has a list layer is never null (the token-shape rule, ITL-1491). + + Replaces the cases that built streams with null list tokens ("null-lists", + "batch-2-of-null-lists", "list-beside-null", and the job over null list tokens + through ``Batch(2)``): such a stream is refused where it is built, naming the + token column, its data column and both types, so neither F, the rows nor a job + ever sees one. It still protects what those cases did: no table is built whose + rows disagree on a token column's type. + """ + with pytest.raises(InputValidationError) as refused: + _ = _with_source_x(values, kind) + message = str(refused.value) + assert "'_source_x'" in message and "'x'" in message + assert str(kind) in message and str(data_type_for(kind)) in message + assert "null" in message + - The rows type ``[None, None]`` as ``large_list``: kept and stored so, - as on ``main``, not as the list of the input's declared list type. +def test_a_job_keeps_and_stores_the_token_type_of_a_batch_of_null_tokens() -> None: + """A bound raw source with null string tokens, through ``Batch(2)`` in ``LOG`` mode. + + A plain string token may be null. ``Batch`` puts the two null tokens into one + list, an element of which may be null: kept and stored as + ``large_list``, the type ``Batch`` declares over string tokens. """ database = InMemoryArrowDatabase() job = _batched_job(database) - job.bind(sources={"s": _with_source_x([None, None], _STRINGS)}) + job.bind(sources={"s": _with_source_x([None, None], pa.large_string())}) job.run() node = job.nodes["batched"] kept = node.as_table(columns={"source": True}) assert kept.schema.field("_source_x").type == _STRINGS + assert kept.column("_source_x").to_pylist() == [[None, None]] stored = node.get_all_records(columns={"source": True}) assert stored is not None assert stored.schema.field("_source_x").type == _STRINGS -def test_a_job_over_tokens_of_two_types_fails_as_main_does() -> None: - """The run raises the rows' ``ArrowInvalid`` after the source node has ended. - - On ``main`` the source node hands its rows on, and the run fails where they are - concatenated for its successor: the same error, after the same events. +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize( + ("values", "kind"), + [ + pytest.param([["s"], []], _STRINGS, id="list-beside-empty"), + pytest.param([[[], [[]]], [[], [[]]]], pa.large_list(_NESTED), id="deep"), + ], +) +def test_a_job_over_tokens_no_value_could_type_alike_completes( + values: list[Any], kind: pa.DataType, asynchronous: bool +) -> None: + """Rows that used to raise where they are built into one table now pass. + + A list token beside an empty list and a token whose value shows fewer levels + than its column (``ArrowTypeError``) raised at the successor's edge, as on + ``main``. The rows keep the stream's token type + (ITL-1491), so the run completes on both orchestrators, with the same events + and the same batch: one more list level of the declared type. """ - job = _batched_job(InMemoryArrowDatabase()) - job.bind(sources={"s": _with_source_x([["s"], None], _STRINGS)}) + from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator + + job = _batched_job(InMemoryArrowDatabase(), kind) + job.bind(sources={"s": _with_source_x(values, kind)}) observer = _NodeEvents() - with pytest.raises(pa.ArrowInvalid, match="Schema at index 1 was different"): - job.run(observer=observer) - assert observer.events == [("start", "s"), ("end", "s")] + orchestrator = ( + AsyncPipelineOrchestrator() if asynchronous else SyncPipelineOrchestrator() + ) + job.run(observer=observer, orchestrator=orchestrator) + assert sorted(observer.events) == sorted( + (event, label) for label in job.nodes for event in ("start", "end") + ) + kept = job.nodes["batched"].as_table(columns={"source": True}) + assert kept.schema.field("_source_x").type == pa.large_list(kind) + assert kept.column("_source_x").to_pylist() == [values] def test_a_source_with_a_nullable_system_tag_is_not_bound() -> None: @@ -391,19 +500,3 @@ def test_a_source_with_a_nullable_system_tag_is_not_bound() -> None: slot = next(label for label in job.nodes if label != "selected") with pytest.raises(SourceSpecMismatchError, match="record_id"): job.bind(sources={slot: ArrowTableStream(with_null, tag_columns=["k"])}) - - -def test_a_token_the_rows_cannot_convert_fails_as_main_does() -> None: - """A conversion failure of F's whole-table build falls back to the rows, as on main. - - Each row's token ``[None, [[]]]`` gives one list level (``source_info_arrow_type``), - whose conversion fails (``ArrowTypeError``). The node builds its rows, which raise - the same error, after the source node has ended (Codex on PR #485, round 2). - """ - nested = pa.large_list(_NESTED) - job = _batched_job(InMemoryArrowDatabase()) - job.bind(sources={"s": _with_source_x([[None, [[]]], [None, [[]]]], nested)}) - observer = _NodeEvents() - with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): - job.run(observer=observer) - assert observer.events == [("start", "s"), ("end", "s")] diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index 8422ffbb5..544cf0429 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -952,13 +952,19 @@ def test_join_keeps_nullable_tied_raw_system_tag_fields() -> None: def _data_tag_stream(data: str, tokens: list[list[str]]) -> ArrowTableStream: - """A stream with data-tag ``k`` whose source info is a token list per row.""" + """A stream with data-tag ``k`` whose source info is a token list per row. + + ``k`` and the data column are lists: a list token needs list data (the + token-shape rule, ITL-1491). The rule reads types only, so a token list may + still be longer than its data list, which is what these tests are about. + """ token_list = pa.large_list(pa.large_string()) + values = pa.large_list(pa.int64()) return ArrowTableStream( pa.table( { - "k": pa.array([1, 2], pa.int64()), - data: pa.array([1, 2], pa.int64()), + "k": pa.array([[1], [2]], values), + data: pa.array([[1], [2]], values), "_source_k": pa.array(tokens, token_list), f"_source_{data}": pa.array([["s"], ["t"]], token_list), } @@ -1164,13 +1170,18 @@ def test_a_source_refuses_a_null_typed_column( def _tokens_stream( data: str, keys: list[int], tokens: list[list[str]] ) -> ArrowTableStream: - """A stream with data-tag ``k`` (keys in this order) and token lists per row.""" + """A stream with data-tag ``k`` (keys in this order) and token lists per row. + + ``k`` and the data column are lists, as their list tokens need (the token-shape + rule, ITL-1491). + """ token_list = pa.large_list(pa.large_string()) + values = pa.large_list(pa.int64()) return ArrowTableStream( pa.table( { - "k": pa.array(keys, pa.int64()), - data: pa.array(list(range(len(keys))), pa.int64()), + "k": pa.array([[key] for key in keys], values), + data: pa.array([[i] for i in range(len(keys))], values), "_source_k": pa.array(tokens, token_list), f"_source_{data}": pa.array([["s"]] * len(keys), token_list), } @@ -1319,12 +1330,21 @@ def test_merge_join_over_inputs_with_a_meta_column( def _token_stream(tokens: list[Any], token_type: pa.DataType) -> ArrowTableStream: - """Tag ``k``, data ``x``, and ``x``'s source info as the given tokens.""" + """Tag ``k``, data ``x``, and ``x``'s source info as the given tokens. + + ``x`` has the tokens' list layers (the token-shape rule, ITL-1491). + """ + from tests.token_shapes import data_for, data_type_for + + data_type = data_type_for(token_type) return ArrowTableStream( pa.table( { "k": pa.array([1, 2], pa.int64()), - "x": pa.array([10, 20], pa.int64()), + "x": pa.array( + [data_for(t, v, data_type) for t, v in zip(tokens, (10, 20))], + data_type, + ), "_source_x": pa.array(tokens, token_type), } ), @@ -1342,22 +1362,26 @@ def _token_stream(tokens: list[Any], token_type: pa.DataType) -> ArrowTableStrea ([None, None], pa.large_string()), ([[], []], SHALLOW), ([[None], []], SHALLOW), + (["s::r0::x", "s::r1::x"], pa.large_string()), ], - ids=["all_null", "empty_lists", "null_item_and_empty"], + ids=["all_null", "empty_lists", "null_item_and_empty", "strings"], ) @pytest.mark.parametrize( "make_kernel", [_join_kernel, _merge_kernel, _semi_kernel], ids=["join", "merge_join", "semi_join"], ) -def test_shallower_source_info_tokens_are_taken_with_every_value( +def test_a_batch_that_declares_another_token_type_than_its_stream_is_refused( tokens: list[Any], token_type: pa.DataType, make_kernel: Callable[[Sequence[StreamProtocol]], StreamingJoinKernel], ) -> None: - """CodeRabbit on PR 510: a batch's source-info token type follows its own tokens, - so nulls and empty lists can give fewer list levels than the input's layout. Such - a batch is taken, every token kept; a token the layout cannot hold is refused.""" + """CodeRabbit on PR 510, restated for ITL-1491: a source-info column's type is + the one its stream declares, and a batch never brings its own. A batch whose + tokens are carried in another type (fewer list levels, as a row once typed + nulls and empty lists from their values; or plain strings) is refused, naming + the column and both types, and changes nothing. It used to be converted to the + stream's type when every value allowed it.""" left = _token_stream([[["a"]], [["b"]]], DEEP) right = ArrowTableStream( pa.table( @@ -1366,30 +1390,97 @@ def test_shallower_source_info_tokens_are_taken_with_every_value( tag_columns=["k"], ) kernel = make_kernel((left, right)) - # The left input's rows as sent, with the tokens in their own, shallower type. sent = _sent(left).combine_chunks() index = sent.schema.get_field_index("_source_x") batch = sent.set_column( index, pa.field("_source_x", token_type), pa.array(tokens, token_type) ).to_batches()[0] assert batch.schema.field("_source_x").type != DEEP - out = kernel.push(0, batch) + with pytest.raises(ValueError, match="_source_x") as refused: + _ = kernel.push(0, batch) + assert str(token_type) in str(refused.value) and str(DEEP) in str(refused.value) + # The refused batch changed nothing: the stream's own batch is taken after it. + out = kernel.push(0, sent.to_batches()[0]) + out += kernel.push(1, _sent(right).combine_chunks().to_batches()[0]) + out += kernel.close(0) + kernel.close(1) + assert sum(batch.num_rows for batch in out) == 2 + + +@pytest.mark.parametrize("mismatch", ["item_name", "item_metadata"]) +@pytest.mark.parametrize( + "make_kernel", + [_join_kernel, _merge_kernel, _semi_kernel], + ids=["join", "merge_join", "semi_join"], +) +def test_a_first_batch_with_different_token_item_fields_is_refused( + mismatch: str, + make_kernel: Callable[[Sequence[StreamProtocol]], StreamingJoinKernel], +) -> None: + """The first batch must match the stream's nested item name and metadata.""" + values = [["a"], ["b"]] + string = pa.large_string() + declared = pa.large_list(pa.field("member", string, metadata={"m": "original"})) + wrong = ( + pa.large_list(pa.field("other", string, metadata={"m": "original"})) + if mismatch == "item_name" + else pa.large_list(pa.field("member", string, metadata={"m": "changed"})) + ) + left = _token_stream(values, declared) + right = ArrowTableStream(pa.table({"k": [1, 2], "y": [5, 6]}), tag_columns=["k"]) + kernel = make_kernel((left, right)) + sent = _sent(left).combine_chunks() + index = sent.schema.get_field_index("_source_x") + field = sent.schema.field(index) + assert field.type.equals(declared, check_metadata=True) + assert not field.type.equals(wrong, check_metadata=True) + batch = sent.set_column( + index, field.with_type(wrong), pa.array(values, type=wrong) + ).to_batches()[0] + with pytest.raises(ValueError, match="_source_x"): + _ = kernel.push(0, batch) + + out = kernel.push(0, sent.to_batches()[0]) out += kernel.push(1, _sent(right).combine_chunks().to_batches()[0]) out += kernel.close(0) + kernel.close(1) + assert sum(batch.num_rows for batch in out) == 2 + assert all( + batch.schema.field("_source_x").type.equals(declared, check_metadata=True) + for batch in out + if batch.num_rows + ) + + +@pytest.mark.parametrize( + "tokens", + [[[], []], [[[None]], [[]]], [[[None]], [["b"]]]], + ids=["empty_lists", "null_and_empty_inner_lists", "null_token_inside"], +) +@pytest.mark.parametrize( + "make_kernel", + [_join_kernel, _merge_kernel, _semi_kernel], + ids=["join", "merge_join", "semi_join"], +) +def test_tokens_that_show_fewer_levels_keep_their_streams_type( + tokens: list[Any], + make_kernel: Callable[[Sequence[StreamProtocol]], StreamingJoinKernel], +) -> None: + """Empty lists and nulls inside a token show fewer list levels than the column + has; carried in the stream's declared type they are taken, every token kept.""" from orcapod.core.operators.static_output_pod import concatenate_batches - # Emitted batches type their source info by their own tokens; the complete - # table settles them (``concatenate_batches``). + left = _token_stream(tokens, DEEP) + right = ArrowTableStream( + pa.table( + {"k": pa.array([1, 2], pa.int64()), "y": pa.array([5, 6], pa.int64())} + ), + tag_columns=["k"], + ) + kernel = make_kernel((left, right)) + out = kernel.push(0, _sent(left).combine_chunks().to_batches()[0]) + out += kernel.push(1, _sent(right).combine_chunks().to_batches()[0]) + out += kernel.close(0) + kernel.close(1) got = concatenate_batches(out) - assert got is not None - assert got.num_rows == 2 + assert got is not None and got.num_rows == 2 + assert got.schema.field("_source_x").type == DEEP by_key = dict(zip(got.column("k").to_pylist(), got.column("_source_x").to_pylist())) assert by_key == {1: tokens[0], 2: tokens[1]} - # A token the layout's type cannot hold is still refused. - refused = sent.set_column( - index, - pa.field("_source_x", pa.large_string()), - pa.array(["s::r0::x", "s::r1::x"], pa.large_string()), - ).to_batches()[0] - with pytest.raises(ValueError, match="_source_x"): - make_kernel((left, right)).push(0, refused) diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index ff7f5d0b2..d72353008 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -2,10 +2,12 @@ from __future__ import annotations +import asyncio import sqlite3 from collections.abc import Collection from pathlib import Path from typing import Any, TypedDict +from uuid import UUID import deltalake import polars as pl @@ -16,6 +18,7 @@ from orcapod import PipelineJob from orcapod.contexts.stored import with_data_context from orcapod.core.nodes.operator_node import OperatorJobNode +from orcapod.core.row_ids import entry_id, instance_id, record_id from orcapod.core.sources import ( ArrowTableSource, CachedSource, @@ -32,7 +35,7 @@ ) from orcapod.core.sources.source_proxy import SourceProxy from orcapod.core.streams import ArrowTableStream -from orcapod.databases import InMemoryArrowDatabase +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.errors import InputValidationError from orcapod.operators import DropNulls from orcapod.protocols.core_protocols import StreamProtocol @@ -119,6 +122,13 @@ def _source( deltalake.write_deltalake(path / "delta", table) return DeltaTableSource(path / "delta", **options) if kind == "sqlite": + if any(field.metadata for field in table.schema): + # SQLite cannot store Arrow field metadata. Supply it at the reader boundary. + monkeypatch.setattr( + "orcapod.core.sources.sqlite_table_source.SQLiteConnector", + lambda *_: _Connector(table), + ) + return SQLiteTableSource(path / "rows.db", "rows", **options) file = path / "rows.db" types = {pa.string(): "TEXT", pa.int64(): "INTEGER"} cols = ", ".join( @@ -211,6 +221,81 @@ def test_refuses_missing_custom_system_tag_columns( _source(kind, table, tmp_path, monkeypatch, system_tag_columns=names) +@pytest.mark.parametrize("kind", SOURCE_KINDS) +@pytest.mark.parametrize( + "metadata", + [ + {b"owner": b"research"}, + {b"ARROW:extension:name": b"user.opaque", b"ARROW:extension:metadata": b""}, + ], + ids=["ordinary", "extension"], +) +@pytest.mark.parametrize("names", [("extra",), ("extra", "rev"), ("rev", "extra")]) +def test_refuses_field_metadata_on_custom_system_tags( + kind: str, + metadata: dict[bytes, bytes], + names: tuple[str, ...], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + table = _table( + pa.field("extra", pa.string(), nullable=False, metadata=metadata), ["a", "b"] + ) + with pytest.raises( + InputValidationError, match=r"'extra'.*[Rr]emove.*field metadata" + ): + _source(kind, table, tmp_path, monkeypatch, system_tag_columns=names) + + +def test_metadata_free_custom_system_tag_keeps_its_existing_row_ids() -> None: + schema = pa.schema( + [ + pa.field("k", pa.int64(), False), + pa.field("g", pa.large_string(), False), + pa.field("x", pa.int64(), False), + pa.field("y", pa.large_string(), False), + pa.field("custom", pa.large_string(), False), + ] + ) + raw = pa.Table.from_pydict( + { + "k": [1, 2], + "g": ["a", "b"], + "x": [3, 4], + "y": ["v", "w"], + "custom": ["p", "q"], + }, + schema=schema, + ) + source = ArrowTableSource( + raw, + tag_columns=TAGS, + tag_only_columns=True, + system_tag_columns=["custom"], + source_id="meta", + ) + hasher = source.data_context.arrow_hasher + actual = [] + for tag, data in source.iter_data(): + entry = entry_id(hasher, tag, data) + instance = instance_id(hasher, tag, data) + record = record_id(hasher, source.content_hash(), instance, UUID(int=40)) + actual.append((entry.to_hex(), instance.to_hex(), record.to_hex())) + # The metadata-free source's hashes at 969ed093. + assert actual == [ + ( + "00000266ff2e58dd5c1cb957ac9ff249ae13e17918a263847f8e2f65d756f746b3f561", + "000002e9be964a36d499b5a1efe697c53d9b7e2e0103b79be7b0e2d489c1be8f7b8636", + "00000279f295215ecb6c92fc49cf4ec41df41327a43c3b351f0baac467b4f45a0f33d2", + ), + ( + "0000029689a4a738cf93bbcfde75085dc43bac31570b0b368eff34b0f3d0fa427769c1", + "000002b6b64a14a2bb8cc662759a15839f8e4e730c89a03230bb8cac2f951fbe8f2002", + "000002fb3fc3affffe0e390dcfb5695db61b332eb2d38f83c2cfab5570c8a956371e18", + ), + ] + + @pytest.mark.parametrize("kind", SOURCE_KINDS) def test_accepts_two_non_nullable_string_system_tags( kind: str, @@ -391,6 +476,249 @@ def test_cached_source_refuses_an_existing_stored_null_column() -> None: cached.as_table() +@pytest.mark.parametrize("route", ["table", "rows", "async_rows", "stored"]) +def test_reopened_cache_refuses_legacy_system_tag_metadata( + route: str, + tmp_path: Path, +) -> None: + source = ArrowTableSource( + _table(pa.field("extra", pa.string(), False), ["a", "b"]), + tag_columns=TAGS, + tag_only_columns=True, + system_tag_columns=["extra"], + source_id="rows", + ) + cache = source.cached(DeltaTableDatabase(tmp_path)) + columns = {"source": True, "system_tags": True} + records = source.as_table(columns=columns) + name = "_tag_extra" + pos = records.schema.get_field_index(name) + field = records.schema.field(pos).with_metadata( + {b"ARROW:extension:name": b"user.opaque"} + ) + records = records.set_column(pos, field, records.column(pos)) + records = records.append_column( + CachedSource.HASH_COLUMN_NAME, pa.array([b"a", b"b"]) + ) + DeltaTableDatabase(tmp_path).add_records( + cache.cache_path, + with_data_context(records, source.data_context_key), + record_id_column=CachedSource.HASH_COLUMN_NAME, + flush=True, + ) + reopened = CachedSource.from_config(cache.to_config()) + + async def consume() -> None: + _ = [row async for row in reopened.async_iter_data()] + + with pytest.raises( + InputValidationError, + match=r"'_tag_extra'.*cache.*written.*field metadata.*[Rr]ebuild", + ): + if route == "table": + reopened.as_table(columns=columns) + elif route == "rows": + list(reopened.iter_data()) + elif route == "async_rows": + asyncio.run(consume()) + else: + reopened.get_all_records() + + +class _ArrowStreamExporter: + def __init__(self, table: pa.Table) -> None: + self.table = table + self.exports = 0 + + def __arrow_c_stream__(self, requested_schema: Any = None) -> Any: + self.exports += 1 + return self.table.__arrow_c_stream__(requested_schema) + + +class _ArrowArrayExporter: + def __init__(self, batch: pa.RecordBatch) -> None: + self.batch = batch + self.exports = 0 + + def __arrow_c_array__(self, requested_schema: Any = None) -> Any: + self.exports += 1 + return self.batch.__arrow_c_array__(requested_schema) + + +class _DualArrowExporter(_ArrowArrayExporter): + def __init__(self, batch: pa.RecordBatch, stream: pa.Table) -> None: + super().__init__(batch) + self.stream = stream + self.stream_exports = 0 + + def __arrow_c_stream__(self, requested_schema: Any = None) -> Any: + self.stream_exports += 1 + return self.stream.__arrow_c_stream__(requested_schema) + + +@pytest.mark.parametrize( + "representation", ["table", "batch", "reader", "stream", "array", "dual"] +) +@pytest.mark.parametrize("row_count", [0, 2]) +@pytest.mark.parametrize("declare_schema", [False, True]) +@pytest.mark.parametrize("field_metadata", [None, {b"owner": b"research"}]) +def test_dataframe_source_validates_arrow_inputs_before_polars( + representation: str, + row_count: int, + declare_schema: bool, + field_metadata: dict[bytes | str, bytes | str] | None, +) -> None: + clean = _table(pa.field("extra", pa.string(), False), ["a", "b"][:row_count]) + pos = clean.schema.get_field_index("extra") + table = ( + clean + if field_metadata is None + else clean.set_column( + pos, + clean.schema.field(pos).with_metadata(field_metadata), + clean.column(pos), + ) + ) + batch = pa.RecordBatch.from_arrays( + [c.combine_chunks() for c in table.columns], schema=table.schema + ) + representations = { + "table": table, + "batch": batch, + "reader": table.to_reader(max_chunksize=1), + "stream": _ArrowStreamExporter(table), + "array": _ArrowArrayExporter(batch), + "dual": _DualArrowExporter(batch, clean), + } + data = representations[representation] + schema = clean.schema if declare_schema else None + + if field_metadata is not None: + with pytest.raises( + InputValidationError, match=r"'extra'.*[Rr]emove.*field metadata" + ): + DataFrameSource( + data, + schema=schema, + tag_columns=TAGS, + system_tag_columns=["rev", "extra"], + ) + else: + source = DataFrameSource( + data, schema=schema, tag_columns=TAGS, system_tag_columns=["rev", "extra"] + ) + expected = DataFrameSource( + clean, schema=schema, tag_columns=TAGS, system_tag_columns=["rev", "extra"] + ) + columns = {"system_tags": True, "source": True} + actual_table = source.as_table(columns=columns) + assert actual_table.num_rows == row_count + assert actual_table.equals( + expected.as_table(columns=columns), check_metadata=True + ) + assert source.source_id == expected.source_id + assert source.content_hash() == expected.content_hash() + assert source.pipeline_hash() == expected.pipeline_hash() + + if isinstance(data, (_ArrowArrayExporter, _ArrowStreamExporter)): + assert data.exports == 1 + if isinstance(data, _DualArrowExporter): + assert data.stream_exports == 0 + + +@pytest.mark.parametrize("route", ["table", "rows", "async_rows", "head"]) +def test_bound_proxy_refuses_delegated_system_tag_metadata( + route: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + source = ArrowTableSource( + _table(pa.field("extra", pa.string(), False), ["a", "b"]), + tag_columns=TAGS, + tag_only_columns=True, + system_tag_columns=["extra"], + source_id="rows", + ) + tags, data = source.output_schema() + proxy = SourceProxy( + source.source_id, + source.content_hash().to_string(), + source.pipeline_hash().to_string(), + tags, + data, + ) + proxy.bind(source) + columns = {"system_tags": True} + table = source.as_table(columns=columns) + pos = table.schema.get_field_index("_tag_extra") + field = table.schema.field(pos).with_metadata({b"owner": b"research"}) + raw = ArrowTableStream( + table.set_column(pos, field, table.column(pos)), + tag_columns=TAGS, + ) + monkeypatch.setattr(source, "as_table", raw.as_table) + monkeypatch.setattr(source, "iter_data", raw.iter_data) + monkeypatch.setattr(source, "head", raw.head) + + async def consume() -> None: + _ = [row async for row in proxy.async_iter_data()] + + with pytest.raises( + InputValidationError, match=r"'_tag_extra'.*[Rr]emove.*field metadata" + ): + if route == "table": + proxy.as_table(columns=columns) + elif route == "rows": + list(proxy.iter_data()) + elif route == "async_rows": + asyncio.run(consume()) + else: + proxy.head(columns=columns) + + +@pytest.mark.parametrize("stored_flag", [False, True]) +def test_cached_source_reads_older_token_field_flags_as_stored( + stored_flag: bool, +) -> None: + """A cache read uses the stored schema when its original source is unavailable.""" + source = ArrowTableSource( + _table(pa.field("extra", pa.string(), False), ["a", "b"]), + tag_columns=TAGS, + tag_only_columns=True, + source_id="rows", + ) + tags, data = 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=tags, + data_schema=data, + ) + database = InMemoryArrowDatabase() + cache = CachedSource(proxy, cache_database=database) + columns = {"source": True, "system_tags": True} + table = source.as_table(columns=columns) + token = "_source_extra" + position = table.schema.get_field_index(token) + table = table.set_column( + position, + table.schema.field(position).with_nullable(stored_flag), + table.column(position), + ) + table = table.append_column(CachedSource.HASH_COLUMN_NAME, pa.array([b"a", b"b"])) + database.add_records( + cache.cache_path, + with_data_context(table, source.data_context_key), + record_id_column=CachedSource.HASH_COLUMN_NAME, + flush=True, + ) + assert cache.as_table(columns=columns).schema.field(token).nullable is stored_flag + assert all( + data.source_info_table().schema.field(token).nullable + for _, data in cache.iter_data() + ) + + @pytest.mark.parametrize("row_count", [0, 2]) def test_derived_source_refuses_stored_null_in_its_direct_table_view( row_count: int, monkeypatch: pytest.MonkeyPatch @@ -458,11 +786,13 @@ def get_all_records( derived.as_table() -def test_spiral_can_nominate_a_tag_copy_as_a_custom_system_tag( +@pytest.mark.parametrize("metadata", [None, {b"owner": b"research"}]) +def test_spiral_validates_field_metadata_on_a_tag_copy_nominated_as_a_system_tag( tmp_path: Path, + metadata: dict[bytes, bytes] | None, ) -> None: schema = pa.schema( - [pa.field("k", pa.string(), False), pa.field("x", pa.int8(), False)] + [pa.field("k", pa.string(), False, metadata), pa.field("x", pa.int8(), False)] ) table = pa.Table.from_pylist([{"k": "a", "x": 1}, {"k": "b", "x": 2}], schema) with fake_spiral_sdk.install(tmp_path): @@ -471,14 +801,24 @@ def test_spiral_can_nominate_a_tag_copy_as_a_custom_system_tag( ) external.write(table) external.record(schema) - source = SpiralDBTableSource( - "project", - "rows", - tag_columns=["k"], - tag_only_columns=True, - tags_as_data={"k": "copy"}, - system_tag_columns=["copy"], - ) + + def build() -> SpiralDBTableSource: + return SpiralDBTableSource( + "project", + "rows", + tag_columns=["k"], + tag_only_columns=True, + tags_as_data={"k": "copy"}, + system_tag_columns=["copy"], + ) + + if metadata is not None: + with pytest.raises( + InputValidationError, match=r"'copy'.*[Rr]emove.*field metadata" + ): + build() + return + source = build() columns = {"system_tags": True} assert source.as_table(columns=columns).column("_tag_copy").to_pylist() == [ "a", 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 c2ada3480..edd0b6370 100644 --- a/tests/test_core/streams/test_iter_data_chunk_layouts.py +++ b/tests/test_core/streams/test_iter_data_chunk_layouts.py @@ -308,7 +308,12 @@ def test_nested_source_info_pairs_with_its_own_row( table = pa.Table.from_pydict( { "id": _chunked(list(range(n)), tag_sizes, pa.int64()), - "x": _chunked([i * 10 for i in range(n)], data_sizes, pa.int64()), + # ``x`` has its token's two list layers (the token-shape rule, ITL-1491). + "x": _chunked( + [[[i * 10], [i * 10, i * 10]] for i in range(n)], + data_sizes, + pa.large_list(pa.large_list(pa.int64())), + ), SOURCE_X: _chunked(tokens, source_sizes, NESTED_SOURCE_TYPE), } ) @@ -317,7 +322,7 @@ def test_nested_source_info_pairs_with_its_own_row( assert len(pairs) == n for row, (tag, data) in enumerate(pairs): assert tag["id"] == row - assert data["x"] == row * 10 + assert data["x"] == [[row * 10], [row * 10, row * 10]] assert data.source_info()["x"] == tokens[row] source_schema = data.as_table(columns={"source": True}).schema assert source_schema.field(SOURCE_X).type == NESTED_SOURCE_TYPE @@ -335,7 +340,11 @@ def test_iter_data_keeps_the_source_info_arrow_type() -> None: table = pa.table( { "id": pa.array([0, 1], type=pa.int64()), - "x": pa.array([0, 10], type=pa.int64()), + # ``x`` has its token's three list layers (the token-shape rule). + "x": pa.array( + [[[], [[0]]], [[[10]], [[10], []]]], + type=pa.large_list(pa.large_list(pa.large_list(pa.int64()))), + ), SOURCE_X: pa.array(tokens, type=source_type), } ) diff --git a/tests/test_core/streams/test_token_shape.py b/tests/test_core/streams/test_token_shape.py new file mode 100644 index 000000000..5f9370be5 --- /dev/null +++ b/tests/test_core/streams/test_token_shape.py @@ -0,0 +1,627 @@ +"""A source-info token's shape must match its data's shape (ITL-1491). + +Developer, November 27, 2026. A token column's type is some list layers on top of +``large_string``. Those layers must match exactly the outer list layers of its data +column's type: a ``large_list`` layer needs a ``large_list`` layer, a fixed-size list +a fixed-size list of the same size. The data may be deeper than its token, and a +plain string token fits any data. A token with a layer is never null (an element +inside it may be); a plain string token may be null. The rule is checked once, where +a stream is built from a table, from the columns' types and validity only. + +Every stream here has two tags and two data columns, in two column layouts, and the +checked column in each role it can have (a data column, a data-tag). +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.core.operators import Batch, GroupBy, MergeJoin, SelectDataColumns +from orcapod.core.sources import ArrowTableSource, DictSource +from orcapod.core.streams import ArrowTableStream +from orcapod.errors import InputValidationError +from orcapod.utils import schema_utils + +STR = pa.large_string() +INT = pa.int64() + + +def large(kind: pa.DataType) -> pa.DataType: + return pa.large_list(kind) + + +def fixed(kind: pa.DataType, size: int = 2) -> pa.DataType: + return pa.list_(kind, size) + + +ROLES = pytest.mark.parametrize("role", ["data", "data_tag"]) +LAYOUTS = pytest.mark.parametrize("layout", ["tags_first", "data_first"]) + + +def _stream( + token_type: pa.DataType, + tokens: list[Any], + data_type: pa.DataType, + data: list[Any], + role: str = "data", + layout: str = "tags_first", +) -> ArrowTableStream: + """Two tags (``g``, ``k``) and two data columns; ``x`` is the checked column. + + In the ``data_tag`` role ``x`` is a tag that is a data-tag too. + """ + rows = len(data) + columns: dict[str, tuple[pa.DataType, list[Any]]] = { + "g": (STR, [f"g{i}" for i in range(rows)]), + "k": (INT, list(range(rows))), + "x": (data_type, data), + "w": (INT, [10 * i for i in range(rows)]), + "_source_x": (token_type, tokens), + "_source_w": (STR, [f"s::row_{i}::w" for i in range(rows)]), + } + names = ( + ["g", "k", "x", "w", "_source_x", "_source_w"] + if layout == "tags_first" + else ["_source_w", "w", "_source_x", "x", "k", "g"] + ) + table = pa.Table.from_arrays( + [pa.array(columns[n][1], columns[n][0]) for n in names], + schema=pa.schema( + [ + pa.field(n, columns[n][0], nullable=None in columns[n][1]) + if n == "x" + else pa.field(n, columns[n][0]) + for n in names + ] + ), + ) + tags = ["g", "k", "x"] if role == "data_tag" else ["g", "k"] + return ArrowTableStream( + table, tag_columns=tags, data_tags=["x"] if role == "data_tag" else [] + ) + + +# (token type, tokens, data type, data): two rows each. +VALID: dict[str, tuple[pa.DataType, list[Any], pa.DataType, list[Any]]] = { + # A plain string token has no layer: it fits any data, and may be null. + "string_over_int": (STR, ["a", "b"], INT, [1, 2]), + "null_string_over_int": (STR, [None, "b"], INT, [1, 2]), + "string_over_list": (STR, ["a", None], large(INT), [[1], [2, 3]]), + "string_over_fixed": (STR, ["a", "b"], fixed(INT), [[1, 2], [3, 4]]), + "string_over_struct": ( + STR, + ["a", "b"], + pa.struct([("p", INT)]), + [{"p": 1}, {"p": 2}], + ), + # One layer. + "list_over_list": (large(STR), [["a"], ["b", "c"]], large(INT), [[1], [2, 3]]), + "non_large_spellings": ( + pa.list_(pa.string()), + [["a"], ["b", "c"]], + pa.list_(INT), + [[1], [2, 3]], + ), + "fixed_over_fixed": ( + fixed(STR), + [["a", "b"], ["c", "d"]], + fixed(INT), + [[1, 2], [3, 4]], + ), + # The data may be deeper than its token. + "list_over_list_of_lists": ( + large(STR), + [["a"], ["b", "c"]], + large(large(INT)), + [[[1]], [[2], [3, 4]]], + ), + "list_over_list_of_fixed": ( + large(STR), + [["a"], ["b", "c"]], + large(fixed(INT)), + [[[1, 2]], [[3, 4], [5, 6]]], + ), + "fixed_over_fixed_of_lists": ( + fixed(STR), + [["a", "b"], ["c", "d"]], + fixed(large(INT)), + [[[1], [2]], [[3, 4], []]], + ), + # Two layers, of either kind at either level. + "two_levels": ( + large(large(STR)), + [[["a"]], [["b"], ["c", "d"]]], + large(large(INT)), + [[[1]], [[2], [3, 4]]], + ), + "two_levels_over_three": ( + large(large(STR)), + [[["a"]], [["b"], ["c"]]], + large(large(large(INT))), + [[[[1]]], [[[2]], [[3, 4]]]], + ), + "list_of_fixed": ( + large(fixed(STR)), + [[["a", "b"]], [["c", "d"], ["e", "f"]]], + large(fixed(INT)), + [[[1, 2]], [[3, 4], [5, 6]]], + ), + "fixed_of_lists": ( + fixed(large(STR)), + [[["a"], []], [["b", "c"], ["d"]]], + fixed(large(INT)), + [[[1], []], [[2, 3], [4]]], + ), + # A token's list is never null at any level, but a string inside the innermost + # list may be. + "null_element": (large(STR), [["a", None], [None]], large(INT), [[1, 2], [3]]), + "empty_list": (large(STR), [[], ["a"]], large(INT), [[], [1]]), + "null_string_two_levels_down": ( + large(large(STR)), + [[[None], ["a"]], [[None, None], []]], + large(large(INT)), + [[[1], [2]], [[3, 4], []]], + ), + "null_element_of_fixed": ( + fixed(STR), + [["a", None], [None, None]], + fixed(INT), + [[1, 2], [3, 4]], + ), + # A layer's item field (name, nullability, metadata) is not compared. + "other_item_field": ( + pa.large_list(pa.field("member", STR, nullable=False, metadata={"m": "v"})), + [["a"], ["b", "c"]], + large(INT), + [[1], [2, 3]], + ), + "other_data_item_field": ( + large(STR), + [["a"], ["b", "c"]], + pa.large_list(pa.field("element", INT, nullable=False)), + [[1], [2, 3]], + ), +} + + +@LAYOUTS +@ROLES +@pytest.mark.parametrize("case", list(VALID)) +def test_a_token_whose_layers_are_its_datas_outer_layers_is_accepted( + case: str, role: str, layout: str +) -> None: + """The stream is built, and its token column keeps the declared layers.""" + token_type, tokens, data_type, data = VALID[case] + stream = _stream(token_type, tokens, data_type, data, role, layout) + table = stream.as_table(columns={"source": True}) + assert table.column("_source_x").to_pylist() == tokens + assert table.column("x").to_pylist() == data + assert schema_utils.token_layers_fit( + table.schema.field("_source_x").type, table.schema.field("x").type + ) + # A stream with no rows is checked on its types alone. + empty = _stream(token_type, [], data_type, [], role, layout) + assert empty.as_table().num_rows == 0 + + +# (token type, tokens, data type, data): the token's layers are not the data's. +WRONG_SHAPE: dict[str, tuple[pa.DataType, list[Any], pa.DataType, list[Any]]] = { + "list_over_int": (large(STR), [["a"], ["b"]], INT, [1, 2]), + "list_over_string": (large(STR), [["a"], ["b"]], STR, ["p", "q"]), + "list_over_struct": ( + large(STR), + [["a"], ["b"]], + pa.struct([("p", large(INT))]), + [{"p": [1]}, {"p": [2]}], + ), + "fixed_over_int": (fixed(STR), [["a", "b"], ["c", "d"]], INT, [1, 2]), + "list_over_fixed": ( + large(STR), + [["a", "b"], ["c", "d"]], + fixed(INT), + [[1, 2], [3, 4]], + ), + "fixed_over_list": ( + fixed(STR), + [["a", "b"], ["c", "d"]], + large(INT), + [[1, 2], [3, 4]], + ), + "fixed_of_another_size": ( + fixed(STR, 2), + [["a", "b"], ["c", "d"]], + fixed(INT, 3), + [[1, 2, 3], [4, 5, 6]], + ), + "two_levels_over_one": ( + large(large(STR)), + [[["a"]], [["b"]]], + large(INT), + [[1], [2]], + ), + "inner_kind_differs": ( + large(fixed(STR)), + [[["a", "b"]], [["c", "d"]]], + large(large(INT)), + [[[1, 2]], [[3, 4]]], + ), + "inner_size_differs": ( + large(fixed(STR, 2)), + [[["a", "b"]], [["c", "d"]]], + large(fixed(INT, 3)), + [[[1, 2, 3]], [[4, 5, 6]]], + ), + # Under its layers a token is a string: any other leaf is refused, also where + # the layers fit (second review of PR #601, finding 1). + "integer_token": (INT, [1, 2], INT, [1, 2]), + "binary_token": (pa.large_binary(), [b"t", b"u"], INT, [1, 2]), + "list_of_integers_token": (large(INT), [[1], [2]], large(INT), [[3], [4]]), + "list_of_binary_token": ( + large(pa.large_binary()), + [[b"t"], [b"u"]], + large(INT), + [[3], [4]], + ), + "nested_integers_token": ( + large(large(INT)), + [[[1]], [[2]]], + large(large(INT)), + [[[3]], [[4]]], + ), + "fixed_of_integers_token": ( + fixed(INT), + [[1, 2], [3, 4]], + fixed(INT), + [[5, 6], [7, 8]], + ), + # A token layer of a kind other than a list is refused, whatever the data. + "struct_token": ( + pa.struct([("t", STR)]), + [{"t": "a"}, {"t": "b"}], + pa.struct([("t", INT)]), + [{"t": 1}, {"t": 2}], + ), + "list_of_struct_token": ( + large(pa.struct([("t", STR)])), + [[{"t": "a"}], [{"t": "b"}]], + large(pa.struct([("t", INT)])), + [[{"t": 1}], [{"t": 2}]], + ), +} + + +def _refusal(build: Any) -> str: + """The message of the ``InputValidationError`` ``build`` raises.""" + with pytest.raises(InputValidationError) as refused: + build() + return str(refused.value) + + +@LAYOUTS +@ROLES +@pytest.mark.parametrize("case", list(WRONG_SHAPE)) +def test_a_token_whose_layers_are_not_its_datas_is_refused( + case: str, role: str, layout: str +) -> None: + """The stream is refused when it is built, with rows and with none, naming the + token column, the data column and both types.""" + token_type, tokens, data_type, data = WRONG_SHAPE[case] + assert not schema_utils.token_layers_fit(token_type, data_type) + for token_values, data_values in ((tokens, data), ([], [])): + message = _refusal( + lambda: _stream( + token_type, token_values, data_type, data_values, role, layout + ) + ) + assert "'_source_x'" in message and "'x'" in message + assert str(token_type) in message and str(data_type) in message + assert "'_source_w'" not in message + + +# A token with a layer that is null on some row; the shapes fit. +NULL_TOKEN: dict[str, tuple[pa.DataType, list[Any], pa.DataType, list[Any]]] = { + "null_list": (large(STR), [["a"], None], large(INT), [[1], [2]]), + "all_null_lists": (large(STR), [None, None], large(INT), [[1], [2]]), + "null_fixed": (fixed(STR), [None, ["a", "b"]], fixed(INT), [[1, 2], [3, 4]]), + "null_two_levels": ( + large(large(STR)), + [None, [["a"]]], + large(large(INT)), + [[[1]], [[2]]], + ), + "null_over_null_data": (large(STR), [None, ["a"]], large(INT), [None, [1]]), +} + + +@LAYOUTS +@ROLES +@pytest.mark.parametrize("case", list(NULL_TOKEN)) +def test_a_null_list_token_is_refused(case: str, role: str, layout: str) -> None: + """A token that has a layer is never null: the stream is refused when built.""" + token_type, tokens, data_type, data = NULL_TOKEN[case] + assert schema_utils.token_layers_fit(token_type, data_type) + message = _refusal( + lambda: _stream(token_type, tokens, data_type, data, role, layout) + ) + assert "'_source_x'" in message and "'x'" in message + assert str(token_type) in message and "null" in message + # With no rows there is no null: the same types are accepted. + assert _stream(token_type, [], data_type, [], role, layout).as_table().num_rows == 0 + + +def test_every_violating_column_is_named_once() -> None: + """Two violating columns, one of each kind, are both named in one refusal.""" + table = pa.table( + { + "k": pa.array([1, 2], INT), + "x": pa.array([1, 2], INT), + "y": pa.array([[1], [2]], large(INT)), + "z": pa.array([5, 6], INT), + "_source_x": pa.array([["a"], ["b"]], large(STR)), + "_source_y": pa.array([None, ["c"]], large(STR)), + "_source_z": pa.array(["s::0::z", None], STR), + } + ) + message = _refusal(lambda: ArrowTableStream(table, tag_columns=["k"])) + assert message.count("'_source_x'") == 1 and message.count("'_source_y'") == 1 + assert "'_source_z'" not in message + + +# --------------------------------------------------------------------------- +# What the library builds satisfies the rule +# --------------------------------------------------------------------------- + + +def _paths(source_id: str) -> DictSource: + return DictSource( + [ + {"g": "m", "k": 1, "p": Path("/a"), "n": 1}, + {"g": "m", "k": 2, "p": Path("/b"), "n": 2}, + {"g": "n", "k": 1, "p": Path("/c"), "n": 3}, + ], + tag_columns=["g", "k"], + tag_only_columns=True, + source_id=source_id, + ) + + +AGGREGATIONS = { + "batch": lambda: Batch(batch_size=2)(_paths("a")), + "group_by": lambda: GroupBy(by=["g"])(_paths("a")), + "merge_join": lambda: MergeJoin()(_paths("a"), _paths("b")), + "group_by_then_batch": lambda: Batch(batch_size=2)(GroupBy(by=["g"])(_paths("a"))), +} + + +@pytest.mark.parametrize("aggregation", list(AGGREGATIONS)) +def test_a_logical_list_counts_as_one_list_layer(aggregation: str) -> None: + """``Batch``, ``GroupBy`` and ``MergeJoin`` over a logical element (a ``Path``). + + The data column is the logical list type built for a list of ``Path`` (an + extension type stored as a list); for the rule it is one ``large_list`` layer + per list level, and its token is a list of strings of as many levels. + """ + table = AGGREGATIONS[aggregation]().as_table(columns={"source": True}) + levels = 2 if aggregation == "group_by_then_batch" else 1 + token = STR + for _ in range(levels): + token = large(token) + for name in ("p", "n"): + assert table.schema.field(f"_source_{name}").type == token + assert schema_utils.token_layers_fit(token, table.schema.field(name).type), ( + table.schema.field(name).type + ) + assert isinstance(table.schema.field("p").type, pa.ExtensionType) + # The same table given back as a raw stream is accepted. + system = AGGREGATIONS[aggregation]().as_table( + columns={"source": True, "system_tags": True} + ) + tags = [n for n in ("g", "k") if n in system.column_names] + assert ArrowTableStream(system, tag_columns=tags).as_table().num_rows > 0 + + +def test_an_operator_over_a_valid_stream_keeps_it_valid() -> None: + """A stream built by hand with fitting layers passes through operators.""" + token_type, tokens, data_type, data = VALID["list_of_fixed"] + stream = _stream(token_type, tokens, data_type, data) + selected = SelectDataColumns(["x"])(stream).as_table(columns={"source": True}) + assert selected.schema.field("_source_x").type == token_type + batched = Batch(batch_size=2)(stream).as_table(columns={"source": True}) + assert batched.schema.field("_source_x").type == large(token_type) + assert schema_utils.token_layers_fit( + batched.schema.field("_source_x").type, batched.schema.field("x").type + ) + + +def test_a_source_builds_plain_string_tokens_over_any_data() -> None: + """A source's tokens are plain strings, also over list and fixed-size data.""" + source = ArrowTableSource( + pa.table( + { + "k": pa.array([1, 2], INT), + "g": pa.array(["m", "n"], STR), + "x": pa.array([[1], [2, 3]], large(INT)), + "w": pa.array([[1, 2], [3, 4]], fixed(INT)), + } + ), + tag_columns=["k", "g"], + tag_only_columns=True, + source_id="lists", + ) + table = source.as_table(columns={"source": True}) + assert table.schema.field("_source_x").type == STR + assert table.schema.field("_source_w").type == STR + + +# --------------------------------------------------------------------------- +# Index: the element's token has the declared type with one layer removed +# --------------------------------------------------------------------------- + + +def _index_rows( + stream: ArrowTableStream, i: int, route: str, out: str | None +) -> pa.Table: + """``Index`` on ``x`` over ``stream``, on the sync or the async route.""" + import asyncio + + from orcapod.channels import Channel + from orcapod.core.operators import Index + + operator = Index("x", i, out=out) + if route == "sync": + return operator(stream).as_table(columns={"source": True}) + + async def run() -> list[Any]: + incoming: Channel[Any] = Channel(buffer_size=16) + outgoing: Channel[Any] = Channel(buffer_size=16) + for row in stream.iter_data(): + await incoming.writer.send(row) + await incoming.writer.close() + await operator.async_execute( + [incoming.reader], + outgoing.writer, + input_pipeline_hashes=[stream.pipeline_hash()], + ) + return await outgoing.reader.collect() + + rows = asyncio.run(run()) + return pa.concat_tables( + [data.as_table(columns={"source": True}) for _, data in rows] + ) + + +ROUTES = pytest.mark.parametrize("route", ["sync", "async"]) +MEMBER = pa.field("member", STR, nullable=False) +# (token type, tokens, data type, data, the element's token type) +INDEXED: dict[ + str, tuple[pa.DataType, list[Any], pa.DataType, list[Any], pa.DataType] +] = { + "list_of_strings": ( + large(STR), + [["a", "b"], ["c", "d"]], + large(INT), + [[1, 2], [3, 4]], + STR, + ), + "list_of_fixed": ( + large(fixed(STR)), + [[["a", "b"], ["c", "d"]], [["e", "f"], ["g", "h"]]], + large(fixed(INT)), + [[[1, 2], [3, 4]], [[5, 6], [7, 8]]], + fixed(STR), + ), + "list_of_named_item_lists": ( + large(pa.large_list(MEMBER)), + [[["a"], ["b", "c"]], [["d"], []]], + large(large(INT)), + [[[1], [2, 3]], [[4], []]], + pa.large_list(MEMBER), + ), + "three_levels": ( + large(large(large(STR))), + [[[[]], [["a"]]], [[["b"]], [[], ["c"]]]], + large(large(large(INT))), + [[[[]], [[1]]], [[[2]], [[], [3]]]], + large(large(STR)), + ), +} + + +@ROUTES +@ROLES +@pytest.mark.parametrize("out", [None, "picked"]) +@pytest.mark.parametrize("i", [0, 1]) +@pytest.mark.parametrize("case", list(INDEXED)) +def test_index_gives_the_element_the_declared_token_type_less_one_layer( + case: str, i: int, out: str | None, role: str, route: str +) -> None: + """The element's token is the token list's element, typed as that list's items. + + ``Index`` typed the element's token again from its value, so a fixed-size + list became a ``large_list`` (which no longer fits fixed-size data), a list's + item field lost its name and nullability, and an empty list lost its inner + levels (ITL-1491). Both routes give the declared type with one layer removed. + """ + token_type, tokens, data_type, data, element_type = INDEXED[case] + if role == "data_tag" and out is None: + pytest.skip("Index replaces a data column in place, not a tag") + stream = _stream(token_type, tokens, data_type, data, role) + table = _index_rows(stream, i, route, out) + name = f"_source_{out or 'x'}" + assert table.schema.field(name).type.equals(element_type, check_metadata=True), ( + table.schema.field(name).type + ) + assert table.column(name).to_pylist() == [token[i] for token in tokens] + assert table.column(out or "x").to_pylist() == [value[i] for value in data] + if out is not None: + assert table.schema.field("_source_x").type.equals( + token_type, check_metadata=True + ) + + +@pytest.mark.parametrize("out", [None, "picked"]) +def test_index_guards_against_a_null_element_where_a_list_token_remains( + out: str | None, +) -> None: + """A null inner list is not a valid token, so no stream holds one. + + A stream with ``[None, ["a"]]`` under a two-level token type is refused where + it is built (a token's list is never null at any level). ``Index`` keeps its + guard for rows that are in no stream: rows built by hand and sent over a bare + row channel. Taking the null element would give a row a null token whose type + is a list; the guard refuses, naming the column. The element that is a list + is taken as before. + """ + import asyncio + + from orcapod.channels import Channel + from orcapod.core.operators import Index + + token_type, data_type = large(large(STR)), large(large(INT)) + data = [[[1], [2]], [[3], [4]]] + with pytest.raises(InputValidationError, match="list level 1"): + _ = _stream(token_type, [[None, ["a"]], [["b"], ["c"]]], data_type, data) + stream = _stream(token_type, [[["z"], ["a"]], [["b"], ["c"]]], data_type, data) + rows: list[Any] = list(stream.iter_data()) + tag, first = rows[0] + rows[0] = (tag, first.with_source_info(x=pa.scalar([None, ["a"]], type=token_type))) + + def taken(i: int) -> list[Any]: + async def run() -> list[Any]: + incoming: Channel[Any] = Channel(buffer_size=16) + outgoing: Channel[Any] = Channel(buffer_size=16) + for row in rows: + await incoming.writer.send(row) + await incoming.writer.close() + await Index("x", i, out=out).async_execute( + [incoming.reader], + outgoing.writer, + input_pipeline_hashes=[stream.pipeline_hash()], + ) + return await outgoing.reader.collect() + + return asyncio.run(run()) + + with pytest.raises((InputValidationError, ExceptionGroup)) as refused: + _ = taken(0) + error: BaseException = refused.value + while isinstance(error, ExceptionGroup): + (error,) = error.exceptions + assert isinstance(error, InputValidationError) + assert f"'_source_{out or 'x'}'" in str(error) and "Index" in str(error) + assert [d.source_info()[out or "x"] for _, d in taken(1)] == [["a"], ["c"]] + + +@ROUTES +def test_index_keeps_a_null_string_element_as_a_null_token(route: str) -> None: + """A null element of a list of string tokens is a null string token: valid.""" + stream = _stream( + large(STR), [[None, "a"], ["b", None]], large(INT), [[1, 2], [3, 4]] + ) + table = _index_rows(stream, 0, route, None) + assert table.schema.field("_source_x").type == STR + assert table.column("_source_x").to_pylist() == [None, "b"] diff --git a/tests/test_core/test_order_invariance.py b/tests/test_core/test_order_invariance.py index 9cdabf77b..7c91c05c4 100644 --- a/tests/test_core/test_order_invariance.py +++ b/tests/test_core/test_order_invariance.py @@ -47,6 +47,7 @@ import sys import warnings from collections.abc import Callable, Sequence +from contextlib import aclosing from dataclasses import dataclass, field from pathlib import Path from typing import Any @@ -74,6 +75,7 @@ ) from orcapod.core.nodes.operator_node import OPERATOR_RECORDED_AT_COL from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.sources.source_proxy import SourceProxy from orcapod.core.streams import ArrowTableStream from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import RestrictedAggregationWarning @@ -81,6 +83,7 @@ from orcapod.system_constants import ( OPERATOR_DB_SCHEMA_VERSION, PIPELINE_DB_SCHEMA_VERSION, + constants, ) from orcapod.types import Condition from orcapod.operators import ( @@ -112,12 +115,14 @@ ArrowTableSource, CachedSource, CSVSource, + DBTableSource, DataFrameSource, DeltaTableSource, DerivedSource, DictSource, ListSource, PollingSource, + PostgreSQLTableSource, SQLiteTableSource, SpiralDBTableSource, ) @@ -140,6 +145,8 @@ make_source, ) from .order_rules import KNOWN_VIOLATIONS, ORDER_EXCEPTIONS +from .sources.test_source_arrow_validation import _Connector +from tests.test_databases import fake_spiral_sdk pytestmark = [ pytest.mark.filterwarnings( @@ -784,6 +791,20 @@ def _cached_source(role: str, order: int, layout: str, _tmp: Path) -> Any: ) +def _bound_source_proxy(role: str, order: int, layout: str, _tmp: Path) -> Any: + delegate = source(MAIN, role, order, layout) + tags, data = delegate.output_schema() + proxy = SourceProxy( + delegate.source_id, + delegate.content_hash().to_string(), + delegate.pipeline_hash().to_string(), + tags, + data, + ) + proxy.bind(delegate) + return proxy + + def _derived_source(role: str, order: int, layout: str, _tmp: Path) -> Any: return DerivedSource( source(MAIN, role, order, layout), @@ -836,6 +857,7 @@ def _side_effect(role: str, order: int, layout: str, _tmp: Path) -> Any: # PollingSource takes no tag_only_columns: its tags are plain. StreamCase("polling_source", _polling_source, roles=(PLAIN,)), StreamCase("cached_source", _cached_source), + StreamCase("bound_source_proxy", _bound_source_proxy), StreamCase("derived_source_tags_as_data", _derived_source), StreamCase("raw_arrow_table_stream", _raw_stream), StreamCase("function_pod_call", _pod_call, with_async=True), @@ -857,18 +879,16 @@ def _side_effect(role: str, order: int, layout: str, _tmp: Path) -> Any: "SQLiteTableSource": "sqlite_table_source", "PollingSource": "polling_source", "CachedSource": "cached_source", - "DerivedSource": "derived_source_tags_as_data", # plain: test_a_job_... + "SourceProxy": "bound_source_proxy", + "DerivedSource": "derived_source_tags_as_data", # plain: test_plain_derived_source_... "ArrowTableStream": "raw_arrow_table_stream", } NOT_APPLICABLE: dict[str, str] = { "RootSource": "the abstract base of every source", "StreamBase": "the abstract base of every stream", - "StreamView": "a view of rows a stream already has; it orders nothing", - "SourceProxy": "stands in for a source a loaded job cannot rebuild; it reads nothing", - "DBTableSource": "the base of the database sources; SQLiteTableSource is its case", - "PostgreSQLTableSource": "needs a PostgreSQL server; a DBTableSource like SQLite", - "SpiralDBTableSource": "needs a SpiralDB project; reads through the same builder", + "StreamView": "exposes its table and has no sync or async datagram iterator", } +CONNECTOR_KINDS = (DBTableSource, PostgreSQLTableSource, SpiralDBTableSource) def _kind_names() -> set[str]: @@ -889,8 +909,9 @@ def _kind_names() -> set[str]: def test_every_exported_source_and_stream_kind_has_a_case() -> None: """A new source or stream kind fails here until it has a case (or a reason).""" - assert _kind_names() == set(KIND_CASES) | set(NOT_APPLICABLE) - assert not set(KIND_CASES) & set(NOT_APPLICABLE) + tested = set(KIND_CASES) | {kind.__name__ for kind in CONNECTOR_KINDS} + assert _kind_names() == tested | set(NOT_APPLICABLE) + assert not tested & set(NOT_APPLICABLE) labels = {case.label for case in STREAM_CASES} assert set(KIND_CASES.values()) <= labels @@ -923,6 +944,146 @@ def test_a_source_stream_or_pod_does_not_depend_on_the_arrangement_of_its_input( assert_all_equal(results) +async def _iter_async_rows(stream: Any, count: int) -> list[Any]: + async with aclosing(stream.async_iter_data()) as rows: + if isinstance(stream, PollingSource): + # Polling subscriptions are live. Read the rows of the finite snapshot. + async with asyncio.timeout(5): + return [await anext(rows) for _ in range(count)] + return [row async for row in rows] + + +def _assert_stream_and_row_fields(stream: Any, *, native_async: bool) -> None: + columns = {"system_tags": True} + table = stream.as_table(columns=columns) + user_tags, data_names = stream.keys() + tag_names = set(user_tags) | { + name + for name in table.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) + } + sync_rows = list(stream.iter_data()) + async_rows = asyncio.run( + _run_async(stream.producer, list(stream.upstreams)) + if native_async + else _iter_async_rows(stream, table.num_rows) + ) + for path, rows in (("sync", sync_rows), ("async", async_rows)): + assert len(rows) == table.num_rows, path + for tag, data in rows: + tag_table, data_table = tag.as_table(columns=columns), data.as_table() + assert set(tag_table.column_names) == tag_names, path + assert set(data_table.column_names) == set(data_names), path + for row_table in (tag_table, data_table): + expected = table.select(row_table.column_names).schema + assert row_table.schema.equals(expected, check_metadata=True), ( + path, + row_table.schema, + expected, + ) + + +@pytest.mark.parametrize( + "case", [*STREAM_CASES], ids=[case.label for case in STREAM_CASES] +) +def test_stream_and_rows_agree_on_tag_and_primary_data_fields( + case: StreamCase, tmp_path: Path +) -> None: + """Compare row fields to the table in both modes across tag orders and layouts. + + Connector-backed kinds have their own fixture below. The only exclusions + are the abstract RootSource and StreamBase, StreamView (table only), and + the unbound form of SourceProxy (cannot read rows). + The standalone SideEffectPod exposes the stream iterator. Async delivery + through the job executor is exercised by the job tests below. + """ + for order, layout in ARRANGEMENTS: + stream = case.build(case.roles[0], order, layout, tmp_path) + _assert_stream_and_row_fields(stream, native_async=case.with_async) + + +@pytest.mark.parametrize("kind", CONNECTOR_KINDS, ids=lambda kind: kind.__name__) +def test_database_stream_and_rows_agree_on_tag_and_primary_data_fields( + kind: type[DBTableSource] | type[SpiralDBTableSource], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + """DB and PostgreSQL use a connector double. SpiralDB scans a local SDK fake.""" + for i, (order, layout) in enumerate(ARRANGEMENTS): + raw = table(MAIN, order, layout) + tags = MAIN.tag_orders()[order] + if kind is SpiralDBTableSource: + with fake_spiral_sdk.install(tmp_path / str(i)): + external = fake_spiral_sdk.ExternalProject("project").create_table( + "default.rows", + key_schema=raw.select(MAIN.tags).schema, + ) + external.write(raw) + external.record(raw.schema) + stream = SpiralDBTableSource( + "project", + "rows", + tag_columns=tags, + tag_only_columns=True, + ) + _assert_stream_and_row_fields(stream, native_async=False) + else: + connector = _Connector(raw) + # The shared fixture defaults to a different key; use this table's key. + if kind is PostgreSQLTableSource: + monkeypatch.setattr( + "orcapod.core.sources.postgresql_table_source.PostgreSQLConnector", + lambda *args, **kwargs: connector, + ) + stream = PostgreSQLTableSource( + "postgresql://localhost/test", + "rows", + tag_columns=tags, + tag_only_columns=True, + record_id_columns=MAIN.tags, + ) + else: + stream = DBTableSource( + connector, + "rows", + tag_columns=tags, + source_id="rows", + tag_only_columns=True, + record_id_columns=MAIN.tags, + ) + _assert_stream_and_row_fields(stream, native_async=False) + + +def test_plain_derived_source_and_rows_agree_on_primary_data_fields() -> None: + for order, layout in ARRANGEMENTS: + job = PipelineJob(name="fields", database=InMemoryArrowDatabase()) + with job: + SelectDataColumns(["d1", "d2", "d3"])( + source(MAIN, PLAIN, order, layout), label="selected" + ) + node = job.nodes["selected"] + node.attach_databases(pipeline_database=job.database, cache_mode=CacheMode.LOG) + job.run() + _assert_stream_and_row_fields(node.as_source(), native_async=False) + + +@pytest.mark.parametrize( + "case", + [ + pytest.param(case, id=case.label) + for cases in OPERATOR_CASES.values() + for case in cases + ], +) +def test_operator_stream_and_rows_agree_on_tag_and_primary_data_fields( + case: OperatorCase, +) -> None: + """Exercise every exported operator's native sync and async row paths.""" + for order, layout in ARRANGEMENTS: + stream = case.build()(*case.sources(case.roles[0], order, layout)) + _assert_stream_and_row_fields(stream, native_async=True) + + @pytest.mark.parametrize("role", ROLES) def test_the_order_of_a_function_pods_inputs_changes_nothing(role: str) -> None: """``pod(a, b)`` joins its inputs: their order is not part of anything.""" diff --git a/tests/test_core/test_row_ids.py b/tests/test_core/test_row_ids.py index 4d552a5a7..ffea5176d 100644 --- a/tests/test_core/test_row_ids.py +++ b/tests/test_core/test_row_ids.py @@ -11,7 +11,7 @@ from __future__ import annotations import uuid -from typing import Any +from typing import Any, cast import pyarrow as pa import pytest @@ -21,7 +21,9 @@ from orcapod.core.data_function import output_source_info from orcapod.core.datagrams import Data, Tag from orcapod.core.datagrams.tag_data import EmptyData +from orcapod.core.streams import ArrowTableStream from orcapod.system_constants import constants +from orcapod.utils import arrow_utils HASHER = get_default_context().arrow_hasher @@ -54,6 +56,87 @@ def _binary(value: bytes) -> "pa.Array[Any]": return pa.array([value], type=pa.large_binary()) +@pytest.mark.parametrize("scalar_last", [False, True]) +def test_with_source_info_uses_the_later_alias_in_every_view(scalar_last: bool) -> None: + """Prefixed and bare spellings update the same token in keyword order.""" + data = Data( + pa.table({"x": [1], "y": [2], "_source_x": ["old"], "_source_y": ["kept"]}) + ) + scalar = pa.scalar(["arrow"], type=pa.large_list(pa.large_string())) + if scalar_last: + updated = data.with_source_info(x="python", _source_x=scalar) + expected = ["arrow"] + expected_type = scalar.type + else: + updated = data.with_source_info(x=scalar, _source_x="python") + expected = "python" + expected_type = pa.large_string() + + assert updated.source_info() == {"x": expected, "y": "kept"} + entry = row_ids.entry_id(HASHER, _tag(), updated) + for table in ( + updated.as_table(columns={"source": True}), + updated.source_info_table(), + row_ids.instance_id_preimage(entry, updated), + ): + assert table.column("_source_x").to_pylist() == [expected] + assert table.schema.field("_source_x").type.equals( + expected_type, check_metadata=True + ) + assert table.column("_source_y").to_pylist() == ["kept"] + + +def test_with_source_info_keeps_a_scalar_type_its_value_cannot_show() -> None: + """Replacing a typed column never infers the Arrow scalar's type.""" + data = Data( + pa.table({"x": [1], "y": [2], "_source_x": ["old"], "_source_y": ["kept"]}) + ) + token_type = pa.large_list(pa.large_list(pa.large_list(pa.large_string()))) + token = [[], [[]]] + updated = data.with_source_info(x=pa.scalar(token, type=token_type)) + + assert updated.source_info() == {"x": token, "y": "kept"} + entry = row_ids.entry_id(HASHER, _tag(), updated) + for table in ( + updated.as_table(columns={"source": True}), + updated.source_info_table(), + row_ids.instance_id_preimage(entry, updated), + ): + assert table.column("_source_x").to_pylist() == [token] + assert table.schema.field("_source_x").type.equals( + token_type, check_metadata=True + ) + assert table.column("_source_y").to_pylist() == ["kept"] + + +@pytest.mark.parametrize( + ("arrow_type", "values"), + [(pa.null(), [None, None]), (pa.large_list(pa.null()), [[None], [None, None]])], +) +def test_entry_id_explains_how_to_replace_a_raw_null_system_tag( + arrow_type: pa.DataType, + values: list[Any], +) -> None: + name = "_tag_record_id::seed" + stream = ArrowTableStream( + pa.table( + { + "subject": pa.array(["m1", "m2"], pa.large_string()), + "session": [1, 2], + "_tag_source_id::seed": pa.array( + ["source", "source"], pa.large_string() + ), + name: pa.array(values, type=arrow_type), + "weight": [25, 30], + } + ), + tag_columns=["subject", "session"], + ) + for tag, data in stream.iter_data(): + with pytest.raises(ValueError, match=rf"{name}.*supported nullable type"): + row_ids.entry_id(HASHER, tag, data) + + class TestEntryId: def test_the_preimage_is_the_tags_the_system_tags_and_the_labelled_data_hash( self, @@ -379,17 +462,28 @@ def _stream(self, nested: bool) -> Any: from orcapod.core.streams import ArrowTableStream tokens_a = ( - pa.array([[None, [[]]], [None, [[]]], [[["t"]]]], self.NESTED) + pa.array([[[], [[]]], [[], [[]]], [[["t"]]]], self.NESTED) if nested else pa.array( ["s::row_0::a", "s::row_1::a", "s::row_2::a"], pa.large_string() ) ) + # ``a`` has its token's list layers (the token-shape rule, ITL-1491). + from tests.token_shapes import data_for, data_type_for + + a_type = data_type_for(tokens_a.type) + data_a = pa.array( + [ + data_for(t, v, a_type) + for t, v in zip(cast("Any", tokens_a).to_pylist(), (10, 20, 30)) + ], + a_type, + ) table = pa.Table.from_arrays( [ pa.array(["m1", "m1", "m2"], pa.large_string()), pa.array([1, 2, 1], pa.int64()), - pa.array([10, 20, 30], pa.int64()), + data_a, pa.array([0.5, 1.5, 2.5], pa.float64()), tokens_a, pa.array(["s::row_0::b", "s::row_1::b", None], pa.large_string()), @@ -398,7 +492,7 @@ def _stream(self, nested: bool) -> Any: [ pa.field("subject", pa.large_string(), nullable=False), pa.field("session", pa.int64(), nullable=False), - pa.field("a", pa.int64(), nullable=False), + pa.field("a", a_type, nullable=False), pa.field("b", pa.float64(), nullable=False), pa.field("_source_a", tokens_a.type, nullable=nested), pa.field("_source_b", pa.large_string()), @@ -454,10 +548,19 @@ def test_a_nested_token_column_is_read_with_its_type_and_never_typed_again( ] assert preimage.schema.field("_source_a").type == self.NESTED ids.add(row_ids.instance_id(HASHER, tag, data)) + # The row's table gives the same typed column, never one typed again + # from the token's value, which fails for the first two rows (ITL-1491). + shown = data.as_table(columns={"source": True}) + assert shown.schema.field("_source_a").type == self.NESTED + assert shown.column("_source_a").equals(typed.column("_source_a")) if index < 2: - # Typing this token again from its value is what fails. with pytest.raises(pa.ArrowTypeError): - data.as_table(columns={"source": True}) + pa.array( + shown.column("_source_a").to_pylist(), + arrow_utils.source_info_arrow_type( + shown.column("_source_a").to_pylist()[0] + ), + ) assert len(ids) == 3 def test_a_changed_row_gives_the_tokens_it_now_has(self) -> None: @@ -567,15 +670,17 @@ def test_a_change_keeps_the_typed_column_of_every_token_it_keeps( ids.add(row_ids.instance_id(HASHER, _tag(), changed)) assert len(ids) == 3 - def test_columns_taken_from_another_row_have_tokens_typed_from_their_values( + def test_columns_taken_from_another_row_keep_their_tokens_types( self, ) -> None: - """``with_columns_of`` (a data-tag falling through a function) types from values. - - The copied columns' tokens are typed again from their values: a stopgap, - not the proper solution (developer, November 27, 2026). A fixed-size list - token becomes a large list; a nested token that cannot be typed from its - value fails here. ITL-1491 removes the re-typing. + """``with_columns_of`` (a data-tag falling through a function) keeps the type. + + The taken columns' tokens keep the typed columns the other row carries + (developer, November 27, 2026, ITL-1491: the pipeline determines a token + column's type; it is never taken from values): a fixed-size list token + stays a fixed-size list, and a nested token that cannot be typed from its + value is taken as it is. The row's own columns (a function's output) keep + their string tokens. """ fixed = pa.list_(pa.large_string(), 2) table = pa.Table.from_arrays( @@ -608,8 +713,9 @@ def test_columns_taken_from_another_row_have_tokens_typed_from_their_values( "_source_y", "_source_z", ] - assert tokens.schema.field("_source_a").type == pa.large_list( - pa.large_string() + assert tokens.schema.field("_source_a").type == fixed + assert tokens.column("_source_a").equals( + other.source_info_table().column("_source_a") ) assert tokens.schema.field("_source_b").type == pa.large_string() # Every view gives the same tokens, and the table view the same types. @@ -626,10 +732,18 @@ def test_columns_taken_from_another_row_have_tokens_typed_from_their_values( ids.add(row_ids.instance_id(HASHER, _tag(), joined)) # Two rows, each with one id whatever the order the columns were taken in. assert len(ids) == 2 - for other in self._nested_rows()[:2]: + for other in self._nested_rows(): own = Data({"y": 1}, source_info={"y": "f::r::y"}) - with pytest.raises(pa.ArrowTypeError): - own.with_columns_of(other, ["a"]).source_info_table() + joined = own.with_columns_of(other, ["a"]) + for view in ( + joined.source_info_table(), + joined.as_table(columns={"source": True}), + ): + assert view.schema.field("_source_a").type == self.NESTED + assert view.column("_source_a").equals( + other.source_info_table().column("_source_a") + ) + assert view.schema.field("_source_y").type == pa.large_string() class TestARenameMovesTheToken: diff --git a/tests/test_pipeline/test_review_findings_510.py b/tests/test_pipeline/test_review_findings_510.py index d2467f69f..b41697476 100644 --- a/tests/test_pipeline/test_review_findings_510.py +++ b/tests/test_pipeline/test_review_findings_510.py @@ -180,7 +180,7 @@ def keys(self, **kwargs: Any) -> Any: assert reads == [1] -# ── streams/base.py:550 (2): system tags the rows retype take the row path ──── +# ── streams/base.py:550 (2): raw stream system-tag fields on channels ───────── def _with_system_tag(column: pa.Array[Any]) -> ArrowTableStream: @@ -197,12 +197,10 @@ def _with_system_tag(column: pa.Array[Any]) -> ArrowTableStream: ], ids=["int16", "int32", "string"], ) -def test_a_channel_on_a_stream_gives_the_rows_system_tag_types( +def test_a_channel_on_a_raw_stream_keeps_the_declared_system_tag_field( column: pa.Array[Any], ) -> None: - """A channel opened on an exact ``ArrowTableStream`` whose system tag rows would - retype delivers what the rows build (``main``'s row path), e.g. ``int16`` as - ``int64``.""" + """Both the channel and the row-built table carry the stream's declared field.""" from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS @@ -212,16 +210,18 @@ def test_a_channel_on_a_stream_gives_the_rows_system_tag_types( list(stream.iter_data()), stream ).as_table(columns=ZERO_ROW_INPUT_COLUMNS) (name,) = [n for n in delivered.column_names if n.startswith("_tag")] - assert delivered.schema.field(name).type == built.schema.field(name).type + expected = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS).schema.field(name) + assert delivered.schema.field(name).equals(expected, check_metadata=True) + assert built.schema.field(name).equals(expected, check_metadata=True) assert delivered[name].to_pylist() == built[name].to_pylist() -def test_a_channel_on_a_stream_whose_rows_cannot_make_one_table_raises() -> None: - """A string system tag holding a null and a value: the rows cannot make one - table; the channel raises what ``main``'s row build raises.""" +def test_a_channel_keeps_null_values_in_a_nullable_raw_system_tag() -> None: + """A single nullable field can hold the rows with and without a value.""" stream = _with_system_tag(pa.array(["a", None], pa.large_string())) - with pytest.raises(pa.ArrowInvalid): - asyncio.run(stream.open_channel().collect()) + table = pa.Table.from_batches(asyncio.run(stream.open_channel().collect())) + assert table.schema.field("_tag_e").equals(pa.field("_tag_e", pa.large_string())) + assert table.column("_tag_e").to_pylist() == ["a", None] def _arrow_table_source() -> ArrowTableSource: diff --git a/tests/test_pipeline/test_row_ids_review_2.py b/tests/test_pipeline/test_row_ids_review_2.py index 5287e64f9..ab121b9b9 100644 --- a/tests/test_pipeline/test_row_ids_review_2.py +++ b/tests/test_pipeline/test_row_ids_review_2.py @@ -521,22 +521,48 @@ def test_a_placeholder_without_a_result_stops_the_run_under_fail_fast( # --------------------------------------------------------------------------- _LIST = pa.large_list(pa.large_string()) -# Token columns ``_source_a`` of three rows, by kind. +# Token columns ``_source_a`` of three rows, by kind. ``a`` is a list column here +# (the token-shape rule, ITL-1491: a list token needs list data; a string token +# fits any data), so list tokens and string tokens are both valid over it. TOKEN_KINDS: dict[str, "pa.Array[Any]"] = { - "null_typed_list": pa.array([None, None, None], _LIST), "null_typed_string": pa.array([None, None, None], pa.large_string()), "strings": pa.array(["s::r0::a", "s::r1::a", "s::r2::a"], pa.large_string()), "lists": pa.array([["s::r0::a"], ["s::r1::a", "t::r1::a"], ["s::r2::a"]], _LIST), + "lists_with_null_elements": pa.array( + [[None], ["s::r1::a", None], ["s::r2::a"]], _LIST + ), +} +# Token columns that are not valid: a token with a list layer is never null. +NULL_LIST_TOKENS: dict[str, "pa.Array[Any]"] = { + "null_typed_list": pa.array([None, None, None], _LIST), "null_and_lists": pa.array([None, ["s::r1::a"], None], _LIST), } +_A_LISTS = [[10], [20, 0], [30]] -def _token_stream(kind: str, session: str = "first") -> ArrowTableStream: - """``_session_stream`` with a token column ``_source_a`` of the given kind.""" +@function_pod(output_keys=["total", "scaled"]) +def combine_lists(a: list[int], b: float) -> tuple[float, float]: + """``combine`` over a list-valued ``a``: its sum takes the place of ``a``.""" + calls["combine_lists"] += 1 + return sum(a) + b, sum(a) * b + + +def _list_session_table(session: str) -> pa.Table: + """``_session_stream``'s rows with ``a`` as a list column (sums 10, 20, 30).""" table = _session_stream(session).as_table() + return table.set_column( + table.schema.get_field_index("a"), + pa.field("a", pa.large_list(pa.int64()), nullable=False), + pa.array(_A_LISTS, pa.large_list(pa.int64())), + ) + + +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( - table.append_column( - pa.field("_source_a", TOKEN_KINDS[kind].type), TOKEN_KINDS[kind] + _list_session_table(session).append_column( + pa.field("_source_a", tokens.type), tokens ), tag_columns=["subject", "session"], ) @@ -553,26 +579,20 @@ def _pipeline_table(database: InMemoryArrowDatabase) -> pa.Table: @PATH @pytest.mark.parametrize( "kinds", - [ - ("null_typed_list", "null_typed_string"), - ("null_typed_string", "null_typed_list"), - ("null_typed_list", "strings"), - ("strings", "null_typed_list"), - ], + [("null_typed_string", "strings"), ("strings", "null_typed_string")], ) -def test_sessions_whose_null_tokens_are_typed_differently_share_a_table( +def test_sessions_with_null_and_with_string_tokens_share_a_table( path: str, kinds: tuple[str, str] ) -> None: - """A null token is a ``large_string`` null, whatever type its column declares. + """A null token is a ``large_string`` null: it shares a column with strings. Two sessions over one pipeline table, in both orders: a token column that holds - only nulls, declared as a list in one session and as a string in the other (or - holding strings in the other). Both complete and the table keeps one column - type (review of PR #583: hashed and stored with the declared type, the second - session failed with ``ArrowInvalid``; ``main`` completed both). + only nulls in one session and strings in the other. Both complete and the table + keeps one column type. (Review of PR #583; the cases whose null tokens were + declared a list are not valid streams: the refusal test below.) """ database = InMemoryArrowDatabase() - pod = combine.pod + pod = combine_lists.pod assert isinstance(pod, FunctionPod) for kind, session in zip(kinds, ("first", "second")): stream = _token_stream(kind, session) @@ -586,37 +606,46 @@ def test_sessions_whose_null_tokens_are_typed_differently_share_a_table( assert table.schema.field("_source_a").type == pa.large_string() -@pytest.mark.parametrize("tokens", ["null_typed_list", "null_typed_string"]) -def test_a_null_tokens_instance_id_does_not_follow_its_columns_type( - tokens: str, -) -> None: - """The id is a function of the row alone: its tags, its data and its tokens.""" - ids = {} - for kind in ("null_typed_list", "null_typed_string"): - stream = _token_stream(kind) - ids[kind] = [ - row_ids.instance_id(HASHER, tag, data) for tag, data in stream.iter_data() - ] - for tag, data in stream.iter_data(): - preimage = row_ids.instance_id_preimage( - row_ids.entry_id(HASHER, tag, data), data - ) - assert preimage.schema.field("_source_a").type == pa.large_string() - assert preimage.column("_source_a").to_pylist() == [None] - assert ids["null_typed_list"] == ids["null_typed_string"] - assert len(set(ids[tokens])) == 3 +@pytest.mark.parametrize("kind", list(NULL_LIST_TOKENS)) +def test_a_stream_with_a_null_list_token_is_refused_when_built(kind: str) -> None: + """A token with a list layer is never null (the token-shape rule, ITL-1491). + Replaces three tests about a null token in a list-typed column (its instance id + not following the column's type; sessions typed differently sharing a table; a + session mixing null and list tokens refused at the write): the stream is now + refused where it is built, naming the token column, its data column and both + types, so no node sees it. It still protects what they did: one pipeline table + never receives a null and a list in one token column. + """ + from orcapod.errors import InputValidationError + + with pytest.raises(InputValidationError) as refused: + _ = _token_stream(kind) + message = str(refused.value) + assert "'_source_a'" in message and "'a'" in message + assert str(_LIST) in message and str(pa.large_list(pa.int64())) in message + assert "null" in message + + +def test_a_null_string_tokens_preimage_is_a_string_null() -> None: + """The id of a row with a null token: a ``large_string`` null in the preimage.""" + stream = _token_stream("null_typed_string") + ids = [row_ids.instance_id(HASHER, tag, data) for tag, data in stream.iter_data()] + for tag, data in stream.iter_data(): + preimage = row_ids.instance_id_preimage( + row_ids.entry_id(HASHER, tag, data), data + ) + assert preimage.schema.field("_source_a").type == pa.large_string() + assert preimage.column("_source_a").to_pylist() == [None] + assert len(set(ids)) == 3 -def test_a_non_null_token_keeps_the_type_of_its_column() -> None: - """Rows of a list-typed column: a list token is a list, a null a string null.""" - types = [ - str(data.source_info_table().schema.field("_source_a").type) - for _, data in _token_stream("null_and_lists").iter_data() - ] - assert types == ["large_string", str(_LIST), "large_string"] + +@pytest.mark.parametrize("kind", ["lists", "lists_with_null_elements"]) +def test_a_list_token_keeps_the_type_of_its_column(kind: str) -> None: + """Rows of a list-typed token column: every token is a list, a null inside too.""" assert [ str(data.source_info_table().schema.field("_source_a").type) - for _, data in _token_stream("lists").iter_data() + for _, data in _token_stream(kind).iter_data() ] == [str(_LIST)] * 3 @@ -644,7 +673,7 @@ def test_sessions_whose_tokens_differ_in_type_are_refused_naming_the_column( from orcapod.errors import OrcapodDatabaseWriteError database = InMemoryArrowDatabase() - pod = combine.pod + pod = combine_lists.pod assert isinstance(pod, FunctionPod) first = _token_stream(kinds[0], "first") node = FunctionJobNode(pod, first, pipeline_database=database) @@ -661,29 +690,6 @@ def test_sessions_whose_tokens_differ_in_type_are_refused_naming_the_column( assert _pipeline_table(database).equals(before) -@PATH -def test_a_session_mixing_null_and_list_tokens_in_one_column_is_refused( - path: str, -) -> None: - """A null token is a string null and a list token a list: two types, one column. - - As on ``main``, where the rows were stored with those two types and the write - failed; the refusal now names the column and both types. - """ - from orcapod.errors import OrcapodDatabaseWriteError - - database = InMemoryArrowDatabase() - pod = combine.pod - assert isinstance(pod, FunctionPod) - stream = _token_stream("null_and_lists") - node = FunctionJobNode(pod, stream, pipeline_database=database) - with pytest.raises((OrcapodDatabaseWriteError, ExceptionGroup)) as raised: - _run_node(node, stream, path) - message = _refusal(raised.value) - assert "_source_a" in message - assert "large_string" in message and "large_list<" in message - - class _AllEvents(_Events): """``_Events`` that also records the node's start and end.""" @@ -778,10 +784,14 @@ def doubled(y: int) -> int: def _data_tag_stream(tags: tuple[str, ...]) -> ArrowTableStream: - """Three rows; ``d`` and ``e`` are data-tags, ``d``'s token a fixed-size list.""" + """Three rows; ``d`` and ``e`` are data-tags, ``d``'s token a fixed-size list. + + ``d`` is a fixed-size list of the same size: a token's list layers are its + data's (the token-shape rule, ITL-1491). + """ columns: dict[str, tuple[Any, pa.DataType, bool]] = { "k": (["a", "b", "c"], pa.large_string(), False), - "d": ([1, 2, 3], pa.int64(), False), + "d": ([[1, 1], [2, 2], [3, 3]], pa.list_(pa.int64(), 2), False), "e": ([0.5, 1.5, 2.5], pa.float64(), False), "x": ([10, 20, 30], pa.int64(), False), "_source_d": ([["p", "q"], ["r", "s"], ["t", "u"]], _FIXED, True), @@ -846,23 +856,34 @@ def test_both_routes_record_one_instance_per_row_in_a_shared_store( ) -> None: """Sessions on either route over one store: one instance id per row, no refusal. - A data-tag falls through both functions with its token. The token's type is - the same whether the row was just computed or is served from the stored - result, and on the sync as on the async route (review of PR #583: the async - route kept a fixed-size list where the sync edge gave a large list, so one - function output had two instance ids, and the second route's write was - refused for the token column's type). Each later session finds the first - one's records: nothing is computed again and no row is added. + A data-tag falls through both functions with its token, value and type + unchanged (developer, November 27, 2026, ITL-1491: the pipeline determines a + token column's type, never its values): ``d``'s token is the stream's + fixed-size list after each function, whether the row was just computed or is + served from the stored result, on the sync as on the async route. Review of + PR #583: the sync edge had typed the token again from its value (a large + list) while the async route kept the fixed-size list, so one function output + had two instance ids and the second route's write was refused for the token + column's type. Each later session finds the first one's records: nothing is + computed again and no row is added. """ database = InMemoryArrowDatabase() + before = { + data.as_dict()["x"]: data.source_info_table().select(["_source_d", "_source_e"]) + for _, data in _data_tag_stream(tags).iter_data() + } stored: list[tuple[Any, ...]] = [] for index, route in enumerate(routes): out = _two_nodes_on(route, database, tags) assert sorted(data.as_dict()["z"] for _, data in out) == [22, 42, 62] for _, data in out: - assert data.source_info_table().schema.field( - "_source_d" - ).type == pa.large_list(pa.large_string()) + # x = z / 2 - 1 names the input row: the token columns after the two + # functions equal the ones before them, type and value. + after = data.source_info_table() + assert after.schema.field("_source_d").type == _FIXED + origin = before[data.as_dict()["z"] // 2 - 1] + assert after.select(["_source_d", "_source_e"]).equals(origin) + assert after.schema.field("_source_z").type == pa.large_string() database.flush() (path,) = [ p @@ -872,7 +893,7 @@ def test_both_routes_record_one_instance_per_row_in_a_shared_store( table = database.get_all_records(path) assert table is not None assert table.num_rows == 3, (index, route) - assert table.schema.field("_source_d").type == pa.large_list(pa.large_string()) + assert table.schema.field("_source_d").type == _FIXED assert table.column("_source_e").null_count == 1 stored.append( tuple( diff --git a/tests/test_pipeline/test_row_ids_stored.py b/tests/test_pipeline/test_row_ids_stored.py index f3ccb3a57..28cf7d514 100644 --- a/tests/test_pipeline/test_row_ids_stored.py +++ b/tests/test_pipeline/test_row_ids_stored.py @@ -828,7 +828,7 @@ def test_each_jobs_trace_finds_its_own_record_after_a_token_only_rerun( pa.array(["s::row_0::b", None, "s::row_2::b"], pa.large_string()), ), "nested": ( - pa.array([[None, [[]]], [None, [[]]], [[["s::row_2::a"]]]], _NESTED_TOKEN), + pa.array([[[], [[]]], [[], [[]]], [[["s::row_2::a"]]]], _NESTED_TOKEN), pa.array( [["s::row_0::b"], [], ["s::row_2::b", None]], pa.large_list(pa.large_string()), @@ -838,10 +838,37 @@ def test_each_jobs_trace_finds_its_own_record_after_a_token_only_rerun( @function_pod(output_keys=["total", "scaled"]) -def combine(a: int, b: float) -> tuple[float, float]: - """Return ``a + b`` and ``a * b``, counting the call.""" +def combine_list_and_number(a: list[int], b: float) -> tuple[float, float]: + """Return ``len(a) + b`` and ``len(a) * b``, counting the call.""" calls["combine"] += 1 - return a + b, a * b + return len(a) + b, len(a) * b + + +@function_pod(output_keys=["total", "scaled"]) +def combine_nested_lists( + a: list[list[list[int]]], b: list[float] +) -> tuple[float, float]: + """Return ``len(a) + len(b)`` and ``len(a) * len(b)``, counting the call.""" + calls["combine"] += 1 + return float(len(a) + len(b)), float(len(a) * len(b)) + + +# Per kind of token columns: the function over data of the tokens' shapes (the +# token-shape rule, ITL-1491: a list token needs list data), and its totals. +COMBINE: dict[str, tuple[Any, list[float]]] = { + "lists_and_a_null_string": (combine_list_and_number, [1.5, 2.5, 3.5]), + "nested": (combine_nested_lists, [2.0, 3.0, 3.0]), +} + + +def _data_like(tokens: "pa.Array[Any]", leaves: list[Any], leaf: pa.DataType) -> Any: + """A data column with the list layers of ``tokens``, ``leaves[i]`` in row ``i``.""" + from tests.token_shapes import data_for, data_type_for + + kind = data_type_for(tokens.type, leaf) + return pa.array( + [data_for(t, v, kind) for t, v in zip(tokens.to_pylist(), leaves)], kind + ) def _typed_token_stream(tokens: str, arrangement: str) -> ArrowTableStream: @@ -850,8 +877,9 @@ def _typed_token_stream(tokens: str, arrangement: str) -> ArrowTableStream: token_a, token_b = TOKEN_COLUMNS[tokens] columns: dict[str, tuple["pa.Array[Any]", bool]] = { **{name: (COLUMNS[name], False) for name in tags}, - "a": (pa.array([10, 20, 30], pa.int64()), False), - "b": (pa.array([0.5, 1.5, 2.5], pa.float64()), False), + # Each data column has its token's list layers, one value per token. + "a": (_data_like(token_a, [10, 20, 30], pa.int64()), False), + "b": (_data_like(token_b, [0.5, 1.5, 2.5], pa.float64()), False), "_source_a": (token_a, True), "_source_b": (token_b, True), } @@ -886,7 +914,8 @@ def test_a_stored_row_keeps_the_token_columns_its_instance_id_was_made_from( """ stream = _typed_token_stream(tokens, arrangement) database = InMemoryArrowDatabase() - pod = combine.pod + function, totals = COMBINE[tokens] + pod = function.pod assert isinstance(pod, FunctionPod) node = FunctionJobNode(pod, stream, pipeline_database=database) rows = list(stream.iter_data()) @@ -894,13 +923,14 @@ def test_a_stored_row_keeps_the_token_columns_its_instance_id_was_made_from( out = list(node.execute(stream).iter_data()) else: out = _through_channels(node, rows) - assert sorted( - cast("list[float]", [data.as_dict()["total"] for _, data in out]) - ) == [10.5, 21.5, 32.5] + assert ( + sorted(cast("list[float]", [data.as_dict()["total"] for _, data in out])) + == totals + ) assert calls["combine"] == 3 database.flush() - stored = _table(database, "combine", "pdb_v2") + stored = _table(database, function.__name__, "pdb_v2") assert stored.num_rows == 3 # The stored token columns have the stream's types, in every row. token_a, token_b = TOKEN_COLUMNS[tokens] @@ -932,12 +962,13 @@ def test_a_stored_row_keeps_the_token_columns_its_instance_id_was_made_from( reread = list(again.execute(stream).iter_data()) else: reread = _through_channels(again, rows) - assert sorted( - cast("list[float]", [data.as_dict()["total"] for _, data in reread]) - ) == [10.5, 21.5, 32.5] + assert ( + sorted(cast("list[float]", [data.as_dict()["total"] for _, data in reread])) + == totals + ) assert calls == Counter() database.flush() - assert _table(database, "combine", "pdb_v2").num_rows == 3 + assert _table(database, function.__name__, "pdb_v2").num_rows == 3 def _ordinary_streams() -> dict[str, Any]: @@ -1026,12 +1057,12 @@ def test_rows_with_no_token_store_null_tokens_and_recompute_their_ids( from orcapod.core.datagrams import Data, Tag rows = [ - (Tag({"subject": s, "session": n}), Data({"a": a, "b": b})) + (Tag({"subject": s, "session": n}), Data({"a": [[[a]]], "b": [b]})) for s, n, a, b in [("m1", 1, 10, 0.5), ("m1", 2, 20, 1.5), ("m2", 1, 30, 2.5)] ] stream = _typed_token_stream("nested", "as_declared") database = InMemoryArrowDatabase() - pod = combine.pod + pod = combine_nested_lists.pod assert isinstance(pod, FunctionPod) node = FunctionJobNode(pod, stream, pipeline_database=database) if path == "sync": @@ -1040,7 +1071,7 @@ def test_rows_with_no_token_store_null_tokens_and_recompute_their_ids( out = _through_channels(node, rows) assert len(out) == 3 and calls["combine"] == 3 database.flush() - stored = _table(database, "combine", "pdb_v2") + stored = _table(database, "combine_nested_lists", "pdb_v2") assert stored.num_rows == 3 tokens = [n for n in stored.column_names if n.startswith("_source_")] assert tokens == ["_source_a", "_source_b"] diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index c9385598e..18c8bb572 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -27,6 +27,7 @@ from tests.test_core.operators.test_row_built_form import ( _NESTED, # pyright: ignore[reportPrivateUsage] # the shared provenance fixtures _NodeEvents, # pyright: ignore[reportPrivateUsage] + _source, # pyright: ignore[reportPrivateUsage] _source_table, # pyright: ignore[reportPrivateUsage] _with_source_x, # pyright: ignore[reportPrivateUsage] ) @@ -35,8 +36,12 @@ def _unconvertible() -> ArrowTableStream: - """Tokens ``[None, [[]]]``: the whole-table build is unavailable, the rows raise.""" - return _with_source_x([[None, [[]]], [None, [[]]]], _UNCONVERTIBLE) + """Tokens ``[[], [[]]]``, three list levels deep: no value shows that type. + + Before ITL-1491 a row typed each token from its value, so building these rows + into one table raised ``ArrowTypeError``. The rows now keep the stream's type. + """ + return _with_source_x([[[], [[]]], [[], [[]]]], _UNCONVERTIBLE) def _plain() -> DictSource: @@ -48,14 +53,25 @@ def _plain() -> DictSource: ) -def test_a_fallback_source_reads_its_rows_once() -> None: - """A source whose whole-table build is unavailable: its rows are read once, when it - runs, and the successor's edge raises the rows' ``ArrowTypeError`` after the - source's end and before the successor starts, as on ``main``.""" +# ``x`` as ``_unconvertible`` has it: the three list layers of its token (the +# token-shape rule, ITL-1491: a list token needs list data of the same layers). +NestedX = list[list[list[int]]] + + +def _nested() -> Any: + """The source whose slot ``_unconvertible`` is bound to: ``x`` three lists deep.""" + return _source(_UNCONVERTIBLE) + + +def test_a_bound_raw_source_with_nested_tokens_reads_its_rows_once() -> None: + """A bound raw stream with nested tokens: its rows are read once, when it runs, + and the run completes: the successor's edge builds the rows into one table with + the stream's token type (ITL-1491; it used to raise the rows' ``ArrowTypeError`` + there, after the source's end, as on ``main``).""" job = PipelineJob(name="read_once", database=InMemoryArrowDatabase()) with job: Batch(batch_size=2)( - _plain().select_data_columns(["x"], label="selected"), label="batched" + _nested().select_data_columns(["x"], label="selected"), label="batched" ) source: Any = _unconvertible() reads: list[int] = [] @@ -68,11 +84,16 @@ def counted() -> Any: source.iter_data = counted job.bind(sources={"s": source}) observer = _NodeEvents() - with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): - job.run(observer=observer) + job.run(observer=observer) assert len(reads) == 1 - assert ("end", "s") in observer.events - assert ("start", "selected") not in observer.events + assert observer.events == [ + (event, label) + for label in ("s", "selected", "batched") + for event in ("start", "end") + ] + batched = job.nodes["batched"].as_table(columns={"source": True}) + assert batched.schema.field("_source_x").type == pa.large_list(_UNCONVERTIBLE) + assert batched.column("_source_x").to_pylist() == [[[[], [[]]], [[], [[]]]]] def test_a_fallback_source_nobody_reads_completes() -> None: @@ -82,7 +103,7 @@ def test_a_fallback_source_nobody_reads_completes() -> None: """ job = PipelineJob(name="leaf", database=InMemoryArrowDatabase()) with job: - _plain().select_data_columns(["x"], label="selected") + _nested().select_data_columns(["x"], label="selected") job.bind(sources={"s": _unconvertible()}) dag: OrcaDAG[Any] = OrcaDAG() dag.add_node(job.nodes["s"]) @@ -214,7 +235,7 @@ def _replay_job(database: InMemoryArrowDatabase, *, with_successor: bool) -> Any """``source -> select x`` with the select node replaying from ``database``.""" job = PipelineJob(name="replay_odd", database=InMemoryArrowDatabase()) with job: - selected = _plain().select_data_columns(["x"], label="selected") + selected = _nested().select_data_columns(["x"], label="selected") if with_successor: Batch(batch_size=2)(selected, label="batched") job.nodes["selected"].attach_databases( @@ -227,15 +248,16 @@ def _replay_job(database: InMemoryArrowDatabase, *, with_successor: bool) -> Any def test_replay_of_a_table_the_whole_table_build_cannot_use( with_successor: bool, ) -> None: - """REPLAY of a stored table with unconvertible tokens hands on its rows. + """REPLAY of a stored table with nested tokens hands on its rows. - The node ends as usual; a leaf completes; a successor's edge raises the rows' - ``ArrowTypeError``, as ``main``'s row rebuild does (Codex on PR #485, round 3). + The node ends as usual and a leaf completes (Codex on PR #485, round 3). A + successor builds the rows with the stored token type and completes too + (ITL-1491; its edge used to raise the rows' ``ArrowTypeError``). """ logged = InMemoryArrowDatabase() job = PipelineJob(name="replay_odd", database=InMemoryArrowDatabase()) with job: - _plain().select_data_columns(["x"], label="selected") + _nested().select_data_columns(["x"], label="selected") node: Any = job.nodes["selected"] node.attach_databases(pipeline_database=logged, cache_mode=CacheMode.LOG) job.run() @@ -246,31 +268,32 @@ def test_replay_of_a_table_the_whole_table_build_cannot_use( odd = stored.set_column( position, pa.field("_source_x", _UNCONVERTIBLE, nullable=True), - pa.array([[None, [[]]]] * stored.num_rows, _UNCONVERTIBLE), + pa.array([[[], [[]]]] * stored.num_rows, _UNCONVERTIBLE), ) seeded = InMemoryArrowDatabase() seeded.add_records(path, odd, record_id_column="__record_id") replay = _replay_job(seeded, with_successor=with_successor) observer = _NodeEvents() + replay.run(observer=observer) + assert ("end", "selected") in observer.events if with_successor: - with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): - replay.run(observer=observer) - assert ("end", "selected") in observer.events - assert ("start", "batched") not in observer.events - else: - replay.run(observer=observer) - assert ("end", "selected") in observer.events + assert ("end", "batched") in observer.events + batched = replay.nodes["batched"].as_table(columns={"source": True}) + assert batched.schema.field("_source_x").type == pa.large_list(_UNCONVERTIBLE) + assert batched.column("_source_x").to_pylist() == [ + [[[], [[]]]] * stored.num_rows + ] # ── round 4: the boundary of the eager route, and the lazy output itself ────── -DELIVERED: list[int] = [] +DELIVERED: list[Any] = [] -def _deliver(x: int, ctx: Any) -> None: - DELIVERED.append(x) +def _deliver(x: NestedX, ctx: Any) -> None: + DELIVERED.append(x[0][0][0]) def _leaf_run(job: PipelineJob, label: str) -> _NodeEvents: @@ -292,11 +315,11 @@ def test_a_bound_tap_stream_delivers_every_row_as_main_does() -> None: tap: Any = tap_pod(_deliver) DELIVERED.clear() - raw = _with_source_x([[None, [[]]], [None, [[]]]], _UNCONVERTIBLE) + raw = _with_source_x([[[], [[]]], [[], [[]]]], _UNCONVERTIBLE) tapped: Any = tap.process(raw) job = PipelineJob(name="tap_bound", database=InMemoryArrowDatabase()) with job: - _plain().select_data_columns(["x"], label="selected") + _nested().select_data_columns(["x"], label="selected") job.bind(sources={"s": tapped}) observer = _leaf_run(job, "s") assert DELIVERED == [1, 2] @@ -423,8 +446,9 @@ def plus(x: int) -> int: def test_a_lazy_output_is_described_and_opened_without_reading() -> None: """Describing an unread output, or opening its channel, builds nothing. - The first read of the channel raises what the rows' build raises (Codex on PR - #485, round 4). + The first read of the channel builds the rows (Codex on PR #485, round 4), with + the token type their stream declares (ITL-1491; the build used to raise the + rows' ``ArrowTypeError``). """ import asyncio @@ -433,7 +457,7 @@ def test_a_lazy_output_is_described_and_opened_without_reading() -> None: job = PipelineJob(name="lazy_out", database=InMemoryArrowDatabase()) with job: - _plain().select_data_columns(["x"], label="selected") + _nested().select_data_columns(["x"], label="selected") job.bind(sources={"s": _unconvertible()}) out: Any = job.nodes["s"].execute() assert isinstance(out, RowsOnRead) @@ -442,8 +466,11 @@ def test_a_lazy_output_is_described_and_opened_without_reading() -> None: assert "x" in out.arrow_schema().names channel = out.open_channel() assert out._stream is None # pyright: ignore[reportPrivateUsage] # nothing built - with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): - asyncio.run(channel.collect()) + batches = asyncio.run(channel.collect()) + assert out._stream is not None # pyright: ignore[reportPrivateUsage] # built by the read + read = pa.Table.from_batches(batches) + assert read.schema.field("_source_x").type == _UNCONVERTIBLE + assert read.column("_source_x").to_pylist() == [[[], [[]]], [[], [[]]]] # ── round 5 ────────────────────────────────────────────────────────────────── @@ -912,10 +939,8 @@ def _system_tag_job(values: list[int | None], exact: bool) -> tuple[Any, Any]: return job, database -def test_a_narrow_system_tag_is_stored_as_the_rows_give() -> None: - """A result over an exact ``ArrowTableStream`` with an ``int16`` system tag: kept, - stored and record-hashed as ``main``'s rows give it (``int64``, non-null), the - same as ``main``'s own row path (an unproven stream) gives.""" +def test_a_narrow_raw_system_tag_is_stored_with_its_declared_field() -> None: + """Both the exact stream and the fallback row path keep the declared field.""" from orcapod.system_constants import constants name = f"{constants.SYSTEM_TAG_PREFIX}region" @@ -925,29 +950,30 @@ def test_a_narrow_system_tag_is_stored_as_the_rows_give() -> None: job.run() node: Any = job.nodes["marked"] kept = node.as_table(columns={"system_tags": True}).schema.field(name) - assert (kept.type, kept.nullable) == (pa.int64(), False) + assert kept.equals(pa.field(name, pa.int16()), check_metadata=True) stored[exact] = database.at("log").get_all_records( node._stored_table_path, # pyright: ignore[reportPrivateUsage] # the raw LOG table record_id_column="_record_hash", ) for table in stored.values(): field = table.schema.field(name) - assert (field.type, field.nullable) == (pa.int64(), False) + assert field.equals(pa.field(name, pa.int16()), check_metadata=True) assert ( stored[True]["_record_hash"].to_pylist() == stored[False]["_record_hash"].to_pylist() ) -def test_a_null_system_tag_raises_at_the_operator_as_main_does() -> None: - """With a null among its values, ``main``'s rows cannot make one table: the - operator raises ``ArrowInvalid`` before its end event, as on ``main``.""" +def test_an_operator_keeps_null_values_in_a_nullable_raw_system_tag() -> None: + """A nullable declared field lets rows with and without a value share a table.""" job, _ = _system_tag_job([None, 2], exact=True) observer = _NodeEvents() - with pytest.raises(pa.ArrowInvalid): - job.run(observer=observer) + job.run(observer=observer) assert ("start", "marked") in observer.events - assert ("end", "marked") not in observer.events + assert ("end", "marked") in observer.events + table = job.nodes["marked"].as_table(columns={"system_tags": True}) + assert table.schema.field("_tag_region").equals(pa.field("_tag_region", pa.int16())) + assert table.column("_tag_region").to_pylist() == [None, 2] def test_a_source_refuses_a_non_text_custom_system_tag() -> None: @@ -1272,65 +1298,39 @@ def _held_job() -> tuple[Any, Any, Any]: from orcapod import function_pod @function_pod(output_keys="y") - def plus_one(x: int) -> int: - return x + 1 + def plus_one(x: NestedX) -> int: + return len(x) + 1 job = PipelineJob(name="held_unconvertible", database=InMemoryArrowDatabase()) with job: - selected = _plain().select_data_columns(["x"], label="selected") + selected = _nested().select_data_columns(["x"], label="selected") plus_one.pod(selected, label="after") other = PipelineJob(name="independent", database=InMemoryArrowDatabase()) with other: - _plain().select_data_columns(["x"], label="independent") + _nested().select_data_columns(["x"], label="independent") independent = next( n for n in other.nodes.values() if type(n).__name__ == "SourceJobNode" ) return job.nodes["selected"], job.nodes["after"], independent -def test_held_rows_that_cannot_make_one_table_raise_at_the_successors_edge() -> None: - """Sync: a held node whose rows cannot make one table (source-info tokens of two - shapes) is built where its successor reads it, after an independent node has run, - and raises the rows' ``ArrowTypeError``, as ``main`` rebuilt the rows there. - - Known difference (ITL-1491): this asserts today's behaviour. The async - orchestrator sends the same held rows on as they are, and the function node - records them (the test below), so the two paths differ on this route. The - build here types each token again from its value - (``StaticOutputOperatorPod._rows_to_table``); ITL-1491 makes it read the typed - token columns the rows carry, after which this run completes as the async one - does. On ``main`` the two paths differed for these rows too.""" - from orcapod.core.operators.static_output_pod import rows_on_read - - held, after, independent = _held_job() - dag: OrcaDAG[Any] = OrcaDAG() - dag.add_node(held) - dag.add_node(independent) - dag.add_edge(held, after) - observer = _NodeEvents() - rows = list(_unconvertible().iter_data()) - with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): - SyncPipelineOrchestrator().run( - dag, observer=observer, held={held: rows_on_read(rows, held)} - ) - starts = [label for event, label in observer.events if event == "start"] - assert starts == [independent.label] - +def _stored_by_after(after: Any) -> pa.Table: + """The pipeline table (``pdb_v2``) the function node ``after`` wrote.""" + database = after._pipeline_database # pyright: ignore[reportPrivateUsage] # the stored rows + database.flush() + (path,) = [p for p in database.list_table_paths() if p[-1] == "pdb_v2"] + stored = database.get_all_records(path) + assert stored is not None + return stored -def test_held_rows_that_cannot_make_one_table_are_sent_on_async() -> None: - """Async: the held rows are sent on as the plan took them, never built into one - table first: the function node after the held node starts every row and ends. - The rows are valid Arrow: their token column is a nested list whose values - cannot be typed again from Python values. The node records each row with the - typed token column it carries (ITL-1471: the stored columns are the ones the - instance id was made from), so the run completes and both rows are stored. On - ``main`` ca1c35d6 the events are the same and the run then raised the rows' - ``ArrowTypeError``, when the record typed the tokens again. +def _held_run(asynchronous: bool) -> tuple[list[tuple[str, str]], pa.Table]: + """Run ``after`` over the held node's rows with nested tokens. - Known difference (ITL-1491): the sync orchestrator still builds the held rows - into one table at the successor's edge and raises there (the test above). - ITL-1491 makes that build read the typed token columns too.""" + Returns: + The node and row events of the function node, and its stored rows. + """ + from orcapod.core.operators.static_output_pod import rows_on_read from orcapod.pipeline import AsyncPipelineOrchestrator held, after, _ = _held_job() @@ -1343,20 +1343,138 @@ def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: self.events.append(("data", node_label)) observer = DataStarts() - AsyncPipelineOrchestrator().run(dag, observer=observer, held_rows={held: rows}) - assert observer.events == [ + if asynchronous: + AsyncPipelineOrchestrator().run(dag, observer=observer, held_rows={held: rows}) + else: + SyncPipelineOrchestrator().run( + dag, observer=observer, held={held: rows_on_read(rows, held)} + ) + return observer.events, _stored_by_after(after) + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_held_rows_with_nested_tokens_reach_the_successor(asynchronous: bool) -> None: + """A held node's rows with a nested token column are recorded by its successor. + + The rows are valid Arrow: their token column is a nested list whose values show + fewer list levels than the column has. The sync orchestrator builds the held + rows into one table at the successor's edge; the async one sends them on as they + are. Both keep the stream's token type (ITL-1491), so the function node after + the held node starts every row, ends, and stores both rows with the nested type. + + Before ITL-1491 the sync edge typed each token again from its value and raised + ``ArrowTypeError`` (as ``main`` did), while the async route recorded the rows. + """ + events, stored = _held_run(asynchronous) + assert events == [ ("start", "after"), ("data", "after"), ("data", "after"), ("end", "after"), ] - database = after._pipeline_database # pyright: ignore[reportPrivateUsage] # the stored rows - database.flush() - (path,) = [p for p in database.list_table_paths() if p[-1] == "pdb_v2"] - stored = database.get_all_records(path) - assert stored is not None and stored.num_rows == 2 + assert stored.num_rows == 2 assert stored.schema.field("_source_x").type == _UNCONVERTIBLE - assert stored.column("_source_x").to_pylist() == [[None, [[]]], [None, [[]]]] + assert stored.column("_source_x").to_pylist() == [[[], [[]]], [[], [[]]]] + + +def test_held_rows_with_nested_tokens_are_stored_alike_on_both_routes() -> None: + """The sync and the async route give the same events and the same stored rows: + tags, system tags, token columns with their types, input hashes and instance ids + (the result id, the record id that covers it and the times differ by design).""" + sync_events, sync = _held_run(False) + async_events, asynchronous = _held_run(True) + assert sync_events == async_events + random = { + "__data_id", + "__pipeline_record_id", + "__recorded_at", + "__pipeline_run_id", + } + kept = [name for name in sync.column_names if name not in random] + assert sorted(kept) == sorted( + name for name in asynchronous.column_names if name not in random + ) + assert "__pipeline_instance_id" in kept and "_source_x" in kept + left = sync.select(kept).sort_by("k") + right = asynchronous.select(kept).sort_by("k") + assert left.schema.equals(right.schema) + assert left.to_pylist() == right.to_pylist() + assert len(set(left.column("__pipeline_instance_id").to_pylist())) == 2 + + +def test_held_rows_that_break_the_token_shape_rule_differ_by_route_itl_1534() -> None: + """A KNOWN LIMIT, pinned here; ITL-1534 decides it. + + The token-shape rule is checked where a stream is built. The rows are built by + hand from one-row tables, outside any stream: a null token in a list-typed + token column. The sync orchestrator builds a held node's rows into a stream + where its successor reads them, which refuses them. The async orchestrator + hands held rows on without building a stream, so the function node after the + held node receives them and records them. Rows a run really holds come from a + stream, which was checked when it was built; only hand-built rows given to an + orchestrator directly reach this difference. + + This test asserts each route's behaviour as it is today. When ITL-1534 makes + the two routes agree, it changes with that decision. + """ + from orcapod.core.datagrams import Data + from orcapod.core.operators.static_output_pod import rows_on_read + from orcapod.errors import InputValidationError + from orcapod.pipeline import AsyncPipelineOrchestrator + + def bad_rows() -> list[Any]: + return [ + ( + tag, + Data( + data.as_table().append_column( + "_source_x", pa.array([None], _UNCONVERTIBLE) + ) + ), + ) + for tag, data in _unconvertible().iter_data() + ] + + def run(asynchronous: bool) -> Any: + held, after, _ = _held_job() + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_edge(held, after) + rows = bad_rows() + if asynchronous: + AsyncPipelineOrchestrator().run(dag, held_rows={held: rows}) + else: + SyncPipelineOrchestrator().run(dag, held={held: rows_on_read(rows, held)}) + return after + + # Sync: refused where the held rows are built into a stream; nothing stored. + with pytest.raises(InputValidationError) as refused: + _ = run(False) + assert "'_source_x'" in str(refused.value) and "'x'" in str(refused.value) + # Async: the rows are handed on as they are, and the successor records them + # (a null token is stored as a ``large_string`` null). + stored = _stored_by_after(run(True)) + assert stored.num_rows == 2 + assert stored.column("_source_x").to_pylist() == [None, None] + assert stored.schema.field("_source_x").type == pa.large_string() + + +def test_held_rows_run_independent_nodes_first() -> None: + """Sync: a held node's rows are built where its successor reads them, after an + independent node has run (the order ``main`` gave).""" + from orcapod.core.operators.static_output_pod import rows_on_read + + held, after, independent = _held_job() + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(held) + dag.add_node(independent) + dag.add_edge(held, after) + observer = _NodeEvents() + rows = list(_unconvertible().iter_data()) + SyncPipelineOrchestrator().run( + dag, observer=observer, held={held: rows_on_read(rows, held)} + ) + starts = [label for event, label in observer.events if event == "start"] + assert starts == [independent.label, after.label] @pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) @@ -1383,7 +1501,7 @@ def test_an_inactive_function_node_passes_rows_with_nested_tokens( from orcapod.core.nodes.function_node import FunctionJobNode @function_pod(output_keys="y") - def never(x: int) -> int: + def never(x: NestedX) -> int: raise AssertionError("an inactive function must not be called") pod = never.pod diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index d19ae759c..666b5faea 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -545,18 +545,25 @@ def test_a_poller_that_fetched_describes_its_rows_order() -> None: ) -def test_a_value_decided_source_info_depth_is_a_named_exception() -> None: - """L7: ``Batch`` over null list tokens; the description and the rows agree but for it. - - The rows give ``[None, None]`` one list level (``large_list``); the - description states the declared token type. A source-info type is decided by the - values of a complete table and is one of the description's named exceptions. +def test_a_source_info_depth_is_the_declared_one_in_the_description_and_the_rows() -> ( + None +): + """L7, restated for ITL-1491: ``Batch`` over empty token lists; the description + and the rows agree on the token type. + + Empty token lists show no level below them. The rows used to type each token + from its value, so the table built from rows had fewer list levels than the + description (a "value-decided" source-info type, a named exception of the + description). A token column's type is now the one the pipeline determines, in + the rows as in the description. (The earlier form of this test used null list + tokens, which are not valid tokens: ``test_token_shape.py``.) """ from orcapod.core.streams import ArrowTableStream - from orcapod.sources import DictSource + from orcapod.sources import ArrowTableSource - table = DictSource( - [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + lists = pa.large_list(pa.int64()) + table = ArrowTableSource( + pa.table({"k": pa.array([1, 2], pa.int64()), "x": pa.array([[], []], lists)}), tag_columns=["k"], tag_only_columns=True, source_id="s", @@ -567,14 +574,15 @@ def test_a_value_decided_source_info_depth_is_a_named_exception() -> None: table.set_column( position, pa.field("_source_x", strings, nullable=True), - pa.array([None, None], strings), + pa.array([[], []], strings), ), tag_columns=["k"], ) batched = Batch(batch_size=2)(raw) built, _, _ = StaticOutputOperatorPod._rows_to_table(list(batched.iter_data())) # pyright: ignore[reportPrivateUsage] # the rows declared = batched.arrow_schema() - assert declared.field("_source_x").type != built.schema.field("_source_x").type + assert declared.field("_source_x").type == pa.large_list(strings) + assert declared.field("_source_x").type == built.schema.field("_source_x").type assert _without_exceptions(declared) == _without_exceptions(built.schema) diff --git a/tests/test_pipeline/test_token_types_end_to_end.py b/tests/test_pipeline/test_token_types_end_to_end.py new file mode 100644 index 000000000..4fa3d00b3 --- /dev/null +++ b/tests/test_pipeline/test_token_types_end_to_end.py @@ -0,0 +1,725 @@ +"""A source-info token column keeps the pipeline's type on every route (ITL-1491). + +The Arrow type of a token column is determined by the pipeline, never taken from the +tokens' values: a source builds ``large_string`` tokens, each operator determines its +output's token types from its inputs' types, and a function node takes the types from +its input's rows. So a job stores the same rows, token types and ids (entry, instance, +record) on the sync and on the async orchestrator, also for token columns whose +values cannot be typed again from Python values (a null or an empty list inside a +list), which used to raise at the sync edge between two nodes while the async route +recorded them. + +Every source has two tag columns and two data columns, three or four rows, in two +arrangements (tag order and data order both reversed). +""" + +from __future__ import annotations + +import uuid +from collections import Counter +from typing import Any, cast + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.contexts import get_default_context +from orcapod.core import row_ids +from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.operators import Batch, GroupBy, MergeJoin +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.system_constants import constants +from orcapod.types import ContentHash +from tests.token_shapes import data_type_for, nested_value, with_token_column + +HASHER = get_default_context().arrow_hasher +ORCHESTRATORS = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} +ARRANGEMENTS = { + "as_declared": (("subject", "session"), ("x", "w")), + "reversed": (("session", "subject"), ("w", "x")), +} +ARRANGEMENT = pytest.mark.parametrize("arrangement", list(ARRANGEMENTS)) +COLUMNS: dict[str, "pa.Array[Any]"] = { + "subject": pa.array(["m1", "m1", "m2", "m2"], pa.large_string()), + "session": pa.array([1, 2, 1, 2], pa.int64()), + "x": pa.array([10, 20, 30, 40], pa.int64()), + "w": pa.array([100, 200, 300, 400], pa.int64()), +} +STRINGS = pa.large_list(pa.large_string()) +NESTED = pa.large_list(STRINGS) +DEEP = pa.large_list(NESTED) +KEY = "__key" + +calls: Counter[str] = Counter() + + +@pytest.fixture(autouse=True) +def _reset() -> None: + """Clear the call counts.""" + calls.clear() + + +@function_pod(output_keys="total") +def add(x: int, w: int) -> int: + """Return ``x + w``.""" + calls["add"] += 1 + return x + w + + +@function_pod(output_keys="twice") +def twice(total: int) -> int: + """Return ``2 * total``.""" + calls["twice"] += 1 + return 2 * total + + +@function_pod(output_keys="total") +def add_lists(x: list[int], w: list[int]) -> int: + """Return the sum of every element of both lists.""" + calls["add_lists"] += 1 + return sum(x) + sum(w) + + +@function_pod(output_keys="total") +def add_nested(x: list[list[int]], w: list[list[int]]) -> int: + """Return the sum of every element of both lists of lists.""" + calls["add_nested"] += 1 + return sum(sum(v) for v in x) + sum(sum(v) for v in w) + + +def _source( + arrangement: str, *, source_id: str = "rows", data_tags: bool = False +) -> ArrowTableSource: + """The four rows as a source, laid out as ``arrangement`` says.""" + tags, data = ARRANGEMENTS[arrangement] + names = [*tags, *data] + schema = pa.schema(pa.field(n, COLUMNS[n].type, nullable=False) for n in names) + return ArrowTableSource( + pa.Table.from_arrays([COLUMNS[n] for n in names], schema=schema), + tag_columns=list(tags), + tag_only_columns=not data_tags, + source_id=source_id, + ) + + +def _shaped_source( + arrangement: str, tokens: dict[str, tuple[list[Any], pa.DataType]] +) -> ArrowTableSource: + """``_source`` whose named data columns have the list layers of their tokens. + + A token's list layers are its data's outer list layers (the token-shape rule), + so the slot a stream with list tokens is bound to declares list data. + """ + tags, data = ARRANGEMENTS[arrangement] + names = [*tags, *data] + arrays = dict(COLUMNS) + for name, (_, kind) in tokens.items(): + data_type = data_type_for(kind) + arrays[name] = pa.array( + [nested_value(v, data_type) for v in COLUMNS[name].to_pylist()], data_type + ) + schema = pa.schema(pa.field(n, arrays[n].type, nullable=False) for n in names) + return ArrowTableSource( + pa.Table.from_arrays([arrays[n] for n in names], schema=schema), + tag_columns=list(tags), + tag_only_columns=True, + source_id="rows", + ) + + +def _with_tokens( + arrangement: str, tokens: dict[str, tuple[list[Any], pa.DataType]] +) -> ArrowTableStream: + """The source's rows as a raw stream, each named token column replaced. + + Each such data column gets its token's list layers, the row's value at every + token position. The stream keeps the source's system-tag pair, so the job's + slot (``_shaped_source``) accepts it. + + Args: + arrangement: The layout of the rows. + tokens: For a data column, its token column's values and Arrow type. + """ + source = _source(arrangement) + table = source.as_table(columns={"source": True, "system_tags": True}) + for name, (values, kind) in tokens.items(): + table = with_token_column(table, name, values, kind) + return ArrowTableStream(table, tag_columns=list(ARRANGEMENTS[arrangement][0])) + + +def _counting(name: str, x: Any, w: Any) -> Any: + """A function pod ``name(x, w) -> total`` that returns 1, for the given types.""" + + def count(x: Any, w: Any) -> int: + calls[name] += 1 + return 1 + + count.__name__ = count.__qualname__ = name + count.__annotations__ = {"x": x, "w": w, "return": int} + return function_pod(output_keys="total")(count) + + +def _stored(database: InMemoryArrowDatabase, function: str) -> pa.Table: + """The pipeline table (``pdb_v2``) of the function named ``function``.""" + database.flush() + (path,) = [ + p for p in database.list_sources() if p[-1] == "pdb_v2" and function in p + ] + records = database.get_all_records(path, record_id_column=KEY) + assert records is not None + return records + + +def _instance_ids(stored: pa.Table) -> list[bytes]: + """The stored instance ids, sorted.""" + return sorted( + cast("list[bytes]", stored.column("__pipeline_instance_id").to_pylist()) + ) + + +def _token_columns(table: pa.Table) -> list[str]: + """The names of ``table``'s source-info columns, sorted.""" + return sorted( + n for n in table.column_names if n.startswith(constants.SOURCE_PREFIX) + ) + + +def _by_instance(stored: pa.Table) -> dict[bytes, dict[str, Any]]: + """Each stored row's tags and tokens, by its instance id. + + The columns that differ between two runs by design are left out: the result id, + the record id that covers it, the insertion time and the run id. + """ + kept = [ + name + for name in stored.column_names + if name in COLUMNS or name.startswith(constants.SOURCE_PREFIX) + ] + return { + cast("bytes", row["__pipeline_instance_id"]): {name: row[name] for name in kept} + for row in stored.to_pylist() + } + + +def _check_record_ids(stored: pa.Table) -> None: + """Every row's record id is the one its own columns give, and is the table's key.""" + for row in stored.to_pylist(): + record = row_ids.record_id( + HASHER, + ContentHash.from_prefixed_digest(row["__node_content_hash"]), + ContentHash.from_prefixed_digest(row["__pipeline_instance_id"]), + uuid.UUID(bytes=row["__data_id"]), + ).to_prefixed_digest() + assert row["__pipeline_record_id"] == record + assert row[KEY] == record + + +def _ids_of_given_rows(node: Any) -> tuple[set[bytes], set[bytes]]: + """The entry ids and the instance ids of the rows ``node`` holds after a run.""" + rows = list(node.iter_data()) + return ( + {row_ids.entry_id(HASHER, t, d).to_prefixed_digest() for t, d in rows}, + {row_ids.instance_id(HASHER, t, d).to_prefixed_digest() for t, d in rows}, + ) + + +def _run_both(build: Any, function: str, given: str) -> dict[str, dict[str, Any]]: + """Run the job ``build`` makes on each orchestrator, each over its own store. + + Args: + build: Called with a database; returns the job. + function: The function whose pipeline table is read. + given: The label of the node that function reads. + + Returns: + Per orchestrator: the stored table, its rows by instance id, the token + columns' types, and the entry and instance ids of the rows the node was given. + """ + seen: dict[str, dict[str, Any]] = {} + for name, orchestrator in ORCHESTRATORS.items(): + database = InMemoryArrowDatabase() + job = build(database) + _ = job.run(orchestrator=orchestrator()) + stored = _stored(database, function) + _check_record_ids(stored) + entries, instances = _ids_of_given_rows(job.nodes[given]) + assert set(stored.column("__pipeline_instance_id").to_pylist()) == instances + seen[name] = { + "stored": stored, + "rows": _by_instance(stored), + "types": {n: stored.schema.field(n).type for n in _token_columns(stored)}, + "entries": entries, + "instances": instances, + } + return seen + + +def _assert_same_on_both_routes(seen: dict[str, dict[str, Any]], rows: int) -> None: + """The two routes stored the same rows, token types and ids.""" + sync, asynchronous = seen["sync"], seen["async"] + assert sync["stored"].num_rows == asynchronous["stored"].num_rows == rows + assert sync["types"] == asynchronous["types"] + assert sync["entries"] == asynchronous["entries"] and len(sync["entries"]) == rows + assert sync["instances"] == asynchronous["instances"] + assert len(sync["instances"]) == rows + assert sync["rows"] == asynchronous["rows"] + + +# --------------------------------------------------------------------------- +# Token columns made by the operators: one and two aggregation levels +# --------------------------------------------------------------------------- + + +def _batched(arrangement: str) -> Any: + return Batch(batch_size=2)(_source(arrangement), label="given") + + +def _grouped(arrangement: str) -> Any: + return GroupBy(by=["subject"])(_source(arrangement), label="given") + + +def _merged(arrangement: str) -> Any: + return MergeJoin()( + _source(arrangement, source_id="left"), + _source(arrangement, source_id="right"), + label="given", + ) + + +def _grouped_then_batched(arrangement: str) -> Any: + return Batch(batch_size=2)( + GroupBy(by=["subject"])(_source(arrangement)), label="given" + ) + + +def _merged_then_batched(arrangement: str) -> Any: + return Batch(batch_size=2)( + MergeJoin()( + _source(arrangement, source_id="left"), + _source(arrangement, source_id="right"), + ), + label="given", + ) + + +AGGREGATIONS: dict[str, tuple[Any, Any, pa.DataType, int]] = { + "batch": (_batched, add_lists, STRINGS, 2), + "group_by": (_grouped, add_lists, STRINGS, 2), + "merge_join": (_merged, add_lists, STRINGS, 4), + "group_by_then_batch": (_grouped_then_batched, add_nested, NESTED, 1), + "merge_join_then_batch": (_merged_then_batched, add_nested, NESTED, 2), +} + + +@ARRANGEMENT +@pytest.mark.parametrize("aggregation", list(AGGREGATIONS)) +def test_aggregated_tokens_are_stored_alike_on_both_routes( + aggregation: str, arrangement: str +) -> None: + """Aggregated token columns have their stream's type on both routes. + + Over these inputs (plain tags; ``x`` and ``w`` are not keys, and collide under + ``MergeJoin``) each of ``Batch``, ``GroupBy`` and ``MergeJoin`` gives a list of + the input's tokens, and two of them a list of lists. A function node stores + the type its input stream has, not one worked out from the tokens. The stored + rows, the token types and the entry, instance and record ids are the same on + both routes. + """ + make, function, kind, rows = AGGREGATIONS[aggregation] + + def build(database: InMemoryArrowDatabase) -> PipelineJob: + job = PipelineJob(name="aggregated", database=database) + with job: + function.pod(make(arrangement), label="f") + return job + + seen = _run_both(build, function.pod.label or function.__name__, "given") + _assert_same_on_both_routes(seen, rows) + assert seen["sync"]["types"] == {"_source_w": kind, "_source_x": kind} + assert calls[function.__name__] == 2 * rows + + +@pytest.mark.parametrize("aggregation", list(AGGREGATIONS)) +def test_the_arrangement_of_the_source_changes_no_stored_instance( + aggregation: str, +) -> None: + """Tag order and data order of the source change no stored instance id.""" + make, function, _, rows = AGGREGATIONS[aggregation] + instances = [] + for arrangement in ARRANGEMENTS: + + def build( + database: InMemoryArrowDatabase, arrangement: str = arrangement + ) -> PipelineJob: + job = PipelineJob(name="aggregated", database=database) + with job: + function.pod(make(arrangement), label="f") + return job + + seen = _run_both(build, function.pod.label or function.__name__, "given") + _assert_same_on_both_routes(seen, rows) + instances.append(seen["sync"]["instances"]) + assert instances[0] == instances[1] + + +# --------------------------------------------------------------------------- +# Token columns whose values cannot be typed again from Python values +# --------------------------------------------------------------------------- + +# One level (as after ``Batch`` or ``GroupBy``), two levels and three: the values +# hold nulls and empty lists, from which no type can be worked out again (a row +# alone shows fewer list levels than its column has, or none at all). +UNTYPEABLE: dict[str, dict[str, tuple[list[Any], pa.DataType]]] = { + "one_level": { + "x": ([[None], [], ["s::0::x", None], ["t"]], STRINGS), + "w": ([[], ["u", "v"], [None, None], []], STRINGS), + }, + "two_levels": { + "x": ([[[None]], [[]], [["a"], []], [[None, "b"]]], NESTED), + "w": ([[[]], [["c"]], [[None]], [[], []]], NESTED), + }, + "three_levels": { + "x": ([[[], [[]]], [[], [[]]], [[["t"]]], [[]]], DEEP), + "w": ([[[["u"]]], [[]], [[[None]]], [[], [[]]]], DEEP), + }, + "one_level_beside_strings": { + "x": ([[None], [], ["s::0::x", None], ["t"]], STRINGS), + }, +} + + +# The function over each case's data: ``x`` and ``w`` have their tokens' list layers. +_L1, _L2, _L3 = list[int], list[list[int]], list[list[list[int]]] +OVER: dict[str, Any] = { + "one_level": _counting("count_one_level", _L1, _L1), + "two_levels": _counting("count_two_levels", _L2, _L2), + "three_levels": _counting("count_three_levels", _L3, _L3), + "one_level_beside_strings": _counting("count_beside_strings", _L1, int), +} + + +def _untypeable_job( + database: InMemoryArrowDatabase, tokens: str, arrangement: str, columns: list[str] +) -> PipelineJob: + """``rows -> select -> count``, the slot bound to the case's raw stream.""" + replaced = UNTYPEABLE[tokens] + job = PipelineJob(name="untypeable", database=database) + with job: + selected = _shaped_source(arrangement, replaced).select_data_columns( + columns, label="given" + ) + OVER[tokens].pod(selected, label="f") + job.bind(sources={"rows": _with_tokens(arrangement, replaced)}) + return job + + +@ARRANGEMENT +@pytest.mark.parametrize("tokens", list(UNTYPEABLE)) +def test_nested_tokens_no_value_can_type_are_stored_alike_on_both_routes( + tokens: str, arrangement: str +) -> None: + """Rows with nested token columns pass an operator and reach a function node. + + The job is ``rows -> select -> add``; the slot is bound to a raw stream whose + token columns are lists (one, two and three levels) holding nulls and empty + lists. The sync route builds a table from the rows at each edge; it used to type + every token again from its value there and raise an Arrow type error, while the + async route sent the rows on (ITL-1491). Both routes now store every row, with + the stream's token types and the same ids. + """ + replaced = UNTYPEABLE[tokens] + name = OVER[tokens].__name__ + seen = _run_both( + lambda database: _untypeable_job(database, tokens, arrangement, ["w", "x"]), + name, + "given", + ) + _assert_same_on_both_routes(seen, 4) + expected = {"_source_w": pa.large_string(), "_source_x": pa.large_string()} + expected |= {f"_source_{name}": kind for name, (_, kind) in replaced.items()} + assert seen["sync"]["types"] == expected + stored = seen["sync"]["stored"].sort_by( + [("subject", "ascending"), ("session", "ascending")] + ) + for column, (values, _) in replaced.items(): + assert stored.column(f"_source_{column}").to_pylist() == values + assert calls[name] == 8 + + +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +@pytest.mark.parametrize("tokens", list(UNTYPEABLE)) +def test_the_arrangement_changes_no_instance_of_rows_with_nested_tokens( + tokens: str, orchestrator: str +) -> None: + """Tag order and data order change no stored instance id of such rows.""" + instances = [] + for arrangement in ARRANGEMENTS: + database = InMemoryArrowDatabase() + job = _untypeable_job(database, tokens, arrangement, ["x", "w"]) + _ = job.run(orchestrator=ORCHESTRATORS[orchestrator]()) + instances.append(set(_instance_ids(_stored(database, OVER[tokens].__name__)))) + assert instances[0] == instances[1] and len(instances[0]) == 4 + + +@pytest.mark.parametrize("first", list(ORCHESTRATORS)) +@pytest.mark.parametrize("tokens", list(UNTYPEABLE)) +def test_a_second_route_over_the_same_store_finds_every_instance( + tokens: str, first: str +) -> None: + """Whichever route ran first, the other finds its records: nothing is added. + + One store, two sessions, one on each orchestrator: the second computes nothing + and writes no row, because a row has one instance id on both routes. + """ + database = InMemoryArrowDatabase() + second = next(name for name in ORCHESTRATORS if name != first) + name = OVER[tokens].__name__ + stored = [] + for arrangement, orchestrator in zip(ARRANGEMENTS, (first, second)): + job = _untypeable_job(database, tokens, arrangement, ["x", "w"]) + _ = job.run(orchestrator=ORCHESTRATORS[orchestrator]()) + table = _stored(database, name) + assert table.num_rows == 4, orchestrator + stored.append(_instance_ids(table)) + assert stored[0] == stored[1] + assert calls[name] == 4 + + +# --------------------------------------------------------------------------- +# An aggregation over a token column that holds nulls +# --------------------------------------------------------------------------- + +# Plain string tokens that are null in some rows (a string token may be null). +# ``Batch`` and ``GroupBy`` put them into lists, an element of which may be null: +# ``[None]``, ``[None, "a"]``, ``[None, None]``. A null LIST token is not a valid +# token (``test_token_shape.py``), so the aggregation never sees one. These lists +# type the same from their values as from the column, so this is a guard, not a +# case the re-typing from values got wrong. +NULL_TOKENS: dict[str, tuple[list[Any], pa.DataType]] = { + "x": ([None, "s::1::x", None, None], pa.large_string()), + "w": (["s::0::w", None, "s::2::w", None], pa.large_string()), +} +OVER_NULL_TOKENS: dict[str, tuple[Any, int]] = { + "batch_1": (lambda stream: Batch(batch_size=1)(stream, label="given"), 4), + "batch_2": (lambda stream: Batch(batch_size=2)(stream, label="given"), 2), + "group_by": (lambda stream: GroupBy(by=["subject"])(stream, label="given"), 2), +} + + +@function_pod(output_keys="count") +def count_members(x: list[int], w: list[int]) -> int: + """Return how many members the row gathers.""" + calls["count_members"] += 1 + return len(x) + len(w) + + +def _null_token_job( + database: InMemoryArrowDatabase, aggregation: str, arrangement: str +) -> PipelineJob: + """``rows -> Batch or GroupBy -> count_members``, the slot bound to ``NULL_TOKENS``.""" + job = PipelineJob(name="null_tokens", database=database) + with job: + count_members.pod( + OVER_NULL_TOKENS[aggregation][0](_source(arrangement)), label="f" + ) + job.bind(sources={"rows": _with_tokens(arrangement, NULL_TOKENS)}) + return job + + +@ARRANGEMENT +@pytest.mark.parametrize("aggregation", list(OVER_NULL_TOKENS)) +def test_an_aggregation_over_null_tokens_is_stored_alike_on_both_routes( + aggregation: str, arrangement: str +) -> None: + """``Batch`` and ``GroupBy`` over string tokens with nulls: lists with null elements. + + The aggregated token column is a list of tokens, and some of its values are + ``[None]`` or ``[None, None]``. The function node after it stores that one list + level on the sync and on the async route, with the same rows and ids. + """ + rows = OVER_NULL_TOKENS[aggregation][1] + seen = _run_both( + lambda database: _null_token_job(database, aggregation, arrangement), + "count_members", + "given", + ) + _assert_same_on_both_routes(seen, rows) + assert seen["sync"]["types"] == {"_source_w": STRINGS, "_source_x": STRINGS} + tokens = seen["sync"]["stored"].column("_source_x").to_pylist() + assert all(token is not None for token in tokens) + assert any(None in token for token in tokens) + assert calls["count_members"] == 2 * rows + + +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +@pytest.mark.parametrize("aggregation", list(OVER_NULL_TOKENS)) +def test_held_rows_of_such_an_aggregation_reach_the_function_again( + aggregation: str, orchestrator: str +) -> None: + """The aggregation's held rows are passed to the function node with their types. + + After a run the function node is cleared, so the next run holds the aggregation + node (it is current) and passes its rows on to the function node, which finds + every instance stored: no row is added and nothing is computed. The sync route + builds the held rows into one table at that edge. + """ + rows = OVER_NULL_TOKENS[aggregation][1] + database = InMemoryArrowDatabase() + job = _null_token_job(database, aggregation, "as_declared") + _ = job.run(orchestrator=ORCHESTRATORS[orchestrator]()) + first = _stored(database, "count_members") + job.nodes["f"].clear_cache() + summary = job.run(orchestrator=ORCHESTRATORS[orchestrator]()) + assert summary.nodes["f"].reused == rows and summary.nodes["f"].computed == 0 + again = _stored(database, "count_members") + assert again.num_rows == first.num_rows == rows + assert _instance_ids(again) == _instance_ids(first) + assert again.schema.field("_source_x").type == STRINGS + assert again.schema.field("_source_w").type == STRINGS + assert len(list(job.nodes["f"].iter_data())) == rows + assert calls["count_members"] == rows + + +# --------------------------------------------------------------------------- +# Data-tags that fall through two functions keep their tokens, type and value +# --------------------------------------------------------------------------- + +TAG_ORDERS = [("pair", "path"), ("path", "pair")] +FIXED = pa.list_(pa.large_string(), 2) +# The token column of each data-tag: a fixed-size list (a type no value gives) and +# a nested list holding nulls and an empty list. Each data-tag has its token's +# list layers (the token-shape rule): ``pair`` is a fixed-size list of two +# strings, ``path`` a list of lists of integers. +DATA_TAG_TOKENS: dict[str, tuple[list[Any], pa.DataType]] = { + "pair": ([["p", "q"], ["r", "s"], ["t", "u"], ["v", "w"]], FIXED), + "path": ([[[None], ["a"]], [[]], [["b"], []], [[None]]], NESTED), +} +DATA_TAGS: dict[str, "pa.Array[Any]"] = { + "pair": pa.array([["m1", "a"], ["m1", "b"], ["m2", "a"], ["m2", "b"]], FIXED), + "path": pa.array( + [[[1], [1]], [[]], [[2], [2]], [[3]]], pa.large_list(pa.large_list(pa.int64())) + ), +} + + +def _data_tag_source(tags: tuple[str, ...]) -> ArrowTableSource: + """Four rows whose two tags, ``pair`` and ``path``, are data-tags too.""" + columns = {**DATA_TAGS, "x": COLUMNS["x"], "w": COLUMNS["w"]} + names = [*tags, "x", "w"] if tags == TAG_ORDERS[0] else ["w", "x", *tags] + schema = pa.schema(pa.field(n, columns[n].type, nullable=False) for n in names) + return ArrowTableSource( + pa.Table.from_arrays([columns[n] for n in names], schema=schema), + tag_columns=list(tags), + tag_only_columns=False, + source_id="rows", + ) + + +def _data_tag_stream(tags: tuple[str, ...]) -> ArrowTableStream: + """The four rows as a raw stream whose two data-tags have typed tokens.""" + table = _data_tag_source(tags).as_table( + columns={"source": True, "system_tags": True} + ) + for name, (values, kind) in DATA_TAG_TOKENS.items(): + column = f"{constants.SOURCE_PREFIX}{name}" + table = table.set_column( + table.schema.get_field_index(column), + pa.field(column, kind, nullable=True), + pa.array(values, kind), + ) + return ArrowTableStream(table, tag_columns=list(tags), data_tags=list(tags)) + + +def _data_tag_job( + database: InMemoryArrowDatabase, tags: tuple[str, ...] +) -> PipelineJob: + """``rows -> add -> twice`` over a source whose two tags are data-tags.""" + job = PipelineJob(name="data_tags", database=database) + with job: + first = add.pod(_data_tag_source(tags), label="given") + twice.pod(first, label="f") + job.bind(sources={"rows": _data_tag_stream(tags)}) + return job + + +def _pair(row: Any) -> tuple[str, ...]: + """A row's ``pair`` data-tag, which names the row.""" + return tuple(cast("list[str]", row["pair"])) + + +@pytest.mark.parametrize("tags", TAG_ORDERS) +def test_data_tags_fall_through_two_functions_with_their_tokens_unchanged( + tags: tuple[str, ...], +) -> None: + """After each function a data-tag's token is the stream's, type and value. + + Two data-tags fall through ``add`` and then ``twice``. The token column of each, + in the rows after the first function, in the rows after the second and in the + second function's stored rows, equals the stream's: a fixed-size list stays a + fixed-size list and a nested list its type, on both routes. A column a function + returns has the function's own string token. + """ + before = {_pair(data): data for _, data in _data_tag_stream(tags).iter_data()} + expected = { + _pair(data): {name: data.source_info()[name] for name in DATA_TAG_TOKENS} + for data in before.values() + } + seen = _run_both(lambda database: _data_tag_job(database, tags), "twice", "given") + # Each route ran over its own store, so ``total``'s token holds another result + # id on each and the instance ids differ (one store: the test below). The + # entries, the token types and the data-tags' tokens are the same. + assert seen["sync"]["entries"] == seen["async"]["entries"] + assert len(seen["sync"]["entries"]) == 4 + assert seen["sync"]["types"] == seen["async"]["types"] + for route in seen.values(): + assert route["stored"].num_rows == 4 + stored = { + _pair(row): {name: row[f"_source_{name}"] for name in DATA_TAG_TOKENS} + for row in route["stored"].to_pylist() + } + assert stored == expected + assert seen["sync"]["types"] == { + "_source_pair": FIXED, + "_source_path": NESTED, + "_source_total": pa.large_string(), + } + for orchestrator in ORCHESTRATORS.values(): + job = _data_tag_job(InMemoryArrowDatabase(), tags) + _ = job.run(orchestrator=orchestrator()) + for label, returned in (("given", "total"), ("f", "twice")): + rows = list(job.nodes[label].iter_data()) + assert len(rows) == 4 + for _, data in rows: + origin = before[_pair(data)].source_info_table() + after = data.source_info_table() + for name in DATA_TAG_TOKENS: + column = f"{constants.SOURCE_PREFIX}{name}" + assert after.schema.field(column).type == DATA_TAG_TOKENS[name][1] + assert after.column(column).equals(origin.column(column)) + own = after.schema.field(f"{constants.SOURCE_PREFIX}{returned}") + assert own.type == pa.large_string() + assert f"::{returned}" in cast("str", data.source_info()[returned]) + + +@pytest.mark.parametrize( + "routes", + [("sync", "async"), ("async", "sync"), ("sync", "sync", "async", "async")], +) +def test_data_tags_have_one_instance_per_row_whichever_route_ran_first( + routes: tuple[str, ...], +) -> None: + """Sessions on either route, in both tag orders, over one store: no row is added.""" + database = InMemoryArrowDatabase() + stored = [] + for index, route in enumerate(routes): + job = _data_tag_job(database, TAG_ORDERS[index % 2]) + _ = job.run(orchestrator=ORCHESTRATORS[route]()) + table = _stored(database, "twice") + assert table.num_rows == 4, (index, route) + assert table.schema.field("_source_pair").type == FIXED + assert table.schema.field("_source_path").type == NESTED + stored.append(_instance_ids(table)) + assert all(ids == stored[0] for ids in stored) and len(set(stored[0])) == 4 + assert calls["add"] == 4 and calls["twice"] == 4 diff --git a/tests/test_pipeline/test_token_types_review_1.py b/tests/test_pipeline/test_token_types_review_1.py new file mode 100644 index 000000000..0c1cbc4d9 --- /dev/null +++ b/tests/test_pipeline/test_token_types_review_1.py @@ -0,0 +1,799 @@ +"""Findings of the independent review of PR #601 (ITL-1491), each as a test. + +The rule under test: the Arrow type of a source-info token column is determined by +the pipeline and kept on every route; no route types a token again from its value +where an Arrow type exists; and inputs that declare one token column with two types +are refused, on the sync and on the async route alike. + +Every job has sources with two tags (both data-tags) and two data columns, in two tag +orders, and runs on both orchestrators. +""" + +from __future__ import annotations + +import asyncio +from collections import Counter +from typing import Any, cast + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.channels import Channel +from orcapod.core.datagrams import Data +from orcapod.core.operators import Join, MergeJoin +from orcapod.core.operators.static_output_pod import ( + SourceInfoTypesDisagree, + StaticOutputOperatorPod, + concatenate_batches, +) +from orcapod.core.record_batch_channels import OutputChannel +from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import InputValidationError +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.system_constants import constants +from tests.token_shapes import data_type_for, nested_value + +ORCHESTRATORS = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} +TAG_ORDERS = {"k_then_g": ("k", "g"), "g_then_k": ("g", "k")} +TAG_ORDER = pytest.mark.parametrize("tags", list(TAG_ORDERS)) + +TOKEN = pa.large_string() +TOKENS = pa.large_list(TOKEN) +# A hand-built token type no value gives: a fixed-size list whose item field has its +# own name and is not nullable. +FIXED = pa.list_(pa.field("member", TOKEN, nullable=False), 2) +FIXED_PLAIN = pa.list_(TOKEN, 2) + +calls: Counter[str] = Counter() + + +@pytest.fixture(autouse=True) +def _reset() -> None: + """Clear the call counts.""" + calls.clear() + + +@function_pod(output_keys="total") +def add_two(x: int, y: int) -> int: + """Return ``x + y``.""" + calls["add_two"] += 1 + return x + y + + +@function_pod(output_keys="total") +def add_three(x: int, y: int, z: int) -> int: + """Return ``x + y + z``.""" + calls["add_three"] += 1 + return x + y + z + + +@function_pod(output_keys="total") +def add_pairs(x: list[list[int]], w: int, v: int) -> int: + """Return the sum of the merged ``x`` and the two other columns.""" + calls["add_pairs"] += 1 + return sum(sum(v_) for v_ in x) + w + v + + +# (first data column, second data column) of each source. +DATA = {"a": ("x", "w"), "b": ("y", "v"), "c": ("z", "u")} +Shapes = dict[str, pa.DataType] + + +def _source( + source_id: str, + tags: tuple[str, ...], + *, + data: tuple[str, str] | None = None, + keys: tuple[int, int] = (1, 2), + data_tags: bool = True, + shapes: Shapes | None = None, +) -> ArrowTableSource: + """Two rows keyed ``k`` and ``g``, with the source's two data columns. + + Args: + source_id: The source's name. + tags: The tag columns, in order. + data: The two data columns' names; the source's own by default. + keys: The two values of ``k``. + data_tags: Whether the tags are data-tags too. + shapes: For a column, the token type whose list layers the column is + given (the token-shape rule: a list token needs list data); each + value is wrapped in those layers. + """ + first, second = data or DATA[source_id] + columns: dict[str, pa.Array[Any]] = { + "k": pa.array(list(keys), pa.int64()), + "g": pa.array(["m", "n"], pa.large_string()), + first: pa.array([10, 20], pa.int64()), + second: pa.array([100, 200], pa.int64()), + } + for name, kind in (shapes or {}).items(): + data_type = data_type_for(kind, columns[name].type) + columns[name] = pa.array( + [nested_value(v, data_type) for v in columns[name].to_pylist()], data_type + ) + names = [*tags, first, second] + schema = pa.schema(pa.field(n, columns[n].type, nullable=False) for n in names) + return ArrowTableSource( + pa.Table.from_arrays([columns[n] for n in names], schema=schema), + tag_columns=list(tags), + tag_only_columns=not data_tags, + source_id=source_id, + ) + + +def _with_tokens( + source: ArrowTableSource, + tags: tuple[str, ...], + tokens: dict[str, tuple[list[Any], pa.DataType]], + *, + data_tags: bool = True, +) -> ArrowTableStream: + """``source``'s rows as a raw stream with the named token columns replaced. + + The source's columns already have the shapes of the tokens they get. + """ + table = source.as_table(columns={"source": True, "system_tags": True}) + for name, (values, kind) in tokens.items(): + column = f"{constants.SOURCE_PREFIX}{name}" + table = table.set_column( + table.schema.get_field_index(column), + pa.field(column, kind, nullable=True), + pa.array(values, kind), + ) + return ArrowTableStream( + table, tag_columns=list(tags), data_tags=list(tags) if data_tags else [] + ) + + +def _stored(database: InMemoryArrowDatabase, function: str) -> pa.Table: + """The pipeline table (``pdb_v2``) of the function named ``function``.""" + database.flush() + (path,) = [ + p for p in database.list_sources() if p[-1] == "pdb_v2" and function in p + ] + records = database.get_all_records(path) + assert records is not None + return records + + +def _by_k(stored: pa.Table) -> pa.Table: + """``stored`` ordered by its key ``k``, which may be a list.""" + keys = [repr(key) for key in stored.column("k").to_pylist()] + order = sorted(range(stored.num_rows), key=keys.__getitem__) + return stored.take(order) + + +def _instance_ids(stored: pa.Table) -> list[bytes]: + """The stored instance ids, sorted.""" + return sorted( + cast("list[bytes]", stored.column("__pipeline_instance_id").to_pylist()) + ) + + +def _async_rows(operator: Any, *streams: Any) -> list[Any]: + """The rows ``operator.async_execute`` yields over the streams' rows.""" + + async def run() -> list[Any]: + channels: list[Channel[Any]] = [Channel(buffer_size=16) for _ in streams] + output: Channel[Any] = Channel(buffer_size=16) + for stream, channel in zip(streams, channels): + for row in stream.iter_data(): + await channel.writer.send(row) + await channel.writer.close() + await operator.async_execute( + [channel.reader for channel in channels], + output.writer, + input_pipeline_hashes=[s.pipeline_hash() for s in streams], + ) + return await output.reader.collect() + + return asyncio.run(run()) + + +# --------------------------------------------------------------------------- +# P1-2: the async Join keeps the declared type of a merged data-tag's token +# --------------------------------------------------------------------------- + +K_TOKENS: dict[str, tuple[list[Any], pa.DataType]] = { + "a": ([["a1", "a2"], ["a3", "a4"]], FIXED), + "b": ([["b1", "b2"], ["b3", "b4"]], FIXED), +} +# ``k`` has its token's layer: a fixed-size list of two integers (the join key). +K_SHAPE: Shapes = {"k": FIXED} + + +def _join_job( + database: InMemoryArrowDatabase, tags: tuple[str, ...], inputs: int +) -> PipelineJob: + """``Join(a, b[, c]) -> add``; ``k`` and ``g`` are data-tags of ``a`` and ``b``. + + ``k`` is a fixed-size list in every input, with a fixed-size-list token in + ``a`` and ``b``. ``c`` has plain tags, so it merges no token and leaves the + first two inputs' merged token pending until the join's last step. + """ + job = PipelineJob(name="merged", database=database) + with job: + sources = [ + _source("a", tags, shapes=K_SHAPE), + _source("b", tags, shapes=K_SHAPE), + ] + if inputs == 3: + sources.append(_source("c", tags, data_tags=False, shapes=K_SHAPE)) + function = add_two if inputs == 2 else add_three + function.pod(Join()(*sources, label="joined"), label="f") + job.bind( + sources={ + name: _with_tokens( + _source(name, tags, shapes=K_SHAPE), tags, {"k": K_TOKENS[name]} + ) + for name in ("a", "b") + } + ) + return job + + +@TAG_ORDER +@pytest.mark.parametrize("inputs", [2, 3]) +def test_a_join_keeps_the_declared_type_of_a_merged_data_tag_token( + inputs: int, tags: str +) -> None: + """Both routes store the merged token with the type both inputs declare. + + ``k`` is a data-tag on two inputs, a fixed-size list of two integers with a + fixed-size-list token (a token's list layers are its data's). The join merges + the two tokens position by position into the same fixed-size list (item field + ``member``, not nullable). The async route rebuilt the merged token from its + Python value as a ``large_list`` (review of PR #601, P1-2), also when a third + input left the merged token pending until the last step. + """ + function = "add_two" if inputs == 2 else "add_three" + seen = {} + for name, orchestrator in ORCHESTRATORS.items(): + database = InMemoryArrowDatabase() + job = _join_job(database, TAG_ORDERS[tags], inputs) + _ = job.run(orchestrator=orchestrator()) + stored = _by_k(_stored(database, function)) + field = stored.schema.field("_source_k") + assert field.type.equals(FIXED, check_metadata=True), (name, field.type) + merged = cast("list[list[str]]", stored.column("_source_k").to_pylist()) + assert [len(token) for token in merged] == [2, 2] + assert all(part.startswith("join_v1:") for token in merged for part in token) + assert len({part for token in merged for part in token}) == 4 + assert stored.schema.field("_source_g").type == TOKEN + seen[name] = (merged, _instance_ids(stored)) + assert seen["sync"] == seen["async"] + + +@TAG_ORDER +@pytest.mark.parametrize("inputs", [2, 3]) +@pytest.mark.parametrize("first", list(ORCHESTRATORS)) +def test_switching_routes_over_one_store_adds_no_row_after_a_join( + first: str, inputs: int, tags: str +) -> None: + """A second session on the other route finds every instance: no write error.""" + function = "add_two" if inputs == 2 else "add_three" + second = next(name for name in ORCHESTRATORS if name != first) + database = InMemoryArrowDatabase() + stored = [] + for route in (first, second): + job = _join_job(database, TAG_ORDERS[tags], inputs) + _ = job.run(orchestrator=ORCHESTRATORS[route]()) + table = _stored(database, function) + assert table.num_rows == 2, route + stored.append(_instance_ids(table)) + assert stored[0] == stored[1] + assert calls[function] == 2 + + +# --------------------------------------------------------------------------- +# Q2 / P2-3: inputs that declare one token column with two types are refused +# --------------------------------------------------------------------------- + +# Pairs of declarations of one token column over one list-valued data column; both +# are valid there (a list token has the data's list layer; a plain string token +# fits any data). A list against a fixed-size list is not such a pair: those tokens +# need two data types, which the operators already refuse on the data column. +TWO_TYPES = { + "item_nullability": ( + pa.large_list(pa.field("item", TOKEN, nullable=False)), + TOKENS, + ), + "list_and_string": (TOKENS, TOKEN), +} +SIDES = pytest.mark.parametrize("swapped", [False, True], ids=["a_b", "b_a"]) + + +def _values(kind: pa.DataType, prefix: str) -> list[Any]: + """Two rows of tokens of ``kind``.""" + if kind == TOKEN: + return [f"{prefix}1", f"{prefix}2"] + return [[f"{prefix}1"], [f"{prefix}2"]] + + +def _two_typed( + column: str, case: str, swapped: bool, tags: tuple[str, ...], keys: tuple[int, int] +) -> tuple[ArrowTableStream, ArrowTableStream]: + """Two inputs that declare ``_source_`` with the case's two types. + + ``column`` is a list in both inputs. For ``column == "x"`` both inputs have the + data columns ``x`` and ``w`` / ``v`` (``x`` collides under ``MergeJoin``); + otherwise their own data columns. + """ + first, second = TWO_TYPES[case] + if swapped: + first, second = second, first + data = {"a": ("x", "w"), "b": ("x", "v")} if column == "x" else DATA + streams = [] + for name, kind, source_keys in (("a", first, (1, 2)), ("b", second, keys)): + source = _source( + name, tags, data=data[name], keys=source_keys, shapes={column: TOKENS} + ) + streams.append( + _with_tokens(source, tags, {column: (_values(kind, name), kind)}) + ) + return streams[0], streams[1] + + +def _refusal(run: Any) -> str: + """The message of the ``InputValidationError`` ``run`` raises. + + The async ``Join`` runs in a task group, which wraps the error it raises. + """ + with pytest.raises((InputValidationError, ExceptionGroup)) as refused: + run() + error: BaseException = refused.value + while isinstance(error, ExceptionGroup): + (error,) = error.exceptions + assert isinstance(error, InputValidationError) + return str(error) + + +def _names_both_types(message: str, column: str, case: str) -> bool: + """Whether a refusal names the column and both declared types.""" + from orcapod.utils import arrow_utils + + return f"'_source_{column}'" in message and all( + arrow_utils.describe_arrow_type(kind) in message for kind in TWO_TYPES[case] + ) + + +@TAG_ORDER +@SIDES +@pytest.mark.parametrize("keys", [(1, 2), (7, 8)], ids=["keys_match", "no_match"]) +@pytest.mark.parametrize("case", list(TWO_TYPES)) +def test_merge_join_refuses_two_declarations_of_a_colliding_token_column( + case: str, keys: tuple[int, int], swapped: bool, tags: str +) -> None: + """``MergeJoin`` refuses, on both routes, inputs whose colliding column's token + types differ, naming the column and both types, whether or not a key matches. + + The colliding column ``x`` is a list in both inputs; one declares a list of + tokens for it and the other a plain string token (or lists whose items differ + in nullability). On the base such a job completed when the tokens' values + typed alike: the sync edge typed both token columns again from their values, so + the declarations no longer differed when the operator saw them (review of PR + #601, P2-3; the refusal is the developer's decision of November 27, 2026). + """ + order = TAG_ORDERS[tags] + left, right = _two_typed("x", case, swapped, order, keys) + sync = _refusal(lambda: MergeJoin()(left, right).as_table()) + assert sync.startswith("MergeJoin") and _names_both_types(sync, "x", case) + assert _refusal(lambda: _async_rows(MergeJoin(), left, right)) == sync + for orchestrator in ORCHESTRATORS.values(): + job = PipelineJob(name="two_types", database=InMemoryArrowDatabase()) + with job: + merged = MergeJoin()( + _source("a", order, data=("x", "w"), shapes={"x": TOKENS}), + _source("b", order, data=("x", "v"), keys=keys, shapes={"x": TOKENS}), + label="merged", + ) + add_pairs.pod(merged, label="f") + job.bind(sources={"a": left, "b": right}) + refused = _refusal(lambda: job.run(orchestrator=orchestrator())) + assert _names_both_types(refused, "x", case) + assert calls["add_pairs"] == 0 + + +@TAG_ORDER +@SIDES +@pytest.mark.parametrize("keys", [(1, 2), (7, 8)], ids=["keys_match", "no_match"]) +@pytest.mark.parametrize("case", list(TWO_TYPES)) +def test_join_refuses_two_declarations_of_a_merged_data_tag_token( + case: str, keys: tuple[int, int], swapped: bool, tags: str +) -> None: + """``Join`` refuses, on both routes, inputs whose shared data-tag's token types + differ, naming the column and both types, whether or not a key matches. + + The key ``k`` is a list in both inputs. The sync route silently took the first + input's type and the async route rebuilt the token from its value (review of + PR #601, P1-2 and P2-3). + """ + order = TAG_ORDERS[tags] + left, right = _two_typed("k", case, swapped, order, keys) + # The commutative Join names its inputs in no fixed order: both types are named. + for refused in ( + _refusal(lambda: Join()(left, right).as_table()), + _refusal(lambda: _async_rows(Join(), left, right)), + ): + assert refused.startswith("Join") and _names_both_types(refused, "k", case) + for orchestrator in ORCHESTRATORS.values(): + job = PipelineJob(name="two_types", database=InMemoryArrowDatabase()) + with job: + joined = Join()( + _source("a", order, shapes={"k": TOKENS}), + _source("b", order, keys=keys, shapes={"k": TOKENS}), + label="joined", + ) + add_two.pod(joined, label="f") + job.bind(sources={"a": left, "b": right}) + refused = _refusal(lambda: job.run(orchestrator=orchestrator())) + assert _names_both_types(refused, "k", case) + assert calls["add_two"] == 0 + + +@TAG_ORDER +@SIDES +def test_tokens_of_two_list_kinds_need_two_data_types_which_are_refused( + swapped: bool, tags: str +) -> None: + """A fixed-size-list token in one input and a ``large_list`` token in the other. + + The reviewer's case for P2-3. Under the token-shape rule each token needs data + of its own list kind, so the colliding column ``x`` has two data types, and + ``MergeJoin`` refuses the inputs, on both routes. (With ``x`` + an integer in both, as in the review, neither stream can be built.) + """ + order = TAG_ORDERS[tags] + kinds = (TOKENS, FIXED_PLAIN) if swapped else (FIXED_PLAIN, TOKENS) + left, right = ( + _with_tokens( + _source(name, order, data=("x", extra), shapes={"x": kind}), + order, + {"x": ([[f"{name}1", f"{name}2"]] * 2, kind)}, + ) + for name, extra, kind in (("a", "w", kinds[0]), ("b", "v", kinds[1])) + ) + # ``x`` has two Arrow types; the refusal names ``x`` or, where the two inputs' + # Python types of ``x`` read alike, its token column. + sync = _refusal(lambda: MergeJoin()(left, right).as_table()) + assert "MergeJoin" in sync and ("'x'" in sync or "'_source_x'" in sync) + # The async route has no validation step: it refuses the same column when the + # rows meet, naming both Arrow types. + late = _refusal(lambda: _async_rows(MergeJoin(), left, right)) + assert "MergeJoin" in late and ("'x'" in late or "'_source_x'" in late) + scalar = _source("a", order, data=("x", "w")) + message = _refusal( + lambda: _with_tokens(scalar, order, {"x": ([["p", "q"]] * 2, FIXED_PLAIN)}) + ) + assert "'_source_x'" in message and "'x'" in message + assert str(FIXED_PLAIN) in message and str(pa.int64()) in message + + +# --------------------------------------------------------------------------- +# P2-4: record batches: item metadata is carried, declarations compared strictly +# --------------------------------------------------------------------------- + +WITH_ITEM_METADATA = { + "large_list": pa.large_list(pa.field("item", TOKEN, metadata={"m": "v"})), + "fixed_size_list": pa.list_(pa.field("item", TOKEN, metadata={"m": "v"}), 2), +} + + +@TAG_ORDER +@pytest.mark.parametrize("kind", list(WITH_ITEM_METADATA)) +def test_a_channel_carries_a_token_columns_item_metadata(kind: str, tags: str) -> None: + """A row-built batch whose token column's item field has metadata is accepted. + + A token column keeps the type its stream declares, item-field metadata + included, so the batch a node builds from such rows carries it. The channel + refused it as "carrying field metadata" (review of PR #601, P2-4). + """ + order = TAG_ORDERS[tags] + declared = WITH_ITEM_METADATA[kind] + stream = _with_tokens( + _source("a", order, shapes={"x": declared}), + order, + {"x": ([["p", "q"], ["r", "s"]], declared)}, + ) + built, tag_keys, data_tags = StaticOutputOperatorPod._rows_to_table( # pyright: ignore[reportPrivateUsage] # the batch a node builds from its rows + list(stream.iter_data()) + ) + assert built.schema.field("_source_x").type.equals(declared, check_metadata=True) + assert (tag_keys, data_tags) == (order, order) + + async def send() -> pa.Table: + output = OutputChannel(stream) + for batch in built.combine_chunks().to_batches(max_chunksize=1): + await output.send(batch) + await output.close() + return output.result().as_table(columns={"source": True, "system_tags": True}) + + result = asyncio.run(send()) + assert result.schema.field("_source_x").type.equals(declared, check_metadata=True) + assert result.column("_source_x").to_pylist() == [["p", "q"], ["r", "s"]] + + +DIFFERING_DECLARATIONS = { + "item_name": ( + pa.large_list(pa.field("member", TOKEN)), + pa.large_list(pa.field("another", TOKEN)), + ), + "item_nullability": ( + pa.large_list(pa.field("item", TOKEN, nullable=False)), + TOKENS, + ), + "item_metadata": ( + pa.large_list(pa.field("item", TOKEN, metadata={"m": "v"})), + TOKENS, + ), + "list_kind": (pa.list_(TOKEN, 1), TOKENS), + "depth": (pa.large_list(TOKENS), TOKENS), +} + + +@pytest.mark.parametrize("swapped", [False, True], ids=["as_listed", "swapped"]) +@pytest.mark.parametrize("case", list(DIFFERING_DECLARATIONS)) +def test_batches_declaring_two_token_types_are_refused_in_either_order( + case: str, swapped: bool +) -> None: + """Two batches of one stream declare one token type, compared strictly. + + A difference in the item field's name, nullability or metadata, in the list + kind or in the depth is refused whichever batch comes first. Batches whose + item fields had two names were put together under the first batch's name, so + the order of the batches decided the result's type (review of PR #601, P2-4). + """ + first, second = DIFFERING_DECLARATIONS[case] + if swapped: + first, second = second, first + + def batch(kind: pa.DataType, key: int) -> pa.RecordBatch: + value: Any = [[]] if kind == pa.large_list(TOKENS) else ["t"] + return pa.RecordBatch.from_arrays( + [pa.array([key], pa.int64()), pa.array([value], kind)], + schema=pa.schema([pa.field("k", pa.int64()), pa.field("_source_x", kind)]), + ) + + with pytest.raises(SourceInfoTypesDisagree, match="_source_x"): + _ = concatenate_batches([batch(first, 1), batch(second, 2)]) + same = concatenate_batches([batch(first, 1), batch(first, 2)]) + assert same is not None + assert same.schema.field("_source_x").type.equals(first, check_metadata=True) + + +@TAG_ORDER +def test_the_whole_table_form_drops_a_token_fields_own_metadata(tags: str) -> None: + """The whole-table form equals the table built from rows for field metadata. + + A row builds each source-info field anew, so the field's own metadata is not + carried; the whole-table form kept it, so the two forms of one node output + differed (review of PR #601, P2-4). Item-field metadata, part of the column's + type, is kept by both. + """ + order = TAG_ORDERS[tags] + kind = WITH_ITEM_METADATA["large_list"] + stream = _with_tokens( + _source("a", order, shapes={"x": kind}), + order, + {"x": ([["p"], ["q", "r"]], kind)}, + ) + table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + index = table.schema.get_field_index("_source_x") + table = table.set_column( + index, + table.schema.field(index).with_metadata({"top": "level"}), + table.column(index), + ) + marked = ArrowTableStream(table, tag_columns=list(order), data_tags=list(order)) + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(marked.iter_data())) # pyright: ignore[reportPrivateUsage] # the rows' form + assert table.schema.field("_source_x").metadata == {b"top": b"level"} + formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # the whole-table form + table, marked.keys() + ) + assert formed.schema.equals(built.schema, check_metadata=True) + assert not formed.schema.field("_source_x").metadata + assert formed.schema.field("_source_x").type.equals(kind, check_metadata=True) + + +# --------------------------------------------------------------------------- +# P2-5: a row made with with_columns_of gains no token column +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("order", [("y", "z"), ("z", "y")]) +def test_rows_built_by_hand_and_by_taking_columns_make_one_table( + order: tuple[str, str], +) -> None: + """A hand-built row and the same row made with ``with_columns_of`` concatenate. + + Neither row has a token for ``x`` or ``w``. The composed row gained null + ``_source_x`` and ``_source_w`` columns the hand-built row does not have, so + the two could not be built into one table (review of PR #601, P2-5). + """ + from orcapod.core.datagrams import Tag + + tokens: dict[str, Any] = {"y": "from-y", "z": ["z1", "z2"]} + direct = Data( + {**{name: 2 for name in order}, "x": 1, "w": 3}, + source_info={name: tokens[name] for name in order}, + ) + other = Data({name: 2 for name in order}, source_info={n: tokens[n] for n in order}) + composed = Data({"x": 1, "w": 3}).with_columns_of(other, list(order)) + expected = [f"_source_{name}" for name in order] + for row in (direct, composed): + shown = row.as_table(columns={"source": True}) + assert [n for n in shown.column_names if n.startswith("_source_")] == expected + assert composed.as_table(columns={"source": True}).schema.equals( + direct.as_table(columns={"source": True}).schema + ) + built, _, _ = StaticOutputOperatorPod._rows_to_table( # pyright: ignore[reportPrivateUsage] # the sync edge's build + [(Tag({"k": 1}), direct), (Tag({"k": 2}), composed)] + ) + assert built.num_rows == 2 + assert [n for n in built.column_names if n.startswith("_source_")] == expected + # For the instance id each data column has a token column, null when missing. + assert composed.source_info_table().column_names == [ + *expected, + "_source_x", + "_source_w", + ] + assert composed.source_info_table().equals( + direct.source_info_table().select(composed.source_info_table().column_names) + ) + + +# --------------------------------------------------------------------------- +# P2-6: a function pod's stream outside a job keeps its input's token types +# --------------------------------------------------------------------------- + +NESTED = pa.large_list(TOKENS) +STREAM_TOKENS: dict[str, tuple[list[Any], pa.DataType]] = { + "k": ([["p", "q"], ["r", "s"]], FIXED), + "g": ([[[None], ["a"]], [[]]], NESTED), +} + + +@TAG_ORDER +def test_a_function_stream_outside_a_job_keeps_fallen_through_token_types( + tags: str, +) -> None: + """``pod(stream).as_table(columns={"source": True})`` keeps the tokens' types. + + Two data-tags fall through the function: ``k``, a fixed-size list with a + fixed-size-list token, and ``g``, a list of lists with a nested token holding a + null and an empty list. The stream's table converted every source-info token + from its Python value and raised ``ValueError: Unsupported Python type: `` (review of PR #601, P2-6; it failed on the base too). + """ + order = TAG_ORDERS[tags] + shapes = {name: kind for name, (_, kind) in STREAM_TOKENS.items()} + stream = _with_tokens(_source("a", order, shapes=shapes), order, STREAM_TOKENS) + + @function_pod(output_keys="total") + def add(x: int, w: int) -> int: + return x + w + + out = add.pod(stream) + table = out.as_table(columns={"source": True}).sort_by("total") + assert table.column("total").to_pylist() == [110, 220] + for name, (values, kind) in STREAM_TOKENS.items(): + field = table.schema.field(f"_source_{name}") + assert field.type.equals(kind, check_metadata=True), field.type + assert table.column(f"_source_{name}").to_pylist() == values + assert table.schema.field("_source_total").type == TOKEN + # The rows and the table agree. + for _, data in out.iter_data(): + row = data.as_table(columns={"source": True}) + for name, (_, kind) in STREAM_TOKENS.items(): + assert row.schema.field(f"_source_{name}").type.equals( + kind, check_metadata=True + ) + + +# --------------------------------------------------------------------------- +# P3: the Python schema of a token column follows its declared type +# --------------------------------------------------------------------------- + + +@TAG_ORDER +def test_the_python_schema_of_a_token_follows_its_columns_type(tags: str) -> None: + """``schema(columns={"source": True})`` agrees with ``arrow_schema``. + + A token ``[]`` in a column declared two list levels deep shows one level; + the Python schema said ``list[str]`` while the Arrow schema had two levels + (review of PR #601, P3). A list holding only a null token is a list too. + """ + order = TAG_ORDERS[tags] + stream = _with_tokens( + _source("a", order, data_tags=False, shapes={"x": NESTED, "w": TOKENS}), + order, + {"x": ([[], [["t"]]], NESTED), "w": ([[None], ["u"]], TOKENS)}, + data_tags=False, + ) + for _, data in stream.iter_data(): + schema = data.schema(columns={"source": True}) + arrow = data.arrow_schema(columns={"source": True}) + assert schema["_source_x"] == list[list[str]] + assert schema["_source_w"] == list[str] + assert arrow.field("_source_x").type == NESTED + assert arrow.field("_source_w").type == TOKENS + + +# --------------------------------------------------------------------------- +# P1-1: a Join never stores its pending marker in a merged token +# --------------------------------------------------------------------------- + +NULL_TOKENS: dict[str, tuple[list[Any], pa.DataType]] = { + "null_lists": ([None, None], TOKENS), + "null_nested": ([None, None], NESTED), + "null_fixed": ([None, None], FIXED_PLAIN), +} + + +@TAG_ORDER +@pytest.mark.parametrize("shaped", [False, True], ids=["scalar_key", "list_key"]) +@pytest.mark.parametrize("case", list(NULL_TOKENS)) +def test_a_stream_whose_merged_data_tag_has_a_null_list_token_is_refused( + case: str, shaped: bool, tags: str +) -> None: + """The input of the reviewer's P1-1 is refused where it is built. + + A data-tag ``k`` whose token column is a list type and null. Over such inputs + the sync ``Join`` wrote its internal pending marker, a string, into the + list-typed column, and pyarrow stored the string's characters as the list's + items, with no error; the async ``Join`` stored a folded string (review of PR + #601, P1-1; the sync fault is on ``main`` too, for a direct ``Join`` over such + raw streams). The stream is not valid (the token-shape rule): over an integer + ``k`` its token has a list layer its data lacks, and over a list ``k`` a token + with a list layer is null. It is refused when built, naming the token column, + its data column and both types, so no ``Join``, on either route, directly or + in a job, is ever given it. + """ + order = TAG_ORDERS[tags] + values, kind = NULL_TOKENS[case] + source = _source("a", order, shapes={"k": kind} if shaped else None) + data_type = source.as_table().schema.field("k").type + message = _refusal(lambda: _with_tokens(source, order, {"k": (values, kind)})) + assert "'_source_k'" in message and "'k'" in message + assert str(kind) in message and str(data_type) in message + assert ("holds a null token" in message) == shaped + + +def test_the_join_never_writes_a_token_that_does_not_fit_its_column() -> None: + """The guard behind P1-1: a merged token is checked against its column's type. + + A stream's tokens have the shape of their column, so the join's merged and + folded tokens always fit. The join still checks before it writes: a string + given for a list type would be stored as its characters. Here the helpers are + handed what no stream can hold (null list tokens to merge), and refuse. + """ + from orcapod.core.operators.join import _token_array, _token_fits # pyright: ignore[reportPrivateUsage] # the guard + + assert _token_fits("t", TOKEN) and _token_fits(None, TOKENS) + assert _token_fits(["a", None], TOKENS) and _token_fits([["a"], []], NESTED) + assert _token_fits(["a", "b"], FIXED_PLAIN) + assert not _token_fits("marker", TOKENS) + assert not _token_fits(["a"], TOKEN) + assert not _token_fits(["marker"], NESTED) + with pytest.raises(RuntimeError, match="_source_k"): + _ = _token_array(["marker"], TOKENS, "_source_k") + assert _token_array([["a"], None], TOKENS, "_source_k").to_pylist() == [["a"], None] + + table = pa.table( + { + "k": pa.array([[1], [2]], pa.large_list(pa.int64())), + "_source_k": pa.array([None, None], TOKENS), + "_merged_k": pa.array([None, None], TOKENS), + } + ) + # A null where a list of tokens is declared is refused before the guard: the + # callers word it as an ``InputValidationError`` naming the operator and column. + from orcapod.core.operators.join import NullTokenListError + + with pytest.raises(NullTokenListError): + _ = Join._merge_source_columns(table, "_source_k", "_merged_k") # pyright: ignore[reportPrivateUsage] # the sync merge diff --git a/tests/test_pipeline/test_token_types_review_2.py b/tests/test_pipeline/test_token_types_review_2.py new file mode 100644 index 000000000..2f35c9f5b --- /dev/null +++ b/tests/test_pipeline/test_token_types_review_2.py @@ -0,0 +1,562 @@ +"""Findings of the second independent review of PR #601 (ITL-1491), each as a test. + +The streams here satisfy the token-shape rule unless a test says otherwise: a +data-tag key ``k`` that is a list has a list token or a plain string token. Every +stream has two tags and two data columns; the operators are run directly on both +routes (sync call, async row channels), in two tag orders. +""" + +from __future__ import annotations + +import asyncio +import os +import subprocess +import sys +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.channels import Channel +from orcapod.core.operators import Batch, Join, MergeJoin +from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator + +STR = pa.large_string() +TOKENS = pa.large_list(STR) +NESTED = pa.large_list(TOKENS) +INTS = pa.large_list(pa.int64()) +ORCHESTRATORS = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} +TAG_ORDERS = {"k_then_g": ("k", "g"), "g_then_k": ("g", "k")} +TAG_ORDER = pytest.mark.parametrize("tags", list(TAG_ORDERS)) +OPERATORS = pytest.mark.parametrize( + "operator", [Join, MergeJoin], ids=["join", "merge"] +) + + +def _keyed( + data: tuple[str, str], + keys: list[Any], + tokens: list[Any], + token_type: pa.DataType, + tags: tuple[str, ...], + *, + key_type: pa.DataType = INTS, + data_tag: bool = True, +) -> ArrowTableStream: + """A raw stream: tags ``k`` (a list key) and ``g``, two integer data columns. + + ``k`` is a data-tag with the given token column unless ``data_tag`` is false. + """ + first, second = data + columns: dict[str, Any] = { + "k": pa.array(keys, key_type), + "g": pa.array(["m"] * len(keys), STR), + first: pa.array(list(range(len(keys))), pa.int64()), + second: pa.array([10 * i for i in range(len(keys))], pa.int64()), + } + names = [*tags, first, second] + if data_tag: + columns["_source_k"] = pa.array(tokens, token_type) + names.append("_source_k") + return ArrowTableStream( + pa.table({name: columns[name] for name in names}), + tag_columns=list(tags), + data_tags=["k"] if data_tag else [], + ) + + +def _async_rows(operator: Any, *streams: Any) -> list[Any]: + """The rows ``operator.async_execute`` yields over the streams' rows.""" + + async def run() -> list[Any]: + channels: list[Channel[Any]] = [Channel(buffer_size=16) for _ in streams] + output: Channel[Any] = Channel(buffer_size=16) + for stream, channel in zip(streams, channels): + for row in stream.iter_data(): + await channel.writer.send(row) + await channel.writer.close() + await operator.async_execute( + [channel.reader for channel in channels], + output.writer, + input_pipeline_hashes=[s.pipeline_hash() for s in streams], + ) + return await output.reader.collect() + + return asyncio.run(run()) + + +def _outcome(run: Any) -> tuple[str, Any]: + """What ``run`` gives: ``("rows", tokens of k)`` or ``(error type, message)``.""" + try: + rows = run() + except (Exception, ExceptionGroup) as error: # noqa: BLE001 # the outcome is compared + while isinstance(error, ExceptionGroup): + (error,) = error.exceptions + return (type(error).__name__, str(error)) + tokens = [] + for _, data in rows: + table = data.as_table(columns={"source": True}) + tokens.append( + { + field.name: (field.type, table.column(field.name).to_pylist()) + for field in table.schema + if field.name.startswith("_source_") + } + ) + return ("rows", tokens) + + +def _both_routes( + operator: Any, *streams: Any +) -> tuple[tuple[str, Any], tuple[str, Any]]: + """The outcome of ``operator`` over ``streams`` on the sync and the async route.""" + return ( + _outcome(lambda: list(operator()(*streams).iter_data())), + _outcome(lambda: _async_rows(operator(), *streams)), + ) + + +def _refused_alike( + outcomes: tuple[tuple[str, Any], tuple[str, Any]], column: str, *kinds: pa.DataType +) -> None: + """Both routes refuse with ``InputValidationError`` naming the column and types.""" + from orcapod.utils import arrow_utils + + for kind, message in outcomes: + assert kind == "InputValidationError", (kind, message) + assert f"'{column}'" in message + for token_type in kinds: + assert arrow_utils.describe_arrow_type(token_type) in message + + +# --------------------------------------------------------------------------- +# 3c. MergeJoin checks a merged data-tag's token types before it renames one +# --------------------------------------------------------------------------- + + +@TAG_ORDER +@pytest.mark.parametrize("swapped", [False, True], ids=["list_left", "list_right"]) +@pytest.mark.parametrize("match", [True, False], ids=["keys_match", "no_match"]) +@OPERATORS +def test_a_list_token_against_a_string_token_of_a_shared_data_tag_is_refused( + operator: Any, match: bool, swapped: bool, tags: str +) -> None: + """One input declares a list token for the shared data-tag, the other a string. + + Both are valid over the list-valued key. ``MergeJoin`` renamed the second + input's token column before it compared the inputs' types, so it completed + when no key matched and raised a ``ValueError`` about merging a list with a + scalar when one did (second review of PR #601, finding 3c). Both operators + refuse on both routes, whether or not a key matches. + """ + order = TAG_ORDERS[tags] + listed = _keyed(("x", "w"), [[1], [2]], [["a"], ["b"]], TOKENS, order) + plain = _keyed( + ("y", "v"), [[1], [2]] if match else [[7], [8]], ["c", "d"], STR, order + ) + inputs = (plain, listed) if swapped else (listed, plain) + outcomes = _both_routes(operator, *inputs) + _refused_alike(outcomes, "_source_k", TOKENS, STR) + assert outcomes[0][1].startswith(operator.__name__) + + +# --------------------------------------------------------------------------- +# 3a. A Join of three inputs decides from every input's declaration +# --------------------------------------------------------------------------- + + +@TAG_ORDER +def test_a_three_input_join_refuses_two_declarations_when_no_row_matches( + tags: str, +) -> None: + """Three inputs with disjoint keys; the third declares another token type. + + The sync path compares the inputs' token columns before it joins. The async + chain compared a step's two sides when each had sent a row, and the first + step's result has no row here, so the last step never compared and the join + completed with no row (second review of PR #601, finding 3a). Each input's + first row now gives its declaration to all the others. + """ + order = TAG_ORDERS[tags] + candidates = [ + _keyed((f"c{i}", f"d{i}"), [[3]], ["o"], STR, order) for i in range(12) + ] + inputs = [ + _keyed(("a", "b"), [[1]], [["m"]], TOKENS, order), + _keyed(("p", "q"), [[2]], [["n"]], TOKENS, order), + max(candidates, key=lambda stream: stream.pipeline_hash().to_hex()), + ] + for rotation in range(3): + rotated = inputs[rotation:] + inputs[:rotation] + _refused_alike(_both_routes(Join, *rotated), "_source_k", TOKENS, STR) + + +@function_pod(output_keys="total") +def add_two(x: int, y: int) -> int: + """Return ``x + y``.""" + return x + y + + +@TAG_ORDER +@pytest.mark.parametrize("empty", ["a", "b"]) +def test_a_join_job_with_an_empty_input_refuses_two_declarations_on_both_routes( + empty: str, tags: str +) -> None: + """In a job the declarations are the nodes': an input with no row has one too. + + One slot is bound to a stream with no rows that declares a string token, the + other to rows with list tokens. Both orchestrators refuse. + """ + order = TAG_ORDERS[tags] + + def source(name: str, data: tuple[str, str]) -> ArrowTableSource: + names = [*order, *data] + columns = { + "k": pa.array([[1], [2]], INTS), + "g": pa.array(["m", "n"], STR), + data[0]: pa.array([10, 20], pa.int64()), + data[1]: pa.array([1, 2], pa.int64()), + } + schema = pa.schema(pa.field(n, columns[n].type, nullable=False) for n in names) + return ArrowTableSource( + pa.Table.from_arrays([columns[n] for n in names], schema=schema), + tag_columns=list(order), + tag_only_columns=False, + source_id=name, + ) + + def bound(name: str, data: tuple[str, str]) -> ArrowTableStream: + table = source(name, data).as_table( + columns={"source": True, "system_tags": True} + ) + if name == empty: + return ArrowTableStream( + table.slice(0, 0), tag_columns=list(order), data_tags=list(order) + ) + table = table.set_column( + table.schema.get_field_index("_source_k"), + pa.field("_source_k", TOKENS), + pa.array([["p"], ["q"]], TOKENS), + ) + return ArrowTableStream(table, tag_columns=list(order), data_tags=list(order)) + + for orchestrator in ORCHESTRATORS.values(): + job = PipelineJob(name="empty_input", database=InMemoryArrowDatabase()) + with job: + joined = Join()(source("a", ("x", "w")), source("b", ("y", "v")), label="j") + add_two.pod(joined, label="f") + job.bind(sources={"a": bound("a", ("x", "w")), "b": bound("b", ("y", "v"))}) + kind, message = _outcome(lambda: job.run(orchestrator=orchestrator()) and []) + assert kind == "InputValidationError", (kind, message) + assert "'_source_k'" in message + + +# --------------------------------------------------------------------------- +# 3b. Item-field differences between two inputs: the routes agree (ITL-1519) +# --------------------------------------------------------------------------- + +ITEM_FIELDS = { + "names": ( + pa.large_list(pa.field("a", STR)), + pa.large_list(pa.field("b", STR)), + ), + "metadata": ( + pa.large_list(pa.field("member", STR, metadata={"m": "a"})), + pa.large_list(pa.field("member", STR, metadata={"m": "b"})), + ), +} + + +@TAG_ORDER +@pytest.mark.parametrize("swapped", [False, True], ids=["as_listed", "swapped"]) +@pytest.mark.parametrize("case", list(ITEM_FIELDS)) +@OPERATORS +def test_item_field_differences_of_a_merged_token_give_one_result_on_both_routes( + operator: Any, case: str, swapped: bool, tags: str +) -> None: + """Two inputs' list tokens differ only in the item field's name or metadata. + + No refusal is added for this (the treatment of a list layer's item field is + ITL-1519). What must hold today: the sync and the async route give the same + rows, with the same token column type, item field included. + """ + order = TAG_ORDERS[tags] + first, second = ITEM_FIELDS[case] + if swapped: + first, second = second, first + left = _keyed(("x", "w"), [[1], [2]], [["a"], ["b"]], first, order) + right = _keyed(("y", "v"), [[1], [2]], [["c"], ["d"]], second, order) + sync, asynchronous = _both_routes(operator, left, right) + assert sync[0] == asynchronous[0] == "rows", (sync, asynchronous) + assert len(sync[1]) == len(asynchronous[1]) == 2 + key = lambda row: repr(sorted((n, v) for n, (_, v) in row.items())) # noqa: E731 + for mine, theirs in zip( + sorted(sync[1], key=key), sorted(asynchronous[1], key=key), strict=True + ): + assert mine.keys() == theirs.keys() + for name in mine: + assert mine[name][0].equals(theirs[name][0], check_metadata=True), name + assert mine[name][1] == theirs[name][1] + + +# --------------------------------------------------------------------------- +# 4. A null inner list in a merged token is refused, not a guard's RuntimeError +# --------------------------------------------------------------------------- + + +@TAG_ORDER +@pytest.mark.parametrize("side", ["both", "left", "right"]) +@OPERATORS +def test_a_null_inner_list_in_a_merged_token_is_refused_naming_the_column( + operator: Any, side: str, tags: str +) -> None: + """A two-level token ``[None, ["a"]]`` over a list-of-lists data-tag key. + + ``Join`` and ``MergeJoin`` reached their guard's ``RuntimeError`` on such a + token (second review of PR #601, finding 4; the base stored the characters of + an internal marker). The developer then decided (November 27, 2026) that a + token's list is never null at any level, so the stream that holds one is + refused where it is built, naming the token column and the level, and the + operators never see it. Their refusal stays as a guard for rows that are in + no stream (``test_token_types_review_3.py``). + """ + from orcapod.errors import InputValidationError + + order = TAG_ORDERS[tags] + keys = [[[1], [2]], [[3], [4]]] + key_type = pa.large_list(INTS) + whole = [[["p"], ["a"]], [["q"], ["b"]]] + holed = [[None, ["a"]], [["q"], ["b"]]] + for data, tokens in ( + (("x", "w"), holed if side != "right" else whole), + (("y", "v"), holed if side != "left" else whole), + ): + if tokens is whole: + continue + with pytest.raises(InputValidationError) as refused: + _ = _keyed(data, keys, tokens, NESTED, order, key_type=key_type) + message = str(refused.value) + assert "'_source_k'" in message and "'k'" in message + assert "list level 1" in message + # Without the null, the same inputs merge, with the declared two levels. + full = _keyed(("x", "w"), keys, whole, NESTED, order, key_type=key_type) + other = _keyed(("y", "v"), keys, whole, NESTED, order, key_type=key_type) + sync, asynchronous = _both_routes(operator, full, other) + assert sync[0] == asynchronous[0] == "rows" + assert len(sync[1]) == len(asynchronous[1]) == 2 + assert all(row["_source_k"][0] == NESTED for row in sync[1] + asynchronous[1]) + + +# --------------------------------------------------------------------------- +# 5. The async Join folds only the tokens it merged +# --------------------------------------------------------------------------- + +PENDING_LOOKALIKE = "\x00join-pending-members\x00[]" + + +@TAG_ORDER +@pytest.mark.parametrize("inputs", [2, 3]) +def test_a_token_that_looks_like_the_joins_pending_marker_is_left_alone( + inputs: int, tags: str +) -> None: + """A data column's own token that starts like the join's internal marker. + + The join never merged that column, so its token is the user's and is kept. The + async route folded every carried token with that prefix into a ``join_v1:`` + digest, changing provenance on one route only (second review of PR #601, + finding 5; on the base too). + """ + order = TAG_ORDERS[tags] + + def stream(data: tuple[str, str], token: str) -> ArrowTableStream: + table = pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "g": pa.array(["m", "n"], STR), + data[0]: pa.array([10, 20], pa.int64()), + data[1]: pa.array([1, 2], pa.int64()), + f"_source_{data[0]}": pa.array([token, "plain"], STR), + f"_source_{data[1]}": pa.array(["t0", PENDING_LOOKALIKE], STR), + } + ) + return ArrowTableStream(table, tag_columns=list(order)) + + streams = [ + stream(("x", "w"), PENDING_LOOKALIKE), + stream(("y", "v"), "s::0::y"), + stream(("z", "u"), PENDING_LOOKALIKE), + ][:inputs] + sync, asynchronous = _both_routes(Join, *streams) + assert sync[0] == asynchronous[0] == "rows", (sync, asynchronous) + key = lambda row: repr(sorted((n, v) for n, (_, v) in row.items())) # noqa: E731 + assert sorted(sync[1], key=key) == sorted(asynchronous[1], key=key) + seen = { + token + for row in asynchronous[1] + for _, values in row.values() + for token in values + } + assert PENDING_LOOKALIKE in seen + assert not any(token.startswith("join_v1:") for token in seen) + + +# --------------------------------------------------------------------------- +# 7. MergeJoin reports the first mismatch in name order, whatever the hash seed +# --------------------------------------------------------------------------- + +_SEEDED = """ +import warnings +warnings.simplefilter("ignore") +import pyarrow as pa +from orcapod.core.operators.merge_join import _output_types +from orcapod.errors import InputValidationError +s = pa.large_string() +left = {"k": pa.int64(), "x": pa.list_(pa.int64(), 2), "_source_x": pa.list_(s, 2), + "y": pa.int8(), "_source_y": s} +right = {"k": pa.int64(), "x": pa.large_list(pa.int64()), "_source_x": pa.large_list(s), + "y": pa.int16(), "_source_y": s} +try: + _output_types(left, right) +except InputValidationError as error: + print(str(error).split("column ")[1].split(":")[0]) +""" + + +def test_merge_join_reports_the_first_mismatch_in_name_order_under_any_hash_seed() -> ( + None +): + """Three columns disagree; the one first in name order is reported. + + ``MergeJoin`` compared its inputs' columns in the order of a set of names, so + which disagreement it reported followed ``PYTHONHASHSEED`` (second review of + PR #601, finding 7; on the base too). A set of names is held sorted. + """ + reported = set() + for seed in ("0", "1", "2", "3", "7"): + result = subprocess.run( + [sys.executable, "-c", _SEEDED], + env={**os.environ, "PYTHONHASHSEED": seed}, + capture_output=True, + text=True, + check=True, + ) + reported.add(result.stdout.strip()) + assert reported == {"'_source_x'"} + + +# --------------------------------------------------------------------------- +# 8. Ordinary sources can declare two token types for one column +# --------------------------------------------------------------------------- + + +def _ordinary_inputs( + operator: Any, tags: tuple[str, ...], keys: tuple[int, int] = (1, 2) +) -> tuple[Any, Any, Any, Any]: + """A ``Batch(1)`` of a source of scalars, and a source that holds lists. + + Both give the same list-valued data (``k`` and ``g`` for ``Join``, where they + are data-tags; the colliding column ``x`` for ``MergeJoin``). The batch's + tokens are lists of tokens; the source's are plain strings. + + Returns: + The batched stream, the list-holding source, and the two root sources. + """ + plain_tags = operator is MergeJoin + + def source(name: str, columns: dict[str, Any], data: tuple[str, ...]) -> Any: + names = [*tags, *data] + schema = pa.schema(pa.field(n, columns[n].type, nullable=False) for n in names) + return ArrowTableSource( + pa.Table.from_arrays([columns[n] for n in names], schema=schema), + tag_columns=list(tags), + tag_only_columns=plain_tags, + source_id=name, + ) + + scalars = source( + "scalars", + { + "k": pa.array([1, 2], pa.int64()), + "g": pa.array(["m", "n"], STR), + "x": pa.array([10, 20], pa.int64()), + "w": pa.array([1, 2], pa.int64()), + }, + ("x", "w"), + ) + second = ("x", "v") if plain_tags else ("y", "v") + lists = source( + "lists", + { + "k": pa.array([[key] for key in keys], INTS), + "g": pa.array([["m"], ["n"]], pa.large_list(STR)), + second[0]: pa.array([[30], [40]], INTS), + second[1]: pa.array([[3], [4]], INTS), + }, + second, + ) + return Batch(batch_size=1)(scalars), lists, scalars, lists + + +@TAG_ORDER +@pytest.mark.parametrize("swapped", [False, True], ids=["batch_first", "source_first"]) +@pytest.mark.parametrize("keys", [(1, 2), (7, 8)], ids=["keys_match", "no_match"]) +@OPERATORS +def test_a_batch_of_scalars_against_a_source_of_lists_is_refused_on_both_routes( + operator: Any, keys: tuple[int, int], swapped: bool, tags: str +) -> None: + """Two token types for one column, from ordinary sources (no hand-built token). + + ``Batch(1)`` over a source of scalars gives list data with LIST tokens (one + token per member). A source that already holds the same list-shaped data has + plain STRING tokens (one per value). Their data types are equal, their token + types are not: ``Join`` on the shared data-tags and ``MergeJoin`` on the + colliding column refuse, on both routes, naming the token column and both + types (second review of PR #601, finding 8; the refusal is the developer's + decision of November 27, 2026). + """ + order = TAG_ORDERS[tags] + batched, lists, _, _ = _ordinary_inputs(operator, order, keys) + inputs = (lists, batched) if swapped else (batched, lists) + column = "_source_x" if operator is MergeJoin else "_source_" + outcomes = _both_routes(operator, *inputs) + for kind, message in outcomes: + assert kind == "InputValidationError", (kind, message) + assert message.startswith(operator.__name__) and column in message + assert "large_list" in message + assert "large_string in" in message or "and large_string" in message + if operator is MergeJoin: + assert outcomes[0][1] == outcomes[1][1] + + +@function_pod(output_keys="n") +def count_lists(x: list[int], y: list[int]) -> int: + """Return how many values the two lists hold.""" + return len(x) + len(y) + + +@TAG_ORDER +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +def test_a_job_joining_a_batch_of_scalars_with_a_source_of_lists_is_refused( + orchestrator: str, tags: str +) -> None: + """The same case in a job, on each orchestrator: refused, nothing computed. + + Before ITL-1491 this job failed too, with ``ValueError: cannot merge the source + info of a list with that of a scalar`` when a key matched. + """ + order = TAG_ORDERS[tags] + _, _, scalars, lists = _ordinary_inputs(Join, order) + job = PipelineJob(name="ordinary", database=InMemoryArrowDatabase()) + with job: + joined = Join()(Batch(batch_size=1)(scalars), lists, label="joined") + count_lists.pod(joined, label="f") + kind, message = _outcome( + lambda: job.run(orchestrator=ORCHESTRATORS[orchestrator]()) and [] + ) + assert kind == "InputValidationError", (kind, message) + assert message.startswith("Join") and "_source_" in message + assert "large_list" in message diff --git a/tests/test_pipeline/test_token_types_review_3.py b/tests/test_pipeline/test_token_types_review_3.py new file mode 100644 index 000000000..3cdb0f090 --- /dev/null +++ b/tests/test_pipeline/test_token_types_review_3.py @@ -0,0 +1,339 @@ +"""Findings of the third independent review of PR #601 (ITL-1491), each as a test. + +They are about the record-batch join kernels, the guards against a null inner +list, the order of the columns a refusal names, and the rule that a token's list +is never null at any level. The findings about the async orchestrator's check of +held rows went with that check, which was taken out of the PR (ITL-1534). +""" + +from __future__ import annotations + +import asyncio +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.channels import Channel +from orcapod.core.operators import Join, MergeJoin +from orcapod.core.operators.join import NullTokenListError, null_token_list_error +from orcapod.core.streams import ArrowTableStream +from orcapod.errors import InputValidationError +from tests.test_core.operators.test_streaming_joins import ( + _join_kernel, # pyright: ignore[reportPrivateUsage] # the shared kernel fixtures + _merge_kernel, # pyright: ignore[reportPrivateUsage] + _sent, # pyright: ignore[reportPrivateUsage] +) +from tests.test_pipeline.test_token_types_review_2 import ( + NESTED, + _keyed, # pyright: ignore[reportPrivateUsage] # the shared stream fixtures +) + +STR = pa.large_string() +TOKENS = pa.large_list(STR) + + +def _unwrapped(error: BaseException) -> BaseException: + while isinstance(error, ExceptionGroup): + (error,) = error.exceptions + return error + + +# --------------------------------------------------------------------------- +# 3. The record-batch join kernels name the column of a null inner list +# --------------------------------------------------------------------------- + + +KEY_OF_LISTS = pa.large_list(pa.large_list(pa.int64())) +KEYS = [[[1], [2]], [[3], [4]]] +WHOLE = [[["p"], ["a"]], [["q"], ["b"]]] +HOLED = [None, ["a"]] + + +def _merge_inputs(tags: tuple[str, ...]) -> tuple[ArrowTableStream, ArrowTableStream]: + """Two valid streams that share the data-tag ``k``, a list of lists.""" + left = _keyed(("x", "w"), KEYS, WHOLE, NESTED, tags, key_type=KEY_OF_LISTS) + right = _keyed(("y", "v"), KEYS, WHOLE, NESTED, tags, key_type=KEY_OF_LISTS) + return left, right + + +def _rows_with_a_null_inner_list(stream: ArrowTableStream) -> list[Any]: + """The stream's rows, the token of ``k`` replaced by one no stream can hold.""" + return [ + (tag, data.with_source_info(k=pa.scalar(HOLED, type=NESTED))) + for tag, data in stream.iter_data() + ] + + +def _over_row_channels(operator: Any, streams: Any, rows: Any) -> list[Any]: + """``operator.async_execute`` over bare row channels fed ``rows``.""" + + async def run() -> list[Any]: + channels: list[Channel[Any]] = [Channel(buffer_size=16) for _ in rows] + output: Channel[Any] = Channel(buffer_size=16) + for channel, sent in zip(channels, rows): + for row in sent: + await channel.writer.send(row) + await channel.writer.close() + await operator.async_execute( + [channel.reader for channel in channels], + output.writer, + input_pipeline_hashes=[s.pipeline_hash() for s in streams], + ) + return await output.reader.collect() + + return asyncio.run(run()) + + +@pytest.mark.parametrize( + ("operator", "kernel"), + [(Join, _join_kernel), (MergeJoin, _merge_kernel)], + ids=["join", "merge"], +) +@pytest.mark.parametrize("tags", [("k", "g"), ("g", "k")], ids=["k_g", "g_k"]) +def test_a_kernel_guards_against_a_null_inner_list_naming_the_column( + operator: Any, kernel: Any, tags: tuple[str, ...] +) -> None: + """The kernels merge a shared data-tag's tokens with ``Join``'s routine. A + null where a list of tokens is declared raised the routine's own blank + ``NullTokenListError`` out of ``push`` (third review of PR #601, finding 3). + + No stream holds such a token (a token's list is never null at any level), so + this is a guard: the batches are built by hand, which a channel does not + check. The kernel words the refusal as its operator does.""" + left, right = _merge_inputs(tags) + with pytest.raises(InputValidationError, match="list level 1"): + _ = _keyed( + ("x", "w"), KEYS, [HOLED, WHOLE[1]], NESTED, tags, key_type=KEY_OF_LISTS + ) + + def holed(table: pa.Table) -> pa.Table: + index = table.schema.get_field_index("_source_k") + return table.set_column( + index, + table.schema.field(index), + pa.array([HOLED] * table.num_rows, NESTED), + ) + + pushing = kernel([left, right]) + with pytest.raises(InputValidationError) as refused: + for batch in holed(_sent(left)).to_batches(): + pushing.push(0, batch) + for batch in _sent(right).to_batches(): + pushing.push(1, batch) + pushing.finish() + assert str(refused.value) == str( + null_token_list_error(operator.__name__, "_source_k", NESTED) + ) + assert "'_source_k'" in str(refused.value) + + +@pytest.mark.parametrize("operator", [Join, MergeJoin], ids=["join", "merge"]) +@pytest.mark.parametrize("side", [0, 1], ids=["left", "right"]) +@pytest.mark.parametrize("tags", [("k", "g"), ("g", "k")], ids=["k_g", "g_k"]) +def test_the_row_channel_operators_guard_against_a_null_inner_list( + operator: Any, side: int, tags: tuple[str, ...] +) -> None: + """Rows built by hand and sent over a bare row channel are in no stream, so a + null inner list can still reach the merge of a shared data-tag's tokens. The + operator refuses with ``InputValidationError`` naming the token column.""" + streams = _merge_inputs(tags) + rows = [list(stream.iter_data()) for stream in streams] + rows[side] = _rows_with_a_null_inner_list(streams[side]) + with pytest.raises((InputValidationError, ExceptionGroup)) as refused: + _ = _over_row_channels(operator(), streams, rows) + error = _unwrapped(refused.value) + assert isinstance(error, InputValidationError), repr(error) + assert "'_source_k'" in str(error) + # The same rows without the null merge on that route. + merged = _over_row_channels( + operator(), streams, [list(s.iter_data()) for s in streams] + ) + assert len(merged) == 2 + + +def test_the_merge_routine_names_what_it_found() -> None: + """The guard under ``Join``, ``MergeJoin`` and both kernels: the routine that + merges two token columns raises its own named error, with a message, for a + null where a list of tokens is declared; each caller words it for the user.""" + table = pa.table( + { + "k": pa.array(KEYS, KEY_OF_LISTS), + "_source_k": pa.array([HOLED, WHOLE[1]], NESTED), + "_merged_k": pa.array(WHOLE, NESTED), + } + ) + for left, right in (("_source_k", "_merged_k"), ("_merged_k", "_source_k")): + with pytest.raises(NullTokenListError, match="null where a list of tokens"): + _ = Join._merge_source_columns(table, left, right) # pyright: ignore[reportPrivateUsage] # the guard is the subject + for operator in ("Join", "MergeJoin"): + worded = null_token_list_error(operator, "_source_k", NESTED) + assert isinstance(worded, InputValidationError) + assert str(worded).startswith(operator) and "'_source_k'" in str(worded) + + +# --------------------------------------------------------------------------- +# 4. The violating columns are named in name order +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("columns", [("x", "y"), ("y", "x")], ids=["x_y", "y_x"]) +def test_a_stream_names_its_violating_columns_in_name_order( + columns: tuple[str, str], +) -> None: + """Two token columns break the rule; whatever the table's column order, the + refusal lists them by name (third review of PR #601, finding 4a).""" + lists = pa.large_list(pa.int64()) + held: dict[str, Any] = {"k": pa.array([1, 2], pa.int64())} + for name in columns: + held[name] = pa.array([[1], [2]], lists) + 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"]) + message = str(refused.value) + assert message.index("'_source_x'") < message.index("'_source_y'") + + +# --------------------------------------------------------------------------- +# 5. A token's list is never null at any level (developer, November 27, 2026) +# --------------------------------------------------------------------------- + +INTS = pa.large_list(pa.int64()) +TWO = pa.large_list(TOKENS) +THREE = pa.large_list(TWO) +FIXED_OF_LISTS = pa.list_(TOKENS, 2) + +# name: (token type, tokens of two rows, data type, data, the level of the null list) +NULL_LISTS: dict[str, tuple[pa.DataType, list[Any], pa.DataType, list[Any], int]] = { + "level_1_of_2": ( + TWO, + [[["a"], ["b"]], [None, ["c"]]], + pa.large_list(INTS), + [[[1], [2]], [[3], [4]]], + 1, + ), + "level_1_of_3": ( + THREE, + [[[["a"]]], [None]], + pa.large_list(pa.large_list(INTS)), + [[[[1]]], [[[2]]]], + 1, + ), + "level_2_of_3": ( + THREE, + [[[["a"]]], [[None, ["b"]]]], + pa.large_list(pa.large_list(INTS)), + [[[[1]]], [[[2], [3]]]], + 2, + ), + "level_1_of_fixed": ( + FIXED_OF_LISTS, + [[["a"], ["b"]], [["c"], None]], + pa.list_(INTS, 2), + [[[1], [2]], [[3], [4]]], + 1, + ), +} + +# The same shapes with a null only where the element is a string: valid. +NULL_STRINGS: dict[str, tuple[pa.DataType, list[Any], pa.DataType, list[Any]]] = { + "string_of_2": ( + TWO, + [[["a", None], []], [[None]]], + pa.large_list(INTS), + [[[1, 2], []], [[3]]], + ), + "string_of_3": ( + THREE, + [[[[None]]], [[["a", None], []]]], + pa.large_list(pa.large_list(INTS)), + [[[[1]]], [[[2, 3], []]]], + ), + "string_of_fixed": ( + FIXED_OF_LISTS, + [[[None], []], [["c", None], [None]]], + pa.list_(INTS, 2), + [[[1], []], [[3, 4], [5]]], + ), +} + + +def _shaped( + token_type: pa.DataType, + tokens: list[Any], + data_type: pa.DataType, + data: list[Any], + role: str, + layout: str, +) -> ArrowTableStream: + """Tags ``g`` and ``k``; data ``x`` (the checked column, a data-tag in that + role) and ``w``; in two table layouts.""" + rows = len(data) + columns: dict[str, Any] = { + "g": pa.array([f"g{i}" for i in range(rows)], STR), + "k": pa.array(list(range(rows)), pa.int64()), + "x": pa.array(data, data_type), + "w": pa.array([10 * i for i in range(rows)], pa.int64()), + "_source_x": pa.array(tokens, token_type), + "_source_w": pa.array([f"s::row_{i}::w" for i in range(rows)], STR), + } + names = list(columns) if layout == "tags_first" else list(reversed(columns)) + data_tag = role == "data_tag" + return ArrowTableStream( + 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 [], + ) + + +ROLES = pytest.mark.parametrize("role", ["data", "data_tag"]) +LAYOUTS = pytest.mark.parametrize("layout", ["tags_first", "reversed"]) + + +@ROLES +@LAYOUTS +@pytest.mark.parametrize("case", list(NULL_LISTS)) +def test_a_stream_with_a_null_list_inside_a_token_is_refused( + case: str, role: str, layout: str +) -> None: + """A token's list is never null at any level; a null is allowed only at the + innermost level, where the element is a string. The stream is refused where it + is built, naming the token column, the data column, both types and the level.""" + token_type, tokens, data_type, data, level = NULL_LISTS[case] + with pytest.raises(InputValidationError) as refused: + _ = _shaped(token_type, tokens, data_type, data, role, layout) + message = str(refused.value) + assert "'_source_x'" in message and "'x'" in message + assert str(token_type) in message or "large_list" in message + assert f"list level {level}" in message + # With no rows the same types make a stream: the rule reads validity only. + empty = _shaped(token_type, [], data_type, [], role, layout) + assert empty.as_table().num_rows == 0 + + +@ROLES +@LAYOUTS +@pytest.mark.parametrize("case", list(NULL_STRINGS)) +def test_a_null_string_inside_a_token_is_valid_at_any_depth( + case: str, role: str, layout: str +) -> None: + token_type, tokens, data_type, data = NULL_STRINGS[case] + stream = _shaped(token_type, tokens, data_type, data, role, layout) + shown = stream.as_table(columns={"source": True}) + assert shown.column("_source_x").to_pylist() == tokens + assert [d.source_info()["x"] for _, d in stream.iter_data()] == tokens + + +def test_a_table_cut_into_chunks_is_checked_in_every_chunk() -> None: + """The null list is in the second chunk of the token column, behind a slice.""" + token_type, tokens, data_type, data, _ = NULL_LISTS["level_1_of_2"] + one = pa.table( + {"x": pa.array(data, data_type), "_source_x": pa.array(tokens, token_type)} + ) + 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) + # 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 diff --git a/tests/test_pipeline/test_token_types_review_4.py b/tests/test_pipeline/test_token_types_review_4.py new file mode 100644 index 000000000..eab775577 --- /dev/null +++ b/tests/test_pipeline/test_token_types_review_4.py @@ -0,0 +1,196 @@ +"""Findings of the fourth independent review of PR #601 (ITL-1491), each as a test. + +The replay of an ordinary pipeline over logical lists (a held operator node whose +rows hold ``list[Path]``), and the sync call sites of the guards against a null +inner list. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any, cast + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators import Batch, GroupBy, Index, MergeJoin +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import InputValidationError +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.sources import DictSource +from tests.test_pipeline.test_token_types_review_2 import ( + _keyed, # pyright: ignore[reportPrivateUsage] # the shared stream fixtures +) + +STR = pa.large_string() +TOKENS = pa.large_list(STR) +NESTED = pa.large_list(TOKENS) +ORCHESTRATORS = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} + +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") + + +# --------------------------------------------------------------------------- +# 1. A held node over logical lists: the replay of an ordinary pipeline +# --------------------------------------------------------------------------- + + +def _paths(source_id: str) -> DictSource: + return DictSource( + [ + {"g": "m", "k": 1, "p": Path("/a"), "n": 1}, + {"g": "m", "k": 2, "p": Path("/b"), "n": 2}, + {"g": "n", "k": 1, "p": Path("/c"), "n": 3}, + ], + tag_columns=["g", "k"], + tag_only_columns=True, + source_id=source_id, + ) + + +@function_pod(output_keys="total") +def count_paths(p: list[Path], n: list[int]) -> int: + return len(p) + sum(n) + + +@function_pod(output_keys="total") +def count_nested_paths(p: list[list[Path]], n: list[list[int]]) -> int: + return sum(len(paths) for paths in p) + sum(sum(numbers) for numbers in n) + + +# name: (the stream of lists the function reads, the function, its rows) +LIST_BUILDERS: dict[str, Any] = { + "batch": (lambda: Batch(batch_size=2)(_paths("a"), label="lists"), count_paths, 2), + "group_by": (lambda: GroupBy(by=["g"])(_paths("a"), label="lists"), count_paths, 2), + "merge_join": ( + lambda: MergeJoin()(_paths("a"), _paths("b"), label="lists"), + count_paths, + 3, + ), + "group_by_then_batch": ( + lambda: Batch(batch_size=2)(GroupBy(by=["g"])(_paths("a")), label="lists"), + count_nested_paths, + 1, + ), +} + + +@pytest.mark.parametrize("second", list(ORCHESTRATORS)) +@pytest.mark.parametrize("first", list(ORCHESTRATORS)) +@pytest.mark.parametrize("builder", list(LIST_BUILDERS)) +def test_a_replay_over_logical_lists_reuses_its_rows( + builder: str, first: str, second: str +) -> None: + """A source with a ``Path`` column, an operator that builds lists, a function + over the lists: this must never fail again. + + After a run, the function's cache alone is cleared and the job runs again: the + operator node is held, and its rows (a ``list[Path]`` column, an Arrow + extension type, with list tokens) feed the function, which finds every row + stored. A check of held rows the async orchestrator had for a while hashed the + rows' Arrow types, and Orcapod's own extension type for a list of a logical + element cannot be hashed: ``TypeError: unhashable type`` on the second run + (fourth review of PR #601, finding 1; the check was taken out, ITL-1534). + Every order of the two routes over one store reuses every row, for ``Batch``, + ``GroupBy``, ``MergeJoin`` and ``GroupBy`` then ``Batch``. + """ + make, function, rows = LIST_BUILDERS[builder] + job = PipelineJob(name="logical_held", database=InMemoryArrowDatabase()) + with job: + function.pod(make(), label="f") + ran = job.run(orchestrator=ORCHESTRATORS[first]()) + assert (ran.nodes["f"].computed, ran.nodes["f"].failed) == (rows, 0) + cast("Any", job.nodes["f"]).clear_cache() + again = job.run(orchestrator=ORCHESTRATORS[second]()) + assert (again.nodes["f"].reused, again.nodes["f"].computed) == (rows, 0) + assert again.nodes["f"].failed == 0 + + +# --------------------------------------------------------------------------- +# 2. The sync call sites of the guards against a null inner list +# --------------------------------------------------------------------------- + +KEY_OF_LISTS = pa.large_list(pa.large_list(pa.int64())) +KEYS = [[[1], [2]], [[3], [4]]] +WHOLE = [[["p"], ["a"]], [["q"], ["b"]]] +HOLED = [None, ["a"]] + + +class _Tampered(ArrowTableStream): + """A stream that hands out a token no stream can hold: its table's + ``_source_k`` is replaced, after construction, by a null inner list.""" + + def as_table(self, *args: Any, **kwargs: Any) -> pa.Table: + table = super().as_table(*args, **kwargs) + if "_source_k" not in table.column_names or not table.num_rows: + return table + index = table.schema.get_field_index("_source_k") + return table.set_column( + index, + table.schema.field(index), + pa.array([HOLED] * table.num_rows, NESTED), + ) + + +def _tampered(stream: ArrowTableStream) -> ArrowTableStream: + cast("Any", stream).__class__ = _Tampered + return stream + + +@pytest.mark.parametrize("side", [0, 1], ids=["first", "second"]) +@pytest.mark.parametrize("tags", [("k", "g"), ("g", "k")], ids=["k_g", "g_k"]) +def test_merge_join_s_sync_call_guards_against_a_null_inner_list( + side: int, tags: tuple[str, ...] +) -> None: + """``MergeJoin`` called on streams: no stream can hold a null inner list, so + one input is made to hand out such a token. The sync merge refuses, naming + the operator and the token column (fourth review of PR #601, finding 2).""" + streams = [ + _keyed(("x", "w"), KEYS, WHOLE, NESTED, tags, key_type=KEY_OF_LISTS), + _keyed(("y", "v"), KEYS, WHOLE, NESTED, tags, key_type=KEY_OF_LISTS), + ] + streams[side] = _tampered(streams[side]) + with pytest.raises(InputValidationError) as refused: + _ = MergeJoin()(*streams).as_table() + message = str(refused.value) + assert message.startswith("MergeJoin") and "'_source_k'" in message + + +@pytest.mark.parametrize("layout", ["tags_first", "reversed"]) +def test_index_s_sync_call_guards_against_a_null_element(layout: str) -> None: + """``Index`` called on a stream whose row hands out a null inner list (no + stream holds one): taking that element would give a null token whose type is + a list, and the sync path refuses, naming the operator and the column. + + This test gives no ``out``. With ``out="picked"`` both outcomes are correct + too, and differ by the element taken: taking the null list (index 0) meets + the same guard, which names ``_source_picked``; taking the valid element + (index 1) succeeds in the row operation, the row keeps ``x`` with its + tampered token, and the result stream is then refused where it is built, + for ``_source_x``.""" + data_type = pa.large_list(pa.large_list(pa.int64())) + columns: dict[str, Any] = { + "g": pa.array(["m", "n"], STR), + "k": pa.array([1, 2], pa.int64()), + "x": pa.array([[[1], [2]], [[3], [4]]], data_type), + "w": pa.array([10, 20], pa.int64()), + "_source_x": pa.array(WHOLE, NESTED), + } + names = list(columns) if layout == "tags_first" else list(reversed(columns)) + table = pa.table({name: columns[name] for name in names}) + table = table.cast(pa.schema([f.with_nullable(False) for f in table.schema])) + + class Handing(ArrowTableStream): + 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"]) + with pytest.raises(InputValidationError) as refused: + _ = Index("x", 0)(stream).as_table() + message = str(refused.value) + assert message.startswith("Index") and "'_source_x'" in message + taken = Index("x", 1)(stream).as_table(columns={"source": True}) + assert taken.column("_source_x").to_pylist() == [["a"], ["a"]] diff --git a/tests/test_utils/test_arrow_utils.py b/tests/test_utils/test_arrow_utils.py index 26bbddda1..3dd4ed140 100644 --- a/tests/test_utils/test_arrow_utils.py +++ b/tests/test_utils/test_arrow_utils.py @@ -995,12 +995,22 @@ def test_nested_list_token_nests_the_list_type(self) -> None: ) def test_stream_with_nested_source_info_iterates(self) -> None: - """``ArrowTableStream(source_info=...)`` accepts a nested token.""" + """``ArrowTableStream(source_info=...)`` accepts a nested token. + + The data column has the token's two list layers (the token-shape rule, + ITL-1491: a list token needs list data of the same layers). + """ from orcapod.core.streams import ArrowTableStream token: SourceInfoValue = [["a", None], ["b"]] + values = pa.large_list(pa.large_list(pa.int64())) stream = ArrowTableStream( - pa.table({"id": [1, 2], "v": [10, 20]}), + pa.table( + { + "id": [1, 2], + "v": pa.array([[[10, 10], [10]], [[20, 20], [20]]], values), + } + ), tag_columns=["id"], source_info={"v": token}, ) diff --git a/tests/token_shapes.py b/tests/token_shapes.py new file mode 100644 index 000000000..7fed278c3 --- /dev/null +++ b/tests/token_shapes.py @@ -0,0 +1,131 @@ +"""Helpers for tests that build a stream with hand-made source-info token columns. + +A token column's list layers must be its data column's outer list layers (the +token-shape rule, ITL-1491). A test that replaces a token column with a list-typed +one gives its data column the same layers with these helpers. +""" + +from __future__ import annotations + +from typing import Any, cast + +import pyarrow as pa + + +def data_type_for( + token_type: pa.DataType, leaf: pa.DataType | None = None +) -> pa.DataType: + """The data type with ``token_type``'s list layers over ``leaf`` (``int64``). + + Args: + token_type: A token column's type: list layers over a string. + leaf: The type under the layers. + + Returns: + The same layers (large list, fixed-size list of the same size) over ``leaf``. + """ + leaf = pa.int64() if leaf is None else leaf + if pa.types.is_fixed_size_list(token_type): + return pa.list_( + data_type_for(token_type.value_type, leaf), token_type.list_size + ) + if pa.types.is_large_list(token_type) or pa.types.is_list(token_type): + return pa.large_list(data_type_for(token_type.value_type, leaf)) + return leaf + + +def _item_type(kind: pa.DataType) -> pa.DataType: + """The type of a list type's items.""" + return cast("pa.DataType", cast("Any", kind).value_type) + + +def _is_list(kind: pa.DataType) -> bool: + return ( + pa.types.is_large_list(kind) + or pa.types.is_list(kind) + or pa.types.is_fixed_size_list(kind) + ) + + +def nested_value(leaf: Any, data_type: pa.DataType) -> Any: + """``leaf`` wrapped in one list per list layer of ``data_type``. + + A fixed-size layer holds its size of copies, any other layer one value. + """ + if not _is_list(data_type): + return leaf + inner = nested_value(leaf, _item_type(data_type)) + count = ( + cast("Any", data_type).list_size + if pa.types.is_fixed_size_list(data_type) + else 1 + ) + return [inner] * count + + +def data_for(token: Any, leaf: Any, data_type: pa.DataType) -> Any: + """A data value of ``data_type`` with the list structure of the token ``token``. + + Args: + token: A token value: a string, ``None`` or (nested) lists of them. + leaf: The value put at every token position. + data_type: The data column's type (the token's layers over a leaf type). + + Returns: + ``leaf`` at every token position, in the token's lists. An empty list of + tokens where the data type has a further list layer gets one value of + that inner type (a token's list is never null at any level, so an empty + list is the only token that shows fewer levels than its column; the data + beside it still holds a value). + """ + if isinstance(token, list): + item_type = _item_type(data_type) + if not token and _is_list(item_type): + return [nested_value(leaf, item_type)] + return [data_for(item, leaf, item_type) for item in token] + return nested_value(leaf, data_type) + + +def with_token_column( + table: pa.Table, + name: str, + tokens: list[Any], + token_type: pa.DataType, + *, + nullable: bool = True, +) -> pa.Table: + """Replace ``_source_`` by ``tokens`` and give ``name`` a fitting shape. + + The data column ``name`` (a scalar column) becomes a column with the token + type's list layers, each row's value repeated at every token position, so the + stream built from the table satisfies the token-shape rule. A token type with + no layer leaves the data column as it is. + + Args: + table: A table holding ``name`` and ``_source_``. + name: The data column. + tokens: The token column's values, one per row. + token_type: The token column's Arrow type. + nullable: Whether the token field is declared nullable. + + Returns: + The table with both columns replaced, in their places. + """ + token_name = f"_source_{name}" + table = table.set_column( + table.schema.get_field_index(token_name), + pa.field(token_name, token_type, nullable=nullable), + pa.array(tokens, token_type), + ) + data_field = table.schema.field(name) + data_type = data_type_for(token_type, data_field.type) + if data_type == data_field.type: + return table + values = table.column(name).to_pylist() + return table.set_column( + table.schema.get_field_index(name), + pa.field(name, data_type, nullable=data_field.nullable), + pa.array( + [data_for(t, v, data_type) for t, v in zip(tokens, values)], data_type + ), + )