diff --git a/.zed/rules b/.zed/rules index 1ebebefc1..454407896 100644 --- a/.zed/rules +++ b/.zed/rules @@ -993,10 +993,12 @@ of its identity (GroupBy's member_order), never the input's column order. ### Column naming conventions - __ prefix — System metadata (ColumnConfig meta) - _source_ prefix — Source info provenance (ColumnConfig source) - _tag:: prefix — System tag (ColumnConfig system_tags) - _context_key — Data context (ColumnConfig context) + __ prefix — System metadata (ColumnConfig meta) + _source_ prefix — Source info provenance (ColumnConfig source) + _input_source_ prefix — Source-info provenance of an input data column as stored by a + function node, e.g. _input_source_age (ColumnConfig(source=True)) + _tag:: prefix — System tag (ColumnConfig system_tags) + _context_key — Data context (ColumnConfig context) Prefixes are computed from SystemConstant in system_constants.py. @@ -1019,9 +1021,12 @@ are also provisional and will be designed alongside the side-effect log (ITL-947 - 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). The pipeline, side-effect log and operator cache layouts moved to v2 before that release, - with the three row ids (developer, November 25, 2026, ITL-1471; below, "Row ids"). A change to the common bookkeeping columns of a table kind - moves its layout version, so the table gets a new path. Never add, rename or retype a stored - column without it. + with the three row ids (developer, November 25, 2026, ITL-1471; below, "Row ids"). + Before the first release, changes to stored columns may keep the layout marker + (decision D33, November 29, 2026). Function pipeline tables keep `pdb_v2` when + their input-token columns become `_input_source_` (ITL-1524). Once + released, a change to the common bookkeeping columns moves the layout version, + so the table gets a new path. - A plain function's result table is at //v/python.function.v1/rev1/rdb_v1, three components with three owners (docs/reference/data-function-types.md): @@ -1263,8 +1268,10 @@ these preimages anywhere else. 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 instance id and the pipeline table use the same `_input_source_` fields from + `row_ids.input_source_info_table`. The helper takes the typed columns from + `DataProtocol.source_info_table()`. Result tables and streams use `_source_` + (ITL-1524). Every field is 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 diff --git a/CLAUDE.md b/CLAUDE.md index 1304ed83d..91ffef8d2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1020,6 +1020,7 @@ of its identity (GroupBy's `member_order`), never the input's column order. |--------|---------|---------|---------------| | `__` | System metadata | `__data_id`, `__pod_version` | `ColumnConfig(meta=True)` | | `_source_` | Source info provenance | `_source_age` | `ColumnConfig(source=True)` | +| `_input_source_` | Source-info provenance of an input data column as stored by a function node | `_input_source_age` | `ColumnConfig(source=True)` | | `_tag::` | System tag | `_tag::source:abc123` | `ColumnConfig(system_tags=True)` | | `_context_key` | Data context | `_context_key` | `ColumnConfig(context=True)` | @@ -1048,9 +1049,11 @@ are also provisional and will be designed alongside the side-effect log (ITL-947 - 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 layouts moved to `v2` before that release, with the three row ids (developer, November 25, - 2026, ITL-1471; below, "Row ids"). A change to the common - bookkeeping columns of a table kind moves its layout version, so the table gets a new path. - Never add, rename or retype a stored column without it. + 2026, ITL-1471; below, "Row ids"). Before the first release, changes to stored + columns may keep the layout marker (decision D33, November 29, 2026). Function pipeline + tables keep `pdb_v2` when their input-token columns become `_input_source_` + (ITL-1524). Once released, a change to the common bookkeeping columns moves the + layout version, so the table gets a new path. - A plain function's result table is at `//v/python.function.v1/rev1/rdb_v1`, three components with three owners (`docs/reference/data-function-types.md`): @@ -1294,8 +1297,10 @@ are defined in one module, `core/row_ids.py`; never build one of these preimages 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 instance id and the pipeline table use the same `_input_source_` fields from + `row_ids.input_source_info_table`. The helper takes the typed columns from + `DataProtocol.source_info_table()`. Result tables and streams use `_source_` + (ITL-1524). Every field is 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 diff --git a/changelog.d/ITL-1524.md b/changelog.d/ITL-1524.md new file mode 100644 index 000000000..a3df0729e --- /dev/null +++ b/changelog.d/ITL-1524.md @@ -0,0 +1,15 @@ +### Breaking changes and migration + +- Function pipeline tables store and hash input provenance under + `_input_source_`, which changes the instance and record IDs for rows + with input tokens. Reading or appending to a pre-release `pdb_v2` table + with the older input-token names raises `StoredTableSchemaError` and + directs the caller to rebuild the pipeline table. The existing rows stay + in the store. + +### Fixed + +- Stored function outputs keep the function's provenance when their names match + input columns. Fall-through data-tags keep their input provenance. Joined + records expose the other input tokens under `_input_source_` when + source info is requested. diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index 986134c80..b6c5b891c 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -331,6 +331,7 @@ shortcut) to control which column groups are included. | `meta` | System metadata columns, when the stream has any | `__` | | `system_tags` | System tag columns (provenance tracking) | `_tag_source_id::`, `_tag_record_id::` | | `source` | Source-info columns (per-data provenance tokens) | `_source_` | +| `source` | Stored input data provenance in a function node's joined records, for example `_input_source_age` | `_input_source_` | | `context` | Data context column | `_context_key` | | `content_hash` | Content hash column | `_content_hash` | | `sort_by_tags` | Sort rows by tag columns | (ordering only) | diff --git a/docs/dev/design_issues/ITL-1524-FN5.md b/docs/dev/design_issues/ITL-1524-FN5.md new file mode 100644 index 000000000..dad52f32f --- /dev/null +++ b/docs/dev/design_issues/ITL-1524-FN5.md @@ -0,0 +1,18 @@ +## `src/orcapod/core/nodes/function_node.py` + +### FN5 — Stored function outputs could report the input's provenance +**Status:** resolved +**Severity:** high +**Issue:** ITL-1524 + +A function job node delivered its own token for an output that shared an input's +name. On readback, the joined table kept the original input's token under that +name and added a suffix to the result token. A downstream function could record +a second instance with the wrong provenance. + +**Fix:** The `pdb_v2` pipeline table and the instance ID preimage use the same +`_input_source_` fields. The joined read presents the result table's +`_source_` fields for outputs and fall-through data-tags. When source +info is requested, the joined view also exposes other inputs' provenance under +`_input_source_`. Plain `DerivedSource` token policy is being considered +with the identity work in ITL-1564. diff --git a/docs/reference/data-function-types.md b/docs/reference/data-function-types.md index 405e9e09f..469d616d8 100644 --- a/docs/reference/data-function-types.md +++ b/docs/reference/data-function-types.md @@ -204,6 +204,7 @@ for the entry, including: | Column | Arrow type | Nullable | Meaning | |---|---|---|---| +| `_input_source_` | the input token's Arrow type | yes | The token of an input data column. The instance id hashes these fields under their stored names. | | `__pipeline_instance_id` | `large_binary` | yes | The row's instance id: the hash of its entry id (tags, system tags, input data hash) and the input's source-info tokens. The node looks a row up by it. | | `__pipeline_record_id` | `large_binary` | yes | The row's record id: the hash of the node's content hash (`__node_content_hash`), its instance id and the id of its result. It is the table's key. | | `__pipeline_run_id` | `large_string` | yes | The ID of the job run that recorded the entry. A node run outside a job stores null. | @@ -263,7 +264,9 @@ print([name for name in joined.column_names if name.startswith("__pipeline_")]) ``` Pipeline tables written by a release candidate before the three ids are at the -layout `pdb_v1`: they are reported as tables of another layout and are not read. +layout `pdb_v1`. Orcapod reports and preserves them. A pre-release `pdb_v2` +table with the older `_source_` input-token names raises +`StoredTableSchemaError` and must be rebuilt with the current version. ## Where it is declared, and how a released declaration is kept diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index d0faf9b24..49826b24c 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -571,8 +571,8 @@ each suffix is the stream's `pipeline_hash()` (sites 1b and 6). |------|-----|-------------| | 7 | `alice` entry id | `6172726f775f76313a000002b2c4dab9ec35d8b2ca236985ab270eeea925894edb55ba37ce6a12321929667c` | | 7 | `bob` entry id | `6172726f775f76313a0000029729ca8b7278a10b991bb9ca6d0cb5d0bf207da06fecc7130c3ae4d34a4d55ee` | -| 8 | `alice` instance id | `6172726f775f76313a0000025d309ba35bcfa8c47f96f8131b565fe3090f26873513d7aab4022192bd68c45a` | -| 8 | `bob` instance id | `6172726f775f76313a000002c2f60a9279aed09fcb0cfefd07639efbc231c0acc8dc269d9c47b4420910d774` | +| 8 | `alice` instance id | `6172726f775f76313a000002c62e6f147b21488bbb708df133ff0258d6be8d534996f197bbaf6a34f14d1348` | +| 8 | `bob` instance id | `6172726f775f76313a000002141ef1d422719784e62afb22beb02c57587c75f6dcb05e9e7e4cd7aaacc8166b` | A record id (site 8b) is not shown: it holds the result id. A result computed anew has a new id (a UUID), so its record id is new; a warm repeat that reuses the stored result reuses its @@ -1347,7 +1347,7 @@ 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, 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 | +| **Inputs** | `__pipeline_entry_id` (the entry id's labelled digest, `pa.large_binary()`), then the `_input_source_*` columns of the input data in name order (`row_ids.input_source_info_table`, built from `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 | diff --git a/src/orcapod/contexts/data/v1.json b/src/orcapod/contexts/data/v1.json index 720612983..107a08dbd 100644 --- a/src/orcapod/contexts/data/v1.json +++ b/src/orcapod/contexts/data/v1.json @@ -250,19 +250,19 @@ "digest": "4d7e6efa1eb0e72175a18d6b40b933d61c6817b1499d590b10e7d016b642f6ba" }, { - "date": "2026-11-28", + "date": "2026-11-29", "release": null, "added": { - "pipeline-02.json": "67a7ed65c5ad810d4ccbe5c01d543770c10a3596ac6eecd3b6796a79cd284d94" + "pipeline-02.json": "cca93cb45ed48622bc58e77d344f8e536a89ee1d5da63c6a8d0b121361c64b5f" }, "previous": "4d7e6efa1eb0e72175a18d6b40b933d61c6817b1499d590b10e7d016b642f6ba", - "digest": "798829ea585e0749af187b6265f163c1ef871ab50967b3c22bf7b3217ca65b32" + "digest": "a900909f035bbec5eb67869b6b0c87648bcf3446171f2d16a862f5f3e672c437" } ], "provisional": { "arrow.json": "02bcc0c62d70f002336a54976a8dccee7c61dffd66a29a7a74c9fb3178d7a1b1", "datagram.json": "6dfd07810f954d7ba1a0e17db337643e6f5a1a579b982c3bc327a256e5e70665", - "pipeline.json": "48c29e9ed3658241324213506896744b9bf6f60249c8877a5fb935880ac0bde5", + "pipeline.json": "85d40b12b2beb5e33736bd6a025723469af8f25f960797e8a311c1fd722bee5f", "schema.json": "470ad4ae62ebe6d47c1ed5b84c3b46b618eb0e8fb9b6bdf6400ad6cdb602c60f", "semantic.json": "20bf56643b67baadb3fc62dd5d3c9f016bba5f642b3b69cb63d14561772a0dc5", "torch.json": "cdfb873bb0c0404ff57a1cf085517c8610cb7b41f1c87ec045f3e27ea1cde451" diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 3931aab3c..9facc8dc3 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -467,9 +467,12 @@ def __init__( f"{expected_data_schema}: {reason}" ) + output_keys = function_pod.data_function.output_data_schema.keys() + schema_utils.require_names_not_system( + {*incoming_tag_types, *incoming_data_types, *output_keys} + ) schema_utils.require_output_keys_not_tags( - incoming_tag_types.keys(), - function_pod.data_function.output_data_schema.keys(), + incoming_tag_types.keys(), output_keys ) self._input_stream = input_stream @@ -1375,10 +1378,10 @@ def _joined_from_stored( ) -> "pa.Table": """Build the joined records from the stored tables, by the rows Polars matched. - The layout is the one Polars' join and diagonal concatenation gave: every - pipeline-table column, then each result column other than the record id (a name - the pipeline table also has takes the suffix ``_right``), in order of first - appearance across ``parts``; a column a part lacks is null in that part's rows. + Pipeline columns come first, followed by result columns in order of first + appearance across ``parts``. The result's copy of the record id is skipped. + Overlaps take the suffix ``_right``. Input and output tokens already have + distinct names. A column a part lacks is null in that part's rows. Args: matched: The matched rows, in output order: a ``_TAGINFO_ROW`` column and, @@ -1400,7 +1403,7 @@ def _joined_from_stored( for name in results.column_names: if name == constants.DATA_RECORD_ID: continue - out = f"{name}_right" if name in taginfo.column_names else name + out = f"{name}_right" if name in names else name result_names.setdefault(out, name) part_rows = [] for row_column, _ in parts: @@ -3324,7 +3327,7 @@ def _add_pipeline_record( # (``row_ids.instance_id_preimage`` takes the same table): a stored row # gives its instance id again from its own columns, whatever their types # (ITL-1471). Never typed again from the token values. - input_source_table = input_data.source_info_table() + input_source_table = row_ids.input_source_info_table(input_data) # Build the meta columns table. meta_table = pa.Table.from_pydict( @@ -3430,16 +3433,36 @@ def _preflight_pipeline_write_schema(self) -> None: path = self._versioned_pipeline_path existing = database.get_table_schema(path) if existing is not None: + self._check_pipeline_source_columns(database, path, existing) self._check_pipeline_write_schema(database, path, existing) # The type of each token column the table holds, for # ``_require_one_type_per_token_column``. self._token_column_types = { field.name: arrow_utils.normalize_to_large_types(field.type, keep_null=True) for field in existing or () - if field.name.startswith(constants.SOURCE_PREFIX) + if field.name.startswith(constants.INPUT_SOURCE_PREFIX) } self._pipeline_preflight_checked = True + def _check_pipeline_source_columns( + self, + database: ArrowDatabaseProtocol, + path: tuple[str, ...], + schema: pa.Schema, + ) -> None: + """Refuse pre-rename input tokens stored at the same layout path.""" + old_columns = [ + name for name in schema.names if name.startswith(constants.SOURCE_PREFIX) + ] + if old_columns: + raise StoredTableSchemaError( + f"Incompatible input source-info columns in the " + f"{describe_database_table(database, path)}: {old_columns}. " + f"Expected {constants.INPUT_SOURCE_PREFIX}. " + "Rebuild the pipeline table with the current version of Orcapod.", + node_label=self.label, + ) + def _check_pipeline_write_schema( self, database: ArrowDatabaseProtocol, @@ -3491,7 +3514,9 @@ def get_all_records( Calls ``_fetch_joined_records`` to obtain the raw joined table, then applies ``ColumnConfig``-driven column dropping to produce a - user-facing result. ``NODE_CONTENT_HASH_COL``, ``RECORD_ID_COL``, + user-facing result. When source info is requested, input tokens use + ``_input_source_`` and output tokens and fall-through data-tags use + ``_source_``. ``NODE_CONTENT_HASH_COL``, ``RECORD_ID_COL``, and ``INSTANCE_ID_COL`` are always dropped — they are internal discriminator columns, not user-facing data. These columns are listed explicitly to ensure they are @@ -3545,7 +3570,11 @@ def get_all_records( ) if not column_config.source and not column_config.all_info: drop_columns.extend( - c for c in joined.column_names if c.startswith(constants.SOURCE_PREFIX) + c + for c in joined.column_names + if c.startswith( + (constants.SOURCE_PREFIX, constants.INPUT_SOURCE_PREFIX) + ) ) if not column_config.system_tags and not column_config.all_info: drop_columns.extend( @@ -3652,6 +3681,9 @@ def _stored_provenance( context_key = self._stored_data_context_key entries = self._pipeline_database.get_all_records(self._versioned_pipeline_path) if entries is not None: + self._check_pipeline_source_columns( + self._pipeline_database, self._versioned_pipeline_path, entries.schema + ) entries = keep_rows_of_data_context(entries, context_key) if self._table_scope == "pipeline_hash": own_hash = self.content_hash().to_prefixed_digest() @@ -3740,6 +3772,10 @@ def _fetch_joined_records( if taginfo is None: return None + self._check_pipeline_source_columns( + self._pipeline_database, self._versioned_pipeline_path, taginfo.schema + ) + # Rows written under another data context are not this node's current # entries: they stay in the table untouched (ITL-944). Result rows are # reached only through the pipeline rows kept here. @@ -3956,6 +3992,15 @@ def _fetch_joined_records( else (taginfo_schema, results_schema) ), ) + # A fall-through data-tag uses its input token as its output token. + # Other input tokens keep their distinct names for the joined record view. + fall_through_tokens = { + constants.INPUT_SOURCE_PREFIX + name: constants.SOURCE_PREFIX + name + for name in data_tags + } + joined = joined.rename_columns( + [fall_through_tokens.get(name, name) for name in joined.column_names] + ) # In memory, each row names its data context in the datagram context column. joined = joined.append_column( pa.field(constants.CONTEXT_KEY, pa.large_string(), nullable=False), @@ -3998,7 +4043,7 @@ def _placeholder_source_info( return { key: gone[key] if key in gone - else row.get(f"{constants.SOURCE_PREFIX}{key}") + else row.get(f"{constants.INPUT_SOURCE_PREFIX}{key}") for key in data_keys } @@ -4053,7 +4098,7 @@ def _stored_tag_keys(self, fetched: _JoinedRecords) -> tuple[str, ...]: c for c in fetched.taginfo_columns if not c.startswith(constants.META_PREFIX) - and not c.startswith(constants.SOURCE_PREFIX) + and not c.startswith(constants.INPUT_SOURCE_PREFIX) and not c.startswith(constants.SYSTEM_TAG_PREFIX) and c != RECORD_ID_COL and c != constants.NODE_CONTENT_HASH_COL @@ -4107,7 +4152,7 @@ def _stored_rows_stream( drop_cols = [ c for c in joined.column_names - if c.startswith(constants.META_PREFIX) + if c.startswith((constants.META_PREFIX, constants.INPUT_SOURCE_PREFIX)) or c == constants.NODE_CONTENT_HASH_COL ] data_ids = [uuid.UUID(bytes=result_ids[row]) for row in chosen_row.values()] diff --git a/src/orcapod/core/row_ids.py b/src/orcapod/core/row_ids.py index d854c74d1..166059534 100644 --- a/src/orcapod/core/row_ids.py +++ b/src/orcapod/core/row_ids.py @@ -109,6 +109,24 @@ def entry_id( raise +def input_source_info_table(data: "DataProtocol") -> "pa.Table": + """Return the typed token columns shared by the pipeline row and instance id. + + Args: + data: The function node's input row, possibly an ``EmptyData`` placeholder. + + Returns: + The input's source-info columns, prefixed for the function pipeline table. + """ + tokens = data.source_info_table() + return tokens.rename_columns( + [ + constants.INPUT_SOURCE_PREFIX + name.removeprefix(constants.SOURCE_PREFIX) + for name in tokens.column_names + ] + ) + + def instance_id_preimage(entry: "ContentHash", data: "DataProtocol") -> "pa.Table": """Build the preimage of a row's instance id. @@ -118,15 +136,15 @@ def instance_id_preimage(entry: "ContentHash", data: "DataProtocol") -> "pa.Tabl Returns: A one-row table: ``__pipeline_entry_id`` (``large_binary``, the labelled - digest of the entry id), then the source-info columns of the data in name - order. A placeholder that carries no token gives the entry id alone. + digest of the entry id), then the pipeline row's input-token columns in + name order. A placeholder that carries no token gives the entry id alone. """ preimage = pa.table( {ENTRY_ID_COL: pa.array([entry.to_prefixed_digest()], type=pa.large_binary())} ) # A placeholder (``EmptyData``) gives the tokens it carries here, and no column # when it carries none. - tokens = data.source_info_table() + tokens = input_source_info_table(data) for name in sorted(tokens.column_names): preimage = preimage.append_column( tokens.schema.field(name), tokens.column(name) diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 7343f5798..dc5dee6f2 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -625,6 +625,7 @@ def _origin_records(self) -> "pa.Table | None": ( constants.META_PREFIX, constants.SOURCE_PREFIX, + constants.INPUT_SOURCE_PREFIX, constants.SYSTEM_TAG_PREFIX, ), ) diff --git a/src/orcapod/pipeline/provenance.py b/src/orcapod/pipeline/provenance.py index 8d2c7b390..6d5041996 100644 --- a/src/orcapod/pipeline/provenance.py +++ b/src/orcapod/pipeline/provenance.py @@ -1018,12 +1018,11 @@ def _token_mismatch(entry: Row, input_row: Row) -> tuple[str, Any] | None: column the two share is equal. """ for name, stored in entry.items(): - if ( - name.startswith(constants.SOURCE_PREFIX) - and name in input_row - and input_row[name] != stored - ): - return name, stored + if name.startswith(constants.INPUT_SOURCE_PREFIX): + column = name.removeprefix(constants.INPUT_SOURCE_PREFIX) + stream_name = constants.SOURCE_PREFIX + column + if stream_name in input_row and input_row[stream_name] != stored: + return stream_name, stored return None @@ -1760,7 +1759,7 @@ def function_step( # every input token it stores must name that record. own = _pairs(entry, _system_tags(entry)) for name in sorted( - c for c in entry if c.startswith(constants.SOURCE_PREFIX) + c for c in entry if c.startswith(constants.INPUT_SOURCE_PREFIX) ): token = entry[name] if isinstance(token, str): @@ -1779,7 +1778,8 @@ def function_step( None, held=False, member=None, - token_column=name, + token_column=constants.SOURCE_PREFIX + + name.removeprefix(constants.INPUT_SOURCE_PREFIX), input_hash=_hash_text( entry[constants.INPUT_DATA_HASH_COL] ), diff --git a/src/orcapod/system_constants.py b/src/orcapod/system_constants.py index 25cb8632d..df8981d97 100644 --- a/src/orcapod/system_constants.py +++ b/src/orcapod/system_constants.py @@ -2,6 +2,7 @@ SYSTEM_COLUMN_PREFIX = "__" DATAGRAM_PREFIX = "_" SOURCE_INFO_PREFIX = "source_" +INPUT_SOURCE_INFO_PREFIX = "input_source_" POD_ID_PREFIX = "pod_id_" PF_VARIATION_PREFIX = "pf_var_" PF_EXECUTION_PREFIX = "pf_exec_" @@ -64,6 +65,11 @@ def DATAGRAM_PREFIX(self) -> str: def SOURCE_PREFIX(self) -> str: return f"{self._global_prefix}{DATAGRAM_PREFIX}{SOURCE_INFO_PREFIX}" + @property + def INPUT_SOURCE_PREFIX(self) -> str: + """Prefix of a function pipeline row's stored and hashed input tokens.""" + return f"{self._global_prefix}{DATAGRAM_PREFIX}{INPUT_SOURCE_INFO_PREFIX}" + @property def CONTEXT_KEY(self) -> str: return f"{self._global_prefix}{DATAGRAM_PREFIX}{DATA_CONTEXT_KEY}" diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index d9d70fba5..22d69eefe 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -1084,6 +1084,8 @@ def _column_role( return "tag" if name in system_tag_columns or name.startswith(constants.SYSTEM_TAG_PREFIX): return "system-tag" + if name.startswith(constants.INPUT_SOURCE_PREFIX): + return "input source-info" if name.startswith(constants.SOURCE_PREFIX): return "source-info" if name == constants.CONTEXT_KEY: @@ -1226,22 +1228,23 @@ def require_names_not_system(names: Collection[str]) -> None: (``_tag_``) as a system tag, one that starts with the source-info prefix (``_source_``) as source info, and the context key column (``_context_key``) as the data context, so a tag or data column renamed to such a name stops - being one (ITL-1160). The meta prefix has its own check, + being one (ITL-1160). Function pipeline tables also reserve a prefix for + input source info. The meta prefix has its own check, ``require_names_not_meta``. Args: names: Tag or data column names. Raises: - InputValidationError: If a name starts with the system-tag or the - source-info prefix, or is the context key column. The message names - the column. + InputValidationError: If a name starts with a reserved prefix or is the + context key column. The message names the column. """ from orcapod.system_constants import constants reserved_prefixes = { constants.SYSTEM_TAG_PREFIX: "system tags", constants.SOURCE_PREFIX: "source info", + constants.INPUT_SOURCE_PREFIX: "input source info", } for name in sorted(names): for prefix, kind in reserved_prefixes.items(): diff --git a/tests/test_core/alignment/records.py b/tests/test_core/alignment/records.py index 7d1249aaf..a79e99749 100644 --- a/tests/test_core/alignment/records.py +++ b/tests/test_core/alignment/records.py @@ -1,10 +1,11 @@ """Check the function node's stored records row by row (ITL-1034). -A record of ``scaled`` holds the input row's tags and system tags, the input's source-info -token, the output, and bookkeeping. Each per-row column is recomputed from the record and -its origin row: +A joined record of ``scaled`` holds the input row's tags, system tags and source-info +token, the output, and bookkeeping. The source-info token is also checked in the +pipeline table. +Each per-row column is recomputed from the record and its origin row: -* the record id is the origin row's, the input token ``_source_x`` names that row; +* the record id is the origin row's, and both copies of the input token name that row; * ``y`` is ``gated_scale`` of the origin's ``x``; * ``__output_data_hash`` is the Arrow hash of the record's own ``y``; * ``__input_data_hash`` (and its ``_right`` copy) is the Arrow hash of the origin's ``x``, @@ -31,6 +32,7 @@ from orcapod import PipelineJob from orcapod.core.nodes.function_node import ( + FunctionJobNode, PIPELINE_RECORDED_AT_COL, PIPELINE_RUN_ID_COL, ) @@ -77,9 +79,12 @@ def assert_records_aligned( this checker passes a tampered copy). """ node = job.nodes["scaled"] + assert isinstance(node, FunctionJobNode) if records is None: records = node.get_all_records(all_info=True) assert records is not None and records.num_rows > 0, "no records stored" + pipeline, _ = node._stored_provenance(results=False) # pyright: ignore[reportPrivateUsage] # raw pipeline entries + assert pipeline is not None outputs = node_outputs(job) context = node.data_context hasher = context.arrow_hasher @@ -95,11 +100,12 @@ def assert_records_aligned( for c in records.column_names if c.startswith(constants.SYSTEM_TAG_RECORD_ID_PREFIX) ] + input_token = constants.INPUT_SOURCE_PREFIX + "x" covered = { *tag_keys, source_id_column, record_id_column, - "_source_x", + input_token, "y", "_source_y", "__data_id", @@ -139,6 +145,10 @@ def assert_records_aligned( f"{sum((wanted - stored).values())} missing, " f"{sum((stored - wanted).values())} extra or repeated" ) + assert Counter(pipeline.column(record_id_column).to_pylist()) == wanted + input_tokens = { + row[record_id_column]: row[input_token] for row in pipeline.to_pylist() + } failures: list[str] = [] for index, row in enumerate(records.to_pylist()): @@ -154,9 +164,17 @@ def fail(column: str, message: str, index: int = index) -> None: for tag in tag_keys: if row[tag] != origin.values[tag]: fail(tag, f"{row[tag]!r}, its row has {origin.values[tag]!r}") - if row["_source_x"] != f"{origin.source_id}::{origin.token}::x": + expected_token = f"{origin.source_id}::{origin.token}::x" + if row[input_token] != expected_token: + fail( + input_token, + f"joined token {row[input_token]!r} should be {expected_token!r}", + ) + pipeline_token = input_tokens[row[record_id_column]] + if pipeline_token != expected_token: fail( - "_source_x", f"{row['_source_x']!r} does not name row {origin.token!r}" + input_token, + f"pipeline token {pipeline_token!r} should be {expected_token!r}", ) if row["y"] != oracle.expected_value("y", origin): fail("y", f"{row['y']!r} is not the output for row {origin.token!r}") diff --git a/tests/test_core/alignment/test_checker.py b/tests/test_core/alignment/test_checker.py index 7f2ab8514..00ac7baa3 100644 --- a/tests/test_core/alignment/test_checker.py +++ b/tests/test_core/alignment/test_checker.py @@ -290,6 +290,16 @@ def test_stored_records_with_a_swapped_output_id_are_named(tmp_path: Path) -> No assert_records_aligned(run.job, run.sources, swapped) +def test_stored_records_with_swapped_input_tokens_are_named(tmp_path: Path) -> None: + """A joined input token names the same source row as its record.""" + run = make_run("unique", "shuffled", "sync", None, "in_memory", tmp_path) + records = run.job.nodes["scaled"].get_all_records(all_info=True) + assert records is not None + input_token = constants.INPUT_SOURCE_PREFIX + "x" + with pytest.raises(AssertionError, match=f"column '{input_token}': joined token"): + assert_records_aligned(run.job, run.sources, rotated(records, input_token)) + + def test_stored_records_with_a_wrong_function_uri_are_named(tmp_path: Path) -> None: """A ``_source_y`` token whose uuid is right but whose function uri is not fails.""" run = make_run("unique", "shuffled", "sync", None, "in_memory", tmp_path) diff --git a/tests/test_core/function_pod/test_function_node_caching.py b/tests/test_core/function_pod/test_function_node_caching.py index 0c48e13c6..b61874afc 100644 --- a/tests/test_core/function_pod/test_function_node_caching.py +++ b/tests/test_core/function_pod/test_function_node_caching.py @@ -397,9 +397,9 @@ def test_pipeline_record_contains_source_columns(self): source_cols = [ c for c in pipeline_records.column_names - if c.startswith(constants.SOURCE_PREFIX) + if c.startswith(constants.INPUT_SOURCE_PREFIX) ] - assert len(source_cols) > 0 + assert source_cols == [constants.INPUT_SOURCE_PREFIX + "x"] def test_pipeline_record_excludes_data_columns_of_input(self): """Pipeline records should NOT include data columns of the input data.""" diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 077303fc4..eccd8406e 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -551,7 +551,7 @@ def test_refuses_field_metadata_on_custom_system_tags( _source(kind, table, tmp_path, monkeypatch, system_tag_columns=names) -def test_metadata_free_custom_system_tag_keeps_its_existing_row_ids() -> None: +def test_metadata_free_custom_system_tag_pins_its_row_ids() -> None: schema = pa.schema( [ pa.field("k", pa.int64(), False), @@ -585,17 +585,17 @@ def test_metadata_free_custom_system_tag_keeps_its_existing_row_ids() -> None: instance = instance_id(hasher, tag, data) record = record_id(hasher, source.content_hash(), instance, UUID(int=40)) actual.append((entry.to_hex(), instance.to_hex(), record.to_hex())) - # The metadata-free source's hashes at 969ed093. + # The instance and record IDs include the renamed input-token fields. assert actual == [ ( "00000266ff2e58dd5c1cb957ac9ff249ae13e17918a263847f8e2f65d756f746b3f561", - "000002e9be964a36d499b5a1efe697c53d9b7e2e0103b79be7b0e2d489c1be8f7b8636", - "00000279f295215ecb6c92fc49cf4ec41df41327a43c3b351f0baac467b4f45a0f33d2", + "000002901df30a2ba140f32dbf43fec67d5d05b93d43bdb713c5ee9da604df0fba61fe", + "00000230cd4fe35505c96c89980db40437e444042e52df8f0117521f7f55ceb651db3b", ), ( "0000029689a4a738cf93bbcfde75085dc43bac31570b0b368eff34b0f3d0fa427769c1", - "000002b6b64a14a2bb8cc662759a15839f8e4e730c89a03230bb8cac2f951fbe8f2002", - "000002fb3fc3affffe0e390dcfb5695db61b332eb2d38f83c2cfab5570c8a956371e18", + "0000023448cf6a0cceaa94adcfbf1b67e743d3cb08b4dc57f8dc43e2f26a7cc266bfa6", + "00000230008bd2bc72708ead139fe14cac0fe8107521cfc70089cc44c3b43e0d7a9df9", ), ] diff --git a/tests/test_core/test_row_ids.py b/tests/test_core/test_row_ids.py index 6beafe11f..b81db7b06 100644 --- a/tests/test_core/test_row_ids.py +++ b/tests/test_core/test_row_ids.py @@ -75,16 +75,16 @@ def test_with_source_info_uses_the_later_alias_in_every_view(scalar_last: bool) assert updated.source_info() == {"x": expected, "y": "kept"} entry = row_ids.entry_id(HASHER, _tag(), updated) - for table in ( - updated.as_table(columns={"source": True}), - updated.source_info_table(), - row_ids.instance_id_preimage(entry, updated), + for table, prefix in ( + (updated.as_table(columns={"source": True}), constants.SOURCE_PREFIX), + (updated.source_info_table(), constants.SOURCE_PREFIX), + (row_ids.instance_id_preimage(entry, updated), constants.INPUT_SOURCE_PREFIX), ): - assert table.column("_source_x").to_pylist() == [expected] - assert table.schema.field("_source_x").type.equals( + assert table.column(prefix + "x").to_pylist() == [expected] + assert table.schema.field(prefix + "x").type.equals( expected_type, check_metadata=True ) - assert table.column("_source_y").to_pylist() == ["kept"] + assert table.column(prefix + "y").to_pylist() == ["kept"] def test_with_source_info_keeps_a_scalar_type_its_value_cannot_show() -> None: @@ -98,16 +98,16 @@ def test_with_source_info_keeps_a_scalar_type_its_value_cannot_show() -> None: assert updated.source_info() == {"x": token, "y": "kept"} entry = row_ids.entry_id(HASHER, _tag(), updated) - for table in ( - updated.as_table(columns={"source": True}), - updated.source_info_table(), - row_ids.instance_id_preimage(entry, updated), + for table, prefix in ( + (updated.as_table(columns={"source": True}), constants.SOURCE_PREFIX), + (updated.source_info_table(), constants.SOURCE_PREFIX), + (row_ids.instance_id_preimage(entry, updated), constants.INPUT_SOURCE_PREFIX), ): - assert table.column("_source_x").to_pylist() == [token] - assert table.schema.field("_source_x").type.equals( + assert table.column(prefix + "x").to_pylist() == [token] + assert table.schema.field(prefix + "x").type.equals( token_type, check_metadata=True ) - assert table.column("_source_y").to_pylist() == ["kept"] + assert table.column(prefix + "y").to_pylist() == ["kept"] @pytest.mark.parametrize( @@ -201,17 +201,17 @@ def test_the_preimage_is_the_labelled_entry_id_then_the_tokens_in_name_order( preimage = row_ids.instance_id_preimage(entry, data) assert preimage.column_names == [ "__pipeline_entry_id", - "_source_length", - "_source_note", - "_source_weight", + "_input_source_length", + "_input_source_note", + "_input_source_weight", ] assert preimage.schema.field("__pipeline_entry_id").type == pa.large_binary() assert preimage.to_pylist() == [ { "__pipeline_entry_id": entry.to_prefixed_digest(), - "_source_length": TOKENS["length"], - "_source_note": TOKENS["note"], - "_source_weight": TOKENS["weight"], + "_input_source_length": TOKENS["length"], + "_input_source_note": TOKENS["note"], + "_input_source_weight": TOKENS["weight"], } ] @@ -222,7 +222,7 @@ def test_the_id_is_the_arrow_hash_of_the_preimage(self) -> None: { "__pipeline_entry_id": _binary(entry.to_prefixed_digest()), **{ - f"_source_{name}": pa.array([TOKENS[name]], pa.large_string()) + f"_input_source_{name}": pa.array([TOKENS[name]], pa.large_string()) for name in sorted(TOKENS) }, } @@ -272,7 +272,7 @@ def test_instance_id_guidance_accounts_for_arrow_list_kind(self) -> None: root = Path(__file__).resolve().parents[2] for guide in ("CLAUDE.md", ".zed/rules"): text = (root / guide).read_text() - guidance = text.split("- The instance id reads a row's tokens", 1)[1].split( + guidance = text.split("For the same entry and token values", 1)[1].split( "\n- A trace resolves", 1 )[0] assert "fixed-size list" in guidance, guide @@ -391,10 +391,10 @@ def test_a_placeholder_with_tokens_is_hashed_as_any_row_with_those_tokens( by_hand = pa.table( { "__pipeline_entry_id": _binary(entry.to_prefixed_digest()), - "_source_y": pa.array( + "_input_source_y": pa.array( [f"{source}::EPHEMERAL_RESULT_GONE::y"], pa.large_string() ), - "_source_z": pa.array( + "_input_source_z": pa.array( [f"{source}::EPHEMERAL_RESULT_GONE::z"], pa.large_string() ), } @@ -544,9 +544,12 @@ def test_an_ordinary_rows_instance_id_is_the_one_its_own_table_gives(self) -> No by_hand = pa.table( {"__pipeline_entry_id": _binary(entry.to_prefixed_digest())} ) - for name in ("_source_a", "_source_b"): + for name in ("a", "b"): + stream_name = constants.SOURCE_PREFIX + name + stored_name = constants.INPUT_SOURCE_PREFIX + name by_hand = by_hand.append_column( - own.schema.field(name), own.column(name) + own.schema.field(stream_name).with_name(stored_name), + own.column(stream_name), ) assert row_ids.instance_id(HASHER, tag, data) == HASHER.hash_table(by_hand) ids.add(row_ids.instance_id(HASHER, tag, data)) @@ -566,10 +569,10 @@ def test_a_nested_token_column_is_read_with_its_type_and_never_typed_again( ) assert preimage.column_names == [ "__pipeline_entry_id", - "_source_a", - "_source_b", + "_input_source_a", + "_input_source_b", ] - assert preimage.schema.field("_source_a").type == self.NESTED + assert preimage.schema.field("_input_source_a").type == self.NESTED ids.add(row_ids.instance_id(HASHER, tag, data)) # The row's table gives the same typed column, never one typed again # from the token's value, which fails for the first two rows (ITL-1491). @@ -823,7 +826,7 @@ def test_every_view_gives_the_renamed_columns_own_token( row_ids.entry_id(HASHER, _tag(), renamed), renamed ) for name, token in expected.items(): - assert preimage.column(f"_source_{name}").to_pylist() == [token] + assert preimage.column(f"_input_source_{name}").to_pylist() == [token] ids.add(row_ids.instance_id(HASHER, _tag(), renamed)) # Renaming back gives the first row's tokens again. back = renamed.rename({new: old for old, new in mapping.items()}) diff --git a/tests/test_hashing/golden/cases.py b/tests/test_hashing/golden/cases.py index 04967742a..20be2e211 100644 --- a/tests/test_hashing/golden/cases.py +++ b/tests/test_hashing/golden/cases.py @@ -2350,6 +2350,85 @@ def pipeline_job() -> dict[str, Any]: return out +def _data_tag_source() -> Any: + """A source with two data-tags, one plain tag and a composite record key.""" + from orcapod.sources import DictSource + + return DictSource( + data=[ + {"trial": 2, "subject": "s2", "age": 4, "weight": 22.25}, + {"trial": 1, "subject": "s1", "age": 3, "weight": 20.5}, + ], + tag_columns=["trial", "subject", "age"], + tag_only_columns=["subject"], + record_id_columns=["subject", "trial"], + source_id="golden_data_tags", + ) + + +def _data_tag_summary(stream: Any) -> dict[str, Any]: + """Pin ordered keys and both halves of a data-tag stream's Arrow schema.""" + from orcapod.utils.schema_utils import arrow_schema_identity + + tag_keys, data_keys = stream.keys() + schema = stream.arrow_schema() + tag_hash, data_hash = arrow_schema_identity( + pa.schema([schema.field(name) for name in tag_keys]), + pa.schema([schema.field(name) for name in data_keys]), + _ctx(), + ) + return { + **stream_summary(stream), + "tag_keys": list(tag_keys), + "data_keys": list(data_keys), + "tag_schema_hash": tag_hash.to_string(), + "data_schema_hash": data_hash.to_string(), + } + + +@case("pipeline", "data_tag_stream") +def pipeline_data_tag_stream() -> dict[str, Any]: + """Pin a stream's identity with plain tags alongside data-tags.""" + return _data_tag_summary(_data_tag_source()) + + +@case("pipeline", "data_tag_job") +def pipeline_data_tag_job() -> dict[str, Any]: + """Pin a function node's fall-through data-tags and their stored markers.""" + from orcapod import PipelineJob + from orcapod.core.data_tags import TAG_KIND_METADATA_KEY + from orcapod.core.row_ids import INSTANCE_ID_COL + from orcapod.databases import InMemoryArrowDatabase + from orcapod.system_constants import PIPELINE_DB_SCHEMA_VERSION + + db = InMemoryArrowDatabase() + job = PipelineJob(name="golden_data_tag_job", database=db) + with job: + golden_ratio.pod(_data_tag_source(), label="ratio") + job.run() + + paths = sorted(db.list_sources()) + (path,) = [path for path in paths if path[-1] == PIPELINE_DB_SCHEMA_VERSION] + records = db.get_all_records(path) + assert records is not None + return { + **_data_tag_summary(job.nodes["ratio"]), + "table_paths": ["/".join(path) for path in paths], + "stored_tag_markers": { + field.name: { + key.decode("ascii"): value.decode("ascii") + for key, value in (field.metadata or {}).items() + if key == TAG_KIND_METADATA_KEY + } + for field in records.schema + if TAG_KIND_METADATA_KEY in (field.metadata or {}) + }, + "stored_instance_ids": sorted( + _jsonable(value) for value in records[INSTANCE_ID_COL].to_pylist() + ), + } + + # --------------------------------------------------------------------------- # Polars values (ITL-578) — semantic, schema and datagram entries # --------------------------------------------------------------------------- diff --git a/tests/test_hashing/golden/data/v1/pipeline-02.json b/tests/test_hashing/golden/data/v1/pipeline-02.json index a6ace3e94..47164f1de 100644 --- a/tests/test_hashing/golden/data/v1/pipeline-02.json +++ b/tests/test_hashing/golden/data/v1/pipeline-02.json @@ -47,6 +47,70 @@ "_tag_source_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192", "_tag_record_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192" ], + "data_tag_job.content_hash": "content_hash_v1:efb20f31fba892f1be3f8822050cc3d7ce3479a7948e88558145bb0d090073ef", + "data_tag_job.data_keys": [ + "trial", + "age", + "ratio" + ], + "data_tag_job.data_schema_hash": "arrow_schema_v1:0000022ec17c304a1d09f91811549760cab0b8fcb6e1c73fc6cc3ade5bd036834c2636", + "data_tag_job.pipeline_hash": "semantic_v1:49987a29b908ccfb9bb0d1e2832b7d515747c41f588d2e0dcb44f56d1b964c88", + "data_tag_job.row[{\"age\":3,\"subject\":\"s1\",\"trial\":1}]._tag_record_id::584bd9a046b3bbe851c09822c321d71ec60664329bde26319b300dc0d87012f4": "{\"subject\":\"s1\",\"trial\":1}", + "data_tag_job.row[{\"age\":3,\"subject\":\"s1\",\"trial\":1}]._tag_source_id::584bd9a046b3bbe851c09822c321d71ec60664329bde26319b300dc0d87012f4": "dict_v1:golden_data_tags", + "data_tag_job.row[{\"age\":3,\"subject\":\"s1\",\"trial\":1}].data_hash": "arrow_v1:00000239902e8f095dee770d757237428da61061e52aceb02acf352267974f36e50c7b", + "data_tag_job.row[{\"age\":4,\"subject\":\"s2\",\"trial\":2}]._tag_record_id::584bd9a046b3bbe851c09822c321d71ec60664329bde26319b300dc0d87012f4": "{\"subject\":\"s2\",\"trial\":2}", + "data_tag_job.row[{\"age\":4,\"subject\":\"s2\",\"trial\":2}]._tag_source_id::584bd9a046b3bbe851c09822c321d71ec60664329bde26319b300dc0d87012f4": "dict_v1:golden_data_tags", + "data_tag_job.row[{\"age\":4,\"subject\":\"s2\",\"trial\":2}].data_hash": "arrow_v1:00000287af454c38539c94842f772934b7ff62c23fb8949b6ddfb40ff926b32cb0eacf", + "data_tag_job.stored_instance_ids": [ + "arrow_v1:0000023b0ff41778a0bbc1f1c6954175963f0e21db3e1a1c2ffa3545f6d41dbc5ff862", + "arrow_v1:0000026bf0df3edc2e2c789bc5b6489da3470fd022dab42ff0972726395c330d21eaeb" + ], + "data_tag_job.stored_tag_markers": { + "age": { + "orcapod:tag_kind": "data_tag" + }, + "trial": { + "orcapod:tag_kind": "data_tag" + } + }, + "data_tag_job.system_tag_columns": [ + "_tag_source_id::584bd9a046b3bbe851c09822c321d71ec60664329bde26319b300dc0d87012f4", + "_tag_record_id::584bd9a046b3bbe851c09822c321d71ec60664329bde26319b300dc0d87012f4" + ], + "data_tag_job.table_paths": [ + "golden_data_tag_job/_result/golden_ratio/43ebfd98b0b9497b3b820bb330f4727dd540e67883fd7588fdd98d1f176733b3/v0/python.function.v1/rev1/rdb_v1", + "golden_data_tag_job/golden_ratio/43ebfd98b0b9497b3b820bb330f4727dd540e67883fd7588fdd98d1f176733b3/v0/python.function.v1/schema:49987a29b908ccfb9bb0d1e2832b7d515747c41f588d2e0dcb44f56d1b964c88/pdb_v2" + ], + "data_tag_job.tag_keys": [ + "trial", + "subject", + "age" + ], + "data_tag_job.tag_schema_hash": "arrow_schema_v1:000002b3b7ec70f44caa31850b902b08c37707e1e75e04fd57683e3a1ba826a1cd467b", + "data_tag_stream.content_hash": "semantic_v1:2cef6ca2ca1fe26f024be4df695463df7766b2894e320ca8fb2d8bb19a78d7c7", + "data_tag_stream.data_keys": [ + "trial", + "age", + "weight" + ], + "data_tag_stream.data_schema_hash": "arrow_schema_v1:000002d2bde4bbeb39126365d26bbb4d29abceec1276b0ac1d950545420c1d40949ae6", + "data_tag_stream.pipeline_hash": "semantic_v1:584bd9a046b3bbe851c09822c321d71ec60664329bde26319b300dc0d87012f4", + "data_tag_stream.row[{\"age\":3,\"subject\":\"s1\",\"trial\":1}]._tag_record_id::584bd9a046b3bbe851c09822c321d71ec60664329bde26319b300dc0d87012f4": "{\"subject\":\"s1\",\"trial\":1}", + "data_tag_stream.row[{\"age\":3,\"subject\":\"s1\",\"trial\":1}]._tag_source_id::584bd9a046b3bbe851c09822c321d71ec60664329bde26319b300dc0d87012f4": "dict_v1:golden_data_tags", + "data_tag_stream.row[{\"age\":3,\"subject\":\"s1\",\"trial\":1}].data_hash": "arrow_v1:000002e7472f9fccdabe79bfc2e4a0dd13bebaf2a9a185d916e36e87055d9c3efaf3d3", + "data_tag_stream.row[{\"age\":4,\"subject\":\"s2\",\"trial\":2}]._tag_record_id::584bd9a046b3bbe851c09822c321d71ec60664329bde26319b300dc0d87012f4": "{\"subject\":\"s2\",\"trial\":2}", + "data_tag_stream.row[{\"age\":4,\"subject\":\"s2\",\"trial\":2}]._tag_source_id::584bd9a046b3bbe851c09822c321d71ec60664329bde26319b300dc0d87012f4": "dict_v1:golden_data_tags", + "data_tag_stream.row[{\"age\":4,\"subject\":\"s2\",\"trial\":2}].data_hash": "arrow_v1:0000027e68e7ddfff929c16044c587530a6d183ee70b29b68805fbafb93cb5941c13a7", + "data_tag_stream.system_tag_columns": [ + "_tag_source_id::584bd9a046b3bbe851c09822c321d71ec60664329bde26319b300dc0d87012f4", + "_tag_record_id::584bd9a046b3bbe851c09822c321d71ec60664329bde26319b300dc0d87012f4" + ], + "data_tag_stream.tag_keys": [ + "trial", + "subject", + "age" + ], + "data_tag_stream.tag_schema_hash": "arrow_schema_v1:000002b3b7ec70f44caa31850b902b08c37707e1e75e04fd57683e3a1ba826a1cd467b", "default_source_ids.arrow_table.content_hash": "semantic_v1:4066df55dd21824c80797995f64049379111024b273c83e2f91002d6e623272b", "default_source_ids.arrow_table.source_id": "arrow_table_v1:arrow_v1:000002e12eafa1dc72203ca9da1ca5d064031683cf089f47bad40744ecd2c923d0fde3", "default_source_ids.data_frame.content_hash": "semantic_v1:e05a59f9fb3c21f836ca134dd4bca5bd50dcff548163fcea65a22a701078ffbd", @@ -168,8 +232,8 @@ "arrow_v1:000002c619a23da2daa78b89cb32837af1561a1e6613d3ef0af83cf95506abeeedab1f" ], "drop_nulls_job.table[golden_drop_null_job/golden_ratio/43ebfd98b0b9497b3b820bb330f4727dd540e67883fd7588fdd98d1f176733b3/v0/python.function.v1/schema:fbe5ea222e164ffeeb59b89b9c4836a3f1b7e5f580dce814091fe75bb60bff20/pdb_v2].instance_ids": [ - "arrow_v1:0000028c8d0fceb1229d2c165c2ad826c24c504ea25fbab2b353f48144999f2971df1b", - "arrow_v1:000002be7cbed6d33fd41c6fe43dab281b19f4cffc813d6e3788a127a852c17dd9e918" + "arrow_v1:000002579e885e00630ac6851072500fa4c5e7370b203d21502c1c1d07599ff9c714bb", + "arrow_v1:000002a43c937aacdc43ea05f22c7429ff075bd178118e4e32bfe67aee15ed025850de" ], "drop_nulls_job.table_paths": [ "golden_drop_null_job/_result/golden_ratio/43ebfd98b0b9497b3b820bb330f4727dd540e67883fd7588fdd98d1f176733b3/v0/python.function.v1/rev1/rdb_v1", @@ -234,8 +298,8 @@ "arrow_v1:000002c945ad08138f51298940c60333852ef5191eb16077d96105386d44840c0ccfdf" ], "job.table[golden_job/golden_adjust/dff0617f9fe7bc2e6d071f4da43376bf59044ed9929bcce9812e9917bc95d39c/v0/python.function.v1/schema:b1212cbf9e4025086e622df7d8e9931ddde18946f29dda37568a13f36dfb39ef/pdb_v2].instance_ids": [ - "arrow_v1:0000024609444ffd64b9f53dd01cc32c3c347d475d3c81ab72bd79ee97852cc9fda584", - "arrow_v1:000002e0a4225b4f5ecc73b83d2423189934560f2bcd78674edfc15bf894c14ea0fa0f" + "arrow_v1:0000020c66959de9548e7d3650528ae6bfc48ff5d0fa035c97727ee6a06037a35c2159", + "arrow_v1:00000263ab846816825e2cb7725581120368e7831a2737dc507dae4607f22dbad64086" ], "job.table_paths": [ "golden_job/_result/golden_adjust/dff0617f9fe7bc2e6d071f4da43376bf59044ed9929bcce9812e9917bc95d39c/v0/python.function.v1/rev1/rdb_v1", diff --git a/tests/test_hashing/golden/data/v1/provisional/pipeline.json b/tests/test_hashing/golden/data/v1/provisional/pipeline.json index 2cec19604..a737a872a 100644 --- a/tests/test_hashing/golden/data/v1/provisional/pipeline.json +++ b/tests/test_hashing/golden/data/v1/provisional/pipeline.json @@ -153,7 +153,7 @@ "arrow_v1:0000026b8369e60be10e43dd72a0be4e8d93a992f827cd6baab33909331dcdaeea8b64" ], "filter_job.table[golden_filter_step_job/golden_adjust/dff0617f9fe7bc2e6d071f4da43376bf59044ed9929bcce9812e9917bc95d39c/v0/python.function.v1/schema:1b55d0d2cce6651fc52aed3a13227619ae3ba68ecd21f99ebfde5d68e56f4fa2/pdb_v2].instance_ids": [ - "arrow_v1:00000294e0adb82b308c36118fa4922a9f5c5da2455aa7f696ce09f3b4db4bfa3976e5" + "arrow_v1:00000221755088ee9838adaf67b9f9301cf889ff767d5ebca640d1fb6efb45cc28dc50" ], "filter_job.table_paths": [ "golden_filter_step_job/_result/golden_adjust/dff0617f9fe7bc2e6d071f4da43376bf59044ed9929bcce9812e9917bc95d39c/v0/python.function.v1/rev1/rdb_v1", @@ -510,7 +510,7 @@ "arrow_v1:0000026b8369e60be10e43dd72a0be4e8d93a992f827cd6baab33909331dcdaeea8b64" ], "polars_filter_expr_job.table[golden_filter_job/golden_adjust/dff0617f9fe7bc2e6d071f4da43376bf59044ed9929bcce9812e9917bc95d39c/v0/python.function.v1/schema:d41530868bebc0f11662b61d07ec45e0ae6bcee9b9602116392a103444a02cb7/pdb_v2].instance_ids": [ - "arrow_v1:000002e665d85abb2155b8d05406b74b6830fc09c5703c778d067946e692cba85cab7c" + "arrow_v1:000002116d85cae9eb021f9dce0473d3dd51804b96676fb373dff2e7e11f74ea503d48" ], "polars_filter_expr_job.table_paths": [ "golden_filter_job/_result/golden_adjust/dff0617f9fe7bc2e6d071f4da43376bf59044ed9929bcce9812e9917bc95d39c/v0/python.function.v1/rev1/rdb_v1", @@ -1490,9 +1490,9 @@ "arrow_v1:000002d1c5b49de38ef6efc552c2a47b8ab59dd267f8eb55d91814edee99b1b52acc65" ], "rejoin_job.table[golden_rejoin_job/golden_ratio/43ebfd98b0b9497b3b820bb330f4727dd540e67883fd7588fdd98d1f176733b3/v0/python.function.v1/schema:2940d188693a284739b066b85def5c18e849c85c1de5fc9a3444d6dfbb25e7ba/pdb_v2].instance_ids": [ - "arrow_v1:00000264d51dd01edfbb777f7047d25e7cdb50e4f52e6b01454ffc56b70aa5b166b920", - "arrow_v1:0000029b103c78b5c06ac0fe36d793fe576563a8609b835d662cf78a5828436f9b8aa3", - "arrow_v1:000002b71bb228680318fe2cc0fc599241136f0fedc28658bda79e2a90915b87c82ef0" + "arrow_v1:00000220b650bf7d360cb349e14a6118f03000bb6505cf436fa2fc5a87509a3e0b687d", + "arrow_v1:00000291d84b7660fc176e0749dad86a95d88abf0c40096e17f8de38a81ac59611906f", + "arrow_v1:000002b1be55546ea4161b66fb240ac0ce8a46e4cda69e43c91145000aad8143620d9a" ], "rejoin_job.table_paths": [ "golden_rejoin_job/_result/golden_ratio/43ebfd98b0b9497b3b820bb330f4727dd540e67883fd7588fdd98d1f176733b3/v0/python.function.v1/rev1/rdb_v1", @@ -1594,9 +1594,9 @@ "arrow_v1:000002d1c5b49de38ef6efc552c2a47b8ab59dd267f8eb55d91814edee99b1b52acc65" ], "rejoin_job_async.table[golden_rejoin_job/golden_ratio/43ebfd98b0b9497b3b820bb330f4727dd540e67883fd7588fdd98d1f176733b3/v0/python.function.v1/schema:2940d188693a284739b066b85def5c18e849c85c1de5fc9a3444d6dfbb25e7ba/pdb_v2].instance_ids": [ - "arrow_v1:00000264d51dd01edfbb777f7047d25e7cdb50e4f52e6b01454ffc56b70aa5b166b920", - "arrow_v1:0000029b103c78b5c06ac0fe36d793fe576563a8609b835d662cf78a5828436f9b8aa3", - "arrow_v1:000002b71bb228680318fe2cc0fc599241136f0fedc28658bda79e2a90915b87c82ef0" + "arrow_v1:00000220b650bf7d360cb349e14a6118f03000bb6505cf436fa2fc5a87509a3e0b687d", + "arrow_v1:00000291d84b7660fc176e0749dad86a95d88abf0c40096e17f8de38a81ac59611906f", + "arrow_v1:000002b1be55546ea4161b66fb240ac0ce8a46e4cda69e43c91145000aad8143620d9a" ], "rejoin_job_async.table_paths": [ "golden_rejoin_job/_result/golden_ratio/43ebfd98b0b9497b3b820bb330f4727dd540e67883fd7588fdd98d1f176733b3/v0/python.function.v1/rev1/rdb_v1", diff --git a/tests/test_hashing/golden/label_feeds.py b/tests/test_hashing/golden/label_feeds.py index d86f8abd9..5736f977c 100644 --- a/tests/test_hashing/golden/label_feeds.py +++ b/tests/test_hashing/golden/label_feeds.py @@ -31,6 +31,7 @@ from typing import Any from orcapod.core import identity_chains +from orcapod.core.row_ids import ENTRY_ID_COL RENAMED: dict[str, str] = { "semantic_v1": "renamedsemantic_v9", @@ -54,7 +55,7 @@ _PREFIXED = re.compile(rb"^([a-z][a-z0-9_]*):") _IDENTIFIER_METADATA = re.compile(r";([a-f0-9]{2,})") -_HASH_COLUMNS = ("__input_data_hash", "__node_content_hash") +_HASH_COLUMNS = ("__input_data_hash", "__node_content_hash", ENTRY_ID_COL) def rename_labels() -> None: diff --git a/tests/test_hashing/test_hash_site_inventory.py b/tests/test_hashing/test_hash_site_inventory.py index f0b87710f..879b865ca 100644 --- a/tests/test_hashing/test_hash_site_inventory.py +++ b/tests/test_hashing/test_hash_site_inventory.py @@ -115,6 +115,29 @@ def test_every_documented_site_exists() -> None: assert not stale, f"documented hash sites that no longer exist: {stale}" +def test_documented_instance_ids_match_the_worked_example() -> None: + """The Site 8 rows in the reference come from the runnable example.""" + result = subprocess.run( + [sys.executable, "scripts/hash_audit_example.py"], + capture_output=True, + text=True, + check=True, + cwd=PROJECT_ROOT, + env=_subprocess_env(), + ) + actual = dict( + re.findall(r"(\w+)\s+instance id \(hex\)\s+= '([0-9a-f]+)'", result.stdout) + ) + documented = dict( + re.findall( + r"\| 8 \| `(\w+)` instance id \| `([0-9a-f]+)` \|", + REFERENCE.read_text(encoding="utf-8"), + ) + ) + assert set(actual) == {"alice", "bob"} + assert documented == actual + + _PERSISTENT_CACHERS = [ ("hashing/hash_cachers.py", "SqliteHashCacher"), ("hashing/postgres_hash_cacher.py", "PostgresHashCacher"), diff --git a/tests/test_pipeline/loaded_job/test_loaded_operator_cache.py b/tests/test_pipeline/loaded_job/test_loaded_operator_cache.py index 31bd63434..feb98d026 100644 --- a/tests/test_pipeline/loaded_job/test_loaded_operator_cache.py +++ b/tests/test_pipeline/loaded_job/test_loaded_operator_cache.py @@ -728,8 +728,8 @@ def test_source_fed_job_pins_its_pipeline_record_keys( keys = records["key"].to_pylist() assert all(isinstance(value, bytes) for value in keys) assert sorted(bytes(value).hex() for value in keys if value is not None) == [ - "6172726f775f76313a000002163d544cf8f74271d43e783c299b0d27b9603fd72e44c6a25700ed0f69b86dfd", - "6172726f775f76313a0000026497aa64d5c1b29a31de9f1b8dead5decc474d129135fdf19fd6803137ac2559", + "6172726f775f76313a0000022da9383a2854ddc3e905325c7cd38c20fe7941a73ba7ee59ebf44d5c6d30f7b3", + "6172726f775f76313a0000027d049f09e43207b1e2fb1562a19222a031d3ccabe2c1be1b45cfd65d9a5af9f5", ] @@ -787,23 +787,23 @@ def test_arrow_dataframe_job_pins_ids_for_nullable_input( expected_ids = { (False, False): ( "00000229127efd218e1c4d9b1e8059f1bb89a6402189b5af3289a346d3afc088d28924", - "0000024377751a82a42ab9ddfa0925e57c971b7277a067b7da53f89ac28330b288dc62", - "000002e558ab956031b903850bf15ce1f063b265cf3d842faf78f6ea03f34250d54cee", + "0000022d5d60e9b7af6a249a28089c0f868ee17e89c2d2586c02a2e1c149e848192c2f", + "000002d0114337c2a5f1c2c4d0c0df1b4a1932b1eab88cb7151aa43cb2af84c2eef641", ), (False, True): ( "0000023351fc9a0df93ca8ab202dff6db47d9baaf18a12ff46a80b7939a97afe31adf9", - "000002302f9cec6defc62ffb06763a1568739b4885813b1ada445f94f19a446aae12c9", - "0000021db84c12b4c9fabbbe6b714246f919bdcaadf5e7ac55d16d423a8b72670f5498", + "00000266a27429e3e8a93a953828067cde789b6a9bd6821ad414f3d6fa10ad2286e5d8", + "000002b57168f6708a225edfdc71499da9fb74d19f2e3af9ba67aa227a5e22843cf3cd", ), (True, False): ( "00000280719058733166e7e3090cabd1b0268ca8a4a411f587537b5527f6765db921fa", - "000002ebecd3c8f65f1adaf01e5bdc65d960515b6b434334d5668a73e8036a9ea9091c", - "000002f229e3f849a8dbd2b7f481fcc3aa1b51b45edf132ab5960ceb9e57d0fb5a4bee", + "000002b188e9a7937f76b9d7b8cd270300d966b40f75b1b877f44cf5e75ce6d7119618", + "00000299f823cca54389c3286b527d972dd91a2c42bd77f138aff830c69b2c37006ad9", ), (True, True): ( "0000024b66a701276fafd90f9da4b27e7a7878324384d720885a3a23c090ff5093e43c", - "0000029153133eba81a1ee1c2f7f5fef995d8a960a293f9930f4dd914d9cfbc9b64579", - "0000021f73eedfb399b1e85370144f2c2d556567bdfb533c4c7b0bcff3d78b7dfe818e", + "000002a87ecd62bdab371bc753347423b358ad1d479c1ee43b096c6b21819b4389d3f6", + "0000025d6c300b2aa4a5790ed572496f40a3be9e500aaeedfb01bf9647e3e27b2e4e91", ), } wanted_entry, wanted_instance, wanted_record = expected_ids[ diff --git a/tests/test_pipeline/test_function_node_stored_tokens.py b/tests/test_pipeline/test_function_node_stored_tokens.py new file mode 100644 index 000000000..e4a578f72 --- /dev/null +++ b/tests/test_pipeline/test_function_node_stored_tokens.py @@ -0,0 +1,240 @@ +"""Provenance of function outputs whose names overlap function inputs.""" + +import asyncio +from pathlib import Path +from typing import cast + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.core.row_ids import INSTANCE_ID_COL, RECORD_ID_COL +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.errors import StoredTableSchemaError +from orcapod.types import NodeConfig +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.sources import ArrowTableSource +from orcapod.system_constants import ( + PIPELINE_DB_SCHEMA_VERSION, + constants, +) + + +@function_pod(output_keys=["x", "y", "w"]) +def _xyw(x: int, y: int, z: int) -> tuple[int, int, int]: + return x + 10, y + 20, z + 30 + + +@function_pod(output_keys=["w", "y", "x"]) +def _wyx(x: int, y: int, z: int) -> tuple[int, int, int]: + return z + 30, y + 20, x + 10 + + +@function_pod(output_keys="out") +def _consume(x: int) -> int: + return x * 10 + + +def _source() -> ArrowTableSource: + schema = pa.schema( + [ + pa.field("cohort", pa.large_string(), nullable=False), + pa.field("subject", pa.large_string(), nullable=False), + *(pa.field(name, pa.int64(), nullable=False) for name in ("x", "y", "z")), + ] + ) + rows = pa.Table.from_arrays( + [ + pa.array(["a", "a", "b"], type=pa.large_string()), + pa.array(["s1", "s2", "s3"], type=pa.large_string()), + pa.array([1, 2, 3], type=pa.int64()), + pa.array([4, 5, 6], type=pa.int64()), + pa.array([7, 8, 9], type=pa.int64()), + ], + schema=schema, + ) + return ArrowTableSource( + rows, + tag_columns=["cohort", "subject"], + tag_only_columns=["subject"], + source_id="stored_tokens", + ) + + +def _job( + database: ArrowDatabaseProtocol, + reverse: bool = False, + ephemeral: InMemoryArrowDatabase | None = None, + *, + downstream: bool = False, +) -> PipelineJob: + job = PipelineJob(name="stored_tokens", database=database) + with job: + node = (_wyx if reverse else _xyw).pod(_source(), label="collide") + if downstream: + _ = _consume.pod(node, label="consumer") + if ephemeral is not None: + job.set_ephemeral_database(ephemeral) + job.apply_node_config(NodeConfig(is_result_ephemeral=True)) + return job + + +def _run(job: PipelineJob, mode: str, *, load_only: bool = False) -> None: + if mode == "async": + _ = asyncio.run(job.run_async(load_only=load_only)) + else: + _ = job.run(load_only=load_only) + + +def _node(job: PipelineJob, label: str) -> FunctionJobNode: + return cast(FunctionJobNode, job.nodes[label]) + + +def _output_with_tokens(table: pa.Table) -> pa.Table: + """Select output values and tokens in a fixed column and row order.""" + return table.select( + [ + "cohort", + "subject", + "x", + "y", + "w", + "_source_cohort", + "_source_x", + "_source_y", + "_source_w", + ] + ).sort_by("subject") + + +@pytest.mark.parametrize("mode", ["sync", "async"]) +@pytest.mark.parametrize("backend", ["memory", "delta"]) +@pytest.mark.parametrize("reverse", [False, True], ids=["xyw", "wyx"]) +@pytest.mark.parametrize( + "keep_ephemeral", [False, True], ids=["persistent", "ephemeral"] +) +def test_stored_results_keep_the_delivered_output_tokens( + tmp_path: Path, mode: str, backend: str, reverse: bool, keep_ephemeral: bool +) -> None: + database = ( + InMemoryArrowDatabase() + if backend == "memory" + else DeltaTableDatabase(tmp_path / "tables") + ) + ephemeral = InMemoryArrowDatabase() if keep_ephemeral else None + first = _job(database, reverse, ephemeral) + _run(first, mode) + + first_node = _node(first, "collide") + delivered = _output_with_tokens(first_node.as_table(columns={"source": True})) + inputs = _source().as_table(columns={"source": True}).sort_by("subject") + assert delivered.column("_source_cohort").equals(inputs.column("_source_cohort")) + for name in ("x", "y", "w"): + assert delivered.column(f"_source_{name}").null_count == 0 + for name in ("x", "y"): + assert not delivered.column(f"_source_{name}").equals( + inputs.column(f"_source_{name}") + ) + + for load_only in (False, True): + fresh = _job(database, reverse, ephemeral) + _run(fresh, mode, load_only=load_only) + read = _node(fresh, "collide").as_table(columns={"source": True}) + assert _output_with_tokens(read).equals(delivered), f"{load_only=}" + + for records in ( + first_node.get_all_records(all_info=True), + first_node.get_all_records(columns={"source": True}), + ): + assert records is not None + assert _output_with_tokens(records).equals(delivered) + ordered = records.sort_by("subject") + for name in ("z", "x", "y"): + input_token = ordered.column(f"_input_source_{name}") + assert input_token.equals(inputs.column(f"_source_{name}")) + + records = first_node.get_all_records() + assert records is not None + assert not any( + name.startswith(("_source_", "_input_source_")) for name in records.column_names + ) + + if ephemeral is None: + saved = tmp_path / "job.json" + first.save(saved) + loaded = PipelineJob.load(saved, database=database) + loaded.bind(sources={"stored_tokens": _source()}) + _run(loaded, mode, load_only=True) + read = _node(loaded, "collide").as_table(columns={"source": True}) + assert _output_with_tokens(read).equals(delivered) + + +@pytest.mark.parametrize("mode", ["sync", "async"]) +def test_a_downstream_node_reuses_its_original_instances_and_records(mode: str) -> None: + database = InMemoryArrowDatabase() + first = _job(database, downstream=True) + _run(first, mode) + + consumer = _node(first, "consumer") + [path] = [ + path + for path in database.list_table_paths() + if path[1:] == (*consumer.node_identity_path, PIPELINE_DB_SCHEMA_VERSION) + ] + stored = database.get_all_records(path) + assert stored is not None + input_token = constants.INPUT_SOURCE_PREFIX + "x" + columns = ["subject", input_token, INSTANCE_ID_COL, RECORD_ID_COL] + original = stored.select(columns).sort_by("subject") + delivered = _node(first, "collide").as_table(columns={"source": True}) + assert original.column(input_token).equals( + delivered.sort_by("subject").column("_source_x") + ) + + fresh = _job(database, downstream=True) + _run(fresh, mode) + fresh_consumer = _node(fresh, "consumer") + assert sorted(fresh_consumer.held_instance_ids()) == sorted( + consumer.held_instance_ids() + ) + stored = database.get_all_records(path) + assert stored is not None + assert stored.select(columns).sort_by("subject").equals(original) + + +@pytest.mark.parametrize("mode", ["sync", "async"]) +def test_pre_rename_pipeline_table_is_refused(mode: str) -> None: + database = InMemoryArrowDatabase() + first = _job(database) + _run(first, mode) + [path] = [ + path + for path in database.list_table_paths() + if path[-1] == PIPELINE_DB_SCHEMA_VERSION + ] + assert path[-1] == "pdb_v2" + records = database.get_all_records(path) + assert records is not None + previous = records.rename_columns( + [ + constants.SOURCE_PREFIX + name.removeprefix(constants.INPUT_SOURCE_PREFIX) + if name.startswith(constants.INPUT_SOURCE_PREFIX) + else name + for name in records.column_names + ] + ) + old_database = InMemoryArrowDatabase() + old_database.add_records(path, previous, record_id_column=RECORD_ID_COL) + seeded = old_database.get_all_records(path) + assert seeded is not None + fresh = _job(old_database) + error = r"Incompatible input source-info columns.*pdb_v2.*_source_x.*Rebuild" + with pytest.raises(StoredTableSchemaError, match=error): + _ = _node(fresh, "collide").get_all_records(all_info=True) + for load_only in (True, False): + with pytest.raises(StoredTableSchemaError, match=error): + _run(fresh, mode, load_only=load_only) + + untouched = old_database.get_all_records(path) + assert untouched is not None and untouched.equals(seeded) diff --git a/tests/test_pipeline/test_provenance_review.py b/tests/test_pipeline/test_provenance_review.py index c22a08ef7..02813d6a0 100644 --- a/tests/test_pipeline/test_provenance_review.py +++ b/tests/test_pipeline/test_provenance_review.py @@ -3452,7 +3452,8 @@ def moved(*args: Any, **kwargs: Any) -> Any: return [ { name: value.replace("::row_0::", "::row_9::") - if name.startswith(constants.SOURCE_PREFIX) and isinstance(value, str) + if name.startswith(constants.INPUT_SOURCE_PREFIX) + and isinstance(value, str) else value for name, value in entry.items() } @@ -3576,7 +3577,8 @@ def ghost(*args: Any, **kwargs: Any) -> Any: return [ { name: value.replace("::x", "::ghost") - if name.startswith(constants.SOURCE_PREFIX) and isinstance(value, str) + if name.startswith(constants.INPUT_SOURCE_PREFIX) + and isinstance(value, str) else value for name, value in entry.items() } @@ -3599,7 +3601,7 @@ def test_a_stored_token_must_be_the_source_rows_own_token_for_its_column( monkeypatch: pytest.MonkeyPatch, ) -> None: """A function over a source with two inputs, x=10 and z=20 in one record: a - stored _source_x token changed to name z in that same record (record, input + stored _input_source_x token changed to name z in that same record (record, input hash and column all exist) is refused, never traced as x's input; a record whose x is null still traces both inputs, x to its null cell.""" from orcapod.pipeline import provenance @@ -3624,7 +3626,7 @@ def test_a_stored_token_must_be_the_source_rows_own_token_for_its_column( real = provenance._entries_for def swapped(*args: Any, **kwargs: Any) -> Any: - x_token = constants.SOURCE_PREFIX + "x" + x_token = constants.INPUT_SOURCE_PREFIX + "x" return [ { **entry, diff --git a/tests/test_pipeline/test_row_ids_review_2.py b/tests/test_pipeline/test_row_ids_review_2.py index ab121b9b9..575cea501 100644 --- a/tests/test_pipeline/test_row_ids_review_2.py +++ b/tests/test_pipeline/test_row_ids_review_2.py @@ -603,7 +603,7 @@ def test_sessions_with_null_and_with_string_tokens_share_a_table( assert sorted(_values(stored, "total")) == TOTALS[session] table = _pipeline_table(database) assert table.num_rows == 6 - assert table.schema.field("_source_a").type == pa.large_string() + assert table.schema.field("_input_source_a").type == pa.large_string() @pytest.mark.parametrize("kind", list(NULL_LIST_TOKENS)) @@ -635,8 +635,8 @@ def test_a_null_string_tokens_preimage_is_a_string_null() -> None: preimage = row_ids.instance_id_preimage( row_ids.entry_id(HASHER, tag, data), data ) - assert preimage.schema.field("_source_a").type == pa.large_string() - assert preimage.column("_source_a").to_pylist() == [None] + assert preimage.schema.field("_input_source_a").type == pa.large_string() + assert preimage.column("_input_source_a").to_pylist() == [None] assert len(set(ids)) == 3 @@ -685,7 +685,7 @@ def test_sessions_whose_tokens_differ_in_type_are_refused_naming_the_column( with pytest.raises((OrcapodDatabaseWriteError, ExceptionGroup)) as raised: _run_node(later, second, path) message = _refusal(raised.value) - assert "_source_a" in message + assert "_input_source_a" in message assert "large_string" in message and "large_list<" in message assert _pipeline_table(database).equals(before) @@ -893,8 +893,8 @@ def test_both_routes_record_one_instance_per_row_in_a_shared_store( table = database.get_all_records(path) assert table is not None assert table.num_rows == 3, (index, route) - assert table.schema.field("_source_d").type == _FIXED - assert table.column("_source_e").null_count == 1 + assert table.schema.field("_input_source_d").type == _FIXED + assert table.column("_input_source_e").null_count == 1 stored.append( tuple( sorted( diff --git a/tests/test_pipeline/test_row_ids_stored.py b/tests/test_pipeline/test_row_ids_stored.py index 7e12be15f..1c6bea959 100644 --- a/tests/test_pipeline/test_row_ids_stored.py +++ b/tests/test_pipeline/test_row_ids_stored.py @@ -182,7 +182,7 @@ def _instance_id_of_stored_row(row: pa.Table) -> ContentHash: ) } ) - for name in sorted(n for n in row.column_names if n.startswith("_source_")): + for name in sorted(n for n in row.column_names if n.startswith("_input_source_")): preimage = preimage.append_column(row.schema.field(name), row.column(name)) return HASHER.hash_table(preimage) @@ -223,12 +223,13 @@ def test_every_pipeline_row_gives_its_instance_and_record_id_again( assert "__pipeline_entry_id" not in stored.column_names assert "__pipeline_recomputation_index" not in stored.column_names assert "__pipeline_base_entry_id" not in stored.column_names - tokens = sorted(n for n in stored.column_names if n.startswith("_source_")) + tokens = sorted(n for n in stored.column_names if n.startswith("_input_source_")) assert ( tokens - == {"inc": ["_source_w", "_source_x"], "add": ["_source_v", "_source_y"]}[ - function - ] + == { + "inc": ["_input_source_w", "_input_source_x"], + "add": ["_input_source_v", "_input_source_y"], + }[function] ) for row in _rows(stored): (instance,) = _values(row, "__pipeline_instance_id") @@ -1083,12 +1084,12 @@ def test_a_stored_row_keeps_the_token_columns_its_instance_id_was_made_from( assert stored.num_rows == 3 # The stored token columns have the stream's types, in every row. token_a, token_b = TOKEN_COLUMNS[tokens] - assert stored.schema.field("_source_a").type == token_a.type - assert stored.schema.field("_source_b").type == token_b.type - assert sorted(map(repr, _values(stored, "_source_a"))) == sorted( + assert stored.schema.field("_input_source_a").type == token_a.type + assert stored.schema.field("_input_source_b").type == token_b.type + assert sorted(map(repr, _values(stored, "_input_source_a"))) == sorted( map(repr, token_a.to_pylist()) ) - assert sorted(map(repr, _values(stored, "_source_b"))) == sorted( + assert sorted(map(repr, _values(stored, "_input_source_b"))) == sorted( map(repr, token_b.to_pylist()) ) given = {node.compute_instance_id(tag, data) for tag, data in rows} @@ -1171,7 +1172,11 @@ def test_an_ordinary_rows_stored_token_columns_are_what_they_were(kind: str) -> for tag, data in rows: as_stored_before = data.as_table(columns={"source": True}) as_stored_before = as_stored_before.select( - [n for n in as_stored_before.column_names if n.startswith("_source_")] + [ + n + for n in as_stored_before.column_names + if n.startswith(constants.SOURCE_PREFIX) + ] ) now = data.source_info_table() assert now.num_columns >= 2 @@ -1187,8 +1192,12 @@ def test_an_ordinary_rows_stored_token_columns_are_what_they_were(kind: str) -> } ) for name in sorted(as_stored_before.column_names): + stored_name = constants.INPUT_SOURCE_PREFIX + name.removeprefix( + constants.SOURCE_PREFIX + ) by_hand = by_hand.append_column( - as_stored_before.schema.field(name), as_stored_before.column(name) + as_stored_before.schema.field(name).with_name(stored_name), + as_stored_before.column(name), ) assert row_ids.instance_id(HASHER, tag, data) == HASHER.hash_table(by_hand) @@ -1201,7 +1210,7 @@ def test_rows_with_no_token_store_null_tokens_and_recompute_their_ids( A data column with no token has a null token, as the same row read from an Arrow table has (review of PR #583): the stored row has one ``large_string`` - null ``_source_*`` column per data column, and its ids are recomputed from them. + null ``_input_source_*`` column per data column, and its ids are recomputed from them. """ from orcapod.core.datagrams import Data, Tag @@ -1222,8 +1231,8 @@ def test_rows_with_no_token_store_null_tokens_and_recompute_their_ids( database.flush() stored = _table(database, "combine_nested_lists", "pdb_v2") assert stored.num_rows == 3 - tokens = [n for n in stored.column_names if n.startswith("_source_")] - assert tokens == ["_source_a", "_source_b"] + tokens = [n for n in stored.column_names if n.startswith("_input_source_")] + assert tokens == ["_input_source_a", "_input_source_b"] for name in tokens: assert stored.schema.field(name).type == pa.large_string() assert stored.column(name).null_count == 3 @@ -1233,8 +1242,11 @@ def test_rows_with_no_token_store_null_tokens_and_recompute_their_ids( for tag, data in rows: table = data.as_table() for name in tokens: + stream_name = constants.SOURCE_PREFIX + name.removeprefix( + constants.INPUT_SOURCE_PREFIX + ) table = table.append_column( - pa.field(name, pa.large_string()), pa.nulls(1, pa.large_string()) + pa.field(stream_name, pa.large_string()), pa.nulls(1, pa.large_string()) ) read_from_tables.add( row_ids.instance_id(HASHER, tag, Data(table)).to_prefixed_digest() diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index c98c8f62f..bf26da772 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -1363,8 +1363,8 @@ def test_held_rows_with_nested_tokens_reach_the_successor(asynchronous: bool) -> ("end", "after"), ] assert stored.num_rows == 2 - assert stored.schema.field("_source_x").type == _UNCONVERTIBLE - assert stored.column("_source_x").to_pylist() == [[[], [[]]], [[], [[]]]] + assert stored.schema.field("_input_source_x").type == _UNCONVERTIBLE + assert stored.column("_input_source_x").to_pylist() == [[[], [[]]], [[], [[]]]] def test_held_rows_with_nested_tokens_are_stored_alike_on_both_routes() -> None: @@ -1384,7 +1384,7 @@ def test_held_rows_with_nested_tokens_are_stored_alike_on_both_routes() -> None: assert sorted(kept) == sorted( name for name in asynchronous.column_names if name not in random ) - assert "__pipeline_instance_id" in kept and "_source_x" in kept + assert "__pipeline_instance_id" in kept and "_input_source_x" in kept left = sync.select(kept).sort_by("k") right = asynchronous.select(kept).sort_by("k") assert left.schema.equals(right.schema) @@ -1444,8 +1444,8 @@ def run(asynchronous: bool) -> Any: # (a null token is stored as a ``large_string`` null). stored = _stored_by_after(run(True)) assert stored.num_rows == 2 - assert stored.column("_source_x").to_pylist() == [None, None] - assert stored.schema.field("_source_x").type == pa.large_string() + assert stored.column("_input_source_x").to_pylist() == [None, None] + assert stored.schema.field("_input_source_x").type == pa.large_string() def test_held_rows_run_independent_nodes_first() -> None: diff --git a/tests/test_pipeline/test_tag_table_source_info.py b/tests/test_pipeline/test_tag_table_source_info.py index 9ace03a7d..c318ba125 100644 --- a/tests/test_pipeline/test_tag_table_source_info.py +++ b/tests/test_pipeline/test_tag_table_source_info.py @@ -2,7 +2,7 @@ A ``FunctionJobNode`` writes one tag-table (pipeline DB, ``pdb_v2``) row per input, carrying that input's source-info tokens. A source-info token is the provenance -value a row holds for one data column: the value of its ``_source_`` +value a row holds for one data column: the value of its ``_input_source_`` column, as ``Data.source_info()`` returns it (for example ``S::row_0::x``). "Token" below always means a source-info token. @@ -127,9 +127,12 @@ def _function_node(job: PipelineJob, label: str) -> FunctionJobNode: def _tag_rows(job: PipelineJob, label: str) -> list[dict[str, Any]]: - """The node's stored records (tag-table rows joined to results), sorted by tag.""" - table = _function_node(job, label).get_all_records( - columns={"source": True, "meta": True, "system_tags": True} + """Read the node's pipeline rows directly, sorted by tag.""" + database = job.database + assert database is not None + node = _function_node(job, label) + table = database.get_all_records( + (_JOB, *node.node_identity_path, PIPELINE_DB_SCHEMA_VERSION) ) assert table is not None return sorted(table.to_pylist(), key=lambda row: str(row["id"])) @@ -168,22 +171,22 @@ def test_source_into_function(self, orchestrator: str): job = _job(InMemoryArrowDatabase()) _run(job, orchestrator) rows = _tag_rows(job, "direct") - assert _column(rows, "_source_x") == _input_source_info_tokens("x") - assert _column(rows, "_source_y") == _input_source_info_tokens("y") + assert _column(rows, "_input_source_x") == _input_source_info_tokens("x") + assert _column(rows, "_input_source_y") == _input_source_info_tokens("y") def test_operator_into_function(self, orchestrator: str): """A function fed through an operator stores each row's source-info tokens.""" job = _job(InMemoryArrowDatabase()) _run(job, orchestrator) assert _column( - _tag_rows(job, "via_op"), "_source_x" + _tag_rows(job, "via_op"), "_input_source_x" ) == _input_source_info_tokens("x") def test_function_into_function(self, orchestrator: str): """A function fed by a function stores each upstream source-info token.""" job = _job(InMemoryArrowDatabase()) _run(job, orchestrator) - stored = _column(_tag_rows(job, "second"), "_source_z") + stored = _column(_tag_rows(job, "second"), "_input_source_z") expected = _output_source_info_tokens(job, "direct", "z") assert len(set(expected)) == 3 assert stored == expected @@ -227,7 +230,7 @@ def test_rerun_keeps_old_rows_and_runs_nothing( _run(old_job) before = {label: _tag_rows(old_job, label) for label in _FUNCTION_NODES} row_zero = _input_source_info_tokens("x")[0] - assert _column(before["direct"], "_source_x") == [row_zero] * 3 + assert _column(before["direct"], "_input_source_x") == [row_zero] * 3 assert sorted(CALLS) == sorted(["add_xy", "times_two", "add_one"] * 3) CALLS.clear() @@ -244,11 +247,11 @@ def test_rerun_keeps_old_rows_and_runs_nothing( } for label in ("direct", "via_op"): assert ( - _column(added[label], "_source_x") + _column(added[label], "_input_source_x") == (_input_source_info_tokens("x")[1:]) ) assert ( - _column(added["second"], "_source_z") + _column(added["second"], "_input_source_z") == (_output_source_info_tokens(new_job, "direct", "z")[1:]) ) # The run's own output carries correct source-info tokens downstream regardless. @@ -303,9 +306,13 @@ def test_all_tag_tables_rebuilt_without_recomputation( assert CALLS == [] after = {label: _tag_rows(job, label) for label in _FUNCTION_NODES} - assert _column(after["direct"], "_source_x") == _input_source_info_tokens("x") - assert _column(after["via_op"], "_source_x") == _input_source_info_tokens("x") - assert len(set(_column(after["second"], "_source_z"))) == 3 + assert _column(after["direct"], "_input_source_x") == _input_source_info_tokens( + "x" + ) + assert _column(after["via_op"], "_input_source_x") == _input_source_info_tokens( + "x" + ) + assert len(set(_column(after["second"], "_input_source_z"))) == 3 for label in _FUNCTION_NODES: for old, new in zip(before[label], after[label], strict=True): assert _ids(new) == _ids(old) @@ -330,7 +337,7 @@ def test_dropping_one_tag_table_leaves_the_others( assert CALLS == [] assert _column( - _tag_rows(job, "direct"), "_source_x" + _tag_rows(job, "direct"), "_input_source_x" ) == _input_source_info_tokens("x") for label in ("second", "via_op"): added = _corrected_instances(before[label], _tag_rows(job, label)) diff --git a/tests/test_pipeline/test_token_types_end_to_end.py b/tests/test_pipeline/test_token_types_end_to_end.py index 4fa3d00b3..6e6edcc74 100644 --- a/tests/test_pipeline/test_token_types_end_to_end.py +++ b/tests/test_pipeline/test_token_types_end_to_end.py @@ -182,7 +182,7 @@ def _instance_ids(stored: pa.Table) -> list[bytes]: def _token_columns(table: pa.Table) -> list[str]: """The names of ``table``'s source-info columns, sorted.""" return sorted( - n for n in table.column_names if n.startswith(constants.SOURCE_PREFIX) + n for n in table.column_names if n.startswith(constants.INPUT_SOURCE_PREFIX) ) @@ -195,7 +195,7 @@ def _by_instance(stored: pa.Table) -> dict[bytes, dict[str, Any]]: kept = [ name for name in stored.column_names - if name in COLUMNS or name.startswith(constants.SOURCE_PREFIX) + if name in COLUMNS or name.startswith(constants.INPUT_SOURCE_PREFIX) ] return { cast("bytes", row["__pipeline_instance_id"]): {name: row[name] for name in kept} @@ -337,7 +337,7 @@ def build(database: InMemoryArrowDatabase) -> PipelineJob: seen = _run_both(build, function.pod.label or function.__name__, "given") _assert_same_on_both_routes(seen, rows) - assert seen["sync"]["types"] == {"_source_w": kind, "_source_x": kind} + assert seen["sync"]["types"] == {"_input_source_w": kind, "_input_source_x": kind} assert calls[function.__name__] == 2 * rows @@ -437,14 +437,17 @@ def test_nested_tokens_no_value_can_type_are_stored_alike_on_both_routes( "given", ) _assert_same_on_both_routes(seen, 4) - expected = {"_source_w": pa.large_string(), "_source_x": pa.large_string()} - expected |= {f"_source_{name}": kind for name, (_, kind) in replaced.items()} + expected = { + "_input_source_w": pa.large_string(), + "_input_source_x": pa.large_string(), + } + expected |= {f"_input_source_{name}": kind for name, (_, kind) in replaced.items()} assert seen["sync"]["types"] == expected stored = seen["sync"]["stored"].sort_by( [("subject", "ascending"), ("session", "ascending")] ) for column, (values, _) in replaced.items(): - assert stored.column(f"_source_{column}").to_pylist() == values + assert stored.column(f"_input_source_{column}").to_pylist() == values assert calls[name] == 8 @@ -546,8 +549,11 @@ def test_an_aggregation_over_null_tokens_is_stored_alike_on_both_routes( "given", ) _assert_same_on_both_routes(seen, rows) - assert seen["sync"]["types"] == {"_source_w": STRINGS, "_source_x": STRINGS} - tokens = seen["sync"]["stored"].column("_source_x").to_pylist() + assert seen["sync"]["types"] == { + "_input_source_w": STRINGS, + "_input_source_x": STRINGS, + } + tokens = seen["sync"]["stored"].column("_input_source_x").to_pylist() assert all(token is not None for token in tokens) assert any(None in token for token in tokens) assert calls["count_members"] == 2 * rows @@ -576,8 +582,8 @@ def test_held_rows_of_such_an_aggregation_reach_the_function_again( again = _stored(database, "count_members") assert again.num_rows == first.num_rows == rows assert _instance_ids(again) == _instance_ids(first) - assert again.schema.field("_source_x").type == STRINGS - assert again.schema.field("_source_w").type == STRINGS + assert again.schema.field("_input_source_x").type == STRINGS + assert again.schema.field("_input_source_w").type == STRINGS assert len(list(job.nodes["f"].iter_data())) == rows assert calls["count_members"] == rows @@ -676,14 +682,14 @@ def test_data_tags_fall_through_two_functions_with_their_tokens_unchanged( for route in seen.values(): assert route["stored"].num_rows == 4 stored = { - _pair(row): {name: row[f"_source_{name}"] for name in DATA_TAG_TOKENS} + _pair(row): {name: row[f"_input_source_{name}"] for name in DATA_TAG_TOKENS} for row in route["stored"].to_pylist() } assert stored == expected assert seen["sync"]["types"] == { - "_source_pair": FIXED, - "_source_path": NESTED, - "_source_total": pa.large_string(), + "_input_source_pair": FIXED, + "_input_source_path": NESTED, + "_input_source_total": pa.large_string(), } for orchestrator in ORCHESTRATORS.values(): job = _data_tag_job(InMemoryArrowDatabase(), tags) @@ -718,8 +724,8 @@ def test_data_tags_have_one_instance_per_row_whichever_route_ran_first( _ = job.run(orchestrator=ORCHESTRATORS[route]()) table = _stored(database, "twice") assert table.num_rows == 4, (index, route) - assert table.schema.field("_source_pair").type == FIXED - assert table.schema.field("_source_path").type == NESTED + assert table.schema.field("_input_source_pair").type == FIXED + assert table.schema.field("_input_source_path").type == NESTED stored.append(_instance_ids(table)) assert all(ids == stored[0] for ids in stored) and len(set(stored[0])) == 4 assert calls["add"] == 4 and calls["twice"] == 4 diff --git a/tests/test_pipeline/test_token_types_review_1.py b/tests/test_pipeline/test_token_types_review_1.py index 0c1cbc4d9..04185512a 100644 --- a/tests/test_pipeline/test_token_types_review_1.py +++ b/tests/test_pipeline/test_token_types_review_1.py @@ -258,13 +258,13 @@ def test_a_join_keeps_the_declared_type_of_a_merged_data_tag_token( job = _join_job(database, TAG_ORDERS[tags], inputs) _ = job.run(orchestrator=orchestrator()) stored = _by_k(_stored(database, function)) - field = stored.schema.field("_source_k") + field = stored.schema.field("_input_source_k") assert field.type.equals(FIXED, check_metadata=True), (name, field.type) - merged = cast("list[list[str]]", stored.column("_source_k").to_pylist()) + merged = cast("list[list[str]]", stored.column("_input_source_k").to_pylist()) assert [len(token) for token in merged] == [2, 2] assert all(part.startswith("join_v1:") for token in merged for part in token) assert len({part for token in merged for part in token}) == 4 - assert stored.schema.field("_source_g").type == TOKEN + assert stored.schema.field("_input_source_g").type == TOKEN seen[name] = (merged, _instance_ids(stored)) assert seen["sync"] == seen["async"]