diff --git a/.zed/rules b/.zed/rules index ca8eb579e..3facf8e88 100644 --- a/.zed/rules +++ b/.zed/rules @@ -853,7 +853,13 @@ Every pipeline element has two parallel hashes: identity: the default source_id of the in-memory sources (:: of the table hash, used when none is given) and the elements of a ListSource. A downstream stream or node hashes its pod's identity plus its upstreams' content hashes; a function pod's identity is its uri, - not its body. Only a datagram (one row's tags or data) has a content_hash() that is a + not its body. The uri holds the hash of the output schema, a set of named, typed outputs + in no order (developer, November 17, 2026, ITL-1244): reordering output_keys changes it + only when a key's type changes; when a name now receives another value (same-typed keys + reordered without the returned values, or the reverse), what the function computes + changed, like a body edit, and it needs a MAJOR version bump (v0.0 to v1.0: the uri + holds only the major, so a minor bump serves the earlier order's stored values) while + there is no check on a cache hit (ITL-1253); reordering both together changes nothing. The input parameters (names and order) are in no part of the uri. Only a datagram (one row's tags or data) has a content_hash() that is a digest of its values; that row hash, not the node's content hash, is what results are memoized by. The node's content hash tells apart, inside a shared table, the rows of pipelines bound to different sources (__node_content_hash). diff --git a/CLAUDE.md b/CLAUDE.md index 9f686af4d..3bcd9644a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -873,7 +873,13 @@ Every pipeline element has two parallel hashes: identity: the default `source_id` of the in-memory sources (`::` of the table hash, used when none is given) and the elements of a `ListSource`. A downstream stream or node hashes its pod's identity plus its upstreams' content hashes; a function pod's identity is its uri, - not its body. Only a datagram (one row's tags or data) has a `content_hash()` that is a + not its body. The uri holds the hash of the output schema, a set of named, typed outputs + in no order (developer, November 17, 2026, ITL-1244): reordering `output_keys` changes it + only when a key's type changes; when a name now receives another value (same-typed keys + reordered without the returned values, or the reverse), what the function computes + changed, like a body edit, and it needs a MAJOR version bump (`v0.0` to `v1.0`: the uri + holds only the major, so a minor bump serves the earlier order's stored values) while + there is no check on a cache hit (ITL-1253); reordering both together changes nothing. The input parameters (names and order) are in no part of the uri. Only a datagram (one row's tags or data) has a `content_hash()` that is a digest of its values; that row hash, not the node's content hash, is what results are memoized by. The node's content hash tells apart, inside a shared table, the rows of pipelines bound to different sources (`__node_content_hash`). diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 479705f91..de18cabc6 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -408,6 +408,12 @@ print("function calls:", len(calls)) values. To force recomputation after changing what a function does, bump the major version, e.g. `@function_pod(output_keys="bmi", version="v1.0")` (the default is `"v0.0"`; a minor bump such as `"v0.1"` is not enough), or rename the function. + The same holds when an output name now receives another value because you reordered + `output_keys` among outputs of the same type without reordering the returned values + (or the reverse): the output schema is a set of named, typed outputs, so its identity + does not change, and only a major version bump makes the function compute the new + values. Reordering both together changes nothing (see *Change detection* in + [Identity & Hashing](identity.md#change-detection)). !!! note "When the database cannot be read" A table that does not exist yet reads as empty, and its rows are computed. In a diff --git a/docs/concepts/identity.md b/docs/concepts/identity.md index 9f2336055..8d1d96c32 100644 --- a/docs/concepts/identity.md +++ b/docs/concepts/identity.md @@ -178,6 +178,46 @@ print(step.pod(source).pipeline_hash() == original) When you change what a function computes, bump its major version (or rename it) so that stale results are not reused. +The output schema is a set of named, typed outputs: each output key with its type, in no +order, like every other schema. `output_keys` also says which position of the returned +tuple each name takes, and that mapping belongs with the body. So reordering the output keys +changes the identity only when a key's type changes. Swapping two keys of the same type +keeps the identity, as a body edit does. When a name now receives another value (the keys +swapped without the returned values, or the reverse), what the function computes changed: +bump the major version. Until stored results are checked against the current function on a +cache hit (ITL-1253), a run serves the earlier results without a warning. Swapping the keys +and the returned values together changes nothing: each name receives the value it had. The +function's input parameters (their names and their order) are not part of the identity +either. + +```python +@function_pod(output_keys=["total", "doubled"]) +def pair(age: int) -> tuple[int, int]: + return age + 1, age * 2 + +original = pair.pod(source).pipeline_hash() + +@function_pod(output_keys=["doubled", "total"]) # same types: same identity +def pair(age: int) -> tuple[int, int]: + return age + 1, age * 2 + +print(pair.pod(source).pipeline_hash() == original) +# True + +@function_pod(output_keys=["label", "next_age"]) +def describe(age: int) -> tuple[str, int]: + return f"age {age}", age + 1 + +original = describe.pod(source).pipeline_hash() + +@function_pod(output_keys=["next_age", "label"]) # next_age is now a str: new identity +def describe(age: int) -> tuple[str, int]: + return f"age {age}", age + 1 + +print(describe.pod(source).pipeline_hash() == original) +# False +``` + ## Order never counts, except where you give it The rule: no hash, identity, stored value or row depends on the order in which you give diff --git a/docs/dev/design_issues/ITL-1244-OK1.md b/docs/dev/design_issues/ITL-1244-OK1.md new file mode 100644 index 000000000..fb628dc14 --- /dev/null +++ b/docs/dev/design_issues/ITL-1244-OK1.md @@ -0,0 +1,28 @@ +## `src/orcapod/core/data_function.py` + +### OK1 — The order of `output_keys` is in no identity +**Status:** resolved (decided: the identity is right as it is; the cache check is ITL-1253) +**Severity:** high +**Issue:** ITL-1244 + +Two pods of one function whose `output_keys` differ only in order (`['sum', 'product']` +against `['product', 'sum']`) have one uri, content hash and pipeline hash: the uri holds +the hash of the output schema, and a schema hash sorts its field names. A job with the +second order on the database of a job with the first is served the first one's stored rows, +so the values appear under the other names. Found by the several-item test audit +(ITL-1236). + +**Fix:** Decided by the developer (November 17, 2026): the outputs of a function are a set of +named, typed values, so the uri holds the order-free output schema, as before. A swap of +differently typed keys changes the schema and so the uri; a swap of same-typed keys does not. +The positional mapping belongs with the body: when a name now receives another value +(same-typed keys swapped without the returned values, or the reverse), what the function +computes changed and needs a major version bump, as a body edit does; swapping both +together changes nothing (the uri holds only the major version, so a minor bump would serve the earlier order's stored values while +a cache hit is not checked, ITL-1253). No code changed. The +behaviour is pinned in `tests/test_core/function_pod/test_output_keys_identity.py` (two and +three keys in every order, sync and async, in memory and in a job on an in-memory and a +Delta database, plain tags and data-tags; input parameters pinned as outside the uri) and +documented in `docs/concepts/identity.md` (*Change detection*). A cache hit whose stored +function variation data differs from the current function is still served silently: that +check is ITL-1253 (a strict xfail test states it). diff --git a/docs/dev/specs/itl-1236-several-item-test-audit.md b/docs/dev/specs/itl-1236-several-item-test-audit.md index d7ddbbfc9..4e382879f 100644 --- a/docs/dev/specs/itl-1236-several-item-test-audit.md +++ b/docs/dev/specs/itl-1236-several-item-test-audit.md @@ -56,7 +56,7 @@ Legend: **yes** (with the best test as evidence), **no** (with what the closest | `GroupBy` `by`, member order | yes: `ops/test_group_by.py::TestGroupByShape::test_one_row_per_distinct_key` | keys only on `main` | yes | no on `main` | 1 key on `main` | | ↳ covered by PR #434 (ITL-1226) | | `test_group_by_member_order.py::test_the_order_of_by_is_not_identity` | plain, data-tag, mixed | `test_no_arrangement_of_the_input_changes_the_result` (24 × 4, source and raw stream) | `test_a_job_gives_the_same_rows_sync_and_async_for_any_arrangement` | | `TagBy` columns | yes: `dt/test_tag_by.py::test_named_data_columns_become_data_tags_in_the_order_given` | yes: `test_the_order_of_the_names_is_part_of_the_identity` (PR #434 reverses this decision) | n/a / yes / refused: `test_an_existing_data_tag_is_refused` | no (1 tag) → NEW `[tag_by/*]` | yes: ASE `tag_by`, `tag_by_reversed` | -| `AddTags` tags | yes: `ops/test_add_tags.py::TestValues::test_arrow_type_of_each_accepted_value_type` | operator hash and keys: `TestIdentity::test_order_is_part_of_the_identity`; stream hashes → NEW `test_add_tags_order_is_the_order_of_the_new_tags_and_its_identity` | yes: `dt/test_add_tags.py` | no → NEW | yes: ASE `add_tags`, `ref_add_tags` | +| `AddTags` tags | yes: `ops/test_add_tags.py::TestValues::test_arrow_type_of_each_accepted_value_type` | operator hash and keys: `TestIdentity::test_order_is_not_part_of_the_identity`; stream hashes → NEW `test_add_tags_order_is_neither_the_order_of_the_new_tags_nor_identity` (ITL-1269 made the order free; it was part of the identity when this audit was written) | yes: `dt/test_add_tags.py` | no → NEW | yes: ASE `add_tags`, `ref_add_tags` | | `SelectTagColumns` columns | **no** (only one name, or all) → NEW | **no** (`WHF::test_tag_column_spellings_share_identity` uses one name) → NEW | yes: `dt/test_roles.py::test_each_operator_acts_by_role` | no → NEW | yes | | `DropTagColumns` columns | **no** → NEW | **no** → NEW | yes | no → NEW | yes | | `SelectDataColumns` columns | yes: ASE `select_data_columns` | hash: `WHF::TestColumnSelectionIdentity`; keys, rows → NEW | yes | no → NEW | yes | @@ -84,7 +84,7 @@ Legend: **yes** (with the best test as evidence), **no** (with what the closest | `CachedSource` | 1 tag | no | **plain only** (data-tag read-back untested) | no | no | | `DerivedSource(tags_as_data=)` | yes: `sources/test_derived_source_tags_as_data.py::TestColumns::test_several_copies_follow_map_order` | content hash only: `TestIdentity::test_mapping_order_does_not_change_content_hash` | plain; data-tag origin `dt/test_derived_source.py::test_tags_as_data_over_a_data_tag_node` | one arrangement | yes | | function pod, several inputs | 2: `function_pod/test_function_pod_auto_select.py::test_call_selects_once_after_the_join`; 3: `dt/test_edi_end_to_end.py` | **no**: `pod(b, a)` never compared with `pod(a, b)` | data-tag parameter (EDI) | no | yes | -| `output_keys`, several | yes: `data_function/test_data_function.py::test_multiple_output_keys` | **no**; order is not in the identity: **ITL-1244** | — | — | value only | +| `output_keys`, several | yes: `data_function/test_data_function.py::test_multiple_output_keys` | decided (ITL-1244): the uri holds the order-free output schema; a swap of differently typed keys is another function, of same-typed keys the same (`function_pod/test_output_keys_identity.py`) | — | — | value only | | automatic select of several extra columns | yes: `test_dropping_logs_one_info_message_naming_the_columns` | no (kept list sorted) | one data-tag falls through | no | yes | | `PipelineJob.bind(sources=)`, several | yes: `test_pipeline/test_pipeline_job.py::TestPipelineJobBind::test_bind_sources_mutates_job` (membership) | n/a (dict order unused) | plain only | — | — | | bind a source in another column order | yes: `test_bind_type_check.py::test_columns_match_by_name_within_each_group_whatever_their_order` (plain, run ok only) | yes (plain) | **mixed roles: ITL-1245** (accepted, then the node's table breaks) | partly | async read in `test_bind_narrower_source.py::test_columns_follow_the_declared_order` | @@ -97,7 +97,7 @@ Legend: **yes** (with the best test as evidence), **no** (with what the closest | 1 | `MergeJoin(A, B)` and `MergeJoin(B, A)` give the source-info lists of tied values in argument order | stored source info (operator cache, downstream tables); not the hashes | ITL-1241 | | 2 | `MapTags` refuses a swap or cycle of data-tags that it accepts for plain tags (`MapData` is right: a data-only move) | error only | ITL-1242 | | 3 | `MergeJoin` raises `TypeError` on a null in a colliding column | error only | ITL-1243 | -| 4 | Swapping `output_keys` keeps the function's uri, so a job serves stored values under swapped names | result cache: wrong values served | ITL-1244 (rule undecided) | +| 4 | Swapping `output_keys` keeps the function's uri, so a job serves stored values under swapped names | result cache: wrong values served | ITL-1244 (decided: identity right as it is; a same-typed swap that gives a name another value needs a major version bump, swapping the returned values with the keys changes nothing; the cache check is ITL-1253) | | 5 | Binding a source with mixed tag roles in another column order is accepted, then the source node's `as_table` raises | error on read; the run is right | ITL-1245 | | 6 | A function pod over data-tags (`FallThroughPod`) hashes its fall-through tags in the input's tag order: two sources that differ only in tag order give the function node another content and pipeline hash | pipeline hash, pipeline table path | ITL-1246 | | 7 | Input whose table layout differs from its tag order: every unary operator's result keys list the tags in the physical order while its rows use the tag order; Join, SemiJoin, MergeJoin (and, with data-tags, the tag select/drop and `MapTags` forms) give the async rows another column order than the sync rows. In a job, an operator node stores one column order on both orchestrators (measured, tested) | column order only; no hash, no stored table | ITL-1249 | @@ -107,7 +107,7 @@ Legend: **yes** (with the best test as evidence), **no** (with what the closest Order- or role-dependent behaviour that reaches a hash or a stored table first. -1. `output_keys` order: not in identity, stored values served under swapped names (ITL-1244). +1. `output_keys` order: decided in ITL-1244 (order-free output schema; a same-typed swap that gives a name another value needs a major version bump; keys and returned values swapped together change nothing); the missing check on a cache hit is ITL-1253. 2. `MergeJoin` tied values: source-info order follows the inputs (ITL-1241). 3. `PolarsFilter` predicate order in identity, constraint order not; never tested with two (ITL-1247). 4. `record_id_columns` key order: moves record ids, tokens and the content hash; never compared. diff --git a/docs/tutorial/06-reruns-and-caching.md b/docs/tutorial/06-reruns-and-caching.md index 625022f60..8ff8b93e8 100644 --- a/docs/tutorial/06-reruns-and-caching.md +++ b/docs/tutorial/06-reruns-and-caching.md @@ -151,9 +151,10 @@ No call, and the **old** values. There is no error and no warning. !!! warning "Editing a function's code does not recompute its results" Orcapod does not look at a function's source code. It identifies a function by three - things: its **name**, its **output** (the `output_keys` and return type), and its - **major version**. As long as those are the same, stored results are reused, whatever - the body now says. + things: its **name**, its **output** (each output name with its type, in any order), + and its **major version**. As long as those are the same, stored results are reused, + whatever the body now says, and whichever position of the returned tuple each output + name takes. ## Bump the major version diff --git a/tests/test_core/data_tags/test_several_items.py b/tests/test_core/data_tags/test_several_items.py index f59035b20..b2b5e4026 100644 --- a/tests/test_core/data_tags/test_several_items.py +++ b/tests/test_core/data_tags/test_several_items.py @@ -5,6 +5,10 @@ column, in both roles for a data-tag, becomes non-nullable. * ``Index`` with ``out=`` reads a list-valued data-tag (after ``Batch``) as it reads a data column, on both paths. + +Each test runs on its input in its declared tag order with the tags first, and in the +reversed tag order with the data first: the result is the same except for the column +order, which follows the input. """ from __future__ import annotations @@ -18,6 +22,7 @@ from orcapod.core.sources import ArrowTableSource from ..operators.several_items import ( + DATA_FIRST_REVERSED, DATA_TAGS, MAIN, MIXED, @@ -41,17 +46,33 @@ ) -def _nullable_source(tag_only: list[str]) -> ArrowTableSource: +# (tag order, table column order) of ``NULLS``: declared and tags first, reversed and +# data first. +NULLS_ARRANGEMENTS = { + "t1-t2/tags_first": (("t1", "t2"), ("t1", "t2", "d1", "d2")), + "t2-t1/data_first_reversed": (("t2", "t1"), ("d2", "d1", "t2", "t1")), +} +CONTROL = "t1-t2/tags_first" + + +def _nullable_source( + tag_only: list[str], arrangement: str = CONTROL +) -> ArrowTableSource: + tag_order, layout = NULLS_ARRANGEMENTS[arrangement] return ArrowTableSource( - NULLS, tag_columns=["t1", "t2"], source_id="n", tag_only_columns=tag_only + NULLS.select(list(layout)), + tag_columns=list(tag_order), + source_id="n", + tag_only_columns=tag_only, ) +@pytest.mark.parametrize("arrangement", list(NULLS_ARRANGEMENTS)) @pytest.mark.parametrize("tag_only", [[], ["t2"]], ids=["data_tags", "mixed"]) def test_drop_nulls_of_several_columns_with_nullable_data_tags( - tag_only: list[str], + tag_only: list[str], arrangement: str ) -> None: - source = _nullable_source(tag_only) + source = _nullable_source(tag_only, arrangement) results = {} for names in itertools.permutations(["t1", "t2", "d1"]): op = DropNulls(list(names)) @@ -85,31 +106,53 @@ def test_drop_nulls_of_several_columns_with_nullable_data_tags( assert [data["d2"] for _, data in kept.iter_data()] == [5] first = next(iter(results.values())) assert all(result == first for result in results.values()) + # The tags follow the input's order; nothing else depends on the arrangement. + assert first["presentation"][0] == NULLS_ARRANGEMENTS[arrangement][0] + control = DropNulls(["t1", "t2", "d1"])(_nullable_source(tag_only)) + assert {k: v for k, v in first.items() if k != "presentation"} == fingerprint( + control + ) +@pytest.mark.parametrize("arrangement", list(NULLS_ARRANGEMENTS)) @pytest.mark.parametrize("tag_only", [[], ["t2"]], ids=["data_tags", "mixed"]) def test_drop_nulls_of_one_data_tag_keeps_the_rows_where_it_has_a_value( - tag_only: list[str], + tag_only: list[str], arrangement: str ) -> None: - kept = DropNulls(["t1"])(_nullable_source(tag_only)) + kept = DropNulls(["t1"])(_nullable_source(tag_only, arrangement)) assert sorted(data["d2"] for _, data in kept.iter_data()) == [5, 7, 8] # pyright: ignore[reportArgumentType] +INDEX_ARRANGEMENTS = { + "t1-t2-t3/tags_first": (MAIN.tags, TAGS_FIRST), + "t3-t2-t1/data_first_reversed": (tuple(reversed(MAIN.tags)), DATA_FIRST_REVERSED), +} + + +@pytest.mark.parametrize("arrangement", list(INDEX_ARRANGEMENTS)) @pytest.mark.parametrize("role", [DATA_TAGS, MIXED]) @pytest.mark.parametrize("column", ["t1", "t3", "d1"]) def test_index_reads_a_list_valued_data_tag_as_a_data_column( - role: str, column: str + role: str, column: str, arrangement: str ) -> None: """After ``Batch``, t1 and t3 are list-valued data-tags (t2 is plain in MIXED).""" + tag_order, layout = INDEX_ARRANGEMENTS[arrangement] batched = Batch(batch_size=3)( - make_source(MAIN, Arrangement(MAIN.tags, TAGS_FIRST, role)) + make_source(MAIN, Arrangement(tag_order, layout, role)) ) op = Index(column, 0, out=f"first_{column}") indexed = op(batched) first = [data[f"first_{column}"] for _, data in indexed.iter_data()] assert first == {"t1": ["b", "b"], "t3": [1, 2], "d1": [10, 40]}[column] - # The data-tag itself is unchanged: still a tag and a data column, with its lists. - assert presentation(indexed)[0] == ("t1", "t2", "t3") + # The data-tag itself is unchanged: still a tag and a data column, with its lists; + # Index keeps its input's tag order as its input presents it (that Batch presents + # the source's tag order is ITL-1249, below), and nothing else depends on the + # arrangement. + assert presentation(indexed)[0] == presentation(batched)[0] + control = Index(column, 0, out=f"first_{column}")( + Batch(batch_size=3)(make_source(MAIN, Arrangement(MAIN.tags, TAGS_FIRST, role))) + ) + assert fingerprint(indexed) == fingerprint(control) assert column in presentation(indexed)[1] lists = {"t1": [["b", "a", "a"], ["b", "a", "b"]], "t3": [[1, 2, 1], [2, 1, 2]]} lists["d1"] = [[10, 20, 30], [40, 50, 60]] @@ -119,3 +162,17 @@ def test_index_reads_a_list_valued_data_tag_as_a_data_column( assert rows_fingerprint( async_rows(Index(column, 0, out=f"first_{column}"), batched) ) == rows_fingerprint(list(indexed.iter_data())) + + +@pytest.mark.xfail( + strict=True, + reason="ITL-1249: an operator presents its output tags in the input table's " + + "physical column order, not in the input stream's tag order", +) +@pytest.mark.parametrize("role", [DATA_TAGS, MIXED]) +def test_batch_presents_its_input_streams_tag_order(role: str) -> None: + """The source's tags are (t3, t2, t1); its table holds them as t1, t2, t3.""" + tag_order, layout = INDEX_ARRANGEMENTS["t3-t2-t1/data_first_reversed"] + source = make_source(MAIN, Arrangement(tag_order, layout, role)) + assert presentation(source)[0] == tag_order + assert presentation(Batch(batch_size=3)(source))[0] == tag_order diff --git a/tests/test_core/function_pod/test_output_keys_identity.py b/tests/test_core/function_pod/test_output_keys_identity.py new file mode 100644 index 000000000..cb1269b01 --- /dev/null +++ b/tests/test_core/function_pod/test_output_keys_identity.py @@ -0,0 +1,584 @@ +"""A function's outputs are a set of named, typed values (ITL-1244). + +The function's uri holds the hash of its output schema: each output key paired with its +type, in no order (the schema hash sorts field names, as for every schema). So: + +* swapping two output keys of different types changes the schema: another uri, content + hash, pipeline hash and stored tables; +* swapping two output keys of the same type leaves the schema as it is: the same uri. + When a name then receives another value (the keys swapped without the returned + values, or the reverse), it is like an edit of the body: it changes what the + function computes, so it needs a major version bump (the uri holds only the + major); a check of the stored function variation data on a cache hit is ITL-1253 + (strict xfail below). Swapping the keys with the returned values changes nothing; +* the input parameters are in no part of the uri (names and order); +* a function with one output key has the identity the golden values pin. + +``@function_pod``, ``FunctionPod.from_fn`` and ``PythonDataFunction`` give one uri, and +``to_config`` / ``from_config`` and a saved and loaded job keep the declared order. + +Every test over a source runs it in two arrangements: the declared tag order with the tags +first, and the reversed tag order with the data first (``SHAPES``); neither changes a +value, a hash or a stored path (over data-tags the last two still do: ITL-1246). +""" + +from __future__ import annotations + +import itertools +import json +import warnings +from pathlib import Path +from typing import Any + +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.contexts import get_default_context +from orcapod.core.data_function import CachedDataFunction, PythonDataFunction +from orcapod.core.datagrams import Data +from orcapod.core.function_pod import FunctionPod +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator + +from ..operators.several_items import ( + DATA_FIRST_REVERSED, + DATA_TAGS, + MAIN, + MIXED, + PLAIN, + TAGS_FIRST, + Arrangement, + fingerprint, + make_source, +) + +GOLDEN_FOLDER = Path(__file__).resolve().parents[2] / "test_hashing/golden/data/v1" + +# (tag order, table layout) of the source: the control, and its reverse with the data +# first. +SHAPES = { + "t1-t2-t3/tags_first": (MAIN.tags, TAGS_FIRST), + "t3-t2-t1/data_first_reversed": (tuple(reversed(MAIN.tags)), DATA_FIRST_REVERSED), +} +CONTROL = "t1-t2-t3/tags_first" + + +def _source(role: str, shape: str = CONTROL) -> Any: + tag_order, layout = SHAPES[shape] + return make_source(MAIN, Arrangement(tag_order, layout, role)) + + +# Output names in sorted order; the tests declare them in every order. +TWO_KEYS = ("first", "second") +THREE_KEYS = ("first", "second", "third") + + +# Outputs of one type: every order of the keys is one schema. +def same2(d1: int, d3: str) -> tuple[int, int]: + return d1 + len(d3), d1 * 2 + + +def same3(d1: int, d3: str) -> tuple[int, int, int]: + return d1 + len(d3), d1 * 2, d1 - 1 + + +# Outputs of different types: every order of the keys is another schema. +def mixed2(d1: int, d3: str) -> tuple[int, str]: + return d1 * 2, d3 * 2 + + +def mixed3(d1: int, d3: str) -> tuple[int, str, float]: + return d1 * 2, d3 * 2, d1 / 4 + + +# Two outputs of one type and one of another. +def partly(d1: int, d3: str) -> tuple[int, int, str]: + return d1 + len(d3), d1 * 2, d3 * 2 + + +FUNCTIONS = { + ("same", 2): same2, + ("same", 3): same3, + ("mixed", 2): mixed2, + ("mixed", 3): mixed3, +} + + +def _orders(n: int) -> list[tuple[str, ...]]: + return list(itertools.permutations(TWO_KEYS if n == 2 else THREE_KEYS)) + + +def _expected(fn: Any, keys: tuple[str, ...], d1: int, d3: str) -> dict[str, Any]: + """Each output name's value: the returned position its key is declared at.""" + return dict(zip(keys, fn(d1, d3))) + + +def _main_values() -> list[tuple[Any, Any]]: + columns = MAIN.columns + return list(zip(columns["d1"].to_pylist(), columns["d3"].to_pylist())) + + +def _identity(pod: Any) -> tuple[Any, ...]: + return (pod.uri, pod.content_hash(), pod.pipeline_hash()) + + +# --------------------------------------------------------------------------- +# Identity +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize(("kind", "n"), list(FUNCTIONS), ids=lambda v: str(v)) +def test_the_uri_holds_the_hash_of_the_output_schema(kind: str, n: int) -> None: + hasher = get_default_context().semantic_hasher + for keys in _orders(n): + pod = FunctionPod.from_fn(FUNCTIONS[(kind, n)], output_keys=list(keys)) + schema = pod.data_function.output_data_schema + assert tuple(schema) == keys + assert pod.uri[1] == hasher.hash_object(schema).to_hex() + + +@pytest.mark.parametrize("n", [2, 3]) +def test_every_order_of_same_typed_output_keys_is_one_function(n: int) -> None: + identities = { + _identity(FunctionPod.from_fn(FUNCTIONS[("same", n)], output_keys=list(keys))) + for keys in _orders(n) + } + assert len(identities) == 1 + + +@pytest.mark.parametrize("n", [2, 3]) +def test_every_order_of_differently_typed_output_keys_is_another_function( + n: int, +) -> None: + orders = _orders(n) + pods = [ + FunctionPod.from_fn(FUNCTIONS[("mixed", n)], output_keys=list(keys)) + for keys in orders + ] + for part in range(3): + assert len({_identity(pod)[part] for pod in pods}) == len(orders) + # Only the output component of the uri differs. + assert len({(pod.uri[0], *pod.uri[2:]) for pod in pods}) == 1 + + +def test_a_swap_changes_the_identity_exactly_when_it_changes_a_keys_type() -> None: + """``partly`` returns (int, int, str): only where ``str`` lands matters.""" + by_str_key: dict[str, set[tuple[Any, ...]]] = {} + for keys in _orders(3): + pod = FunctionPod.from_fn(partly, output_keys=list(keys)) + by_str_key.setdefault(keys[2], set()).add(_identity(pod)) + assert all(len(identities) == 1 for identities in by_str_key.values()) + assert len(set().union(*by_str_key.values())) == 3 + + +def test_only_a_major_version_bump_tells_apart_keys_swapped_without_values() -> None: + """The uri holds the major version only: a minor bump keeps the swapped order's uri. + + ``same2`` returns its values in one order, so swapping its keys gives each name + the other value. While a cache hit is not checked (ITL-1253), only a major bump + makes the swapped order compute its own values. + """ + original = FunctionPod.from_fn(same2, output_keys=["first", "second"]) + minor = FunctionPod.from_fn(same2, output_keys=["second", "first"], version="v0.1") + major = FunctionPod.from_fn(same2, output_keys=["second", "first"], version="v1.0") + assert minor.uri == original.uri + assert major.uri != original.uri + assert major.uri[2] == "v1" + + +# ``partly``'s outputs by name: two of one type and one of another. +PARTLY_TYPES = {"first": int, "second": int, "third": str} + + +def _partly_by_name(d1: int, d3: str) -> dict[str, Any]: + return {"first": d1 + len(d3), "second": d1 * 2, "third": d3 * 2} + + +def _partly_returning(keys: tuple[str, ...]) -> Any: + """``partly`` declaring ``keys`` and returning its values in the same order. + + Every order has the same name, so only the keys and the returned tuple differ. + """ + + def partly_in_order(d1: int, d3: str) -> Any: + values = _partly_by_name(d1, d3) + return tuple(values[key] for key in keys) + + return_type: Any = tuple[tuple(PARTLY_TYPES[key] for key in keys)] + partly_in_order.__annotations__ = {"d1": int, "d3": str, "return": return_type} + return partly_in_order + + +def _partly_pod(keys: tuple[str, ...]) -> Any: + return FunctionPod.from_fn(_partly_returning(keys), output_keys=list(keys)) + + +def _partly_expected() -> list[tuple[Any, ...]]: + """Each row's values by name, in sorted name order.""" + return sorted( + tuple(_partly_by_name(d1, d3)[key] for key in THREE_KEYS) + for d1, d3 in _main_values() + ) + + +def test_swapping_the_keys_with_the_returned_values_is_one_function() -> None: + """Every order of the keys, each with the returned values in that order: one uri. + + Each name receives the value it had, so nothing a stored result means has changed + and no version bump is needed; the outputs of two types change no identity either. + """ + identities = {_identity(_partly_pod(keys)) for keys in _orders(3)} + assert len(identities) == 1 + + +def test_renaming_an_output_key_is_another_function() -> None: + renamed = FunctionPod.from_fn(same2, output_keys=["first", "total"]) + original = FunctionPod.from_fn(same2, output_keys=list(TWO_KEYS)) + assert renamed.uri != original.uri + + +def test_a_one_output_function_has_the_identity_the_golden_values_pin() -> None: + """The uri ``pod_default_version.decorator.uri`` pins for ``golden_ratio``. + + Read from the pipeline golden file that pins it, so the test follows the pin. + """ + from tests.test_hashing.golden.cases import golden_ratio + + pinned = [ + entries["pod_default_version.decorator.uri"] + for path in sorted(GOLDEN_FOLDER.glob("pipeline-*.json")) + if "pod_default_version.decorator.uri" + in (entries := json.loads(path.read_text())) + ] + assert len(pinned) == 1 + assert list(golden_ratio.pod.uri) == pinned[0] + + +def test_the_input_parameters_are_in_no_part_of_the_uri() -> None: + """Names and order of the parameters: one uri, content hash and pipeline hash. + + The uri holds the function's name, output schema hash, major version and kind. + A change of signature, like one of the body, is the user's to mark with a version. + """ + + def forward(d1: int, d3: str) -> tuple[int, str]: + return d1 * 2, d3 * 2 + + def backward(d3: str, d1: int) -> tuple[int, str]: + return d1 * 2, d3 * 2 + + def renamed(a: int, b: str) -> tuple[int, str]: + return a * 2, b * 2 + + for keys in (["first", "second"], ["second", "first"]): + identities = { + _identity(FunctionPod.from_fn(fn, output_keys=keys, name="f")) + for fn in (forward, backward, renamed) + } + assert len(identities) == 1 + + +@pytest.mark.parametrize("keys", _orders(3), ids="-".join) +def test_every_way_of_making_a_pod_gives_one_uri(keys: tuple[str, ...]) -> None: + decorated = function_pod(output_keys=list(keys))(mixed3).pod + from_fn = FunctionPod.from_fn(mixed3, output_keys=list(keys)) + direct = FunctionPod(PythonDataFunction(mixed3, output_keys=list(keys))) # pyright: ignore[reportArgumentType] # PythonDataFunction is not yet typed as matching DataFunctionProtocol; it works at runtime + assert _identity(decorated) == _identity(from_fn) == _identity(direct) + + +@pytest.mark.parametrize("keys", _orders(3), ids="-".join) +def test_the_config_keeps_the_declared_order_and_the_uri(keys: tuple[str, ...]) -> None: + data_function = PythonDataFunction(mixed3, output_keys=list(keys)) + config = data_function.to_config() + assert config["config"]["output_keys"] == list(keys) + assert list(config["config"]["output_data_schema"]) == list(keys) + assert config["uri"] == list(data_function.uri) + restored = PythonDataFunction.from_config(config) + assert tuple(restored.output_data_schema) == keys + assert restored.uri == data_function.uri + + +# --------------------------------------------------------------------------- +# Values: in memory, a cached data function, a job +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("role", [PLAIN, DATA_TAGS, MIXED]) +@pytest.mark.parametrize(("kind", "n"), list(FUNCTIONS), ids=lambda v: str(v)) +def test_in_memory_each_order_names_its_own_values( + kind: str, n: int, role: str +) -> None: + """In every arrangement of the source: the same values (hashes: below).""" + fn = FUNCTIONS[(kind, n)] + for keys in _orders(n): + expected = sorted( + tuple(_expected(fn, keys, d1, d3)[k] for k in keys) + for d1, d3 in _main_values() + ) + for shape in SHAPES: + stream = FunctionPod.from_fn(fn, output_keys=list(keys))( + _source(role, shape) + ) + _, data_keys = stream.keys() + assert tuple(k for k in data_keys if k in keys) == keys + rows = sorted( + tuple(data[k] for k in keys) for _, data in stream.iter_data() + ) + assert rows == expected, (keys, shape) + + +@pytest.mark.parametrize("role", [PLAIN, DATA_TAGS, MIXED]) +def test_in_memory_keys_swapped_with_their_values_give_each_name_its_value( + role: str, +) -> None: + """Every order of keys and returned values, in every arrangement: the same values.""" + for keys in _orders(3): + for shape in SHAPES: + stream = _partly_pod(keys)(_source(role, shape)) + rows = sorted( + tuple(data[key] for key in THREE_KEYS) for _, data in stream.iter_data() + ) + assert rows == _partly_expected(), (keys, shape) + + +FALL_THROUGH_ORDER_ISSUE = "ITL-1246" +# Over data-tags the pod is a fall-through pod, whose identity holds the data-tags in +# the input's tag order (ITL-1246, fixed by PR 453). Only an assertion can fail here. +_FALL_THROUGH_ORDER = pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason=f"{FALL_THROUGH_ORDER_ISSUE}: the fall-through tags enter the pod's identity " + + "in the input's tag order", +) + + +@pytest.mark.parametrize( + "role", + [ + PLAIN, + pytest.param(DATA_TAGS, marks=_FALL_THROUGH_ORDER), + pytest.param(MIXED, marks=_FALL_THROUGH_ORDER), + ], +) +@pytest.mark.parametrize(("kind", "n"), list(FUNCTIONS), ids=lambda v: str(v)) +def test_the_arrangement_of_the_source_changes_no_hash_or_stored_path( + kind: str, n: int, role: str +) -> None: + """Each order of the keys, over every arrangement: one stream and one node path.""" + fn = FUNCTIONS[(kind, n)] + for keys in _orders(n): + fingerprints, paths = [], [] + for shape in SHAPES: + pod = FunctionPod.from_fn(fn, output_keys=list(keys)) + # Each computation names fresh output records: leave source info out. + fingerprints.append( + fingerprint(pod(_source(role, shape)), source_info=False) + ) + job = PipelineJob(name="outputs", database=InMemoryArrowDatabase()) + with job: + pod(_source(role, shape), label="outputs") + paths.append(job.nodes["outputs"].node_identity_path) + assert all(f == fingerprints[0] for f in fingerprints), keys + assert len(set(paths)) == 1, keys + + +def test_a_cached_data_function_stores_differently_typed_orders_apart() -> None: + database = InMemoryArrowDatabase() + cached = { + keys: CachedDataFunction( + PythonDataFunction(mixed2, output_keys=list(keys)), # pyright: ignore[reportArgumentType] # PythonDataFunction is not yet typed as matching DataFunctionProtocol; it works at runtime + result_database=database, + ) + for keys in _orders(2) + } + assert len({function.record_path for function in cached.values()}) == 2 + data = Data({"d1": 10, "d3": "xy"}) + for keys, function in cached.items(): + result = function.call(data) + assert result is not None + assert result.as_dict() == _expected(mixed2, keys, 10, "xy") + for keys, function in cached.items(): + stored = function.get_cached_output_for_data(data) + assert stored is not None + assert stored.as_dict() == _expected(mixed2, keys, 10, "xy") + + +def _database(kind: str, tmp_path: Path) -> Any: + if kind == "delta": + return DeltaTableDatabase(tmp_path / "store") + return InMemoryArrowDatabase() + + +def _values(node: Any, keys: tuple[str, ...]) -> list[tuple[Any, ...]]: + return sorted(tuple(data[k] for k in keys) for _, data in node.iter_data()) + + +def _expected_values(fn: Any, keys: tuple[str, ...]) -> list[tuple[Any, ...]]: + return sorted( + tuple(_expected(fn, keys, d1, d3)[k] for k in keys) for d1, d3 in _main_values() + ) + + +@pytest.mark.parametrize( + "orchestrator", + [SyncPipelineOrchestrator, AsyncPipelineOrchestrator], + ids=["sync", "async"], +) +@pytest.mark.parametrize("database_kind", ["in_memory", "delta"]) +@pytest.mark.parametrize("shape", list(SHAPES)) +@pytest.mark.parametrize("role", [PLAIN, DATA_TAGS]) +@pytest.mark.parametrize("n", [2, 3]) +def test_jobs_with_differently_typed_orders_on_one_database_store_their_own_rows( + n: int, + role: str, + shape: str, + database_kind: str, + orchestrator: type, + tmp_path: Path, +) -> None: + """Every order in turn on one database: each computes and stores its own rows. + + A second pass over every order finds each order's rows stored, under its names. + """ + fn = FUNCTIONS[("mixed", n)] + database = _database(database_kind, tmp_path) + orders = _orders(n) + paths = set() + for pass_number in (1, 2): + for keys in orders: + job = PipelineJob(name="outputs", database=database) + with job: + FunctionPod.from_fn(fn, output_keys=list(keys))( + _source(role, shape), label="outputs" + ) + summary = job.run(orchestrator=orchestrator()) + node = job.nodes["outputs"] + counts = summary.nodes["outputs"] + if pass_number == 1: + assert (counts.computed, counts.reused) == (6, 0), keys + paths.add(node.node_identity_path) + else: + assert (counts.computed, counts.reused) == (0, 6), keys + assert _values(node, keys) == _expected_values(fn, keys), keys + assert len(paths) == len(orders) + + +@pytest.mark.parametrize( + "orchestrator", + [SyncPipelineOrchestrator, AsyncPipelineOrchestrator], + ids=["sync", "async"], +) +@pytest.mark.parametrize("shape", list(SHAPES)) +@pytest.mark.parametrize("role", [PLAIN, DATA_TAGS]) +def test_jobs_with_keys_swapped_with_their_values_share_correct_rows( + role: str, shape: str, orchestrator: type +) -> None: + """The first order computes; every other order is served its rows, which are right. + + One uri and one stored table for every order of keys and returned values, and each + name holds its own value in every order: serving the stored rows is correct. + """ + database = InMemoryArrowDatabase() + paths = set() + for index, keys in enumerate(_orders(3)): + job = PipelineJob(name="outputs", database=database) + with job: + _partly_pod(keys)(_source(role, shape), label="outputs") + summary = job.run(orchestrator=orchestrator()) + counts = summary.nodes["outputs"] + expected_counts = (6, 0) if index == 0 else (0, 6) + assert (counts.computed, counts.reused) == expected_counts, keys + node = job.nodes["outputs"] + paths.add(node.node_identity_path) + assert _values(node, THREE_KEYS) == _partly_expected(), keys + assert len(paths) == 1 + + +@pytest.mark.parametrize("shape", list(SHAPES)) +def test_a_saved_and_loaded_job_keeps_the_declared_order( + shape: str, tmp_path: Path +) -> None: + keys = ("third", "first", "second") + job = PipelineJob(name="outputs", database=DeltaTableDatabase(tmp_path / "store")) + with job: + FunctionPod.from_fn(mixed3, output_keys=list(keys))( + _source(PLAIN, shape), label="outputs" + ) + job.run() + uri = job.nodes["outputs"].node_uri + path = tmp_path / "job.json" + job.save(path) + + loaded = PipelineJob.load(path, database=DeltaTableDatabase(tmp_path / "store")) + node = loaded.nodes["outputs"] + assert node.node_uri == uri + assert tuple(k for k in node.output_schema()[1] if k in keys) == keys + assert _values(node.as_source(), keys) == _expected_values(mixed3, keys) + + +# --------------------------------------------------------------------------- +# Open issues +# --------------------------------------------------------------------------- + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="ITL-1253 (needs ITL-1256: the output keys in the stored signature hash): " + + "a cache hit whose stored function variation data differs from the current " + + "function is served silently", +) +@pytest.mark.parametrize("shape", list(SHAPES)) +@pytest.mark.parametrize("n", [2, 3]) +def test_a_same_typed_swap_is_never_served_the_other_orders_rows_silently( + n: int, shape: str +) -> None: + """Same-typed keys swapped without the returned values share a uri: the second job + finds the first's rows, which give each name the other value. + + What the safety net must do: either compute the second order's own values, or + say so (a warning or an error); never serve the first order's values under the + second order's names without a word. It needs two changes: the stored variation + data must tell the two orders apart (ITL-1256: the output keys enter the stored + signature hash) and a cache hit must compare it (ITL-1253). Only the assertion is + the expected failure (``raises=AssertionError``): an error from the run, such as a + future mismatch error, fails the test instead of hiding as an expected failure. + """ + fn = FUNCTIONS[("same", n)] + first, second = _orders(n)[0], _orders(n)[-1] + database = InMemoryArrowDatabase() + warned = False + job = None + for keys in (first, second): + job = PipelineJob(name="outputs", database=database) + with job: + FunctionPod.from_fn(fn, output_keys=list(keys))( + _source(PLAIN, shape), label="outputs" + ) + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter("always") + job.run() + # Only the last (second) run's warnings count. + warned = bool(recorded) + assert job is not None + served_its_own = _values(job.nodes["outputs"], second) == _expected_values( + fn, second + ) + assert served_its_own or warned + + +@pytest.mark.xfail( + strict=True, + reason="ITL-1254: a dict returned where a tuple is declared is iterated by its keys", +) +def test_a_dict_returned_for_a_tuple_annotation_is_refused() -> None: + def first_and_second(a: str, b: str) -> tuple[str, str]: + # The defect under test: a dict where the annotation declares a tuple. + return {"first": a, "second": b} # pyright: ignore[reportReturnType] + + data_function = PythonDataFunction( + first_and_second, output_keys=["first", "second"] + ) + with pytest.raises((TypeError, ValueError), match="first_and_second"): + data_function.call(Data({"a": "x", "b": "y"})) diff --git a/tests/test_core/function_pod/test_several_items.py b/tests/test_core/function_pod/test_several_items.py index 53cccd60c..5a8ad936a 100644 --- a/tests/test_core/function_pod/test_several_items.py +++ b/tests/test_core/function_pod/test_several_items.py @@ -219,26 +219,23 @@ def test_the_tag_order_of_the_input_does_not_change_a_fall_through_pods_hashes( assert all(result == first for result in results.values()) -OUTPUT_KEYS_ISSUE = "ITL-1244 (rule undecided)" +def test_swapped_output_keys_change_the_uri_exactly_when_they_change_a_type() -> None: + """The uri holds the output schema: each key with its type, in no order (ITL-1244). - -@pytest.mark.xfail( - strict=True, - reason=f"{OUTPUT_KEYS_ISSUE}: the order of output_keys is not in the identity", -) -def test_swapped_output_keys_are_another_function() -> None: - """Swapped output keys map the results to other names: not the same function. - - Today both have one uri, so a job serves one's stored values under the other's - names. + Swapping keys of different types is another function; swapping keys of one type + is the same function (a change of what it computes, like a body edit: a version + bump). ``test_output_keys_identity.py`` covers it in full. """ def make(keys: list[str]): @function_pod(output_keys=keys) - def stats(d1: int, t2: int) -> tuple[int, int]: - return d1 + t2, d1 * t2 + def stats(d1: int, t2: int, d3: str) -> tuple[int, int, str]: + return d1 + t2, d1 * t2, d3 - return stats + return stats.pod - forward, backward = make(["sum", "product"]), make(["product", "sum"]) - assert forward.pod.uri != backward.pod.uri + forward = make(["sum", "product", "label"]) + same_typed_swap = make(["product", "sum", "label"]) + typed_swap = make(["label", "product", "sum"]) + assert forward.uri == same_typed_swap.uri + assert forward.uri != typed_swap.uri diff --git a/tests/test_core/operators/test_several_items.py b/tests/test_core/operators/test_several_items.py index aafb4326d..f0552382d 100644 --- a/tests/test_core/operators/test_several_items.py +++ b/tests/test_core/operators/test_several_items.py @@ -18,8 +18,9 @@ nothing, with two, three and four inputs. ``GroupBy`` is not here: its arrangement and ``by`` order are tested by ITL-1226 -(``test_group_by_member_order.py``). The order of ``AddTags``'s names is the order of -the new tags and part of its identity, and is tested as such below. +(``test_group_by_member_order.py``). The order of ``AddTags``'s names is neither the +order of the new tags nor part of its identity (ITL-1269: they are held in name order), +and is tested as such below. """ from __future__ import annotations diff --git a/tests/test_core/sources/test_several_items.py b/tests/test_core/sources/test_several_items.py index 6e6bc85fa..c35dcc560 100644 --- a/tests/test_core/sources/test_several_items.py +++ b/tests/test_core/sources/test_several_items.py @@ -16,8 +16,10 @@ from __future__ import annotations +import asyncio import itertools import json +from typing import Any import pyarrow as pa import pytest @@ -41,6 +43,7 @@ Arrangement, fingerprint, make_source, + ordered_rows_fingerprint, presentation, ) @@ -214,6 +217,16 @@ def no_rows(*args: object, **kwargs: object) -> pa.Table: assert fingerprint(again) == fingerprint(cached) +def _async_rows(stream: Any) -> list[Any]: + async def collect() -> list[Any]: + return [row async for row in stream.async_iter_data()] + + return asyncio.run(collect()) + + +@pytest.mark.parametrize( + "tag_columns", [["t1", "t2"], ["t2", "t1"]], ids=["t1-t2", "t2-t1"] +) @pytest.mark.parametrize( "data_schema", [ @@ -224,9 +237,14 @@ def no_rows(*args: object, **kwargs: object) -> pa.Table: ) @pytest.mark.parametrize("role", ROLES) def test_a_schema_in_another_field_order_gives_the_same_source( - data_schema: dict[str, type], role: str + data_schema: dict[str, type], role: str, tag_columns: list[str] ) -> None: - """A ``DictSource`` schema with several fields, in the rows' order or another.""" + """A ``DictSource`` schema with several fields, in the rows' order or another. + + Neither the schema's field order nor the tag order changes the source (rows, hashes, + column names); the tags are presented in the order given, and the async rows are + the sync rows. + """ rows = [ {"t1": "a", "t2": 1, "d1": 10, "d3": "x"}, {"t1": "b", "t2": 2, "d1": 20, "d3": "y"}, @@ -234,7 +252,7 @@ def test_a_schema_in_another_field_order_gives_the_same_source( tag_only = {PLAIN: True, DATA_TAGS: [], MIXED: ["t2"]}[role] source = DictSource( rows, - tag_columns=["t1", "t2"], + tag_columns=tag_columns, source_id="d", data_schema=data_schema, tag_only_columns=tag_only, @@ -247,4 +265,7 @@ def test_a_schema_in_another_field_order_gives_the_same_source( tag_only_columns=tag_only, ) assert fingerprint(source) == fingerprint(reference) - assert presentation(source)[0] == ("t1", "t2") + assert presentation(source)[0] == tuple(tag_columns) + assert ordered_rows_fingerprint(_async_rows(source)) == ordered_rows_fingerprint( + list(source.iter_data()) + ) diff --git a/tests/test_core/streams/test_several_items_methods.py b/tests/test_core/streams/test_several_items_methods.py index fa31c955f..59f47edfe 100644 --- a/tests/test_core/streams/test_several_items_methods.py +++ b/tests/test_core/streams/test_several_items_methods.py @@ -3,7 +3,8 @@ Every stream method that builds an operator from several items (names, a mapping, keywords, predicates) gives the stream that operator gives: same rows, hashes and column order, for plain tags, data-tags and a mix, on a stream with three tags and three -data columns. ``polars_filter`` merges ``constraint_map`` and keyword constraints, the +data columns, with its items in the order given and reversed; a method that takes data +columns is also given a data-tag. ``polars_filter`` merges ``constraint_map`` and keyword constraints, the keywords winning. Several ``ColumnConfig`` groups together give the ``all_info`` columns of those groups, in the same order. """ @@ -11,8 +12,9 @@ from __future__ import annotations import itertools -from collections.abc import Callable +from collections.abc import Callable, Sequence from dataclasses import dataclass +from typing import Any import polars as pl import pytest @@ -35,12 +37,15 @@ TagBy, ) from orcapod.core.sources import ArrowTableSource +from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants from ..operators.several_items import ( + DATA_TAGS, LAYOUTS, MAIN, + MIXED, P, ROLES, TAGS_FIRST, @@ -55,102 +60,193 @@ ) # The stream methods are on the stream classes, not on ``StreamProtocol``. -Build = Callable[[ArrowTableSource], StreamProtocol] +Build = Callable[[ArrowTableSource, Sequence[Any]], StreamProtocol] + +# What the order of the items does. +ORDER_FREE = "order_free" # nothing but, at most, the column order +ORDER_IS_IDENTITY = "order_is_identity" # the same rows, another operator (hash) + +# Roles in which every column a case names is a data-tag or data column, never plain. +DATA_TAG_ROLES = (DATA_TAGS, MIXED) @dataclass(frozen=True) class MethodCase: - """A stream method call and the operator call it must equal.""" + """A stream method call and the operator call it must equal, given its items. + + ``items`` are the several items in the order given (pairs for a mapping or + keywords); every case is also run with them reversed. ``order`` says what that + changes; ``roles`` are the roles of the source in which the case applies. + """ label: str + items: tuple[Any, ...] method: Build operator: Build + order: str = ORDER_FREE + roles: tuple[str, ...] = ROLES CASES = [ MethodCase( "select_tag_columns", - lambda s: s.select_tag_columns(["t3", "t1"]), - lambda s: SelectTagColumns(["t3", "t1"])(s), + ("t3", "t1"), + lambda s, i: s.select_tag_columns(list(i)), + lambda s, i: SelectTagColumns(list(i))(s), ), MethodCase( "select_data_columns", - lambda s: s.select_data_columns(["d3", "d1"]), - lambda s: SelectDataColumns(["d3", "d1"])(s), + ("d3", "d1"), + lambda s, i: s.select_data_columns(list(i)), + lambda s, i: SelectDataColumns(list(i))(s), + ), + MethodCase( + "select_data_columns_with_a_data_tag", + ("t3", "d1"), + lambda s, i: s.select_data_columns(list(i)), + lambda s, i: SelectDataColumns(list(i))(s), + roles=DATA_TAG_ROLES, ), MethodCase( "drop_tag_columns", - lambda s: s.drop_tag_columns(["t3", "t1"]), - lambda s: DropTagColumns(["t3", "t1"])(s), + ("t3", "t1"), + lambda s, i: s.drop_tag_columns(list(i)), + lambda s, i: DropTagColumns(list(i))(s), ), MethodCase( "drop_data_columns", - lambda s: s.drop_data_columns(["d3", "d1"]), - lambda s: DropDataColumns(["d3", "d1"])(s), + ("d3", "d1"), + lambda s, i: s.drop_data_columns(list(i)), + lambda s, i: DropDataColumns(list(i))(s), + ), + MethodCase( + "drop_data_columns_with_a_data_tag", + ("t3", "d1"), + lambda s, i: s.drop_data_columns(list(i)), + lambda s, i: DropDataColumns(list(i))(s), + roles=DATA_TAG_ROLES, ), MethodCase( "select_columns_positional", - lambda s: s.select_columns("d3", "t2", "d1"), - lambda s: SelectColumns(["d3", "t2", "d1"])(s), + ("d3", "t2", "d1"), + lambda s, i: s.select_columns(*i), + lambda s, i: SelectColumns(list(i))(s), ), MethodCase( "drop_columns_positional", - lambda s: s.drop_columns("d3", "t2"), - lambda s: DropColumns(["d3", "t2"])(s), + ("d3", "t2"), + lambda s, i: s.drop_columns(*i), + lambda s, i: DropColumns(list(i))(s), ), MethodCase( "map_tags", - lambda s: s.map_tags({"t3": "u3", "t1": "u1"}), - lambda s: MapTags({"t3": "u3", "t1": "u1"})(s), + (("t3", "u3"), ("t1", "u1")), + lambda s, i: s.map_tags(dict(i)), + lambda s, i: MapTags(dict(i))(s), ), MethodCase( "map_data", - lambda s: s.map_data({"d3": "e3", "d1": "e1"}), - lambda s: MapData({"d3": "e3", "d1": "e1"})(s), + (("d3", "e3"), ("d1", "e1")), + lambda s, i: s.map_data(dict(i)), + lambda s, i: MapData(dict(i))(s), + ), + MethodCase( + "map_data_with_a_data_tag", + (("t3", "e3"), ("d1", "e1")), + lambda s, i: s.map_data(dict(i)), + lambda s, i: MapData(dict(i))(s), + roles=DATA_TAG_ROLES, ), MethodCase( "drop_nulls", - lambda s: s.drop_nulls(["d2", "t2"]), - lambda s: DropNulls(["d2", "t2"])(s), + ("d2", "t2"), + lambda s, i: s.drop_nulls(list(i)), + lambda s, i: DropNulls(list(i))(s), ), + # The order of the predicates belongs to the filter (docs/concepts/operators.md). MethodCase( "polars_filter_predicates", - lambda s: s.polars_filter(pl.col("d1") > 10, pl.col("t3") == 1), - lambda s: PolarsFilter(predicates=[pl.col("d1") > 10, pl.col("t3") == 1])(s), + (pl.col("d1") > 10, pl.col("t3") == 1), + lambda s, i: s.polars_filter(*i), + lambda s, i: PolarsFilter(predicates=list(i))(s), + order=ORDER_IS_IDENTITY, ), MethodCase( "polars_filter_constraints", - lambda s: s.polars_filter(t1="a", t2=1), - lambda s: PolarsFilter(constraints={"t1": "a", "t2": 1})(s), + (("t1", "a"), ("t2", 1)), + lambda s, i: s.polars_filter(**dict(i)), + lambda s, i: PolarsFilter(constraints=dict(i))(s), ), # Keyword constraints win over the map's value for the same name. MethodCase( "polars_filter_constraint_map_and_keywords", - lambda s: s.polars_filter(constraint_map={"t1": "a", "t2": 2}, t2=1), - lambda s: PolarsFilter(constraints={"t1": "a", "t2": 1})(s), + (("t1", "a"), ("t2", 2)), + lambda s, i: s.polars_filter(constraint_map=dict(i), t2=1), + lambda s, i: PolarsFilter(constraints={**dict(i), "t2": 1})(s), ), + # The new tags are a set (ITL-1269): identity and placement in name order. MethodCase( "add_tags", - lambda s: s.add_tags(x=1, y="z"), - lambda s: AddTags({"x": 1, "y": "z"})(s), + (("x", 1), ("y", "z")), + lambda s, i: s.add_tags(**dict(i)), + lambda s, i: AddTags(dict(i))(s), ), + # TagBy takes data columns only; a data-tag is refused (already a tag). MethodCase( "tag_by", - lambda s: s.tag_by(["d3", "d1"]), - lambda s: TagBy(["d3", "d1"])(s), + ("d3", "d1"), + lambda s, i: s.tag_by(list(i)), + lambda s, i: TagBy(list(i))(s), ), ] -@pytest.mark.parametrize("role", ROLES) -@pytest.mark.parametrize("case", CASES, ids=lambda case: case.label) +@pytest.mark.parametrize( + ("case", "role"), + [ + pytest.param(case, role, id=f"{case.label}-{role}") + for case in CASES + for role in case.roles + ], +) def test_a_stream_method_with_several_items_equals_its_operator( case: MethodCase, role: str ) -> None: + """In the order given and reversed: the method equals its operator. + + Reversing the items keeps the rows; it changes nothing else for an order-free + argument, and the operator's identity (content and pipeline hash) for one whose + order is part of it. + """ + source = make_source(MAIN, Arrangement(MAIN.tags, TAGS_FIRST, role)) + results = [] + for items in (case.items, tuple(reversed(case.items))): + by_method, by_operator = ( + case.method(source, items), + case.operator(source, items), + ) + assert presentation(by_method) == presentation(by_operator) + assert fingerprint(by_method) == fingerprint(by_operator) + results.append(by_method) + forward, backward = results + assert fingerprint(forward)["rows"] == fingerprint(backward)["rows"] + if case.order == ORDER_FREE: + assert fingerprint(forward) == fingerprint(backward) + assert presentation(forward) == presentation(backward) + else: + assert forward.content_hash() != backward.content_hash() + assert forward.pipeline_hash() != backward.pipeline_hash() + + +@pytest.mark.parametrize("role", ROLES) +def test_tag_by_refuses_a_data_tag_in_either_order(role: str) -> None: + """``TagBy`` gives a data column the tag role: a data-tag already has it.""" source = make_source(MAIN, Arrangement(MAIN.tags, TAGS_FIRST, role)) - by_method, by_operator = case.method(source), case.operator(source) - assert presentation(by_method) == presentation(by_operator) - assert fingerprint(by_method) == fingerprint(by_operator) + for names in (["t3", "d1"], ["d1", "t3"]): + with pytest.raises(InputValidationError, match="t3"): + TagBy(names)(source) + with pytest.raises(InputValidationError, match="t3"): + source.tag_by(names) @pytest.mark.parametrize("role", ROLES)