diff --git a/.zed/rules b/.zed/rules index c02e143d6..c46929a35 100644 --- a/.zed/rules +++ b/.zed/rules @@ -978,8 +978,8 @@ generation of hashing; rows of the current data context are the current entries. Function pipeline — pdb_v2 (PIPELINE_DB_SCHEMA_VERSION) Function result — rdb_v1, after the type's revision rev1 (RESULT_DB_SCHEMA_VERSION) Side-effect log — tdb_v2 (TRACKING_DB_SCHEMA_VERSION) - Operator cache — odb_v2 (OPERATOR_DB_SCHEMA_VERSION) - Cached source — sdb_v1 (SOURCE_DB_SCHEMA_VERSION) + Operator cache — odb_v3 (OPERATOR_DB_SCHEMA_VERSION) + Cached source — sdb_v2 (SOURCE_DB_SCHEMA_VERSION) - The layout version is the last component of a table path. Every layout marker started at v1 for the first release, 0.4.0 (developer, November 18, 2026, ITL-1259; 0.3.0 was withdrawn). @@ -1028,7 +1028,7 @@ generation of hashing; rows of the current data context are the current entries. hashes in a path differ between builds. find_stale_tables(..., name_path=...) lists the store under the hash-free beginning of the node's path (ArrowDatabaseProtocol.list_table_paths; , side_effect_function/, side_effects/, relative to the node's - database; /source for a cached source) and every table there whose last component + database; the explicit cache_path or /source for a cached source) and every table there whose last component is not in contexts/stored.CURRENT_LAYOUTS is of another layout (tables_of_another_layout). A new layout constant must be added to CURRENT_LAYOUTS. A store that cannot list raises TableListingNotSupportedError: side-effecting nodes then warn and proceed (developer, @@ -1100,30 +1100,151 @@ 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` for a column it holds no + Arrow token column for, 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). + `with_source_info` writes a Python replacement under the row's held token type and + preserves the item name, nullability and metadata (`arrow_utils.source_info_replacement`, + ITL-1557). It refuses a string for a list, a list for a string, a wrong depth, a null item + under a required item field, and `None` for a list type at any depth. Under a held string type, + `with_source_info(x=None)` writes a `large_string` null in both `as_table` and + `source_info_table`. The `Data` constructor also checks non-`None` replacements against + the held type. `Data(table, source_info={"x": None})` keeps the token the table already + holds for `x`. +- **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. The first-batch rule (ITL-1557): the token type an output + channel's stream declares (`declared_token_types`) binds every batch sent into it, the + first and an empty one included, so a batch never replaces a declared token type (item + metadata included); the first batch settles a token column's type only where the stream + declares none for it. 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. For the same entry and token values, a row built + from Python values and a row read from a table have one instance id when + `source_info_arrow_type` infers the table's declared Arrow token types. For example, + Python `["a", "b"]` infers a large list of strings. The same values in a fixed-size list + give another instance id. A value with fewer visible list levels than its declared + type (`[[]]` in a three-level column) also gives another instance id. Ids are a function + of the row alone, independent of session order. 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 @@ -1317,6 +1438,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 @@ -1344,9 +1466,23 @@ 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. - A raw `ArrowTableStream` still preserves `null` in its table in ITL-1543 part A. + 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. DataFrameSource uses an explicit schema for + custom system-tag nullability and validates the raw values, types and metadata before casting. + Join's sync and batch sort pairs source and record IDs within each printed + provenance path. The rebuilt ID field can hold nulls when any corresponding + input field can hold nulls or an input lacks that field. Custom tags keep their + input positions in these tables. Standalone row channels sort the custom tags + of a tied path with its IDs at every link. Join rows infer tied system-tag + fields from values. Non-tied system-tag fields keep their Arrow declarations. + A raw `ArrowTableStream` preserves the system-tag fields in its table and + rows, including the Arrow Null type (ITL-1543). + Streams, rows and record batches declare every `_source_*` token field nullable (ITL-1557). + The top-level flag comes from `arrow_utils.source_info_field` and is independent + of the token values and of any list item fields. CachedSource writes these fields + and their record hashes under `sdb_v2`. The operator cache stores and hashes the + output stream's declared fields under `odb_v3` (ITL-1562). 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 @@ -1851,15 +1987,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 be9064757..217bfd081 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1007,8 +1007,8 @@ current data context are the current entries. | Function pipeline | `pdb_v2` | `PIPELINE_DB_SCHEMA_VERSION` | | Function result | `rdb_v1` (after the type's revision, `rev1`) | `RESULT_DB_SCHEMA_VERSION` | | Side-effect log | `tdb_v2` | `TRACKING_DB_SCHEMA_VERSION` | -| Operator cache | `odb_v2` | `OPERATOR_DB_SCHEMA_VERSION` | -| Cached source | `sdb_v1` | `SOURCE_DB_SCHEMA_VERSION` | +| Operator cache | `odb_v3` | `OPERATOR_DB_SCHEMA_VERSION` | +| Cached source | `sdb_v2` | `SOURCE_DB_SCHEMA_VERSION` | - Every layout marker started at `v1` for the first release, 0.4.0 (developer, November 18, 2026, ITL-1259; 0.3.0 was withdrawn). The pipeline, side-effect log and operator cache @@ -1059,7 +1059,7 @@ current data context are the current entries. hashes in a path differ between builds. `find_stale_tables(..., name_path=...)` lists the store under the hash-free beginning of the node's path (`ArrowDatabaseProtocol.list_table_paths`; ``, `side_effect_function/`, `side_effects/`, relative to the - node's database; `/source` for a cached source) and every table there whose last + node's database; the explicit `cache_path` or `/source` for a cached source) and every table there whose last component is not in `contexts/stored.CURRENT_LAYOUTS` is of another layout (`tables_of_another_layout`). A new layout constant must be added to `CURRENT_LAYOUTS`. A store that cannot list raises `TableListingNotSupportedError`: side-effecting nodes then @@ -1131,30 +1131,151 @@ 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 +- 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` for a column it holds no + Arrow token column for, 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). + `with_source_info` writes a Python replacement under the row's held token type and + preserves the item name, nullability and metadata (`arrow_utils.source_info_replacement`, + ITL-1557). It refuses a string for a list, a list for a string, a wrong depth, a null item + under a required item field, and `None` for a list type at any depth. Under a held string type, + `with_source_info(x=None)` writes a `large_string` null in both `as_table` and + `source_info_table`. The `Data` constructor also checks non-`None` replacements against + the held type. `Data(table, source_info={"x": None})` keeps the token the table already + holds for `x`. +- **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. The first-batch rule (ITL-1557): the token type an output + channel's stream declares (`declared_token_types`) binds every batch sent into it, the + first and an empty one included, so a batch never replaces a declared token type (item + metadata included); the first batch settles a token column's type only where the stream + declares none for it. 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. For the same entry and token values, a row built + from Python values and a row read from a table have one instance id when + `source_info_arrow_type` infers the table's declared Arrow token types. For example, + Python `["a", "b"]` infers a large list of strings. The same values in a fixed-size list + give another instance id. A value with fewer visible list levels than its declared + type (`[[]]` in a three-level column) also gives another instance id. Ids are a function + of the row alone, independent of session order. 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. + (`_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 @@ -1365,6 +1486,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 @@ -1392,9 +1514,23 @@ 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. - A raw `ArrowTableStream` still preserves `null` in its table in ITL-1543 part A. + 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. DataFrameSource uses an explicit schema for + custom system-tag nullability and validates the raw values, types and metadata before casting. + Join's sync and batch sort pairs source and record IDs within each printed + provenance path. The rebuilt ID field can hold nulls when any corresponding + input field can hold nulls or an input lacks that field. Custom tags keep their + input positions in these tables. Standalone row channels sort the custom tags + of a tied path with its IDs at every link. Join rows infer tied system-tag + fields from values. Non-tied system-tag fields keep their Arrow declarations. + A raw `ArrowTableStream` preserves the system-tag fields in its table and + rows, including the Arrow Null type (ITL-1543). + Streams, rows and record batches declare every `_source_*` token field nullable (ITL-1557). + The top-level flag comes from `arrow_utils.source_info_field` and is independent + of the token values and of any list item fields. CachedSource writes these fields + and their record hashes under `sdb_v2`. The operator cache stores and hashes the + output stream's declared fields under `odb_v3` (ITL-1562). 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 @@ -1903,16 +2039,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..05ca86f9d 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,8 @@ 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. Join preserves those declarations for non-tied + operands. IDs can change for hand-built streams with unusual system-tag + fields outside a tie. Entry-ID errors for a raw Arrow Null system tag name + the column and ask for a supported nullable type. diff --git a/changelog.d/ITL-1557.md b/changelog.d/ITL-1557.md new file mode 100644 index 000000000..a164a698b --- /dev/null +++ b/changelog.d/ITL-1557.md @@ -0,0 +1,36 @@ +### Breaking changes and migration + +- Cached sources write nullable source-info fields and new record hashes under + `sdb_v2`. Older `sdb_v1` tables are reported and left untouched. A bound source + populates the new cache from its live data. + +- Operator caches store and hash the output stream's declared fields under + `odb_v3`. Older `odb_v2` tables are reported and left untouched. LOG runs + populate the new table (ITL-1562). +- A bare ArrowTableStream with a formerly required token field has a new content + hash. Jobs over that stream have new downstream node content hashes and stored + pipeline record keys. Entry and instance IDs are preserved. +- Jobs fed by an Arrow-backed DataFrameSource without an explicit schema can + move when a null-free data field was declared nullable, including a data-tag. + Preserving that declaration changes the source row entry ID, function instance + and record IDs, and the `pdb_v2` path and key in both execution modes. A + generated source ID also changes. An explicit source ID and the `rdb_v1` path + and result key match the previous behavior when the result ID is held fixed. + +### Fixed + +- Source-info token fields are nullable in streams, rows, and streaming batches, + including empty outputs. +- DataFrameSource uses its explicit schema for custom system-tag declarations and + validates the raw values, types and metadata before applying the schema. +- Adding Python system tags to an Arrow-backed Tag preserves its existing + system-tag field declarations. +- Record-batch channels keep the accepted schema for empty results and reject + nulls inside required system-tag fields. Record batches and function output + rows refuse conflicting token declarations. `with_source_info` applies Python + replacements under the held token type and rejects null lists at any depth. + The `Data` constructor also checks non-`None` replacements against the held + type. `Data(table, source_info={"x": None})` keeps the token the table already + holds for `x`. +- DBTableSource validates nominated system-tag fields against the batch schema + when the connector provides no column information. diff --git a/changelog.d/ITL-1563.md b/changelog.d/ITL-1563.md index d72ede6d7..e8f22909f 100644 --- a/changelog.d/ITL-1563.md +++ b/changelog.d/ITL-1563.md @@ -32,7 +32,5 @@ The values are the row's, wrapped under the declared field, never cast. - The token type that is checked is the one the row carries (ITL-1563): a hand-built output made from an Arrow table whose token column is dictionary-encoded or binary - is refused, naming that type. Before, `as_table` typed such a token from its value - and it was stored as a string. Still open until rows keep their token columns' - Arrow types: a NULL token in a column declared with another type is stored as a - `large_string` null and is not refused. + is refused, naming that type. With ITL-1557, the row keeps the declared token + column type even when the token is null, so the same check refuses it. diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 03d09578f..e6b0490a5 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -1133,7 +1133,7 @@ from that database, and no rows under that key is an empty result, not an error. over the same sources, not only the saved run's inputs. Rows come in the order the database returns them; sort them if order matters. The node itself (`as_table()`, `iter_data()`, `head()`) is empty: it has not run in this process. -- Operators (a join, a filter) store outputs only when caching is enabled, under `odb_v2`. +- Operators (a join, a filter) store outputs only when caching is enabled, under `odb_v3`. The saved file does not record an operator's cache mode (follow-up ITL-977), so attach a loaded operator node in `CacheMode.REPLAY` to read the rows its run stored: `loaded.nodes["joined"].attach_databases(pipeline_database=store.at(""), 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..d922a9811 100644 --- a/docs/dev/design_issues/ITL-1543-AS2.md +++ b/docs/dev/design_issues/ITL-1543-AS2.md @@ -1,14 +1,21 @@ ## `src/orcapod/core/streams/` ### AS2 — A stream's Arrow table and its rows can disagree about column types -**Status:** in progress +**Status:** resolved **Severity:** high **Issue:** ITL-1543 -The stream defines the Arrow schema of each row. Today a row can rebuild its -columns in a different form, which makes identity and storage depend on how the -data was read. For example, a Join of streams tied on pipeline hash can declare -its sorted system tags nullable, although its rows have non-nullable system tags. +The stream defines the Arrow schema of each row. A row that rebuilds its +columns in a different form can make identity and storage depend on how the +data was read. For example, a Join of streams tied on pipeline hash could +declare its sorted system tags nullable while its rows used required fields. -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. +**Fix:** + +Part A corrected the Join schema and rejected Arrow Null in sources, including +nested Null. Part B carries declared system-tag fields through rows, tables and +batches, including standalone async joins and both Join and MergeJoin kernels. +Operators with an Arrow output declaration check the materialized fields before +writing cache rows. ITL-1557 makes every top-level source-info field nullable and +ITL-1491 carries the pipeline's declared token types through transport. ITL-1534 +tracks hand-built rows passed directly from a held node on the async route. diff --git a/docs/dev/design_issues/ITL-1543-AS4.md b/docs/dev/design_issues/ITL-1543-AS4.md new file mode 100644 index 000000000..5dc6bc655 --- /dev/null +++ b/docs/dev/design_issues/ITL-1543-AS4.md @@ -0,0 +1,17 @@ +## `src/orcapod/core/operators/join.py` — system-tag provenance + +### AS4 — Join could lose record IDs or attach ID pairs to the wrong operand +**Status:** open +**Severity:** high +**Issue:** ITL-1543 + +The ID sorter grouped operands by the printed provenance path. Distinct full +pipeline hashes with the same shortened suffix could exchange source and record +IDs, even though other system tags stayed with their operands. A tied Join +could also sort an existing record ID into a position with no declared record-ID +field and drop it. For equal source IDs, the old sort raised on the missing +record ID. The null-safe sort let the affected operand order silently lose it. + +The suffix collision requires the hash truncation setting. PR #636 removes +that setting and delivers the corrected entry IDs accepted by the developer +on 2026-11-28 (D27). PR #607 keeps main's tied-Join tables, rows, and entry IDs. diff --git a/docs/dev/design_issues/ITL-1557-AS3.md b/docs/dev/design_issues/ITL-1557-AS3.md new file mode 100644 index 000000000..b45232411 --- /dev/null +++ b/docs/dev/design_issues/ITL-1557-AS3.md @@ -0,0 +1,21 @@ +## `src/orcapod/core/streams/` + +### AS3 — Token fields disagree between streams and rows +**Status:** resolved +**Severity:** high +**Issue:** ITL-1557 + +Sources declared generated source-info fields non-nullable while the rows read +from those streams declared them nullable. A bare stream and a CachedSource +incorporated the stream field into their hashes, while a function node used the +row field for its instance ID. + +**Fix:** Declare every source-info field nullable at the top level in +`arrow_utils.source_info_field`. Write CachedSource fields and record hashes +under `sdb_v2` and report older tables through stale-table accounting. Function +entry and instance IDs are preserved for the token-nullability change. The +separate fix to preserve nullable data fields on schema-free Arrow-backed +DataFrameSource inputs moves these IDs for affected jobs. Concrete record-batch +channels and Python replacements on Arrow-backed Data retain the declared +token types. Operator caches follow the output stream's declared fields under +ITL-1562. diff --git a/docs/dev/design_issues/ITL-1562-OC1.md b/docs/dev/design_issues/ITL-1562-OC1.md new file mode 100644 index 000000000..bf963310e --- /dev/null +++ b/docs/dev/design_issues/ITL-1562-OC1.md @@ -0,0 +1,14 @@ +## `src/orcapod/core/nodes/operator_node.py` + +### OC1 — Operator cache token fields depend on the write's values +**Status:** resolved +**Severity:** high +**Issue:** ITL-1562 + +An operator cache used required token fields for null-free writes and nullable +fields for writes with missing tokens. Appending the other schema could fail or +store a key that could not be reproduced under the table's held schema. + +**Fix:** Keep the output stream's declared fields through the operator output +keeper and hash rows under those fields. Store the records under `odb_v3` and +report `odb_v2` tables through the existing stale-layout accounting. diff --git a/docs/dev/design_issues/ITL-1563-RTC1.md b/docs/dev/design_issues/ITL-1563-RTC1.md index b602d7a2e..2f750bdc9 100644 --- a/docs/dev/design_issues/ITL-1563-RTC1.md +++ b/docs/dev/design_issues/ITL-1563-RTC1.md @@ -23,9 +23,7 @@ no output of the row is refused. No stored column, path, record id or hash moved. The stored field is the declared one whatever the row's field says (a non-nullable token field is wrapped under the nullable field, never cast), and the type checked is -the one the row carries (`source_info_table`), so a dictionary-encoded or binary token -column is refused. Open until rows keep their token columns' Arrow types: a null token -in a column declared with another type reaches the store as a `large_string` null and -is not refused (a strict `xfail` in -`tests/test_core/data_function/test_result_token_column_type.py` names it). A table -that already holds a list token column is not migrated. +the one the row carries. With ITL-1557, `as_table(columns={"source": True})` preserves +the declared type even for a null token, so list, dictionary-encoded, and binary token +columns are refused before writing. A table that already holds a list token column is +not migrated. diff --git a/docs/reference/data-function-types.md b/docs/reference/data-function-types.md index 51c09f494..b2ca7bcf8 100644 --- a/docs/reference/data-function-types.md +++ b/docs/reference/data-function-types.md @@ -156,11 +156,9 @@ output of the result is refused the same way, before anything is written. The stored field is the declared one whatever the written row's own field says: a row whose token field is non-nullable is stored under the nullable field, with its values -unchanged. The type that is checked is the one the row carries -(`DataProtocol.source_info_table`), so a token column that is dictionary-encoded or -binary is refused too. One case is not refused yet: a null token in a column declared -with another type, which a row gives as a `large_string` null and which is stored as -one. +unchanged. The cache checks the type in both the serialized row and its +`DataProtocol.source_info_table`. A list, dictionary-encoded, or binary token +column is refused even when its value is null. A result table that already holds a list token column, written before this rule by a custom `record_data`, is not rewritten: its path and column type stay, and every later diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 8a4fdcc1a..732a8a22a 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1123,6 +1123,11 @@ The record id names the row, and the source-info token names the row and its col value may contain `::`, so the record id may too; a source id and a column name cannot, so the token is split at its first `::` and its last `::` only, never at every `::`. +Source-info fields (`_source_*`) are always nullable at the top level, including +in a stream with no rows. List item fields follow the token type's own rules. +A bare builder stream hashes the flags as part of its full Arrow table. A +function node's row identity already uses nullable token fields. + ```python subjects = DictSource( data=[{"subject": "s1", "age": 3, "weight": 20.5}], @@ -1161,6 +1166,11 @@ and `k` such stages stacked carry each one `2 ** k` times (ITL-1114). The table `head()` and the notebook preview of a stream that has not run are built from carries the system tag columns too, so those calls are as wide as the joins make them (ITL-1132). +Join sorts source and record IDs as pairs within each printed provenance path. +Sync and record-batch tables keep custom system tags in their input positions. +Standalone row channels sort custom tags on the same path with the ID pair. +Join rows on these tied paths infer their system-tag fields from values. + --- ### Site 6b — Aggregating operator system tag fold @@ -1272,12 +1282,151 @@ 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=...)`, or `with_source_info` +given a Python value for a column the row holds no Arrow token column for), and the string +tokens Orcapod itself creates (a source's, a function output's, `Pick`'s, a placeholder's), +which are `large_string`. + +A row read from an Arrow table holds its token columns' types. `with_source_info` writes a +Python replacement under the held type and preserves the list item's name, nullability and +metadata. It refuses a string for a list, a list for a string, a wrong depth, a null item +where the item field is required, and `None` for a list type at any depth. `with_source_info(x=None)` +under a held string type writes a `large_string` null in both +`as_table(columns={"source": True})` and `source_info_table()`. The `Data` constructor +also checks non-`None` replacements against the held type. With +`Data(table, source_info={"x": None})`, the constructor keeps the token the table already +holds for `x`. + +#### 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 token type the stream of an output channel declares binds every batch +sent into it, the first batch and an empty batch included: a batch that declares another +type for that column (other item metadata is enough) is refused, never taken as the +stream's new type. The first batch settles a token column's type only where the stream +declares none for it. + 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, @@ -1892,12 +2041,19 @@ Every row Orcapod stores names its data context in the column `__data_context`: |---|---| | Function-node pipeline table | `pdb_v2` | | Function result table | `rdb_v1`, after the revision of the data function type's record (`.../python.function.v1/rev1/rdb_v1`; see [Data function types](data-function-types.md)) | -| Operator-node cache table | `odb_v2` | -| Cached-source table | `sdb_v1` | +| Operator-node cache table | `odb_v3` | +| Cached-source table | `sdb_v2` | | Side-effect invocation log | `tdb_v2` | The layout component is always the last component of a table's path, also when a -`CachedSource` is given an explicit `cache_path`. +`CachedSource` is given an explicit `cache_path`. The `sdb_v2` layout stores +nullable token fields and hashes records with those flags. An `sdb_v1` +table is reported as an older layout and left untouched. A bound source can +populate a new `sdb_v2` table from its live data. + +Operator caches use the output stream's declared Arrow fields for records and their +hashes under `odb_v3`. An `odb_v2` table is reported as an older layout and left +untouched. LOG computes fresh records for the new layout. **Rows of the current data context are the current entries.** Key lookups match rows of the current data context only, and every read of a whole table (a node's `as_table()`, @@ -1914,8 +2070,8 @@ at a computed path. The beginning of a path holds no hash: the job, then the nam function (`//...` and `/_result//...`, or `/...` in a separate result database; `side_effect_function/` for a function pod that takes the invocation context; -`side_effects/` for a side-effect pod; `/source` for a cached source without -an explicit `cache_path`). A node lists the tables stored under that beginning +`side_effects/` for a side-effect pod; the explicit `cache_path` or `/source` +for a cached source). A node lists the tables stored under that beginning (`list_table_paths` of the database) and reports, once, those whose last component is not a current layout. They are not read, so they are reported without a number of rows: diff --git a/src/orcapod/contexts/data/v1.json b/src/orcapod/contexts/data/v1.json index 8e8e56936..37707119b 100644 --- a/src/orcapod/contexts/data/v1.json +++ b/src/orcapod/contexts/data/v1.json @@ -236,18 +236,18 @@ "folder": "v1", "history": [ { - "date": "2026-11-23", + "date": "2026-11-27", "release": null, "added": { "arrow-01.json": "fa69c71eca676cb308cb1f5eb1a8db23b6d3e31ed76f0f6b36b88d76915581d6", "datagram-01.json": "8bc6f549f46254c0dd33c03215ff2bfba50d63b81d9b4c52afdc07153d2a04c6", "pipeline-01.json": "f80f3f764c3770b720bb85a77d9d4f68a4efb5eacd45fb43bb46fee8a301a2c9", - "schema-01.json": "81205905754b7ee6cc0f2dca50abcded70fc3c98272cfd3a9a11de088d248dc2", + "schema-01.json": "bc31869f9f8e6bbe8b41cbf0802c53eb2199cc807ccdaee68f566803c39601ea", "semantic-01.json": "3784a1353e9c818f57debc0c26f65fc1622e14e22f9004187a312b1c37033254", "torch-01.json": "ca3d163bab055381827226140568f3bef7eaac187cebd76878e0b63e9e442356" }, "previous": null, - "digest": "373ad66e7e9cc3a411708a4470a30d2176aedf9c9ba1ecdbe1111359ceb25867" + "digest": "bee03a9ad12cd2b8fb44edcf3bd90bb8e3ba69dd506361a4506afbee72d4619d" }, { "date": "2026-11-26", @@ -255,8 +255,8 @@ "added": { "pipeline-02.json": "fcc0de37838f5d59003c953c5e3650b45495ea2cad13800e68247ebb265a6958" }, - "previous": "373ad66e7e9cc3a411708a4470a30d2176aedf9c9ba1ecdbe1111359ceb25867", - "digest": "5799c75e5b382a8699151a44822fdb9b608b77763f8cae47b96e79d72caedb44" + "previous": "bee03a9ad12cd2b8fb44edcf3bd90bb8e3ba69dd506361a4506afbee72d4619d", + "digest": "136ec3c849f14f5560e0cb8d3465410803103acfd1eaa0599a339d888eab8a0a" } ], "provisional": { 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..15a2a086f 100644 --- a/src/orcapod/core/datagrams/tag_data.py +++ b/src/orcapod/core/datagrams/tag_data.py @@ -18,8 +18,8 @@ import logging import uuid -from collections.abc import Iterator, Mapping, Sequence -from typing import TYPE_CHECKING, Any, Self +from collections.abc import Collection, Iterator, Mapping, Sequence +from typing import cast, TYPE_CHECKING, Any, Self import pyarrow as pa @@ -56,9 +56,9 @@ def _source_info_field(name: str, token: SourceInfoValue) -> pa.Field[Any]: """The field of source-info column ``name`` holding ``token``, as a row's table has it.""" - import pyarrow as _pa - - return _pa.field(name, arrow_utils.source_info_arrow_type(token)) + return arrow_utils.source_info_field( + name, arrow_utils.source_info_arrow_type(token) + ) class Tag(Datagram): @@ -89,7 +89,8 @@ def __init__( if isinstance(data, _pa.RecordBatch): data = _pa.Table.from_batches([data]) - extracted_sys_tags: dict[str, DataValue] + 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,16 +108,12 @@ def __init__( if c.startswith(constants.SYSTEM_TAG_PREFIX) ] if sys_tag_cols: - extracted_sys_tags = ( - self._data_context.type_converter.arrow_table_to_python_dicts( - self._data_table.select(sys_tag_cols) # type: ignore[union-attr] - )[0] + system_tag_table = arrow_utils.normalize_table_to_large_types( + data.select(sys_tag_cols), keep_null=True ) self._data_table = self._data_table.drop_columns(sys_tag_cols) # type: ignore[union-attr] # Invalidate derived caches self._data_arrow_schema = None - else: - extracted_sys_tags = {} else: # Dict path: extract system-tag keys before calling super() data_only = { @@ -138,7 +135,44 @@ def __init__( **kwargs, ) - self._set_system_tags({**extracted_sys_tags, **(system_tags or {})}) + if system_tag_table is None: + self._set_system_tags({**extracted_sys_tags, **(system_tags or {})}) + return + + if system_tags: + system_tag_table = self._merge_system_tag_table( + system_tag_table, system_tags + ) + self._set_system_tag_table(system_tag_table) + + def _merge_system_tag_table( + self, table: "pa.Table", tags: Mapping[str, DataValue] + ) -> "pa.Table": + """Apply Python tags, reusing existing Arrow fields for replacements.""" + replacements = {name: tags[name] for name in table.column_names if name in tags} + additions = { + name: value for name, value in tags.items() if name not in replacements + } + if replacements: + schema = arrow_utils.schema_select(table.schema, list(replacements)) + for field in schema: + if not field.nullable and replacements[field.name] is None: + raise ValueError(f"Column {field.name!r} is declared non-nullable") + updated = self.converter.python_dicts_to_arrow_table( + [replacements], arrow_schema=schema + ) + table = arrow_utils.hstack_tables( + table.drop_columns(list(replacements)), updated + ).select(table.column_names) + if additions: + added = self.converter.python_dicts_to_arrow_table( + [additions], + python_schema=infer_python_schema_from_pylist_data( + [additions], default_type=str + ), + ) + table = arrow_utils.hstack_tables(table, added) + return table def _set_system_tags(self, system_tags: dict[str, DataValue]) -> None: """Hold ``system_tags`` as this tag's system tags.""" @@ -147,12 +181,24 @@ 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") -> None: + """Hold the system-tag fields and values supplied by an Arrow table.""" + self._system_tags_table = table + self._system_tags = self.converter.arrow_table_to_python_dicts(table)[0] + self._system_tags_python_schema = Schema( + self.converter.arrow_schema_to_python_schema(table.schema) + ) + self._system_tags_from_arrow = True @classmethod def rows_of( cls, table: "pa.Table", data_context: "str | contexts.DataContext | None" = None, + *, + infer_system_tags: Collection[str] = (), ) -> Iterator[Self]: """Yield the tag of each row of ``table``, in row order. @@ -167,6 +213,7 @@ def rows_of( table: The rows: user-tag and system-tag columns. data_context: The data context of every tag; ``None`` reads each row's own from the table's data-context column, or takes the default. + infer_system_tags: Tied Join fields built from Python values. Yields: One tag per row. @@ -178,13 +225,24 @@ 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 + if system_tag_row is None: + tag._set_system_tags({}) + elif infer_system_tags: + names = system_tag_row.column_names + infer = [name for name in names if name in infer_system_tags] + values = tag.converter.arrow_table_to_python_dicts( + system_tag_row.select(infer) )[0] - if system_tag_row is not None - else {} - ) + tag._set_system_tags(values) + if len(infer) != len(names): + kept = system_tag_row.drop_columns(infer) + tag._set_system_tag_table( + arrow_utils.hstack_tables( + kept, tag._ensure_system_tags_table() + ).select(names) + ) + else: + tag._set_system_tag_table(system_tag_row) yield tag # ------------------------------------------------------------------ @@ -287,7 +345,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 +372,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)) + + +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. - arrow_type = arrow_utils.source_info_arrow_type(value) + 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 +453,9 @@ 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 token columns keep the table's types. A Python value + # supplies the type only when the table has no token column for it. + typed = si_table if si_table.num_rows == 1 else None else: typed = None # Dict path: extract source-info keys before calling super() @@ -402,9 +480,8 @@ def __init__( self._source_info = {**contained_source_info, **(source_info or {})} self._source_info_table: "pa.Table | None" = None - # The row's source-info columns as the Arrow table it was read from gave - # them, when it was read from one (here, or ``rows_of``); ``None`` - # otherwise, and after any change of the columns or tokens. + # The row's typed token columns, read from Arrow or carried forward by a + # row operation. A row built from Python values starts without them. self._typed_source_info: "pa.Table | None" = typed @staticmethod @@ -421,9 +498,30 @@ def _data_and_source_info_tables( The table without its source-info columns, and a table with one source-info column per data column (null where there is no token). """ + untyped: dict[str, SourceInfoValue] = {} + for key, token in source_info.items(): + name = f"{constants.SOURCE_PREFIX}{key}" + index = table.schema.get_field_index(name) + if index == -1 or token is None: + untyped[key] = token + elif ( + key in table.column_names + and key != constants.CONTEXT_KEY + and not key.startswith(constants.META_PREFIX) + ): + field = table.schema.field(index) + kind = arrow_utils.normalize_to_large_types(field.type) + try: + array = arrow_utils.source_info_replacement( + token, kind, table.num_rows + ) + except (pa.ArrowInvalid, pa.ArrowTypeError) as error: + error.add_note(f"Replacing source-info column {name!r}") + raise + table = table.set_column(index, field.with_type(kind), array) data_table, prefixed_tables = arrow_utils.prepare_prefixed_columns( table, - {constants.SOURCE_PREFIX: source_info}, + {constants.SOURCE_PREFIX: untyped}, exclude_columns=[constants.CONTEXT_KEY], exclude_prefixes=[constants.META_PREFIX], ) @@ -484,6 +582,27 @@ 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( + [ + arrow_utils.source_info_field(f.name, f.type) + for f in typed.schema + ] + ), + ) if self._source_info_table is None: import pyarrow as _pa @@ -577,27 +696,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 +727,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({}) - # 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 + return self._token_columns({}, every_column=True) + # A row's token fields use the shared nullable declaration. 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)] + [ + arrow_utils.source_info_field(name, column.type) + for name, column in zip(column_names, columns, strict=True) + ] ), ) - 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 _source_info_for_transport(self) -> "pa.Table": + """Return the row's token fields for table transport, including typed nulls.""" + if self._typed_source_info is not None: + return self._typed_source_info + return self._ensure_source_info_table() + + def _token_columns( + self, kept: "Mapping[str, pa.ChunkedArray[Any]]", *, every_column: bool = False + ) -> "pa.Table": + """Return this row's token columns in data column order. 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,47 +779,105 @@ 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)]) arrays.append(array) - fields.append(pa.field(column_name, array.type)) + fields.append(arrow_utils.source_info_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 Python replacement of a token whose column the row holds as Arrow (a + row read from a table) is written under that held type, and one that + does not fit it is refused: a list for a string, a string for a list, a + wrong depth, a null item where the item field is required, and ``None`` + for a list type (a list token is never null). ``None`` under a held + string type is a ``large_string`` null, in ``as_table`` and in + ``source_info_table`` alike. Only a row with no Arrow token column for + the name types the token from its value. + 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 + name = f"{constants.SOURCE_PREFIX}{key}" + typed = self._typed_source_info + if typed is not None and name in typed.column_names: + try: + replacement = arrow_utils.source_info_replacement( + token, typed.schema.field(name).type + ) + except (pa.ArrowInvalid, pa.ArrowTypeError) as error: + error.add_note(f"Replacing source-info column {name!r}") + raise + typed_given[key] = pa.chunked_array([replacement]) + 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 +906,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 +1059,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 +1100,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 db62a212b..4b5f82ac0 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -39,6 +39,7 @@ from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER from orcapod.errors import ( InconsistentSourceError, + InputValidationError, OrcapodDatabaseError, TypeIdentityError, ) @@ -1141,6 +1142,55 @@ 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. + + Raises: + InputValidationError: If any two rows declare different types for a token, + including the metadata or nullability of any nested item field. + """ + types: dict[str, pa.DataType] = {} + for row in rows: + for field in row.schema: + expected = types.setdefault(field.name, field.type) + if not expected.equals(field.type, check_metadata=True): + raise InputValidationError( + f"Function output rows disagree on token {field.name!r}: " + f"{arrow_utils.describe_arrow_type(expected)} vs " + f"{arrow_utils.describe_arrow_type(field.type)}." + ) + schema = pa.schema( + [arrow_utils.source_info_field(name, kind) for name, kind in types.items()] + ) + tables = [] + for row in rows: + if row.schema.equals(schema, check_metadata=True): + tables.append(row) + continue + columns = dict(zip(row.column_names, row.columns, strict=True)) + tables.append( + pa.Table.from_arrays( + [ + columns[name] if name in columns 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, + ) + ) + return pa.concat_tables(tables) + + class FunctionPodStream(StreamBase): """Recomputable stream wrapping a data function.""" @@ -1554,22 +1604,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 @@ -1577,8 +1648,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( @@ -1588,7 +1659,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 953359409..6058b1b1c 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3339,11 +3339,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/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 6ef01fb4b..83a1d406c 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -41,7 +41,6 @@ from orcapod.channels import Channel, ChannelClosed, ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig from orcapod.core.operators.static_output_pod import ( - RowBuiltFormUnavailable, StaticOutputOperatorPod, produced_stream, rows_on_read, @@ -74,7 +73,9 @@ UnstorableColumnError, ) from orcapod.contexts.stored import ( + account_for_stale_tables, data_context_field, + find_stale_tables, require_storable, keep_rows_of_data_context, require_same_data_context, @@ -139,10 +140,9 @@ class _InputTap: each input with no rows and applies the operator to those, as the sync path applies it to the rebuilt upstream rows (ITL-1080). Those columns and types are what ``StaticOutputOperatorPod._rows_to_table`` makes of the input's - rows, and the only thing in them that depends on more than one row is the - nullability of a source-info column (nullable when some row's token is - ``None``). So the tap keeps the first row, and the first row with a ``None`` - token for each source-info column, never the whole input. + rows. Keep the first row and the first occurrence of an absent token in + each source-info column. These sampled rows still go through the existing + row-built token type check before they are sliced to zero rows. Attributes: rows: The kept rows, in arrival order. @@ -862,6 +862,7 @@ class OperatorJobNode(ProvenanceMethods, RunHoldingNode, OperatorNodeBase): # Set once a read has reported the stored rows it skipped (rows of another data # context); a class default so nodes rebuilt from a saved descriptor start unset. _skipped_rows_reported: bool = False + _stale_tables_checked: bool = False # The job file's expected row count for a loaded node, and whether it was checked # against the attached database (ITL-1043). Advisory: a mismatch only warns. _expected_row_count: int | None = None @@ -1036,6 +1037,7 @@ def attach_databases( # runs or changes (ITL-1162). self.require_storable_tables(pipeline_database, cache_mode) self._skipped_rows_reported = False + self._stale_tables_checked = False self._row_count_checked = False self._pipeline_database = pipeline_database self._cache_mode = cache_mode @@ -1403,6 +1405,7 @@ def _store_output_stream(self, stream: StreamProtocol) -> None: raise RuntimeError( f"OperatorJobNode {self.label!r} has no pipeline database attached." ) + self._account_for_stale_tables() output_table = stream.as_table( columns={"source": True, "system_tags": True, "context": True}, ) @@ -1419,6 +1422,39 @@ def _store_output_stream(self, stream: StreamProtocol) -> None: require_same_data_context(row_context_key, self.data_context_key) output_table = output_table.drop([constants.CONTEXT_KEY]) + declared = self._typed_zero_row_table() + if declared is not None: + from orcapod.core.operators.join import Join + + # On tied Join paths, the table describes the input declarations + # while rows infer their own provenance fields from the values. + row_inferred = ( + self._operator.row_inferred_system_tags( + self._input_streams, declared.column_names + ) + if isinstance(self._operator, Join) + else frozenset() + ) + expected_fields = {field.name: field for field in declared.schema} + actual_fields = {field.name: field for field in output_table.schema} + for name in sorted(expected_fields.keys() | actual_fields.keys()): + expected = expected_fields.get(name) + actual = actual_fields.get(name) + if ( + expected is not None + and actual is not None + and ( + name in row_inferred + or expected.equals(actual, check_metadata=True) + ) + ): + continue + raise InputValidationError( + f"OperatorJobNode {self.label!r} output field {name!r} differs " + f"from its declared type, nullability or metadata. " + f"Declared {expected!r}; materialized {actual!r}." + ) + # The entry id of each row (ITL-1471) is computed from the row as the stream # gives it, before the bookkeeping columns are added. rows = list(stream.iter_data()) @@ -1512,6 +1548,19 @@ def _store_output_stream(self, stream: StreamProtocol) -> None: [self.HASH_COLUMN_NAME, constants.NODE_CONTENT_HASH_COL] ) + def _account_for_stale_tables(self) -> None: + """Report operator caches at other layouts once per attached database.""" + if self._stale_tables_checked or self._pipeline_database is None: + return + account_for_stale_tables( + find_stale_tables( + self._pipeline_database, name_path=self.node_uri[:1] or None + ), + delivers_side_effects=False, + current_context=self.data_context_key, + ) + self._stale_tables_checked = True + def _read_stored_records(self) -> "pa.Table | None": """Read this node's stored rows written under the current data context. @@ -1554,6 +1603,7 @@ def _read_current_context_records(self) -> "pa.Table | None": data-tags (ITL-1019). """ assert self._pipeline_database is not None + self._account_for_stale_tables() records = self._pipeline_database.get_all_records( self._stored_table_path, record_id_column=self.HASH_COLUMN_NAME ) @@ -1721,10 +1771,10 @@ def execute( as in any run. Returns: - The node's output stream: its rows as the table ``_rows_to_table`` builds - from them (``StaticOutputOperatorPod._output_stream``), with this node's - identity, built from the operator's result table without making rows - (ITL-1347, stage 2). The sync orchestrator hands it to every successor. + The output stream under the operator's declared fields, with this node's + identity. When the result already holds its Arrow table, the keeper + uses that table directly. The sync orchestrator hands the stream to + every successor. Raises: ValueError: If the node caches (``LOG`` or ``REPLAY``) and a source @@ -1752,16 +1802,16 @@ def execute( # Check REPLAY cache first cached_output = self.get_cached_output() if cached_output is not None: - try: - output = StaticOutputOperatorPod._output_stream( - cached_output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), - cached_output.keys(), + table = cached_output.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + if table.num_rows: + output = StaticOutputOperatorPod._as_upstream_stream( + table, + cached_output.keys()[0], + stream_data_tags(cached_output), self, ) - except RowBuiltFormUnavailable: - # A stored table F cannot build from: its rows, built when read, - # as main handed them on (ITL-1347). - output = rows_on_read(cached_output.iter_data(), self) + else: + output = rows_on_read([], self) ctx_obs.on_node_end(node_label, node_hash) return output @@ -1806,16 +1856,13 @@ def execute( # Cache, in row order with or without rows (ITL-1131, ITL-1133). if result_table.num_rows: - try: - kept_table = StaticOutputOperatorPod._row_built_form( - result_table, keys - ) - except RowBuiltFormUnavailable as error: - StaticOutputOperatorPod._raise_as_rows_do( - produced.iter_data(), error + self._cached_output_stream = ( + StaticOutputOperatorPod._keep_output_table( + result_table, produced ) - self._cached_output_stream = ArrowTableStream( - kept_table, tag_columns=tag_keys, data_tags=data_tags + ) + kept_table = self._cached_output_stream.as_table( + columns=ZERO_ROW_INPUT_COLUMNS ) # The output stream, built once the node holds its run (as the # sync orchestrator built a successor's input after ``execute`` @@ -1856,7 +1903,11 @@ def _compute_output(self) -> StreamProtocol: run on its own has the columns, in memory and stored, of the same node in a job (ITL-1133). The rows are computed here, not when first read. """ - result = self._operator.process(*self._input_streams) + result = produced_stream(self._operator.process(*self._input_streams)) + if reads_as_its_class(result, ArrowTableStream): + return StaticOutputOperatorPod._keep_output_table( + result.as_table(columns=ZERO_ROW_INPUT_COLUMNS), result + ) return StaticOutputOperatorPod._kept_output(result, list(result.iter_data())) def _compute_and_store(self, *, store: bool = True) -> None: @@ -2415,7 +2466,11 @@ async def forward() -> None: # with no rows replaces an earlier run's output too: the node then # reads as a zero-row table. if collected: - stream = StaticOutputOperatorPod._materialize_to_stream(collected) + stream = StaticOutputOperatorPod._stream_over_row_table( + StaticOutputOperatorPod._rows_to_table( + collected, keep_token_fields=True + ) + ) self._cached_output_stream = stream if should_store: self._store_output_stream(stream) diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index 9d9153c74..4dfcbc5ec 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -189,7 +189,11 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: list_type = arrow_utils.aggregated_list_type( field.type, type_converter, column=field.name ) - fields.append(pa.field(field.name, list_type, nullable=False)) + fields.append( + arrow_utils.source_info_field(field.name, list_type) + if field.name.startswith(constants.SOURCE_PREFIX) + else pa.field(field.name, list_type, nullable=False) + ) arrays.append(arrow_utils.aggregated_list_array(column, offsets, list_type)) batched_table = pa.Table.from_arrays(arrays, schema=pa.schema(fields)) @@ -334,8 +338,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/group_by.py b/src/orcapod/core/operators/group_by.py index c5b03cbd6..c544fee70 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -539,7 +539,11 @@ def folded(c: str) -> pa.Array[Any]: list_type = arrow_utils.aggregated_list_type( field.type, type_converter, column=c ) - fields.append(pa.field(c, list_type, nullable=False)) + fields.append( + arrow_utils.source_info_field(c, list_type) + if c.startswith(constants.SOURCE_PREFIX) + else pa.field(c, list_type, nullable=False) + ) arrays.append( arrow_utils.aggregated_list_array( table.column(c).take(order), offsets, list_type diff --git a/src/orcapod/core/operators/index.py b/src/orcapod/core/operators/index.py index 3a6f3e4d5..59012b9bf 100644 --- a/src/orcapod/core/operators/index.py +++ b/src/orcapod/core/operators/index.py @@ -254,6 +254,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, @@ -317,13 +344,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 @@ -410,15 +458,10 @@ 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_field = pa.field( + token_type = self._element_token_type(input_token_type) + token_field = arrow_utils.source_info_field( f"{constants.SOURCE_PREFIX}{self.out or self.column}", token_type, - nullable=input_token.nullable, ) if self.out is None: position = input_schema.get_field_index(self.column) @@ -430,7 +473,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: output_schema = input_schema.append(element_field) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized output_schema = output_schema.append(token_field) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized return ArrowTableStream( - self._as_row_built_table(output_schema.empty_table(), tag_columns), + self._in_row_order(output_schema.empty_table(), tag_columns), tag_columns=tag_columns, data_context=stream.data_context, data_tags=stream_data_tags(stream), diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 0ad0fe26f..2dc5bfe51 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -2,7 +2,8 @@ import functools import itertools import json -from collections.abc import Callable, Collection, Mapping, Sequence +from collections import Counter +from collections.abc import Callable, Collection, Iterator, Sequence from typing import Any, ClassVar, get_args import polars as pl @@ -36,6 +37,7 @@ key_nullable, reconcile_key_nullability, ) +from orcapod.core.datagrams import Tag from orcapod.core.streams import ArrowTableStream from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import ( @@ -45,7 +47,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 @@ -73,6 +75,29 @@ _COMMON_JOIN_KEY = "_common" +def repeated_system_tag_suffixes(suffixes: Sequence[str]) -> frozenset[str]: + """Return the printed positional suffixes whose hash prefix occurs twice or more.""" + prefixes = [suffix.rsplit(constants.FIELD_SEPARATOR, 1)[0] for suffix in suffixes] + counts = Counter(prefixes) + return frozenset( + constants.BLOCK_SEPARATOR + suffix + for suffix, prefix in zip(suffixes, prefixes, strict=True) + if counts[prefix] > 1 + ) + + +def _system_tag_names_with_suffixes( + names: Collection[str], suffixes: Collection[str] +) -> frozenset[str]: + """Select system-tag fields from operands whose printed hash suffix is shared.""" + endings = tuple(suffixes) + return frozenset( + name + for name in names + if name.startswith(constants.SYSTEM_TAG_PREFIX) and name.endswith(endings) + ) + + def _with_common_key(table: "pa.Table") -> "pa.Table": """Return ``table`` with the constant join key ``_COMMON_JOIN_KEY`` as its first column. @@ -180,6 +205,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): @@ -540,6 +702,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)) @@ -550,7 +721,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) @@ -579,12 +755,53 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: + data_order + [col for col in table.column_names if col not in listed] ) - return ArrowTableStream( + return self._join_result_stream( result_table, + streams, tag_columns=tuple(tag_order), data_tags=data_tag_names(tag_schema, data_schema), ) + def row_inferred_system_tags( + self, streams: Sequence[StreamProtocol], names: Collection[str] + ) -> frozenset[str]: + """Return the Join output columns whose row tags are built from values.""" + suffixes = self._compute_system_tag_suffixes( + [stream.pipeline_hash() for stream in streams] + ) + return _system_tag_names_with_suffixes( + names, repeated_system_tag_suffixes(suffixes) + ) + + def _join_result_stream( + self, + result_table: pa.Table, + streams: Sequence[StreamProtocol], + *, + tag_columns: Collection[str], + data_tags: Collection[str], + ) -> ArrowTableStream: + """Keep the table's fields and apply tied provenance inference to row reads.""" + inferred = self.row_inferred_system_tags(streams, result_table.column_names) + if any( + field.name in inferred + and ( + field.nullable + or field.metadata + or not pa.types.is_large_string(field.type) + ) + for field in result_table.schema + ): + return _TiedJoinStream( + result_table, + tag_columns=tag_columns, + data_tags=data_tags, + inferred_system_tags=inferred, + ) + return ArrowTableStream( + result_table, tag_columns=tag_columns, data_tags=data_tags + ) + @staticmethod def _merge_source_columns( table: "pa.Table", left_name: str, right_name: str @@ -600,17 +817,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) @@ -628,9 +850,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) @@ -777,9 +1000,8 @@ async def _streaming_join( suffixes: Per-input system-tag suffixes (positional). """ n = len(inputs) - block_sep = constants.BLOCK_SEPARATOR - if n == 2: + repeated_suffixes = repeated_system_tag_suffixes(suffixes) # Join in canonical order so the merged tag and data keys follow # the order ``output_schema`` defines, whatever the operand order. left_idx, right_idx = self._canonical_input_order(suffixes) @@ -791,10 +1013,15 @@ 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, repeated_suffixes + ) await self._binary_streaming_join( - inputs[left_idx], inputs[right_idx], output, merge_fn + inputs[left_idx], + inputs[right_idx], + output, + merge_fn, ) return @@ -848,10 +1075,23 @@ 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]] = {} + repeated_suffixes = repeated_system_tag_suffixes(suffixes) + + 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 @@ -859,15 +1099,15 @@ 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, + repeated_suffixes, + functools.partial(declare, position), ) ) renamed_readers.append(ch.reader) @@ -889,7 +1129,12 @@ 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, + repeated_suffixes=repeated_suffixes, + ), ) ) @@ -970,6 +1215,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: @@ -1073,27 +1327,28 @@ 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, + repeated_suffixes: Collection[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, + repeated_suffixes, ) await ch_out.send((tag, pkt)) finally: @@ -1164,27 +1419,54 @@ 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 _build_tag( table: "pa.Table | None", - system_tags: Mapping[str, DataValue], + system_tags: "pa.Table | None", data_context_key: str, + repeated_suffixes: Collection[str], ) -> TagProtocol: - """Build a ``Tag`` from a merged Arrow table and its system tags. + """Build a tag, sorting by value for tied system-tag paths.""" + if system_tags is None: + return Tag( + table if table is not None else {}, data_context=data_context_key + ) - Args: - table: The tag's user columns, or ``None`` for a tag without any. - system_tags: The tag's system tags, already renamed and sorted. - data_context_key: The data context key of the incoming datagrams. + names = system_tags.column_names + tied_names = _system_tag_names_with_suffixes(names, repeated_suffixes) + if tied_names: + from orcapod.contexts import resolve_context - Returns: - The new tag. - """ - from orcapod.core.datagrams import Tag + converter = resolve_context(data_context_key).type_converter + tied = system_tags.select([name for name in names if name in tied_names]) + values = Join._sort_merged_system_tags( + converter.arrow_table_to_python_dicts(tied)[0] + ) + if len(tied_names) == len(names): + return Tag( + table if table is not None else {}, + system_tags=values, + data_context=data_context_key, + ) + inferred = Tag({}, system_tags=values, data_context=data_context_key) + kept = system_tags.drop_columns(list(tied_names)) + inferred_table = inferred._ensure_system_tags_table() # pyright: ignore[reportPrivateUsage] # use Tag's system-field inference + system_tags = arrow_utils.hstack_tables(kept, inferred_table).select(names) - 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) + if table is not None: + system_tags = arrow_utils.hstack_tables(table, system_tags) + return Tag(system_tags, data_context=data_context_key) @staticmethod def _merge_data( @@ -1193,6 +1475,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. @@ -1212,6 +1495,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``. @@ -1222,6 +1508,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(), @@ -1234,17 +1522,61 @@ 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( + [ + arrow_utils.source_info_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()] @@ -1256,7 +1588,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, ) @@ -1288,11 +1620,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, @@ -1300,7 +1709,7 @@ def _merge_pair_rename( right_tag: TagProtocol, right_pkt: DataProtocol, suffixes: list[str], - block_sep: str, + repeated_suffixes: Collection[str], ) -> tuple[TagProtocol, DataProtocol]: """Merge a matched pair, renaming system tags with per-side suffixes. @@ -1308,22 +1717,17 @@ 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) + for tag, suffix in zip((left_tag, right_tag), suffixes, strict=True) + if (table := Join._system_tag_table(tag)) is not None + ] + merged_sys = arrow_utils.hstack_tables(*tables) if tables else None merged_tag = Join._build_tag( Join._merge_tag_tables(left_tag, right_tag), merged_sys, left_tag.data_context_key, + repeated_suffixes, ) return merged_tag, Join._merge_data(left_tag, left_pkt, right_tag, right_pkt) @@ -1333,29 +1737,38 @@ def _merge_pair_passthrough( left_pkt: DataProtocol, right_tag: TagProtocol, right_pkt: DataProtocol, + *, + repeated_suffixes: Collection[str], 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) + tables = [ + table + for tag in (left_tag, right_tag) + if (table := Join._system_tag_table(tag)) is not None + ] + merged_sys = arrow_utils.hstack_tables(*tables) if tables else None merged_tag = Join._build_tag( Join._merge_tag_tables(left_tag, right_tag), merged_sys, left_tag.data_context_key, + repeated_suffixes, ) 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 @@ -1434,3 +1847,23 @@ def identity_structure(self) -> Any: def __repr__(self) -> str: return "Join()" + + +class _TiedJoinStream(ArrowTableStream): + """A Join table whose tied system-tag fields are inferred on row reads.""" + + def __init__( + self, + table: pa.Table, + *, + tag_columns: Collection[str], + data_tags: Collection[str], + inferred_system_tags: frozenset[str], + ) -> None: + super().__init__(table, tag_columns=tag_columns, data_tags=data_tags) + self._inferred_system_tags = inferred_system_tags + + def _iter_tags(self, table: pa.Table) -> Iterator[Tag]: + return Tag.rows_of( + table, self.data_context, infer_system_tags=self._inferred_system_tags + ) diff --git a/src/orcapod/core/operators/merge_join.py b/src/orcapod/core/operators/merge_join.py index 4b3cb7c74..e84ed0300 100644 --- a/src/orcapod/core/operators/merge_join.py +++ b/src/orcapod/core/operators/merge_join.py @@ -1,4 +1,4 @@ -from collections.abc import Sequence +from collections.abc import Collection, Sequence from typing import Any, ClassVar, cast import numpy as np @@ -14,6 +14,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 @@ -55,7 +57,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( @@ -68,6 +72,53 @@ def _output_types( return resolved +def _output_nullability( + left: pa.Schema, + right: pa.Schema, + shared_tags: Collection[str], + colliding_data: Collection[str], +) -> dict[str, bool]: + """Derive the output flags from its input fields and the join's column roles.""" + nullable = {field.name: field.nullable for field in right} + for field in left: + nullable[field.name] = field.nullable or nullable.get(field.name, False) + for name in shared_tags: + nullable[name] = key_nullable( + left.field(name).nullable, right.field(name).nullable + ) + for name in colliding_data: + nullable[name] = False + return nullable + + +def _output_schema( + names: Sequence[str], + types: dict[str, pa.DataType], + nullable: dict[str, bool], + input_schemas: tuple[pa.Schema, pa.Schema], +) -> pa.Schema: + """Declare the output fields without consulting the matched rows.""" + system_tags = { + field.name: field + for schema in input_schemas + for field in schema + if field.name.startswith(constants.SYSTEM_TAG_PREFIX) + } + return pa.schema( + [ + arrow_utils.source_info_field(name, types[name]) + if name.startswith(constants.SOURCE_PREFIX) + else pa.field( + name, + types[name], + nullable=nullable[name], + metadata=system_tags[name].metadata if name in system_tags else None, + ) + for name in names + ] + ) + + def _merged_list( first: "pa.ChunkedArray[Any]", second: "pa.ChunkedArray[Any]", @@ -429,6 +480,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] @@ -446,46 +508,13 @@ def binary_static_process( for key in sorted(shared_tag_keys): require_matchable_key("MergeJoin", key, output_types[key]) - # The joined table is built from arrays with no field flags, so the - # flags are taken from the inputs. Only tag and data columns are - # captured: system tag and source columns are internally created with - # Arrow's all-nullable default; those fall through to null-count - # inference below. - captured_cols = ( - set(left_tag_keys) - | set(left_data_keys) - | set(right_tag_keys) - | set(right_data_keys) + output_nullable = _output_nullability( + left_table.schema, right_table.schema, shared_tag_keys, colliding_keys ) - left_nullable = { - f.name: f.nullable for f in left_table.schema if f.name in captured_cols - } - right_nullable = { - f.name: f.nullable for f in right_table.schema if f.name in captured_cols - } - # Build expected output nullable map - output_nullable: dict[str, bool] = {} - output_nullable.update(left_nullable) - for name, nullable in right_nullable.items(): - if name not in output_nullable: - output_nullable[name] = nullable - # A shared tag key is nullable only when nullable in both inputs: a null - # key matches nothing (ITL-829). Equal flags give the flag as before. - for name in shared_tag_keys: - output_nullable[name] = key_nullable( - left_nullable[name], right_nullable[name] - ) - # Merged (colliding) data columns become 2-element lists — always non-null - for col in colliding_keys: - output_nullable[col] = False - source_col = f"{constants.SOURCE_PREFIX}{col}" - if source_col in output_nullable: - output_nullable[source_col] = False # Inner join on the shared tag keys. A constant key makes the join a # cartesian product when the inputs share no tag; int8 explicitly, so a # zero-row table doesn't produce a null-typed column (same as Join). - output_nullable.pop(_COMMON_JOIN_KEY, None) left_table = _with_common_key(left_table) right_table = _with_common_key(right_table) join_keys = sorted(shared_tag_keys | {_COMMON_JOIN_KEY}) @@ -499,7 +528,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 @@ -555,23 +589,11 @@ def binary_static_process( other_cols = [c for c in joined.column_names if c not in listed] joined = joined.select(tag_cols + data_cols + other_cols) - # Reconstruct the schema: every column takes the type decided above - # from the inputs (the large-normalized input type for pass-through - # columns; the list type built above for merged columns), and - # nullability comes from the captured input flags, falling back to - # null-count inference for system tag and source-info columns. The - # values are the inputs'. - result_schema = pa.schema( - [ - pa.field( - col_name, - output_types[col_name], - nullable=output_nullable.get( - col_name, joined.column(i).null_count > 0 - ), - ) - for i, col_name in enumerate(joined.column_names) - ] + result_schema = _output_schema( + joined.column_names, + output_types, + output_nullable, + (right_table.schema, left_table.schema), ) # Only a column whose type differs is cast (a layout change): Arrow's cast of # a ``large_list`` column to its own type corrupts it. diff --git a/src/orcapod/core/operators/pick.py b/src/orcapod/core/operators/pick.py index 06ff42845..970e56d8c 100644 --- a/src/orcapod/core/operators/pick.py +++ b/src/orcapod/core/operators/pick.py @@ -419,7 +419,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: # A picked value's token is a string (``_process_one``), typed by the # source-info type rule. token_name = f"{constants.SOURCE_PREFIX}{self.out or self.column}" - token_field = pa.field( + token_field = arrow_utils.source_info_field( token_name, arrow_utils.source_info_arrow_type(token_name) ) if self.out is None: @@ -432,7 +432,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: output_schema = input_schema.append(value_field) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized output_schema = output_schema.append(token_field) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized return ArrowTableStream( - self._as_row_built_table(output_schema.empty_table(), tag_columns), + self._in_row_order(output_schema.empty_table(), tag_columns), tag_columns=tag_columns, data_context=stream.data_context, data_tags=stream_data_tags(stream), diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 3c1534d7c..f386d543f 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``). """ @@ -370,19 +369,18 @@ def __call__(self, *streams: StreamProtocol, **kwargs) -> DynamicPodStream: @staticmethod def _rows_to_table( rows: Sequence[tuple[TagProtocol, DataProtocol]], + *, + keep_token_fields: bool = False, ) -> tuple[pa.Table, tuple[str, ...], tuple[str, ...]]: """Concatenate (Tag, Data) pairs into one table, keeping per-row source info. Each row contributes its own system-tag and ``_source_*`` columns, so every row keeps its own provenance tokens (a token embeds a per-row - identifier, so rows never share one). A ``_source_*`` field is declared - non-nullable unless some row's token is ``None``; ``Data.as_table`` - declares every source-info field nullable, and this keeps the field - flags (which the operator node's per-row record hash covers) what they - were when a broadcast token made them non-nullable. + identifier, so rows never share one). Args: rows: Non-empty sequence of (Tag, Data) pairs. + keep_token_fields: Preserve Arrow token fields carried by the rows. A data-tag (a name in both the tag and the data of a row) is one column: it is taken from the tags, and its source info from the data. @@ -393,6 +391,7 @@ def _rows_to_table( Raises: ValueError: If ``rows`` is empty. """ + from orcapod.core.datagrams import Data from orcapod.utils import arrow_utils if not rows: @@ -401,7 +400,16 @@ def _rows_to_table( first_tag, first_data = rows[0] data_tags = data_tag_names(first_tag.keys(), first_data.keys()) tag_tables = [tag.as_table(columns={"system_tags": True}) for tag, _ in rows] - data_tables = [data.as_table(columns={"source": True}) for _, data in rows] + data_tables = [] + for _, data in rows: + if keep_token_fields and isinstance(data, Data): + tokens = data._source_info_for_transport() # pyright: ignore[reportPrivateUsage] # transport keeps the row's declaration + table = data.as_table() + if tokens.num_columns: + table = arrow_utils.hstack_tables(table, tokens) + data_tables.append(table) + else: + data_tables.append(data.as_table(columns={"source": True})) if data_tags: data_tables = [t.drop_columns(list(data_tags)) for t in data_tables] @@ -410,10 +418,6 @@ def _rows_to_table( combined_tags = arrow_utils.concat_tables_by_name(tag_tables) combined_data = arrow_utils.concat_tables_by_name(data_tables) - combined_data = StaticOutputOperatorPod._flag_source_info_nullability( - combined_data - ) - full_table = arrow_utils.hstack_tables(combined_tags, combined_data) return full_table, tuple(first_tag.keys()), data_tags @@ -443,26 +447,6 @@ def _in_row_order(table: pa.Table, tag_keys: Sequence[str]) -> pa.Table: data = [n for n in names if n not in placed] return table.select([*tag_keys, *system_tags, *data, *source_info]) - @staticmethod - def _as_row_built_table(table: pa.Table, tag_keys: Sequence[str]) -> pa.Table: - """Return ``table`` as ``_rows_to_table`` would build it from the same rows. - - Its columns in row order (``_in_row_order``) and each source-info field flagged - nullable only when some row's token is ``None`` - (``_flag_source_info_nullability``). For a table with no rows: what a result - built from rows has, with no row (ITL-1131). - - Args: - table: A table of user tags, system tags, data and source info. - tag_keys: The user tag columns, in order. - - Returns: - The same arrays, reordered, under the new source-info field flags. - """ - return StaticOutputOperatorPod._flag_source_info_nullability( - StaticOutputOperatorPod._in_row_order(table, tag_keys) - ) - @staticmethod def _zero_rows_in_row_order(result: StreamProtocol) -> StreamProtocol: """Return an operator's result with no rows as a run with rows would keep it. @@ -496,114 +480,22 @@ def _kept_output( result: StreamProtocol, rows: Sequence[tuple[TagProtocol, DataProtocol]], ) -> StreamProtocol: - """Return what an operator node keeps, and stores, of a run of its operator. - - The rows of the run as ``_materialize_to_stream`` builds them, or, with no row, - the result with no rows in the same order (``_zero_rows_in_row_order``). Every - way a node runs its operator (a job run, sync or async, and ``node.run()`` on - its own) keeps this, so a node has one column order, the row order, in memory - and in its stored table (ITL-1133). - - Args: - result: The operator's result of the run. - rows: ``result``'s rows, in order. - - Returns: - A stream over the rows, in row order. - """ + """Keep the operator's output rows under their declared token fields.""" if rows: - return StaticOutputOperatorPod._materialize_to_stream(rows) + return StaticOutputOperatorPod._stream_over_row_table( + StaticOutputOperatorPod._rows_to_table(rows, keep_token_fields=True) + ) 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. - - 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. - - Args: - table: A table of user tags, system tags, data and source info. - - Returns: - The same arrays under the new field flags, with no schema metadata. - """ - prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) - fields = [ - field.with_nullable(table.column(i).null_count > 0) - if field.name.startswith(prefixes) - else field - for i, field in enumerate(table.schema) - ] - # 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), - ), + def _keep_output_table(table: pa.Table, result: StreamProtocol) -> ArrowTableStream: + """Put the result table in row order using its declared fields.""" + tag_keys = result.keys()[0] + return ArrowTableStream( + StaticOutputOperatorPod._in_row_order(table, tag_keys), + tag_columns=tag_keys, + data_tags=stream_data_tags(result), + data_context=result.data_context_key, ) @staticmethod @@ -612,14 +504,9 @@ def _row_built_form( ) -> pa.Table: """Return ``table`` as ``_rows_to_table`` builds it from the table's own rows. - 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``). + The row-built form selects and orders columns using their row fields without + building the rows. It keeps the declared system-tag fields and each token + column's declared type, and drops table-level schema metadata. 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,17 +520,12 @@ 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) - ) - ) + return row_built_columns(table, keys).replace_schema_metadata(None) except RowBuiltFormUnavailable: raise except pa.ArrowException as error: @@ -706,30 +588,6 @@ def _output_stream( node, ) - @staticmethod - def _flag_source_info_nullability(table: pa.Table) -> pa.Table: - """Declare each ``_source_*`` field nullable only if some row's token is ``None``. - - The rule ``_rows_to_table`` applies to the rows it concatenates, and that a - zero-row input (``_zero_row_input``) applies to no row: there, no token is - ``None``, so every source-info field is non-nullable. - - Args: - table: A table whose ``_source_*`` columns hold source-info tokens. - - Returns: - The same arrays under the new field flags. - """ - from orcapod.system_constants import constants - - schema = table.schema - for i, field in enumerate(schema): - if field.name.startswith(constants.SOURCE_PREFIX): - nullable = table.column(i).null_count > 0 - schema = schema.set(i, field.with_nullable(nullable)) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized - # Same arrays, new field flags: no cast, so no value or type can change. - return pa.Table.from_arrays(table.columns, schema=schema) - @staticmethod def _zero_row_input(upstream: StreamProtocol) -> StreamProtocol | None: """Return ``upstream`` as an operator input with no rows, typed as its rows are. @@ -737,8 +595,8 @@ def _zero_row_input(upstream: StreamProtocol) -> StreamProtocol | None: The zero-row form of what ``_materialize_upstream`` builds from an upstream's rows: the upstream's zero-row table (``typed_zero_row_table``: user tags, system tags, data and source info, with the Arrow types its rows have) in the - column order and with the source-info flags ``_rows_to_table`` gives, as the - upstream's stream (``_as_upstream_stream``), so the stream's identity, + column order ``_rows_to_table`` gives, as the upstream's stream + (``_as_upstream_stream``), so the stream's identity, pipeline hash and system-tag column names are the upstream's (ITL-912). Args: @@ -754,7 +612,7 @@ def _zero_row_input(upstream: StreamProtocol) -> StreamProtocol | None: return None tag_keys = upstream.keys()[0] return StaticOutputOperatorPod._as_upstream_stream( - StaticOutputOperatorPod._as_row_built_table(table, tag_keys), + StaticOutputOperatorPod._in_row_order(table, tag_keys), tag_keys, stream_data_tags(upstream), upstream, @@ -1038,7 +896,9 @@ def _materialize_input_stream( """ from orcapod.system_constants import constants - table, tag_keys, data_tags = StaticOutputOperatorPod._rows_to_table(rows) + table, tag_keys, data_tags = StaticOutputOperatorPod._rows_to_table( + rows, keep_token_fields=True + ) table = table.append_column( pa.field(constants.CONTEXT_KEY, pa.large_string(), nullable=False), pa.array([data.data_context_key for _, data in rows], pa.large_string()), @@ -1140,9 +1000,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) @@ -1308,7 +1167,10 @@ async def _streams_of(inputs: Sequence[RecordBatchInput]) -> list[StreamProtocol def stream_from_batches( - stream: StreamProtocol, batches: Sequence[pa.RecordBatch] + stream: StreamProtocol, + batches: Sequence[pa.RecordBatch], + *, + declared_schema: pa.Schema | None = None, ) -> StreamProtocol: """Return the Arrow record batches of ``stream``'s rows as a stream. @@ -1317,24 +1179,41 @@ 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, - typed by its description and never by rows. + (``_output_stream``): declared system-tag flags are restored, and source-info + fields are nullable and keep the stream's declared types. If the stream + has no token types yet, the populated batches establish them. + The result keeps ``stream``'s producer, upstreams, pipeline hash and data context. + With no batch it is ``stream``'s zero-row input, or the accepted channel schema + if the stream cannot supply a typed zero-row input. Args: stream: The describing stream: the node or stream the rows are of. batches: Its rows (``row_built_columns``), in order. + declared_schema: The declaration already accepted by an output channel. Returns: A complete, re-readable stream over the rows. """ - if not batches: - return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator - table = concatenate_batches(batches) + typed = typed_zero_row_table(stream) + if declared_schema is None and typed is not None: + declared_schema = typed.schema + if declared_schema is None and batches: + declared_schema = batches[0].schema + table = concatenate_batches( + batches, + declared_schema=declared_schema, + declared_tokens=declared_token_types(stream), + ) if table is None: - return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator + if typed is not None or declared_schema is None: + return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator + table = declared_schema.empty_table() + tag_keys, data_keys = _keys_in_delivered_order( + stream.keys(), table.column_names + ) + return StaticOutputOperatorPod._as_upstream_stream( # pyright: ignore[reportPrivateUsage] # the zero-row result under the channel declaration + table, tag_keys, data_tag_names(tag_keys, data_keys), stream + ) 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 ) @@ -1370,174 +1249,134 @@ def _keys_in_delivered_order( return ordered_tags, data_tags + plain +def declared_token_types( + stream: StreamProtocol, schema: pa.Schema | None = None +) -> dict[str, pa.DataType]: + """Return the concrete stream's token types, if known before reading a batch.""" + from orcapod.core.nodes.source_node import SourceJobNode, SourceNode + + if isinstance(stream, SourceNode): + return {} + if isinstance(stream, SourceJobNode): + bound = stream.bound_source + return {} if bound is None else declared_token_types(bound) + if not stream.arrow_types_declared: + return {} + if schema is None: + schema = stream.arrow_schema() + return { + field.name: field.type + for field in schema + if field.name.startswith(constants.SOURCE_PREFIX) + } + + def settle_token_types( - batch: pa.RecordBatch, accepted: Mapping[str, pa.DataType] + batch: pa.RecordBatch, + accepted: Mapping[str, pa.DataType], + *, + check_empty: bool = False, ) -> 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. When the stream declares its type, even empty batches must match. Args: batch: A record batch of a stream's rows. - accepted: Each column's token type from the batches accepted so far. + accepted: Each column's declared type or its type from accepted batches. + check_empty: Check the types of empty batches against the declaration. Returns: 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: + if not batch.num_rows and not check_empty: 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: +def concatenate_batches( + batches: Sequence[pa.RecordBatch], + *, + declared_schema: pa.Schema | None = None, + declared_tokens: Mapping[str, pa.DataType] | None = None, +) -> 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. + System tags keep their declared fields, and each source-info column keeps the + type every batch declares. Batches with no rows contribute no values. Args: batches: Record batches of one stream's rows, in order. + declared_schema: The stream or channel declaration, or the first batch's + schema when no earlier declaration is available. + declared_tokens: Concrete token types the batches must match, when known. Returns: 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. """ + from orcapod.utils import arrow_utils + + settled = dict(declared_tokens or {}) + for batch in batches: + settled = settle_token_types(batch, settled, check_empty=bool(declared_tokens)) rows = [batch for batch in batches if batch.num_rows] if not rows: return None - settled: dict[str, pa.DataType] = {} - for batch in rows: - settled = settle_token_types(batch, settled) - prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) - opened: list[pa.RecordBatch] = [] + + if declared_schema is None: + declared_schema = batches[0].schema + aligned: list[pa.RecordBatch] = [] for batch in rows: 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) + field = arrow_utils.source_info_field(field.name, settled[field.name]) + if field.name.startswith(constants.SYSTEM_TAG_PREFIX): + if field.name not in declared_schema.names: + raise ValueError( + f"System-tag field {field.name!r} has no declaration." + ) + expected = declared_schema.field(field.name) + if not expected.equals( + field.with_nullable(expected.nullable), check_metadata=True + ): + raise ValueError( + f"System-tag field {field.name!r} differs from its declaration." + ) + if not expected.nullable and column.null_count: + raise ValueError( + f"Required system-tag field {field.name!r} contains nulls." + ) + field = expected columns.append(column) fields.append(field) - opened.append(pa.RecordBatch.from_arrays(columns, schema=pa.schema(fields))) - return pa.Table.from_batches(opened) + aligned.append(pa.RecordBatch.from_arrays(columns, schema=pa.schema(fields))) + return pa.Table.from_batches(aligned) class RowsOnRead: diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 75d0ea2a1..8bf696552 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -62,11 +62,8 @@ position, field flags, merged source info, system-tag value sorting, merged lists), with the sync path's helpers. Each of them works row by row, so applying them per batch of pairs gives the sync rows. -- **Field flags.** A batch's flags are the sync result's, except the system-tag and - source-info fields: a complete table decides those by its values (``StaticOutputOperatorPod._flag_by_values``, - the last step of F). The input layout declares these fields nullable and the stream - made from the batches settles them. Join's sorted system-tag fields are already - declared non-nullable when the kernel emits them. +- **Field flags.** Source-info fields are always nullable. Each kernel keeps the + declared system-tag nullability using the sync operator's rules. A kernel holds only what can still match: a side's rows are dropped when the other side closes (nothing can arrive to match them), and an arriving row is not kept once the @@ -79,7 +76,7 @@ from __future__ import annotations from abc import ABC, abstractmethod -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Callable, Collection, Mapping, Sequence from typing import Any, ClassVar import numpy as np @@ -93,14 +90,18 @@ _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, + repeated_system_tag_suffixes, ) from orcapod.core.operators.base import require_shared_arrow_type -from orcapod.core.operators.key_nullability import key_nullable from orcapod.core.operators.merge_join import ( MergeJoin, _merged_list, # pyright: ignore[reportPrivateUsage] # MergeJoin's one rule + _output_nullability, # pyright: ignore[reportPrivateUsage] # MergeJoin's one rule + _output_schema, # pyright: ignore[reportPrivateUsage] # MergeJoin's one rule _output_types, # pyright: ignore[reportPrivateUsage] # MergeJoin's one rule ) from orcapod.core.operators.rejoin import ( @@ -112,10 +113,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 @@ -131,25 +130,8 @@ _ROW = ("__streaming_left_row", "__streaming_right_row") -def _settled_by_values(schema: pa.Schema, *, system_tags: bool = True) -> pa.Schema: - """``schema`` with source-info and, optionally, system-tag fields nullable. - - What a kernel declares for the fields a complete table decides by its values - (``StaticOutputOperatorPod._flag_by_values``): one record batch of many cannot. - """ - prefixes = (constants.SOURCE_PREFIX,) - if system_tags: - prefixes = (*prefixes, constants.SYSTEM_TAG_PREFIX) - return pa.schema( - [ - field.with_nullable(True) if field.name.startswith(prefixes) else field - for field in schema - ] - ) - - def _row_built_zero_rows( - stream: StreamProtocol, *, keep_system_tag_flags: bool = False + stream: StreamProtocol, *, strip_system_tag_metadata: bool = False ) -> tuple[StreamProtocol, bool]: """``stream`` with no rows, as an input rebuilt from rows of it reads. @@ -158,7 +140,7 @@ def _row_built_zero_rows( Args: stream: An input stream (its description). - keep_system_tag_flags: Use the input's declared system-tag nullability. + strip_system_tag_metadata: Use the row-built fields of a tied Join input. Returns: The zero-row stream in the row-built form, and whether its Arrow types differ @@ -168,10 +150,10 @@ def _row_built_zero_rows( pod = StaticOutputOperatorPod zero = pod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the operators' one form of an input table = zero.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - row_built = pod._flag_by_values(row_built_columns(table, stream.keys())) # pyright: ignore[reportPrivateUsage] # F's last step - if keep_system_tag_flags: + row_built = row_built_columns(table, stream.keys()).replace_schema_metadata(None) + if strip_system_tag_metadata: fields = [ - field.with_nullable(table.schema.field(field.name).nullable) + field.remove_metadata() if field.name.startswith(constants.SYSTEM_TAG_PREFIX) else field for field in row_built.schema @@ -424,10 +406,13 @@ class StreamingJoinKernel(ABC): # How many inputs the operator takes; ``None`` for one or more. ARITY: ClassVar[int | None] = None - KEEP_SYSTEM_TAG_FLAGS: ClassVar[bool] = False def __init__( - self, operator: StaticOutputOperatorPod, inputs: Sequence[StreamProtocol] + self, + operator: StaticOutputOperatorPod, + inputs: Sequence[StreamProtocol], + *, + strip_system_tag_metadata: Collection[int] = (), ) -> None: if not inputs or (self.ARITY is not None and len(inputs) != self.ARITY): raise ValueError( @@ -441,19 +426,15 @@ def __init__( # form), and whether that differs from how it reads the input with none. built = [ _row_built_zero_rows( - stream, keep_system_tag_flags=self.KEEP_SYSTEM_TAG_FLAGS + stream, strip_system_tag_metadata=index in strip_system_tag_metadata ) - for stream in self.inputs + for index, stream in enumerate(self.inputs) ] self._zero_rows: tuple[StreamProtocol, ...] = tuple(z for z, _ in built) self._null_typed: tuple[bool, ...] = tuple(d for _, d in built) - # The schema of every batch of an input, in its row-built layout; the fields a - # complete table decides by values declared nullable. + # Every batch uses its input's declared fields in the row-built layout. self._layouts: tuple[pa.Schema, ...] = tuple( - _settled_by_values( - stream.as_table(columns=TRANSPORT_COLUMNS).schema, - system_tags=not self.KEEP_SYSTEM_TAG_FLAGS, - ) + stream.as_table(columns=TRANSPORT_COLUMNS).schema for stream in self._zero_rows ) self._closed: list[bool] = [False] * len(self.inputs) @@ -607,9 +588,10 @@ def _as_input_table(self, input_index: int, batch: pa.RecordBatch) -> pa.Table: """Return a batch's columns in the input's layout, under one schema per input. The schema is the input's row-built form (``null`` columns as ``large_string``, - ITL-1319), every system-tag and source-info field nullable (a complete table - decides those). A batch with no rows may also carry a column in the type of the - input's zero-row form (``null``): it holds no value. + ITL-1319), with nullable source-info fields and system-tag flags from the + input layout. A batch with no rows may also carry a column in the type of the + input's zero-row form (``null``). A token field can use that exception only + when the stream declares that token field as ``null``. """ layout = self._layouts[input_index] # Tokens that cannot make one table with the input's earlier batches are @@ -625,21 +607,23 @@ 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)] - ) + if not field.name.startswith(constants.SOURCE_PREFIX): continue - except RowBuiltFormUnavailable: - pass + declared = self.inputs[input_index].arrow_schema() + if field.name in declared.names and pa.types.is_null( + declared.field(field.name).type + ): + continue + # 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 " @@ -669,19 +653,14 @@ def _check_settled_token_types( def _emitted(self, tables: list[pa.Table]) -> list[pa.RecordBatch]: """The record batches of the output tables, holding ``output_columns``. - A source-info field is nullable until the complete table settles its flag - (``StaticOutputOperatorPod._flag_by_values``). System tags keep the field - from the kernel so Join's sorted tags retain their non-nullable declaration. + System tags keep the kernel's fields so Join's sorted tags retain their + declared nullability. """ batches: list[pa.RecordBatch] = [] for table in tables: if table.num_rows: self._emitted_any = True table = table.select(list(self.output_columns)).combine_chunks() - table = pa.Table.from_arrays( - table.columns, - schema=_settled_by_values(table.schema, system_tags=False), - ) batches.extend(table.to_batches()) return batches @@ -706,14 +685,21 @@ class StreamingJoin(StreamingJoinKernel): inputs: Its input streams, in call order. """ - KEEP_SYSTEM_TAG_FLAGS: ClassVar[bool] = True - def __init__(self, operator: Join, inputs: Sequence[StreamProtocol]) -> None: - super().__init__(operator, inputs) - self._join = operator - order = sorted( - range(len(inputs)), key=lambda i: inputs[i].pipeline_hash().to_hex() + hashes = [stream.pipeline_hash() for stream in inputs] + suffixes = operator._compute_system_tag_suffixes(hashes) # pyright: ignore[reportPrivateUsage] # Join's naming rule + repeated = repeated_system_tag_suffixes(suffixes) + super().__init__( + operator, + inputs, + strip_system_tag_metadata={ + i + for i, suffix in enumerate(suffixes) + if constants.BLOCK_SEPARATOR + suffix in repeated + }, ) + self._join = operator + order = sorted(range(len(inputs)), key=lambda i: hashes[i].to_hex()) self._position = {index: position for position, index in enumerate(order)} self._renames: dict[int, dict[str, str]] = {} self._links: list[_BinaryLink] = [] @@ -770,7 +756,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): @@ -884,9 +875,6 @@ def __init__(self, operator: MergeJoin, inputs: Sequence[StreamProtocol]) -> Non if f"{constants.SOURCE_PREFIX}{name}" in right_names } self._colliding = (set(left_data) & set(right_data)) - merged - self._captured = ( - set(left_tags) | set(left_data) | set(right_tags) | set(right_data) - ) # The left input's converter, as the sync path takes it. self._type_converter = StaticOutputOperatorPod._upstream_context( # pyright: ignore[reportPrivateUsage] # the operators' one rule left @@ -955,33 +943,18 @@ def _finish( {f.name: f.type for f in left_schema}, {f.name: f.type for f in right_schema}, ) - left_nullable = { - f.name: f.nullable for f in left_schema if f.name in self._captured - } - right_nullable = { - f.name: f.nullable for f in right_schema if f.name in self._captured - } - output_nullable = {**right_nullable, **left_nullable} - for name in self._shared_tags: - output_nullable[name] = key_nullable( - left_nullable[name], right_nullable[name] - ) - for name in self._colliding: - output_nullable[name] = False - source_name = f"{constants.SOURCE_PREFIX}{name}" - if source_name in output_nullable: - output_nullable[source_name] = False - # The columns the sync path does not capture (system tags and source info) are - # flagged by their values over the complete table; a batch declares them - # nullable (module docstring). - for schema in (right_schema, left_schema): - for field in schema: - if field.name not in self._captured: - output_nullable.setdefault(field.name, True) + output_nullable = _output_nullability( + left_schema, right_schema, self._shared_tags, self._colliding + ) 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}" @@ -1013,11 +986,11 @@ def _finish( joined = joined.add_column(index, base_name, column_data) else: joined = joined.drop_columns([suffixed_name]) - schema = pa.schema( - [ - pa.field(name, output_types[name], nullable=output_nullable[name]) - for name in joined.column_names - ] + schema = _output_schema( + joined.column_names, + output_types, + output_nullable, + (right_schema, left_schema), ) return pa.Table.from_arrays( [ diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 3e94bbe12..1ea7c3bda 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -22,6 +22,7 @@ from orcapod.channels import ChannelClosed from orcapod.core.operators.static_output_pod import ( + declared_token_types, settle_token_types, stream_from_batches, ) @@ -150,9 +151,9 @@ 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. + # Concrete token types, or the types settled by the populated batches. self._token_types: dict[str, pa.DataType] = {} + self._has_declared_tokens = False # The column order of the channel's batches: the first batch with rows'. self._order: list[str] | None = None self._changed = asyncio.Event() @@ -209,6 +210,8 @@ def _check_schema(self, batch: pa.RecordBatch) -> pa.RecordBatch: ) if not self._schema_known: self._schema = _description(self._stream) + self._token_types = declared_token_types(self._stream, self._schema) + self._has_declared_tokens = bool(self._token_types) self._schema_known = True schema = self._schema if schema is None: @@ -230,9 +233,23 @@ def _check_schema(self, batch: pa.RecordBatch) -> pa.RecordBatch: f"A record batch sent as {_named(self._stream)} does not have that " + f"stream's columns: {mismatch}." ) - token_types = settle_token_types(batch, self._token_types) + token_types = settle_token_types( + batch, self._token_types, check_empty=self._has_declared_tokens + ) self._schema = schema self._token_types = token_types + fields = [] + for field in batch.schema: + if field.name.startswith(constants.SYSTEM_TAG_PREFIX): + field = schema.field(field.name) + elif field.name.startswith(constants.SOURCE_PREFIX): + field = arrow_utils.source_info_field(field.name, field.type) + fields.append(field) + if any( + field.nullable != sent.nullable + for field, sent in zip(fields, batch.schema, strict=True) + ): + batch = pa.RecordBatch.from_arrays(batch.columns, schema=pa.schema(fields)) if batch.num_rows: if self._order is None: self._order = names @@ -377,7 +394,9 @@ def result(self) -> StreamProtocol: + "is a stream only once it is complete." ) if self._result is None: - self._result = stream_from_batches(self._stream, self._batches) + self._result = stream_from_batches( + self._stream, self._batches, declared_schema=self._schema + ) return self._result @@ -405,6 +424,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 +446,26 @@ 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. Source-info fields in + transit are nullable. The channel checks token types separately against the + concrete stream, or settles them across batches when no type is declared. """ 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,14 +477,7 @@ 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 - ): - return f"column {column.name!r} carries field metadata" - continue - if expected.nullable != column.nullable: + if not system_tag and expected.nullable != column.nullable: flags = {True: "nullable", False: "not nullable"} return ( f"column {column.name!r} is {flags[column.nullable]}, the stream's is " @@ -470,6 +495,8 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: if (expected.metadata or None) != (column.metadata or None) or not ( column.type.equals(carried, check_metadata=True) ): + if system_tag: + return f"column {column.name!r} carries field metadata that differs from its stream" return ( f"column {column.name!r} has field metadata {column.metadata} (or in " + f"its type {column.type}), the stream's is {expected.metadata}" @@ -562,18 +589,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/result_cache.py b/src/orcapod/core/result_cache.py index e341983bf..6186c0765 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -121,8 +121,8 @@ def _with_declared_token_columns( data_table: The output row, with the source-info columns it has. output_keys: The row's output keys, in order. carried: The schema of the row's own token columns - (``DataProtocol.source_info_table``), which keeps the Arrow type of a - token that ``data_table`` gives typed from its value. + (``DataProtocol.source_info_table``), checked alongside the token + fields in ``data_table`` for the required Arrow type. Returns: The row with one token column per output. 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 545078f9b..6795e9a16 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, @@ -309,7 +312,7 @@ def _unversioned_cache_path(self) -> tuple[str, ...]: def cache_path(self) -> tuple[str, ...]: """Cache table path: scoped to the source's content hash, then the layout version. - The layout version (``sdb_v1``) is always the last component, also when an + The layout version (``sdb_v2``) is always the last component, also when an explicit ``cache_path`` was given. """ return self._unversioned_cache_path + (SOURCE_DB_SCHEMA_VERSION,) @@ -320,8 +323,8 @@ def _account_for_stale_tables(self) -> None: Without an explicit ``cache_path`` the path holds a hash that can differ between builds, so caches of another layout are looked for anywhere under ``/source`` (ITL-954): those are caches of any source stored - there, and they are reported without a number of rows. They are not read and - are left unchanged. + there, and they are reported without a number of rows. With an explicit path, + list the layouts under that path. Older layouts are left untouched. """ if self._stale_tables_checked: return @@ -329,7 +332,7 @@ def _account_for_stale_tables(self) -> None: account_for_stale_tables( find_stale_tables( self._cache_database, - name_path=None + name_path=self._unversioned_cache_path if self._explicit_cache_path is not None else self._cache_path_prefix + ("source",), ), @@ -381,7 +384,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 @@ -441,9 +444,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) @@ -513,6 +514,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. @@ -544,12 +556,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: @@ -577,9 +586,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( @@ -749,9 +756,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 fc1eff7fb..a435b32fb 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 @@ -12,14 +13,21 @@ from orcapod.core.sources.stream_builder import SourceStreamBuilder from orcapod.core.sources.stream_builder import ( normalize_record_id_columns, + declare_native_custom_system_tags, require_custom_system_tags, + require_custom_system_tags_values, require_supported_nullable_types, ) +from orcapod.errors import InputValidationError from orcapod.utils import arrow_utils, polars_data_utils from orcapod.utils.schema_utils import _normalize_column_list if TYPE_CHECKING: - from polars._typing import FrameInitTypes + from polars._typing import ( + ArrowArrayExportable, + ArrowStreamExportable, + FrameInitTypes, + ) logger = logging.getLogger(__name__) @@ -65,10 +73,43 @@ def __init__( ) -> None: super().__init__(source_id=source_id, **kwargs) - df = pl.DataFrame(data) + arrow_input_schema = None + # Keep pandas and Polars on their native paths even if they export Arrow. + # For Arrow inputs, materialize once before Polars drops field metadata. + if not isinstance(data, (pd.DataFrame, pl.DataFrame, pl.Series)) and ( + hasattr(data, "__arrow_c_stream__") or hasattr(data, "__arrow_c_array__") + ): + # Like Polars, prefer the array export when both are available. + if hasattr(data, "__arrow_c_array__"): + batch = pa.record_batch(cast("ArrowArrayExportable", data)) + arrow_input = pa.Table.from_batches([batch]) + else: + arrow_input = pa.table(cast("ArrowStreamExportable", data)) + if schema is None: + require_custom_system_tags(arrow_input, system_tag_columns) + else: + require_custom_system_tags_values(arrow_input, system_tag_columns) + require_custom_system_tags( + arrow_input, system_tag_columns, schema=schema + ) + arrow_input_schema = arrow_input.schema + # 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] + for name in object_columns: + if name in system_tag_columns: + raise InputValidationError( + f"Custom system-tag column {name!r} has type {pl.Object}. " + "Declare a non-nullable string column with no null values " + "and convert its values to text first." + ) if object_columns: logger.info( f"Converting {len(object_columns)} object column(s) to Arrow format" @@ -92,15 +133,26 @@ def __init__( arrow_table = df.to_arrow() if schema is not None: require_supported_nullable_types(schema) - require_custom_system_tags(arrow_table, system_tag_columns, schema=schema) + if arrow_input_schema is None: + require_custom_system_tags_values(arrow_table, system_tag_columns) + require_custom_system_tags( + arrow_table, system_tag_columns, schema=schema + ) arrow_table = arrow_table.cast(schema) + elif arrow_input_schema is not None: + arrow_table = arrow_utils.restore_schema_nullability( + arrow_table, arrow_input_schema + ) else: - # Polars defaults all fields to nullable=True; infer the correct - # flags from the actual data before passing to the builder. + arrow_table = declare_native_custom_system_tags( + arrow_table, system_tag_columns + ) require_supported_nullable_types(arrow_table.schema) - arrow_table = arrow_table.cast( - arrow_utils.infer_schema_nullable(arrow_table) + # Native frames carry no Arrow nullability declarations. + inferred = arrow_utils.infer_schema_nullable( + arrow_table.drop_columns(list(system_tag_columns)) ) + arrow_table = arrow_utils.restore_schema_nullability(arrow_table, inferred) self._key_columns = normalize_record_id_columns(record_id_columns) or () builder = SourceStreamBuilder(self.data_context) diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index e49199372..7bb5019de 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -26,6 +26,7 @@ from orcapod.core.sources.source_ids import location_source_name from orcapod.core.sources.reload import keep_nullable_columns, same_rows from orcapod.core.sources.stream_builder import ( + require_custom_system_tags, require_supported_nullable_types, normalize_record_id_columns, SourceStreamBuilder, @@ -166,6 +167,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 +175,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 +236,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 ] ) @@ -243,9 +253,8 @@ def _read_table( [table.column(i) for i in range(table.num_columns)], schema=db_schema, ) - # No column info available — fall back to inferring nullable flags - # from actual data so columns without nulls are not spuriously marked - # nullable=True (Arrow's default). + # Validate nominated fields before fallback inference for ordinary columns. + require_custom_system_tags(table, self._system_tag_columns) require_supported_nullable_types(table.schema) inferred = table.cast(arrow_utils.infer_schema_nullable(table)) return inferred if held is None else keep_nullable_columns(inferred, held) diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index a2cee2919..1b00e7b05 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, ) @@ -861,9 +862,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/dict_source.py b/src/orcapod/core/sources/dict_source.py index 00f5c5f77..26eefb169 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -14,6 +14,7 @@ from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, + declare_native_custom_system_tags, require_supported_nullable_types, ) from orcapod.types import DataValue, SchemaLike @@ -96,6 +97,9 @@ def __init__( python_schema=data_schema, ) if data_schema is None: + arrow_table = declare_native_custom_system_tags( + arrow_table, system_tag_columns + ) # No explicit schema — infer nullable from actual values. # The type converter defaults all fields to nullable=True; derive # the correct flags here so the builder can trust the schema as-is. diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 107a42328..6157f0893 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, @@ -559,8 +560,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) @@ -1082,8 +1084,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 c72518e59..441d9fb88 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -18,6 +18,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, @@ -170,6 +171,7 @@ def bind(self, source: SourceProtocol) -> None: if errors: raise ValueError(f"Cannot bind source to SourceProxy: {'; '.join(errors)}") + self._validate_delegate_schema(source) self._delegate = source # Another source's data now stands behind the proxy (ITL-1102). self._update_modified_time() @@ -274,6 +276,11 @@ def keys( # Data access — delegate if bound, raise otherwise # ------------------------------------------------------------------------- + @staticmethod + def _validate_delegate_schema(delegate: SourceProtocol) -> None: + """Validate hidden system-tag fields without fetching the delegate's rows.""" + validate_source_table(delegate.head(0, columns={"system_tags": True}).table) + def _require_delegate(self) -> SourceProtocol: """Return the delegate or raise if not bound.""" if self._delegate is None: @@ -291,10 +298,19 @@ 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() + self._validate_delegate_schema(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, @@ -302,7 +318,10 @@ 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) + delegate = self._require_delegate() + table = delegate.as_table(columns=columns, all_info=all_info) + self._validate_delegate_schema(delegate) + return validate_source_table(table) def head( self, @@ -313,9 +332,10 @@ 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 - ) + self._validate_delegate_schema(self._delegate) + 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 29cf32b9b..743de64aa 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -35,24 +35,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) @@ -62,22 +50,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 @@ -90,6 +123,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 @@ -109,6 +147,74 @@ def require_custom_system_tags( ) +def declare_native_custom_system_tags( + table: pa.Table, names: Collection[str] +) -> pa.Table: + """Declare native custom system tags as required large strings. + + Args: + table: A table inferred from native Python values. + names: The columns nominated as custom system tags. + + Returns: + The table with nominated fields declared as non-nullable large strings. + + Raises: + InputValidationError: If a nominated column is not text or contains nulls. + """ + if not names: + return table + require_custom_system_tags_values(table, names) + schema = pa.schema( + [ + pa.field( + field.name, + pa.large_string(), + nullable=False, + metadata=field.metadata, + ) + if field.name in names + else field + for field in table.schema + ], + metadata=cast(dict[bytes | str, bytes | str] | None, table.schema.metadata), + ) + return table.cast(schema) + + +def require_custom_system_tags_values(table: pa.Table, names: Collection[str]) -> None: + """Validate values and types before declaring native custom system tags. + + Args: + table: A table inferred from native Python values. + names: The columns nominated as custom system tags. + + Raises: + ValueError: If a nominated column is missing. + InputValidationError: If a nominated column is not text or contains nulls. + """ + if missing := sorted(set(names) - set(table.column_names)): + raise ValueError( + f"system_tag_columns not found in table: {missing}. " + f"Available columns: {sorted(table.column_names)}" + ) + for name in names: + field = table.schema.field(name) + require_system_tag_without_field_metadata(field) + has_nulls = table.column(name).null_count > 0 + if has_nulls or not ( + pa.types.is_string(field.type) + or pa.types.is_large_string(field.type) + or pa.types.is_string_view(field.type) + ): + raise InputValidationError( + f"Custom system-tag column {name!r} has type {field.type} " + f"({'contains null values' if has_nulls else 'non-text values'}). " + "Declare a non-nullable string column with no null values " + "and convert its values to text first." + ) + + def normalize_record_id_columns( record_id_columns: str | Collection[str] | None, ) -> tuple[str, ...] | None: diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index df49eaff6..9727f3a8b 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( @@ -442,6 +453,10 @@ def clear_cache(self) -> None: """ self._cached_elements = None + def _iter_tags(self, table: pa.Table) -> Iterator[Tag]: + """Build this stream's tags in table order.""" + return Tag.rows_of(table, self.data_context) + def iter_data(self) -> Iterator[tuple[TagProtocol, Data]]: """Iterates over the rows of the stream as ``(Tag, Data)`` pairs. @@ -474,11 +489,7 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, Data]]: # The table is prepared once for all of its rows (ITL-1348): building # ``Tag(row)`` and ``Data(row)`` from one-row slices normalized every row # three times and split its columns again. - tags = ( - Tag.rows_of(rows.select(tag_columns), self.data_context) - if tag_columns - else None - ) + tags = self._iter_tags(rows.select(tag_columns)) if tag_columns else None for data in Data.rows_of(rows.select(data_columns), self.data_context): # A fresh empty tag per row, so rows never share one object. tag = next(tags) if tags is not None else Tag({}) diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 78d6ae944..1d0a7d8e3 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -87,14 +87,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. @@ -274,13 +270,8 @@ 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. - - 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. + 4. Keep the declared system-tag fields. Strip top-level metadata from + source-info fields while preserving their types (``row_built_provenance``). Args: table: A table of user tags, system tags, data and source info. @@ -290,73 +281,41 @@ 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. + Rows keep the declared token types, including nested field metadata. + The top-level source-info fields are nullable and carry no field metadata. 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 = [ + arrow_utils.source_info_field(field.name, field.type) + 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) ), @@ -444,12 +403,9 @@ def stream_arrow_schema( stream that cannot type itself without rows answers with its Python 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 + ``schema_requires_io``) answers with no column. Source-info fields are nullable + and keep their declared token type. System-tag fields keep their flags and + metadata. A ``null`` column keeps the zero-row ``null`` type; rows carry ``large_string`` (ITL-1319). ITL-1307 later reads it from ``Schema`` instead, here. @@ -502,19 +458,16 @@ def stream_arrow_schema( ) for name in data_schema: table = table.append_column( - pa.field(f"{constants.SOURCE_PREFIX}{name}", pa.large_string()), + arrow_utils.source_info_field( + f"{constants.SOURCE_PREFIX}{name}", pa.large_string() + ), pa.array([], pa.large_string()), ) # The rows' keys: the data in the order of the stream's table (a poller that # fetched its columns in another order than it declares lists them so). 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): - schema = schema.set(index, field.with_nullable(True)) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized - return schema + return row_built_provenance(table.select(names)).schema class CompleteStreamFeed: @@ -565,13 +518,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/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index c8c72abd6..ebd16346a 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -187,12 +187,10 @@ def arrow_schema(self) -> "pa.Schema": tags, system tags, data, source info; data and source info in data-key order), with the Arrow types, nullability and field metadata of the rows; no context and no meta column (ITL-1347). Known without reading, computing or polling a row. - Three properties are decided by the values of a complete table, not by the - description: whether a system-tag or source-info field is nullable (stated - nullable here), and a source-info field's type (stated as the declared token - type; a list of ``None`` or of empty lists shows fewer levels, so consumers must - not rely on it). And a ``null`` column keeps the ``null`` type a zero-row table - has (rows carry ``large_string``; ITL-1319). + System-tag fields keep their declared flags and metadata. Source-info fields + are nullable and keep their declared token types, including list layers and + nested field declarations. A ``null`` column keeps the ``null`` type a + zero-row table has (rows carry ``large_string``, ITL-1319). Returns: The declared Arrow schema. diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 866298130..c04b7f286 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -330,12 +330,12 @@ def _table_of_rows( ) if column_config.context: parts.append(pa.schema([context_key_field()]).empty_table()) - # A row's data table declares every source-info field nullable - # (``Data.as_table``), and the rows' table is those tables concatenated. source_table = typed.select(source_info) - nullable = pa.schema([f.with_nullable(True) for f in source_table.schema]) - # Same arrays, new field flags: no cast. - parts.append(pa.Table.from_arrays(source_table.columns, schema=nullable)) + source_schema = pa.schema( + arrow_utils.source_info_field(field.name, field.type) + for field in source_table.schema + ) + parts.append(pa.Table.from_arrays(source_table.columns, schema=source_schema)) full = arrow_utils.hstack_tables(*parts) else: # No rows and no Arrow types without them: the declared columns, with the diff --git a/src/orcapod/system_constants.py b/src/orcapod/system_constants.py index fe3dbbda4..25cb8632d 100644 --- a/src/orcapod/system_constants.py +++ b/src/orcapod/system_constants.py @@ -31,8 +31,8 @@ PIPELINE_DB_SCHEMA_VERSION = "pdb_v2" RESULT_DB_SCHEMA_VERSION = "rdb_v1" TRACKING_DB_SCHEMA_VERSION = "tdb_v2" -OPERATOR_DB_SCHEMA_VERSION = "odb_v2" -SOURCE_DB_SCHEMA_VERSION = "sdb_v1" +OPERATOR_DB_SCHEMA_VERSION = "odb_v3" +SOURCE_DB_SCHEMA_VERSION = "sdb_v2" STORED_DATA_CONTEXT = "data_context" # The data context of everything Orcapod wrote before v0.3. Its manifest is not shipped: # stored rows that carry this key, and tables without a data context column, belong to it. diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 57b5115a5..c69d5ccdb 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -1053,6 +1053,64 @@ def _source_info_arrow_type_and_depth_known( return pa.large_list(fallback), False +def source_info_field(name: str, kind: "pa.DataType") -> "pa.Field[Any]": + """Declare a nullable Arrow field for a source-info token. + + Stream construction separately validates token values. Only string leaves + may be null. Every list layer of a list-valued token must be present. + + Args: + name: The prefixed column name. + kind: The token's Arrow type, including any list item fields. + + Returns: + A field whose top-level nullability is always true. + """ + return pa.field(name, kind, nullable=True) + + +def source_info_replacement( + token: SourceInfoValue, kind: "pa.DataType", num_rows: int = 1 +) -> "pa.Array[Any]": + """Write a Python replacement under an existing token type. + + Args: + token: The replacement token. + kind: The declared Arrow type, including any list item fields. + num_rows: The number of rows to fill with the replacement. + + Returns: + An array of the declared type. + + Raises: + pa.ArrowTypeError: If a token cannot fit the declaration, also a null + given for a list type: a list token is never null. + """ + + def require_fit(value: SourceInfoValue, data_type: "pa.DataType") -> None: + """Check nested nullability and reject strings that Arrow would split.""" + if not isinstance( + data_type, (pa.ListType, pa.LargeListType, pa.FixedSizeListType) + ): + return + if value is None: + raise pa.ArrowTypeError( + f"A list token is never null: no null replacement for type {data_type}" + ) + if not isinstance(value, list): + raise pa.ArrowTypeError(f"Expected a list token for type {data_type}") + child = data_type.value_field + for item in value: + if item is None and not child.nullable: + raise pa.ArrowTypeError( + f"Token item {child.name!r} does not allow nulls" + ) + require_fit(item, child.type) + + require_fit(token, kind) + return pa.array([token] * num_rows, type=kind) + + def prepare_prefixed_columns( table: "pa.Table | pa.RecordBatch", prefix_info: Collection[str] @@ -1093,8 +1151,7 @@ def prepare_prefixed_columns( assigned to any prefix group, and ``prefixed_tables`` is a dictionary mapping each recognized prefix to its constructed ``pyarrow.Table``. - Nullability is preserved from the source columns for columns copied - directly from ``table``. + Ordinary fields keep their nullability. Source-info fields are always nullable. """ all_prefix_info = {} if isinstance(prefix_info, Mapping): @@ -1134,7 +1191,6 @@ def prepare_prefixed_columns( prefixed_column_names = defaultdict(list) prefixed_columns = defaultdict(list) - prefixed_column_nullables: dict[str, list[bool]] = defaultdict(list) target_column_names = [ c @@ -1146,7 +1202,6 @@ def prepare_prefixed_columns( for prefix, value_lut in all_prefix_info.items(): target_prefixed_column_names = prefixed_column_names[prefix] target_prefixed_columns = prefixed_columns[prefix] - target_nullables = prefixed_column_nullables[prefix] for col_name in target_column_names: prefixed_col_name = f"{prefix}{col_name}" @@ -1158,35 +1213,25 @@ def prepare_prefixed_columns( value = value_lut if value is not None: - # Concrete token supplied as a Python value — column is never - # null. No Arrow type is attached, so the source-info rule + # No Arrow type is attached, so the source-info rule # types it (a list token, nested or not, keeps its depth). # Every caller passes source-info tokens here. token = cast(SourceInfoValue, value) column_values = pa.array( [token] * num_rows, type=source_info_arrow_type(token) ) - col_nullable = False elif col_name in existing_columns: - # Pass-through from the source table — inherit its nullable flag. existing_col = table[prefixed_col_name] if existing_col.type == pa.string(): # Convert to large_string column_values = pa.compute.cast(existing_col, pa.large_string()) # type: ignore else: column_values = existing_col - col_nullable = table.schema.field(prefixed_col_name).nullable else: # No value available — column is genuinely all-null. column_values = pa.array([None] * num_rows, type=pa.large_string()) - col_nullable = True - # Safety: never declare non-nullable when the data actually has nulls - # (e.g. a pass-through column from a source that was non-nullable can - # gain nulls after a join populates only one side of the result). - col_nullable = col_nullable or bool(column_values.null_count > 0) target_prefixed_column_names.append(prefixed_col_name) target_prefixed_columns.append(column_values) - target_nullables.append(col_nullable) # Step 3: Create the final table, preserving nullable flags from the source table data_fields = [table.schema.field(name) for name in data_column_names] @@ -1196,11 +1241,9 @@ def prepare_prefixed_columns( for prefix in all_prefix_info: schema = pa.schema( [ - pa.field(name, col.type, nullable=nullable) - for name, col, nullable in zip( - prefixed_column_names[prefix], - prefixed_columns[prefix], - prefixed_column_nullables[prefix], + source_info_field(name, col.type) + for name, col in zip( + prefixed_column_names[prefix], prefixed_columns[prefix], strict=True ) ] ) @@ -1325,6 +1368,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. @@ -1912,11 +1967,8 @@ def add_source_info( [f"{source_val}::{col}" for source_val in base_source], type=pa.large_string(), ) - # Source info columns are always computed strings, never null. table = table.append_column( - pa.field( - f"{constants.SOURCE_PREFIX}{col}", pa.large_string(), nullable=False - ), + source_info_field(f"{constants.SOURCE_PREFIX}{col}", col_source.type), col_source, ) diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 37be8b8aa..d9d70fba5 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -15,6 +15,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.""" @@ -838,6 +843,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_node_async_execute.py b/tests/test_channels/test_node_async_execute.py index bdec92872..a581f602b 100644 --- a/tests/test_channels/test_node_async_execute.py +++ b/tests/test_channels/test_node_async_execute.py @@ -924,7 +924,13 @@ def double(x: int) -> int: { "id": pa.array([0, 1, 2], type=pa.int64()), "result": pa.array([0, 2, 4], type=pa.int64()), - } + }, + schema=pa.schema( + [ + pa.field("id", pa.int64(), nullable=False), + pa.field("result", pa.int64(), nullable=False), + ] + ), ) stage1_stream = ArrowTableStream(stage1_table, tag_columns=["id"]) op = SelectDataColumns(["result"]) diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index cceaf6d05..df37f0765 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, ) @@ -73,6 +72,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.""" @@ -103,6 +157,21 @@ def source(n: int = 7, source_id: str = "events") -> ArrowTableSource: ) +def shaped_source(kind: pa.DataType, n: int = 2) -> ArrowTableStream: + """Return a stream whose amplitude and token have the declared list layers.""" + from tests.token_shapes import nested_value, with_token_column + + table = with_token_column( + source(n).as_table(columns=ALL), + "amplitude", + [nested_value("seed", kind)] * n, + kind, + ) + return ArrowTableStream( + table, tag_columns=["subject", "trial"], data_tags=["trial"] + ) + + 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] @@ -2098,7 +2167,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() @@ -2148,24 +2217,48 @@ 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 batch with no rows has no token and fixes no type. + # 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"]]]], + ), + # Without a declaration, an empty batch does not settle the token type. "zero_rows_first": ( [(0, [], TOKEN), (0, [["a"]], TOKENS), (1, [["b"]], TOKENS)], TOKENS, @@ -2174,13 +2267,19 @@ 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) + if case == "zero_rows_first": + stream = _UntypedStream( + stream.as_table(columns=ALL), + tag_columns=["subject", "trial"], + data_tags=["trial"], + ) (batch,) = batches_of(stream) - parts, settled, tokens = SETTLING_CASES[case] async def write() -> tuple[Any, Any]: output = OutputChannel(stream) @@ -2193,31 +2292,54 @@ 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 = _UntypedStream( + shaped_source(first).as_table(columns=ALL), + tag_columns=["subject", "trial"], + data_tags=["trial"], + ) (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: @@ -2234,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) @@ -2246,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) @@ -2254,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: @@ -2268,3 +2391,124 @@ async def read() -> Any: output = run(read) assert getattr(output, ROW_BUILT_OUTPUT, False) assert same(output.as_table(columns=ALL), R(node)) + + +def test_channel_keeps_first_system_tag_declaration_and_entry_id() -> None: + """A later batch containing a null cannot change an earlier row's entry ID.""" + from orcapod.core import row_ids + + name = "_tag_custom" + field = pa.field(name, pa.large_string(), metadata={b"owner": b"test"}) + table = pa.Table.from_arrays( + [pa.array([1, 2]), pa.array([7, 8]), pa.array(["kept", None], field.type)], + schema=pa.schema([pa.field("k", pa.int64()), pa.field("x", pa.int64()), field]), + ) + stream = _UntypedStream(table, tag_columns=["k"]) + first, second = batches_of(ArrowTableStream(table, tag_columns=["k"]), rows=1) + + async def read(pieces: Sequence[pa.RecordBatch]): + channel = OutputChannel(stream) + for batch in pieces: + await channel.send(batch) + await channel.close() + outputs = [channel.result(), await channel.open_reader().to_stream()] + ids = [] + for result in outputs: + assert isinstance(result, ArrowTableStream) + tag, data = next(result.iter_data()) + declared = result.as_table(columns=ALL).schema.field(name) + assert declared.equals(field, check_metadata=True) + ids.append(row_ids.entry_id(result.data_context.arrow_hasher, tag, data)) + return ids + + assert run(lambda: read([first])) == run(lambda: read([first, second])) + + +@pytest.mark.parametrize("num_rows", [0, 1]) +@pytest.mark.parametrize("wrong_type", [TOKEN, TOKENS]) +def test_concrete_channel_refuses_first_batch_with_a_different_token_type( + num_rows: int, wrong_type: pa.DataType +) -> None: + """A concrete stream's declared token type also applies to its first batch.""" + from orcapod.core.operators.static_output_pod import SourceInfoTypesDisagree + + declared = pa.large_list(pa.field("leaf", TOKEN, metadata={b"kind": b"token"})) + stream = ArrowTableStream( + pa.table( + { + "amplitude": pa.array([[1]], pa.large_list(pa.int64())), + "_source_amplitude": pa.array([["old"]], declared), + } + ), + tag_columns=[], + ) + (batch,) = batches_of(stream) + values = ["wrong"] if wrong_type == TOKEN else [["wrong"]] + wrong = _with_amplitude_tokens(batch, 0, values[:num_rows], wrong_type) + with pytest.raises(SourceInfoTypesDisagree, match="_source_amplitude"): + _ = stream_from_batches(stream, [wrong]) + + async def write() -> None: + output = OutputChannel(stream) + reader = output.open_reader() + with pytest.raises(SourceInfoTypesDisagree, match="_source_amplitude"): + await output.send(wrong) + await output.send(batch) + await output.close() + delivered = await reader.receive() + assert delivered is not None + for schema in ( + delivered.schema, + output.result().arrow_schema(), + ): + assert schema.field("_source_amplitude").equals( + stream.arrow_schema().field("_source_amplitude"), check_metadata=True + ) + + run(write) + + +def test_unbound_slot_settles_only_its_provisional_token_type() -> None: + """An unbound slot's scalar token description can settle to a list declaration.""" + from orcapod.core.operators.static_output_pod import SourceInfoTypesDisagree + + declared = pa.large_list(pa.field("leaf", TOKEN, metadata={b"kind": b"token"})) + tags, data = shaped_source(declared).output_schema() + slot = SourceJobNode(name="events", tag_schema=tags, data_schema=data) + assert slot.bound_source is None and not slot.arrow_types_declared + provisional = slot.arrow_schema() + assert provisional.field("_source_amplitude").type == TOKEN + (batch,) = batches_of(shaped_source(declared)) + system_columns = iter( + batch.column(index) + for index, field in enumerate(batch.schema) + if field.name.startswith("_tag_") + ) + index = provisional.get_field_index("_source_amplitude") + declared_field = batch.schema.field("_source_amplitude") + schema = provisional.set(index, declared_field) + settled = pa.RecordBatch.from_arrays( + [ + next(system_columns) + if field.name.startswith("_tag_") + else batch.column(batch.schema.get_field_index(field.name)) + for field in schema + ], + schema=schema, + ) + + async def write() -> None: + output = OutputChannel(slot) + reader = output.open_reader() + await output.send(settled) + with pytest.raises(SourceInfoTypesDisagree, match="_source_amplitude"): + await output.send(_with_amplitude_tokens(settled, 0, ["wrong"], TOKEN)) + await output.close() + for result in (output.result(), await reader.to_stream()): + assert ( + result.arrow_schema() + .field("_source_amplitude") + .equals(declared_field, check_metadata=True) + ) + + run(write) diff --git a/tests/test_channels/test_record_batch_review_findings.py b/tests/test_channels/test_record_batch_review_findings.py index 2a2902143..a170a75e3 100644 --- a/tests/test_channels/test_record_batch_review_findings.py +++ b/tests/test_channels/test_record_batch_review_findings.py @@ -378,15 +378,22 @@ async def write() -> None: asyncio.run(write()) -def _list_token_stream() -> ArrowTableStream: - """A raw stream whose source-info column holds list tokens.""" +def _list_token_stream(token_type: pa.DataType | None = None) -> ArrowTableStream: + """A raw stream whose source-info column holds list tokens. + + Args: + token_type: The token column's declared type; a plain large list of + strings when not given. + """ return 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()) + [["s::r0::x"], ["s::r1::x"]], + token_type or pa.large_list(pa.large_string()), ), } ), @@ -394,26 +401,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 +424,80 @@ async def write() -> None: asyncio.run(write()) +def test_a_token_columns_item_metadata_is_part_of_its_declared_type() -> None: + """Restated for ITL-1557 (fifth review of PR #607, finding 1; first restated + for ITL-1491, review of PR #601, P2-4): metadata on a token list's item field + is part of the column's declared type. A stream that declares it keeps it, in + its table and in its record batches, and the stream an output channel produces + declares it too. The stream's declaration binds every batch, the first one + included: a batch without the metadata is refused whenever it is sent, and a + batch with it is taken.""" + from orcapod.core.operators.static_output_pod import SourceInfoTypesDisagree + + plain_type = pa.large_list(pa.large_string()) + tagged_type = _with_metadata_inside(plain_type) + stream = _list_token_stream(tagged_type) + (tagged,) = batches_of(stream) + index = next( + i for i, n in enumerate(tagged.schema.names) if n.startswith("_source_") + ) + field = tagged.schema.field(index) + # The declared stream and its batches hold the item metadata. + declared = stream.as_table(columns={"source": True}).schema.field(field.name) + assert declared.type.equals(tagged_type, check_metadata=True) + assert field.type.equals(tagged_type, check_metadata=True) + plain = tagged.set_column( + index, field.with_type(plain_type), tagged.column(index).cast(plain_type) + ) + + async def write() -> pa.Table: + output = OutputChannel(stream) + with pytest.raises(SourceInfoTypesDisagree, match=field.name): + await output.send(plain.slice(0, 1)) + await output.send(tagged.slice(0, 1)) + with pytest.raises(SourceInfoTypesDisagree, match=field.name): + await output.send(plain.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 + + +def test_a_batch_may_not_add_item_metadata_to_a_declared_token_type() -> None: + """Fifth review of PR #607, finding 1: a concrete stream's declared token type + binds its first batch too, item metadata included. A first batch whose token + item field carries metadata the stream does not declare is refused (it used to + be taken, and replaced the stream's declared type), and the stream's own batch + is then taken with the declared type.""" + 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) + with pytest.raises(SourceInfoTypesDisagree, match=field.name): + await output.send(tagged) + await output.send(batch) + await output.close() + return output.result().as_table(columns={"source": True}) + + result = asyncio.run(write()) + assert result.schema.field(field.name).type.equals(field.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 +807,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 +826,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 +849,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) == [] @@ -856,6 +941,67 @@ async def write() -> None: asyncio.run(write()) +def test_a_system_tag_cannot_hold_a_null_in_a_required_struct_child() -> None: + name = "_tag_extra" + kind = pa.struct( + [pa.field("required", pa.int64(), nullable=False, metadata={b"unit": b"m"})] + ) + stream = ArrowTableStream( + pa.table( + { + "k": [1, 2], + "x": [3, 4], + name: pa.array([{"required": 1}, None], type=kind), + } + ), + tag_columns=["k"], + ) + (good,) = pa.Table.from_batches(batches_of(stream)).combine_chunks().to_batches() + index = good.schema.get_field_index(name) + bad = good.set_column( + index, + good.schema.field(index), + pa.array([{"required": None}, None], type=kind), + ) + + async def write() -> None: + output = OutputChannel(stream) + with pytest.raises(ValueError, match=r"_tag_extra.*required.*not nullable"): + await output.send(bad) + await output.send(good) + await output.close() + result = output.result().as_table(columns={"system_tags": True}) + assert result.schema.field(name).equals( + good.schema.field(name), check_metadata=True + ) + assert result[name].to_pylist() == [{"required": 1}, None] + + asyncio.run(write()) + + +def test_empty_channel_result_keeps_accepted_arrow_schema( + monkeypatch: pytest.MonkeyPatch, +) -> None: + field = pa.field("x", pa.int8(), nullable=True, metadata={b"unit": b"m"}) + table = pa.schema([field]).empty_table() + stream = ArrowTableStream(table, tag_columns=[]) + monkeypatch.setattr(stream, "_typed_zero_row_table", lambda: None) + batch = pa.RecordBatch.from_arrays([pa.array([], pa.int8())], schema=table.schema) + + async def run() -> None: + output = OutputChannel(stream) + await output.send(batch) + await output.close() + assert ( + output.result() + .as_table() + .schema.field("x") + .equals(field, check_metadata=True) + ) + + asyncio.run(run()) + + # --- CodeRabbit on PR 510, final pass (365f2a08) ------------------------------------ @@ -866,7 +1012,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 +1028,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 +1053,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,36 +1193,45 @@ 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 (two list levels, then one) 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) + deep = _token_batch(clean, [[["a"]], [["b"]]], DEEP_TOKENS).slice(0, 1) + shallow = _token_batch(clean, [[], []], SHALLOW_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"]]] + + sent: list[pa.RecordBatch] = [] + + class ObservedOutput(OutputChannel): + async def send(self, batch: pa.RecordBatch) -> None: + await super().send(batch) + sent.append(batch) async def go() -> OutputChannel: - output = OutputChannel(op(clean)) + output = ObservedOutput(op(clean)) with pytest.raises(SourceInfoTypesDisagree): await op.async_execute_batches( - [InputChannel(clean, _ListFeed([shallow, deep]))], output + [InputChannel(clean, _ListFeed([deep, shallow]))], output ) + assert [batch.column("k").to_pylist() for batch in sent] == [[1]] return output output = asyncio.run(go()) @@ -1080,12 +1248,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 +1273,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 +1306,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/data_function/test_result_token_column_type.py b/tests/test_core/data_function/test_result_token_column_type.py index f8e8f81c8..e7158cc78 100644 --- a/tests/test_core/data_function/test_result_token_column_type.py +++ b/tests/test_core/data_function/test_result_token_column_type.py @@ -532,8 +532,7 @@ def test_a_typed_arrow_token_column_is_refused_by_the_type_the_row_carries( stored_first: bool, tmp_path: Path, ) -> None: - """Review finding 2: ``as_table`` types a token from its value; the row's own - token columns (``source_info_table``) are what is checked.""" + """Reject the Arrow type the row carries, even if a view normalizes it.""" type_text, array = TYPED_TOKENS[kind] function = _function(_database(backend, tmp_path), keys) if stored_first: @@ -576,10 +575,6 @@ def test_a_small_string_arrow_token_column_is_stored_as_large_string( assert found.source_info() == dict.fromkeys(keys, "custom::id::small") -# A NULL token in a column declared with another type: a row gives it as a -# ``large_string`` null on every view today (``source_info_table``: "a null token is a -# large_string null whatever type its column declares"), so the declared type never -# reaches ``ResultCache.store``. NULL_TYPED_TOKENS: dict[str, pa.Array[Any]] = { "list": pa.nulls(1, pa.large_list(pa.large_string())), "dictionary": pa.array([None], type=pa.large_string()).dictionary_encode(), @@ -587,46 +582,19 @@ def test_a_small_string_arrow_token_column_is_stored_as_large_string( } -@pytest.mark.xfail( - strict=True, - raises=pytest.fail.Exception, - reason=( - "ITL-1563, open until PR 607: a row gives a null token as a large_string " - "null whatever Arrow type its column declares, so the declared type of an " - "all-null token column does not reach ResultCache.store and the row is " - "stored with a null large_string token. PR 607 makes a row keep its token " - "columns' Arrow types; remove this mark then." - ), -) @pytest.mark.parametrize("keys", KEY_ORDERS) @pytest.mark.parametrize("kind", sorted(NULL_TYPED_TOKENS)) def test_a_null_token_in_a_typed_arrow_column_is_refused( keys: tuple[str, ...], kind: str ) -> None: + """The Arrow type survives table transport even when the token is null.""" function = _function(InMemoryArrowDatabase(), keys) - output = _table_output(keys, {"total": NULL_TYPED_TOKENS[kind]}) - with pytest.raises(InputValidationError): + array = NULL_TYPED_TOKENS[kind] + output = _table_output(keys, {"total": array}) + with pytest.raises(InputValidationError) as error: function.record_data(Data({"x": 3, "y": 4}), output) - - -@pytest.mark.parametrize("keys", KEY_ORDERS) -@pytest.mark.parametrize("kind", sorted(NULL_TYPED_TOKENS)) -def test_a_null_token_in_a_typed_arrow_column_is_stored_as_a_large_string_null( - keys: tuple[str, ...], kind: str -) -> None: - """What the open route does today: the value and the stored type are sound.""" - function = _function(InMemoryArrowDatabase(), keys) - output = _table_output(keys, {"total": NULL_TYPED_TOKENS[kind]}) - function.record_data(Data({"x": 3, "y": 4}), output) - assert function.call(Data({"x": 1, "y": 2})) is not None - table = function.get_all_cached_outputs() - assert table is not None and table.num_rows == 2 - for key in keys: - field = table.schema.field(f"{constants.SOURCE_PREFIX}{key}") - assert (field.type, field.nullable) == (pa.large_string(), True) - found = function.get_cached_output_for_data(Data({"x": 3, "y": 4})) - assert found is not None - assert found.source_info()["total"] is None + assert f"'{constants.SOURCE_PREFIX}total' is {array.type}" in str(error.value) + assert function.get_all_cached_outputs() is None @pytest.mark.parametrize("keys", KEY_ORDERS) diff --git a/tests/test_core/data_tags/test_operator_node_storage.py b/tests/test_core/data_tags/test_operator_node_storage.py index e567cd66e..e76755f53 100644 --- a/tests/test_core/data_tags/test_operator_node_storage.py +++ b/tests/test_core/data_tags/test_operator_node_storage.py @@ -100,7 +100,7 @@ def _join_job( def _operator_table(store: ArrowDatabaseProtocol) -> pa.Table: - """The one stored operator cache table (``odb_v2``).""" + """The one stored operator cache table (``odb_v3``).""" paths = [p for p in store.list_table_paths() if p[-1] == OPERATOR_DB_SCHEMA_VERSION] assert len(paths) == 1, paths table = store.get_all_records(paths[0]) @@ -428,3 +428,207 @@ def unstorable_column_reason( with_data_tags.attach_databases( pipeline_database=database, cache_mode=CacheMode.OFF ) + + +@STORES +@pytest.mark.parametrize("mode", ["sync", "async", "run"]) +@pytest.mark.parametrize("mixed_first", [False, True]) +@pytest.mark.parametrize("nested", [False, True]) +def test_operator_storage_keeps_one_declared_token_schema( + make_store: Callable[[Path], ArrowDatabaseProtocol], + tmp_path: Path, + mode: str, + mixed_first: bool, + nested: bool, +) -> None: + """A repeated row has the same stored key in both batches.""" + import asyncio + + from orcapod.channels import Channel + from orcapod.operators import Filter + from orcapod.streams import ArrowTableStream + from orcapod.types import col + + op_filter = Filter(col("k") >= 0) + origin = op.sources.DictSource( + [{"k": 0, "x": 1}], tag_columns=["k"], tag_only_columns=True, source_id="seed" + ) + schema = pa.schema( + [ + pa.field("k", pa.int64(), nullable=False), + pa.field( + "x", + pa.large_list(pa.large_list(pa.int64())) if nested else pa.int64(), + nullable=False, + ), + pa.field( + "_source_x", + pa.large_list(pa.large_list(pa.large_string())) + if nested + else pa.large_string(), + ), + ] + ) + + def stream(mixed: bool) -> ArrowTableStream: + rows: list[dict[str, int | str | list[list[int]] | list[list[str]] | None]] = [ + { + "k": 0, + "x": [[1]] if nested else 1, + "_source_x": [["seed::0::x"]] if nested else "seed::0::x", + } + ] + if mixed: + rows.append( + { + "k": 1, + "x": [[2]] if nested else 2, + "_source_x": [] if nested else None, + } + ) + return ArrowTableStream( + pa.Table.from_pylist(rows, schema=schema), + tag_columns=["k"], + producer=op_filter, + upstreams=(origin,), + ) + + class Snapshots(ArrowTableStream): + """Keep the producer identity while a source snapshot is replaced.""" + + current: ArrowTableStream = stream(mixed_first) + + def as_table(self, **kwargs): + return self.current.as_table(**kwargs) + + def iter_data(self): + return self.current.iter_data() + + stream_value = Snapshots( + schema.empty_table(), tag_columns=["k"], producer=op_filter, upstreams=(origin,) + ) + store = make_store(tmp_path) + node = OperatorJobNode( + op_filter, [stream_value], pipeline_database=store, cache_mode=CacheMode.LOG + ) + + async def execute_async() -> None: + incoming, outgoing = Channel(buffer_size=8), Channel(buffer_size=8) + for row in stream_value.iter_data(): + await incoming.writer.send(row) + await incoming.writer.close() + await node.async_execute([incoming.reader], outgoing.writer) + _ = await outgoing.reader.collect() + + for mixed in (mixed_first, not mixed_first): + stream_value.current = stream(mixed) + node.clear_cache() + if mode == "run": + node.run() + elif mode == "sync": + node.execute(stream_value) + else: + asyncio.run(execute_async()) + store.flush() + + assert len(store.list_table_paths()) == 1 + path = store.list_table_paths()[0] + assert path[-1] == "odb_v3" + stored = store.get_all_records(path, record_id_column="_record_hash") + assert stored is not None + assert stored.num_rows == 2 + assert stored.schema.field("_source_x") == schema.field("_source_x") + preimage = stored.select([*schema.names, constants.NODE_CONTENT_HASH_COL]) + for i, saved in enumerate(stored["_record_hash"].to_pylist()): + assert ( + node.data_context.arrow_hasher.hash_table( + preimage.slice(i, 1) + ).to_prefixed_digest() + == saved + ) + assert node.as_source().as_table().sort_by("k").to_pylist() == [ + {"k": 0, "x": [[1]] if nested else 1}, + {"k": 1, "x": [[2]] if nested else 2}, + ] + node.attach_databases(pipeline_database=store, cache_mode=CacheMode.REPLAY) + replayed = node.execute(stream_value).as_table(columns={"source": True}) + assert replayed.schema.field("_source_x") == schema.field("_source_x") + + +@STORES +@pytest.mark.parametrize("reverse", [False, True]) +def test_merge_join_cache_keeps_declared_system_tag_fields( + make_store: Callable[[Path], ArrowDatabaseProtocol], tmp_path: Path, reverse: bool +) -> None: + """Every match subset stores the same fields and reproduces its record keys.""" + from orcapod.operators import MergeJoin + from orcapod.streams import ArrowTableStream + + left = ArrowTableStream( + pa.table({"k": [1, 2], "x": [3, 4], "_tag_custom": ["one", None]}), + tag_columns=["k"], + ) + right = ArrowTableStream(pa.table({"k": [1, 2], "y": [5, 6]}), tag_columns=["k"]) + subset = ArrowTableStream(right.as_table().slice(0, 1), tag_columns=["k"]) + store = make_store(tmp_path) + node = OperatorJobNode( + MergeJoin(), [left, right], pipeline_database=store, cache_mode=CacheMode.LOG + ) + [system_tag] = [ + field for field in node.arrow_schema() if field.name.startswith("_tag_custom") + ] + assert system_tag.nullable + for delivery in (right, subset) if reverse else (subset, right): + node.clear_cache() + node.execute(left, delivery) + store.flush() + [path] = store.list_table_paths() + stored = store.get_all_records(path, record_id_column="_record_hash") + assert stored is not None + assert sorted(cast("list[int]", stored["k"].to_pylist())) == [1, 2] + assert stored.schema.field(system_tag.name).equals(system_tag, check_metadata=True) + preimage = stored.select( + [*node.arrow_schema().names, constants.NODE_CONTENT_HASH_COL] + ) + assert [ + node.data_context.arrow_hasher.hash_table( + preimage.slice(i, 1) + ).to_prefixed_digest() + for i in range(stored.num_rows) + ] == stored["_record_hash"].to_pylist() + + +def test_operator_cache_refuses_output_field_that_disagrees_with_declaration( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The cache must reject a changed field before writing record keys.""" + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.operators import Filter + from orcapod.types import col + + source = op.sources.DictSource([{"k": 1, "x": 2}], tag_columns=["k"]) + store = InMemoryArrowDatabase() + node = OperatorJobNode( + Filter(col("x") > 0), + [source], + pipeline_database=store, + cache_mode=CacheMode.LOG, + ) + original = StaticOutputOperatorPod._keep_output_table # pyright: ignore[reportPrivateUsage] + declared = node.arrow_schema().field("x") + + def wrong_flag(table, result): + pos = table.schema.get_field_index("x") + return original( + table.set_column( + pos, declared.with_nullable(not declared.nullable), table.column(pos) + ), + result, + ) + + monkeypatch.setattr( + StaticOutputOperatorPod, "_keep_output_table", staticmethod(wrong_flag) + ) + with pytest.raises(InputValidationError, match=r"output.*'x'.*nullab"): + node.run() + assert not store.list_table_paths() diff --git a/tests/test_core/datagrams/test_arrow_type_preservation.py b/tests/test_core/datagrams/test_arrow_type_preservation.py index 5c38b3855..ac5f6ddc6 100644 --- a/tests/test_core/datagrams/test_arrow_type_preservation.py +++ b/tests/test_core/datagrams/test_arrow_type_preservation.py @@ -58,6 +58,29 @@ def _typed_table() -> pa.Table: DATA_COLUMNS = list(INPUT_TYPES) +@pytest.mark.parametrize("override", [False, True]) +def test_tag_preserves_arrow_system_tag_fields_with_python_system_tags( + override: bool, +) -> None: + field = pa.field( + "_tag_custom", pa.int16(), nullable=True, metadata={b"owner": b"raw"} + ) + table = pa.Table.from_pylist( + [{"name": "sample", field.name: 123}], + schema=pa.schema([pa.field("name", pa.large_string()), field]), + ) + new_tags = {"_tag_unrelated": "more"} + if override: + new_tags = {**new_tags, field.name: 456} + tag = Tag(table, system_tags=new_tags) + result = tag.copy(include_cache=False).as_table(columns={"system_tags": True}) + assert result.schema.field(field.name).equals(field, check_metadata=True) + assert result.column(field.name).to_pylist() == [456 if override else 123] + assert result.schema.field("_tag_unrelated") == pa.field( + "_tag_unrelated", pa.large_string(), nullable=False + ) + + @dataclass(frozen=True) class Mutation: """A datagram mutator and the input columns it legitimately changes or removes.""" diff --git a/tests/test_core/datagrams/test_data_source_info_types.py b/tests/test_core/datagrams/test_data_source_info_types.py index 93d547b83..7207005fc 100644 --- a/tests/test_core/datagrams/test_data_source_info_types.py +++ b/tests/test_core/datagrams/test_data_source_info_types.py @@ -7,8 +7,10 @@ from __future__ import annotations import pyarrow as pa +import pytest from orcapod.core.datagrams import Data +from orcapod.types import SourceInfoValue def _data_with_mixed_source_info() -> Data: @@ -85,3 +87,84 @@ def test_arrow_table_construction_recovers_list_token(self): assert data.as_table(columns={"source": True}).column( "_source_path" ).to_pylist() == [["s0", "s1"]] + + +@pytest.mark.parametrize("via_constructor", [True, False]) +@pytest.mark.parametrize( + "replacement", + [["new"], "wrong depth", [None]], + ids=["preserves-item-field", "refuses-scalar", "refuses-null-item"], +) +def test_python_token_replacement_uses_the_held_type( + via_constructor: bool, replacement: SourceInfoValue +) -> None: + """Replacements use the declared list item name, metadata and nullability.""" + kind = pa.large_list( + pa.field( + "leaf", pa.large_string(), nullable=False, metadata={b"unit": b"token"} + ) + ) + table = pa.table({"x": [[1]], "_source_x": pa.array([["old"]], type=kind)}) + + def replace() -> Data: + if via_constructor: + return Data(table, source_info={"x": replacement}) + return Data(table).with_source_info(x=replacement) + + if replacement != ["new"]: + with pytest.raises((pa.ArrowInvalid, pa.ArrowTypeError)): + _ = replace() + return + updated = replace().as_table(columns={"source": True}) + assert updated.schema.field("_source_x").equals( + pa.field("_source_x", kind, nullable=True), check_metadata=True + ) + assert updated["_source_x"].to_pylist() == [replacement] + + +def test_a_null_replacement_agrees_with_the_held_string_type() -> None: + """Fifth review of PR #607, finding 2: ``with_source_info(x=None)`` on an + Arrow-backed row whose token column is a string gives one declaration, a + ``large_string`` null, in ``as_table`` and in ``source_info_table``.""" + table = pa.table({"x": [1], "_source_x": pa.array(["old"], type=pa.large_string())}) + cleared = Data(table).with_source_info(x=None) + expected = pa.field("_source_x", pa.large_string(), nullable=True) + shown = cleared.as_table(columns={"source": True}) + for held in (shown, cleared.source_info_table()): + assert held.schema.field("_source_x").equals(expected, check_metadata=True) + assert held["_source_x"].to_pylist() == [None] + + +def test_a_null_replacement_of_a_held_list_token_is_refused() -> None: + """Fifth review of PR #607, finding 2: a list token is never null, so + ``with_source_info(x=None)`` on an Arrow-backed row whose token column is a + list is refused. It used to give the row two declarations: a null list in + ``as_table`` and a ``large_string`` null in ``source_info_table``.""" + kind = pa.large_list( + pa.field("leaf", pa.large_string(), nullable=True, metadata={b"u": b"t"}) + ) + table = pa.table({"x": [[1]], "_source_x": pa.array([["old"]], type=kind)}) + row = Data(table) + with pytest.raises(pa.ArrowTypeError, match="list token is never null"): + _ = row.with_source_info(x=None) + # The row is unchanged, and its two forms agree with the held type. + for held in (row.as_table(columns={"source": True}), row.source_info_table()): + assert held.schema.field("_source_x").type.equals(kind, check_metadata=True) + assert held["_source_x"].to_pylist() == [["old"]] + + +@pytest.mark.parametrize("via_constructor", [False, True]) +def test_a_replacement_cannot_put_a_null_inside_nested_token_lists( + via_constructor: bool, +) -> None: + kind = pa.large_list(pa.large_list(pa.large_string())) + table = pa.table({"x": [[[1]]], "_source_x": pa.array([[["old"]]], type=kind)}) + row = Data(table) + with pytest.raises(pa.ArrowTypeError, match="list token is never null"): + if via_constructor: + _ = Data(table, source_info={"x": [None]}) + else: + _ = row.with_source_info(x=[None]) + assert row.with_source_info(x=[[None]]).source_info_table()[ + "_source_x" + ].to_pylist() == [[[None]]] 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/function_pod/test_function_node_arrow_types.py b/tests/test_core/function_pod/test_function_node_arrow_types.py index 35a5fe768..5d37acf8b 100644 --- a/tests/test_core/function_pod/test_function_node_arrow_types.py +++ b/tests/test_core/function_pod/test_function_node_arrow_types.py @@ -22,6 +22,7 @@ from orcapod import PipelineJob, function_pod from orcapod.contexts import resolve_context +from orcapod.core.function_pod import _token_rows # pyright: ignore[reportPrivateUsage] # test the row-to-table boundary from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.errors import InputValidationError from orcapod.pipeline import AsyncPipelineOrchestrator @@ -32,6 +33,21 @@ _DAYS = [_T0 + dt.timedelta(days=i) for i in range(3)] +def test_function_table_refuses_conflicting_token_item_metadata() -> None: + item = pa.field("item", pa.large_string(), metadata={b"origin": b"declared"}) + declared = pa.large_list(item) + different = pa.large_list(item.remove_metadata()) + first = pa.table({"_source_x": pa.array([["a"]], type=declared)}) + second = pa.table({"_source_x": pa.array([["b"]], type=different)}) + with pytest.raises(InputValidationError, match=r"disagree on token '_source_x'"): + _ = _token_rows([first, second]) + assert ( + _token_rows([first, first]) + .schema.field("_source_x") + .type.equals(declared, check_metadata=True) + ) + + def _logical(py_type: type, values: list[Any]) -> pa.Array[Any]: """A column of a logical type, built by the type converter.""" converter = resolve_context(None).type_converter diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index e8e4f0a49..4cf8090d5 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -15,9 +15,12 @@ import asyncio import decimal +import itertools +import math import re from collections.abc import Callable, Sequence from dataclasses import dataclass +from hashlib import sha256 from pathlib import Path from typing import Any, TypeAlias, cast @@ -25,18 +28,24 @@ import pytest from orcapod.channels import Channel -from orcapod.contexts import get_default_context, get_default_type_converter +from orcapod.contexts import ( + get_default_arrow_hasher, + 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.nodes import OperatorJobNode from orcapod.core.operators import ( AddTags, Batch, DropColumns, DropDataColumns, DropNulls, - Filter, DropTagColumns, + Filter, GroupBy, Index, Join, @@ -44,9 +53,9 @@ MapData, MapTags, MergeJoin, - Rejoin, Pick, PolarsFilter, + Rejoin, SelectColumns, SelectDataColumns, SelectTagColumns, @@ -54,6 +63,8 @@ TagBy, ) from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.operators.streaming_joins import TRANSPORT_COLUMNS, StreamingJoin +from orcapod.core.row_ids import ENTRY_ID_COL, entry_id from orcapod.core.sources import ArrowTableSource from orcapod.core.streams import ArrowTableStream from orcapod.databases import InMemoryArrowDatabase @@ -63,7 +74,7 @@ StreamProtocol, TagProtocol, ) -from orcapod.types import Condition, col +from orcapod.types import CacheMode, Condition, col from orcapod.utils import arrow_utils # The ``semijoin_shared_data_column`` case shares a data column name on purpose; SemiJoin @@ -1018,6 +1029,532 @@ 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_tied_join_table_keeps_declared_identifier_fields( + reverse_columns: bool, + metadata: str, +) -> None: + """Keep table identifier flags and infer tied identifiers when reading rows.""" + 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) + for field in tag_table.schema: + if field.name.startswith(record_id): + assert field.nullable == (tag_table[field.name].null_count > 0) + assert field.metadata is None + else: + assert field.equals( + table.schema.field(field.name), check_metadata=True + ) + data_table = data.as_table() + assert data_table.schema.equals( + table.select(data_table.column_names).schema, check_metadata=True + ) + + +def _tied_join_inputs( + arity: int, + *, + distinct_revisions: bool = False, +) -> list[ArrowTableStream]: + """Build equal-pipeline inputs with distinct identifiers and optional revision values.""" + names = ["k", "_tag_source_id", "_tag_record_id", "_tag_rev"] + schema = pa.schema( + [pa.field("k", pa.int64(), nullable=False)] + + [pa.field(name, pa.large_string(), nullable=False) for name in names[1:]] + ) + inputs = [] + pairs = ( + ("az", "record-a"), + ("z", "record-z"), + ("zzzz", "record-last"), + ("z", "record-b"), + ) + for index, (source_id, record_id) in enumerate(pairs[:arity]): + key = 1 + revision = f"revision-{index}" if distinct_revisions else "shared" + table = pa.Table.from_pylist( + [dict(zip(names, (key, source_id, record_id, revision), strict=True))], + schema=schema, + ) + inputs.append(ArrowTableStream(table, tag_columns=["k"], data_tags=["k"])) + assert len({stream.pipeline_hash() for stream in inputs}) == 1 + return inputs + + +def _tied_join_outputs( + mode: str, join: Join, inputs: Sequence[StreamProtocol] +) -> tuple[pa.Table, list[Row]]: + """Return the system-tag view and rows for a tied Join. + + Sync uses the Join table, rows uses the async row tags, and batches uses + the emitted Arrow fields in Join's column order. + """ + columns = {"system_tags": True} + if mode == "rows": + rows = async_rows(join, *inputs) + return ( + pa.concat_tables([tag.as_table(columns=columns) for tag, _ in rows]) + if rows + else pa.table({}) + ), rows + if mode == "sync": + stream = join(*inputs) + return stream.as_table(columns=columns), list(stream.iter_data()) + kernel = StreamingJoin(join, inputs) + batches = [ + result + for i, operand in enumerate(inputs) + for packet in operand.as_table(columns=TRANSPORT_COLUMNS).to_batches() + for result in kernel.push(i, packet) + ] + batches.extend(result for i in range(len(inputs)) for result in kernel.close(i)) + if not batches: + return kernel.zero_row_result.as_table(columns=columns), [] + table = pa.Table.from_batches(batches) + # The kernel returns Arrow batches. Use Join's row reader to calculate the + # entry IDs corresponding to those tables, and check the emitted fields as-is. + tag_names = inputs[0].keys()[0] + stream = join._join_result_stream( # pyright: ignore[reportPrivateUsage] # the kernel returns tables, not rows + table, inputs, tag_columns=tag_names, data_tags=tag_names + ) + layout = stream.as_table(columns=columns).column_names + return table.select(layout), list(stream.iter_data()) + + +def _symmetric_tie_snapshot(arity: int, mode: str) -> tuple[str, ...]: + """Digest the Arrow IPC tables and collect the entry IDs in permutation order.""" + hasher = get_default_arrow_hasher() + snapshot = [] + for order in itertools.permutations(_tied_join_inputs(arity)): + table, rows = _tied_join_outputs(mode, Join(), order) + output = pa.BufferOutputStream() + with pa.ipc.new_stream(output, table.schema) as writer: + writer.write_table(table.combine_chunks()) + snapshot.append(sha256(output.getvalue().to_pybytes()).hexdigest()) + snapshot.extend(entry_id(hasher, tag, data).to_string() for tag, data in rows) + return tuple(snapshot) + + +# Captured from origin/main at 37f78431, where all permutations and modes agree. +@pytest.mark.parametrize( + ("arity", "table_digest", "expected_entry_id"), + [ + ( + 2, + "da59e70321d0172c50fe3e828b4a1889ce7bab343e24e1c288405a43056b061e", + "arrow_v1:0000029a37059d124668f54cd4a141a99266d84c5ba57f4007947f0ac0bee1e88eadbf", + ), + ( + 3, + "c0745b28e9bfcb112a8ef786e01e9188de67c1f8c9bd15c9dc633dc6ce031bb4", + "arrow_v1:000002b259085d031998a9850c2a998f2e41a76e931410be81f8b1f5198dd1416d5170", + ), + ( + 4, + "e1f1b75a17ac2d9006a7c3bf606050703a8216db58901cb0e515c3da84e90f4a", + "arrow_v1:00000278a840e460fa1d24285bfec361a11ac9a3efc5d0ddea290a6683cdaec5c119fc", + ), + ], +) +@pytest.mark.parametrize("mode", ["sync", "rows", "batches"]) +def test_symmetric_tied_join_matches_main( + arity: int, mode: str, table_digest: str, expected_entry_id: str +) -> None: + """Pin the table and entry IDs for every symmetric input permutation.""" + assert _symmetric_tie_snapshot(arity, mode) == ( + table_digest, + expected_entry_id, + ) * math.factorial(arity) + + +@pytest.mark.parametrize("arity", [2, 3, 4]) +def test_standalone_tied_join_keeps_custom_tags_with_ids(arity: int) -> None: + """Keep each revision value paired with the identifiers from its input.""" + inputs = _tied_join_inputs(arity, distinct_revisions=True) + suffix = inputs[0].pipeline_hash().to_hex() + expected = {} + names = ("_tag_source_id", "_tag_record_id", "_tag_rev") + bundles = [ + tuple(table[name][0].as_py() for name in names) + for table in ( + stream.as_table(columns={"system_tags": True}) for stream in inputs + ) + ] + for position, values in enumerate(sorted(bundles)): + for name, value in zip(names, values, strict=True): + expected[f"{name}::{suffix}:{position}"] = value + + for order in itertools.permutations(inputs): + [(tag, _)] = async_rows(Join(), *order) + assert tag.system_tags() == expected + + +def _tied_declaration_inputs(arity: int, variant: str) -> list[StreamProtocol]: + """Vary the declaration or values of the tied Join's custom revision tag. + + Nullable changes the first field's nullability, owner and extension add + their respective metadata keys, and distinct varies the values. Source + uses a nominated ArrowTableSource tag with a required string field and data-tag k. + """ + if variant == "source": + ids = ("az", "z", "zz", "zzz")[:arity] + schema = pa.schema( + [ + pa.field("k", pa.int64(), False), + pa.field("rev", pa.large_string(), False), + ] + ) + sources: list[StreamProtocol] = [ + ArrowTableSource( + pa.Table.from_pylist([{"k": 1, "rev": f"rev-{source_id}"}], schema), + tag_columns=["k"], + system_tag_columns=["rev"], + source_id=source_id, + ) + for source_id in ids + ] + for source in sources: + assert source.keys() == (("k",), ("k",)) + return sources + inputs: list[StreamProtocol] = [] + for position in range(arity): + metadata_key = { + "owner": b"owner", + "extension": b"ARROW:extension:name", + }.get(variant) + schema = pa.schema( + [ + pa.field("k", pa.int64(), nullable=False), + pa.field("_tag_source_id", pa.large_string(), nullable=False), + pa.field("_tag_record_id", pa.large_string(), nullable=False), + pa.field( + "_tag_rev", + pa.large_string(), + nullable=variant == "nullable" and position == 0, + metadata={metadata_key: str(position).encode()} + if metadata_key + else None, + ), + ] + ) + ids = ("a", "z") if arity == 2 else ("a", "b", "c", "z")[:arity] + source_ids = [ids[position], ids[arity - position - 1]] + table = pa.Table.from_pydict( + { + "k": [0, 1], + "_tag_source_id": source_ids, + "_tag_record_id": [f"record-{source_id}" for source_id in source_ids], + "_tag_rev": [str(position)] * 2 + if variant == "distinct" + else ["same"] * 2, + }, + schema=schema, + ) + inputs.append(ArrowTableStream(table, tag_columns=["k"], data_tags=["k"])) + assert len({stream.pipeline_hash() for stream in inputs}) == 1 + return inputs + + +def _ipc_bytes(table: pa.Table) -> bytes: + """Serialize a table with rebuilt buffers for a stable snapshot.""" + output = pa.BufferOutputStream() + with pa.ipc.new_stream(output, table.schema) as writer: + writer.write_table(pa.Table.from_pylist(table.to_pylist(), schema=table.schema)) + return output.getvalue().to_pybytes() + + +def _tied_declaration_snapshot(arity: int, variant: str, mode: str) -> str: + """Digest all tables, row declarations, and entry IDs in permutation order.""" + hasher = get_default_arrow_hasher() + snapshot = sha256() + columns = {"system_tags": True} + for order in itertools.permutations(_tied_declaration_inputs(arity, variant)): + table, rows = _tied_join_outputs(mode, Join(), order) + snapshot.update(_ipc_bytes(table.sort_by("k"))) + for tag, data in sorted(rows, key=lambda row: cast(int, row[0].as_dict()["k"])): + snapshot.update(_ipc_bytes(tag.as_table(columns=columns))) + snapshot.update(entry_id(hasher, tag, data).to_string().encode()) + return snapshot.hexdigest() + + +# Captured from origin/main at 37f78431. Normalize IPC array buffers before +# hashing so representation details such as buffer padding cannot affect this. +@pytest.mark.parametrize( + ("arity", "mode", "expected"), + [ + (2, "sync", "280a42832ee7f60b55ad196d02b9cfaf1e2c85d7d0503db828ab303ebb1320c0"), + (2, "rows", "9314587b25beec1a7584b1d1591aba5897a4f0d31e6a281582160153931764a2"), + ( + 2, + "batches", + "26d1cbeaa025d775dedb3f0d961c40d15cd958c7684d9c616d1ceced779545dd", + ), + (3, "sync", "cd68e71f26e095b30152cf7957d282c6aa5d136e0975098c327566e75e83f87b"), + (3, "rows", "f0845a9b6838c6fe841f070cdf2c488395132e8da736e5356c73e7fa64997ee2"), + ( + 3, + "batches", + "033fe0d17906706f270dac8d17123d4f97e88b661fe7c2c0f692e3fdd087e0b8", + ), + (4, "sync", "fb5f218d39d728d6f2f5d30baa0858ae72964208b0a66c99d6886d94ba90b5ae"), + (4, "rows", "a5c00b4f0b7b1e63c687bb0f08cf4a6adfddf652aebf5534773b0f1dc5869454"), + ( + 4, + "batches", + "2e1e2be35f60e429a95c62526db88cdee44912e1d65fe5b1afd825d4132e5c56", + ), + ], +) +def test_tied_join_declarations_and_entry_ids_match_main( + arity: int, mode: str, expected: str +) -> None: + """Pin main's per-mode table and row declarations and entry IDs.""" + fingerprints = [ + _tied_declaration_snapshot(arity, variant, mode) + for variant in ("nullable", "extension", "owner", "distinct", "source") + ] + assert sha256("".join(fingerprints).encode()).hexdigest() == expected + + +@pytest.mark.parametrize("variant", ["nullable", "extension", "owner"]) +@pytest.mark.parametrize("mode", ["run", "sync", "async"]) +def test_tied_join_direct_log_matches_main(variant: str, mode: str) -> None: + """Pin the stored system-tag fields and entry IDs of all direct LOG routes.""" + operands = _tied_declaration_inputs(2, variant) + store = InMemoryArrowDatabase() + node = OperatorJobNode( + Join(), operands, pipeline_database=store, cache_mode=CacheMode.LOG + ) + + async def run() -> list[Row]: + """Execute the node over row channels and collect its output.""" + channels: list[Channel[Row]] = [Channel(buffer_size=8) for _ in operands] + output: Channel[Row] = Channel(buffer_size=8) + for stream, channel in zip(operands, channels, strict=True): + for row in stream.iter_data(): + await channel.writer.send(row) + await channel.writer.close() + await node.async_execute( + [channel.reader for channel in channels], output.writer + ) + return await output.reader.collect() + + if mode == "run": + node.run() + rows = list(node.iter_data()) + elif mode == "sync": + rows = list(node.execute(*operands).iter_data()) + else: + rows = asyncio.run(run()) + columns = {"system_tags": True} + hasher = get_default_arrow_hasher() + ids = [entry_id(hasher, tag, data) for tag, data in rows] + assert sorted(digest.to_string() for digest in ids) == [ + "arrow_v1:00000237bf6d56a4fbd90a304813372028248268b9561e94a279986a92d83506c6b1d6", + "arrow_v1:0000023c89fc6badf559f658c77af9ee84b5a1d3644995eb9a6c24d0b9e0193e958ce1", + ] + store.flush() + (path,) = store.list_table_paths() + stored = store.get_all_records(path, record_id_column="_record_hash") + assert stored is not None + assert sorted(cast(list[bytes], stored[ENTRY_ID_COL].to_pylist())) == sorted( + digest.to_prefixed_digest() for digest in ids + ) + for tag, _ in rows: + for field in tag.as_table(columns=columns).schema: + if field.name.startswith("_tag_"): + assert stored.schema.field(field.name).equals( + field, check_metadata=True + ) + + +@pytest.mark.parametrize("arity", [2, 3, 4]) +@pytest.mark.parametrize("mode", ["sync", "rows", "batches"]) +def test_tied_join_with_asymmetric_empty_input_matches_main( + arity: int, mode: str +) -> None: + """Keep main's zero-row layout when a tied input omits a record ID.""" + inputs = _tied_join_inputs(arity) + columns = {"system_tags": True} + empty_table = ( + inputs[-1].as_table(columns=columns).drop(["_tag_record_id"]).slice(0, 0) + ) + inputs[-1] = ArrowTableStream(empty_table, tag_columns=["k"], data_tags=["k"]) + for order in itertools.permutations(inputs): + join = Join() + tags, _ = join.output_schema(*order, columns=columns) + assert ( + len([name for name in tags if name.startswith("_tag_record_id")]) + == arity - 1 + ) + table, rows = _tied_join_outputs(mode, join, order) + assert not rows and not table.num_rows + if mode != "rows": + assert set(table.column_names) == set(tags) + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_join_suffixes_distinguish_hashes_with_the_same_prefix(reverse: bool) -> None: + """Disambiguate inputs by full pipeline hash in every Join mode.""" + source_id, record_id, custom = "_tag_source_id", "_tag_record_id", "_tag_rev" + left, right = [ + ArrowTableStream( + pa.table( + { + "k": [1], + data: [1], + source_id: [owner], + record_id: [f"{owner}-record"], + custom: [f"{owner}-revision"], + } + ), + tag_columns=["k"], + ) + for data, owner in (("left_data", "left"), ("right_data_5", "right")) + ] + left_hash, right_hash = ( + left.pipeline_hash().to_hex(), + right.pipeline_hash().to_hex(), + ) + assert left_hash[0] == right_hash[0] + assert right_hash < left_hash + operands = (right, left) if reverse else (left, right) + join = Join() + columns = {"system_tags": True} + [(tag, _)] = async_rows(join, *operands) + kernel = StreamingJoin(join, operands) + batches = [ + result + for index, operand in enumerate(operands) + for batch in operand.as_table(columns=TRANSPORT_COLUMNS).to_batches() + for result in kernel.push(index, batch) + ] + expected = { + f"{field}::{digest}:{position}": value + for position, (digest, owner) in enumerate( + ((right_hash, "right"), (left_hash, "left")) + ) + for field, value in ( + (source_id, owner), + (record_id, f"{owner}-record"), + (custom, f"{owner}-revision"), + ) + } + for result in ( + tag.as_table(columns=columns), + join(*operands).as_table(columns=columns), + pa.Table.from_batches(batches), + ): + assert result.select(list(expected)).to_pylist() == [expected] + + +@pytest.mark.parametrize("reverse_columns", [False, True]) +def test_raw_stream_rows_keep_system_tag_width_flags_and_metadata( + reverse_columns: bool, +) -> None: + """Keep both system tags and their Arrow fields through a cache-free copy.""" + 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 set(got.column_names) == {"k", "g", "_tag_rank", "_tag_label"} + 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) ────────────────────────────── @@ -2416,3 +2953,202 @@ 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")} +_MERGE_RIGHT_FIRST_TOKENS: dict[str, list[Any]] = { + "one_level": ["right"], + "two_levels": [["right"]], + "fixed_size_and_strings": ["right", "right"], +} + + +def _token_stream( + layout: str, + tags: Sequence[str], + data: Sequence[str] = ("a", "b"), + source_id: str = "t", + *, + first_token: list[Any] | None = None, +) -> 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. + ``first_token`` overrides the first row's token in the first data column. + """ + 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()): + if name == first and first_token is not None: + values = [first_token, *values[1:]] + 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(["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, ...]: + """Give the right MergeJoin operand a different token at (m, 1).""" + return tuple( + _token_stream( + layout, + order, + data, + source_id=f"t{index}", + first_token=_MERGE_RIGHT_FIRST_TOKENS[layout] + if operator == "merge_join" and index == 1 + else None, + ) + 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()) + if operator != "select" or name == "a" + } + input_tokens = dict( + zip((("m", 1), ("m", 2), ("n", 1)), _TOKEN_LAYOUTS[layout]["a"][0], strict=True) + ) + for rows in (expected, actual): + for tag, data in rows: + in_transit = data.as_table(columns={"source": True}) + if operator in ("select", "merge_join"): + tags_by_name = tag.as_dict() + key = (cast(str, tags_by_name["g"]), cast(int, tags_by_name["k"])) + if operator == "select": + assert in_transit.column_names == ["a", "_source_a"] + assert in_transit["_source_a"].to_pylist() == [input_tokens[key]] + elif key == ("m", 1): + assert in_transit["_source_a"].to_pylist() == [ + [input_tokens[key], _MERGE_RIGHT_FIRST_TOKENS[layout]] + ] + 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_chained_aggregation.py b/tests/test_core/operators/test_chained_aggregation.py index 241736998..1ebfce37f 100644 --- a/tests/test_core/operators/test_chained_aggregation.py +++ b/tests/test_core/operators/test_chained_aggregation.py @@ -252,7 +252,7 @@ def test_column_types_are_one_list_level_deeper(self, chain: Chain) -> None: assert not field.nullable, name def test_source_info_columns_nest_their_incoming_type(self, chain: Chain) -> None: - """``_source_`` is ``large_list`` of the upstream ``_source_`` type.""" + """A nullable token field holds a list of the upstream token type.""" upstream = chain.upstream.as_table(columns=WITH_SOURCE).schema result = chain.result.as_table(columns=WITH_SOURCE).schema source_columns = [n for n in upstream.names if n.startswith(SOURCE)] @@ -260,7 +260,7 @@ def test_source_info_columns_nest_their_incoming_type(self, chain: Chain) -> Non for name in source_columns: incoming = upstream.field(name).type assert result.field(name).type == LL(incoming), name - assert not result.field(name).nullable, name + assert result.field(name).nullable, name @pytest.mark.parametrize("columns", [{}, {"system_tags": True}], ids=str) def test_prediction_matches_static_process( 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_join_meta_columns.py b/tests/test_core/operators/test_join_meta_columns.py index 954f89c9b..866ffbb15 100644 --- a/tests/test_core/operators/test_join_meta_columns.py +++ b/tests/test_core/operators/test_join_meta_columns.py @@ -277,3 +277,20 @@ def test_raw_inputs_keep_their_other_columns() -> None: "vx": pa.int8(), "vy": pa.int8(), } + + +def test_standalone_join_uses_the_shared_token_field_declaration() -> None: + """The standalone row merge delegates its token field to the shared constructor.""" + import ast + import inspect + import textwrap + + tree = ast.parse(textwrap.dedent(inspect.getsource(Join._merge_data))) # pyright: ignore[reportPrivateUsage] # audit the declaration site + assert any( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "source_info_field" + and isinstance(node.func.value, ast.Name) + and node.func.value.id == "arrow_utils" + for node in ast.walk(tree) + ) diff --git a/tests/test_core/operators/test_materialize_source_info.py b/tests/test_core/operators/test_materialize_source_info.py index f415d34db..af0b6ac0b 100644 --- a/tests/test_core/operators/test_materialize_source_info.py +++ b/tests/test_core/operators/test_materialize_source_info.py @@ -145,17 +145,39 @@ def _materialize_buffer(buf: Sequence[Row], node: Any) -> StreamProtocol: def _broadcast_row_zero(monkeypatch: pytest.MonkeyPatch) -> None: - """Make every materialization stamp row 0's source info, as before ITL-845.""" + """Reproduce a broadcast-token write under today's declared fields.""" + keep = StaticOutputOperatorPod._keep_output_table # pyright: ignore[reportPrivateUsage] # intercept the keeper + + def broadcasting(table: pa.Table, result: StreamProtocol) -> StreamProtocol: + """Replace each source-info column by its first token repeated.""" + for i, field in enumerate(table.schema): + if field.name.startswith(constants.SOURCE_PREFIX): + first = table.column(i).slice(0, 1).combine_chunks() + table = table.set_column( + i, field, pa.concat_arrays([first] * table.num_rows) + ) + return keep(table, result) + + monkeypatch.setattr( + StaticOutputOperatorPod, "_keep_output_table", staticmethod(broadcasting) + ) + + +def _broadcast_row_zero_in_transport(monkeypatch: pytest.MonkeyPatch) -> None: + """Seed historical broadcast tokens on source and function job edges.""" # Non-public on purpose: re-creating the pre-fix behaviour has no public hook. original = StaticOutputOperatorPod._rows_to_table # pyright: ignore[reportPrivateUsage] def broadcasting( rows: Sequence[Row], + *, + keep_token_fields: bool = False, ) -> tuple[pa.Table, tuple[str, ...], tuple[str, ...]]: """Stamp row 0's source info on every row, then build the table.""" row_zero = rows[0][1].source_info() return original( - [(tag, data.with_source_info(**row_zero)) for tag, data in rows] + [(tag, data.with_source_info(**row_zero)) for tag, data in rows], + keep_token_fields=keep_token_fields, ) original_form = StaticOutputOperatorPod._row_built_form # pyright: ignore[reportPrivateUsage] @@ -165,6 +187,8 @@ def broadcasting_form( ) -> pa.Table: """Stamp row 0's source info on every row of the row-built form (ITL-1347).""" formed = original_form(table, keys) + if not formed.num_rows: + return formed for i, name in enumerate(formed.column_names): if name.startswith(constants.SOURCE_PREFIX): column = formed.column(i) @@ -176,8 +200,6 @@ def broadcasting_form( monkeypatch.setattr( StaticOutputOperatorPod, "_rows_to_table", staticmethod(broadcasting) ) - # An operator node keeps the row-built form of its result's table, without - # making the rows (ITL-1347, stage 2). monkeypatch.setattr( StaticOutputOperatorPod, "_row_built_form", staticmethod(broadcasting_form) ) @@ -279,39 +301,32 @@ def test_data_columns_and_types_unchanged(self): class TestSourceInfoArrowFields: - """The ``_source_*`` fields keep the Arrow type and nullability they had before. + """Materialized token fields are nullable for scalar and list-valued tokens.""" - Before ITL-845 a concrete (broadcast) source-info token made the field - non-nullable, and a row-0 ``None`` passed the column through as nullable. The - fix declares a field nullable exactly when some row's source-info token is - ``None``, which matches the old flag whenever the old values were right; the - stored schema, and so the operator node's per-row record hash, depend on it. - """ - - def test_scalar_source_info_tokens_non_nullable_large_string(self): - """Scalar source-info token fields stay non-nullable ``large_string``.""" + def test_scalar_source_info_tokens_nullable_large_string(self): + """Scalar source-info token fields are nullable ``large_string``.""" stream = _materialize(list(_source().iter_data())) fields = _source_fields(stream.as_table(columns={"source": True})) assert fields == { - "_source_x": pa.field("_source_x", pa.large_string(), nullable=False), - "_source_y": pa.field("_source_y", pa.large_string(), nullable=False), + "_source_x": pa.field("_source_x", pa.large_string(), nullable=True), + "_source_y": pa.field("_source_y", pa.large_string(), nullable=True), } - def test_list_source_info_tokens_non_nullable_large_list(self): - """List source-info fields stay non-nullable ``large_list``.""" + def test_list_source_info_tokens_nullable_large_list(self): + """List source-info fields are nullable ``large_list``.""" rows = list(Batch(2)(_source(4)).iter_data()) stream = _materialize(rows) field = _source_fields(stream.as_table(columns={"source": True}))["_source_x"] assert field == pa.field( - "_source_x", pa.large_list(pa.large_string()), nullable=False + "_source_x", pa.large_list(pa.large_string()), nullable=True ) list_type = field.type assert isinstance(list_type, pa.LargeListType) assert list_type.value_field.nullable is True @pytest.mark.parametrize("none_row", [0, 2]) - def test_field_nullable_when_a_source_info_token_is_none(self, none_row: int): - """A ``_source_*`` field is nullable iff a row's source-info token is None.""" + def test_field_nullable_even_when_every_token_is_present(self, none_row: int): + """Each source-info field is nullable, including columns without a missing token.""" rows = list(_source(3).iter_data()) rows[none_row] = (rows[none_row][0], rows[none_row][1].with_source_info(x=None)) stream = _materialize(rows) @@ -319,7 +334,7 @@ def test_field_nullable_when_a_source_info_token_is_none(self, none_row: int): assert fields["_source_x"] == pa.field( "_source_x", pa.large_string(), nullable=True ) - assert fields["_source_y"].nullable is False + assert fields["_source_y"].nullable # --------------------------------------------------------------------------- @@ -551,7 +566,7 @@ def test_buffer_keeps_list_source_info_tokens(self): assert stream.content_hash() == node.content_hash() fields = _source_fields(stream.as_table(columns={"source": True})) assert fields["_source_x"] == pa.field( - "_source_x", pa.large_list(pa.large_string()), nullable=False + "_source_x", pa.large_list(pa.large_string()), nullable=True ) def test_empty_buffer(self): @@ -595,26 +610,10 @@ def _record_ids(node: OperatorJobNode) -> dict[str, bytes]: class TestIdentityPinned: - """Values recorded on ``main`` at ab544982, before the fix. - - Re-recorded under starfix hash format 2 (``arrow_v1``, ITL-910): the node content - hash and the record hashes are Arrow-derived; the pipeline hash is not. - - Re-recorded for ITL-957: the pinned source has no given ``source_id``, so its default - id (now ``arrow_table: