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 37561f578..6b38e5d80 100644 --- a/docs/dev/specs/itl-1236-several-item-test-audit.md +++ b/docs/dev/specs/itl-1236-several-item-test-audit.md @@ -99,6 +99,7 @@ Legend: **yes** (with the best test as evidence), **no** (with what the closest | 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) | | 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 | | Q1 | `PolarsFilter`: the order of the predicates is in the identity (and the stored path); the order of the constraints is not | pipeline hash | ITL-1247 (rule undecided) | @@ -122,9 +123,27 @@ Order- or role-dependent behaviour that reaches a hash or a stored table first. 14. `DerivedSource(tags_as_data=)` reversed: default `source_id` and pipeline hash. 15. `CachedSource` over a data-tag source; `Pick` / `Index` from a data-tag with `out=`; schema arguments in another field order; the stream methods' several-argument forms (`polars_filter` with `constraint_map` and keywords). +## Checked and found as documented (part 2) + +- A source's `tag_columns` order and table layout: keys follow the tag order; rows, record + ids, system tags, content and pipeline hashes do not change (plain, data-tags, mixed). +- `tag_only_columns` given in two orders: no change. +- `record_id_columns` in another key order: record ids follow the key order; the content + hash changes, the pipeline hash and the source id do not; a set is refused. +- `DerivedSource(tags_as_data=)` reversed: only the new columns' order changes. +- `CachedSource` over a source of each role and arrangement: reads back as the source. +- `pod(a, b, c)` in every input order: same rows, hashes and columns; a job over the inputs + in another order finds every result stored (sync and async). The in-memory output's + source info names a fresh random record per computation, so comparisons leave it out. +- `bind(sources=)` with two sources: both bound, nothing moves; one refused, neither bound. + A plain or data-tag source in any arrangement binds and reads; a mixed one is ITL-1245. + ## Tests added `tests/test_core/operators/several_items.py` is the shared family: `MAIN` (tags `t1`, `t2`, `t3`; data `d1`, `d2`, `d3`) and join partners `P`, `Q`, `R`, each in any tag order, three layouts and three role settings. `ops/test_several_items.py` uses it for every -operator (gaps 5, 6, 7, 9, 11 and the operator half of 1, 2, 3). +operator (gaps 5, 6, 7, 9, 11 and the operator half of 1, 2, 3). Part 2: +`tests/test_core/sources/test_several_items.py` (gaps 4, 13, 14, 15: CachedSource), +`tests/test_core/function_pod/test_several_items.py` (gaps 1, 10; ITL-1244, ITL-1246) and +`tests/test_pipeline/test_bind_several_items.py` (gap 8; ITL-1245). diff --git a/tests/test_core/function_pod/test_several_items.py b/tests/test_core/function_pod/test_several_items.py new file mode 100644 index 000000000..53cccd60c --- /dev/null +++ b/tests/test_core/function_pod/test_several_items.py @@ -0,0 +1,244 @@ +"""Function pods over several inputs, reading several parameters, with several outputs (ITL-1236). + +The rules tested: + +* ``pod(a, b, c)`` joins its inputs as ``Join`` does, so the order of the inputs changes + nothing: rows, hashes, system-tag names and column order, in memory and in a job (a + second job over the inputs in another order finds every result stored). +* Data columns that the function does not read are dropped by the automatic select + (ITL-807), whatever their number and position. +* The function's parameters are matched by name, never by position. +* A data-tag is a data column a function may read (ITL-1023). +""" + +from __future__ import annotations + +import itertools + +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.sources import ArrowTableSource +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator + +from ..operators.several_items import ( + DATA_TAGS, + LAYOUTS, + MAIN, + MIXED, + ROLES, + TAGS_FIRST, + Arrangement, + P, + Q, + Spec, + fingerprint, + make_source, + presentation, + rows_fingerprint, +) + +INPUTS: tuple[Spec, ...] = (MAIN, P, Q) + + +# Parameters in another order than the columns: q2 is in Q, d1 in MAIN, p1 in P. +@function_pod(output_keys=["total", "product"]) +def combine(q2: int, d1: int, p1: int) -> tuple[int, int]: + # Weighted: no two parameters can be swapped without changing ``total``. + return q2 + 2 * d1 + 3 * p1, d1 * p1 + + +def _inputs(role: str) -> list[ArrowTableSource]: + return [ + make_source(spec, Arrangement(spec.tags, TAGS_FIRST, role)) for spec in INPUTS + ] + + +@pytest.mark.parametrize("role", ROLES) +def test_the_order_of_the_inputs_changes_nothing(role: str) -> None: + """All six orders of three inputs: same rows, hashes and columns. + + Each in-memory computation names a fresh record in its outputs' source info, so the + rows are compared without it. + """ + results = {} + for permutation in itertools.permutations(range(len(INPUTS))): + inputs = _inputs(role) + stream = combine.pod(*(inputs[i] for i in permutation)) + results[permutation] = { + **fingerprint(stream, source_info=False), + "presentation": presentation(stream), + } + first = results[(0, 1, 2)] + for permutation, result in results.items(): + assert result == first, permutation + # The extra data columns (d2, d3, p2, q1) were dropped; every tag stays. + tag_keys, data_keys = first["presentation"] + assert sorted(tag_keys) == ["t1", "t2", "t3"] + assert {"d2", "d3", "p2", "q1"}.isdisjoint(data_keys) + assert {"total", "product"} <= set(data_keys) + + +@pytest.mark.parametrize("role", ROLES) +def test_values_are_matched_by_parameter_name(role: str) -> None: + stream = combine.pod(*_inputs(role)) + rows = sorted( + (tag["t1"], tag["t2"], tag["t3"], data["total"], data["product"]) + for tag, data in stream.iter_data() + ) + # MAIN x P on (t1, t2) x Q on (t2, t3); total = q2 + 2 d1 + 3 p1, product = d1 p1. + assert rows == [ + ("a", 1, 1, 400 + 2 * 50 + 3 * 9, 50 * 9), + ("a", 1, 2, 100 + 2 * 20 + 3 * 9, 20 * 9), + ("a", 2, 1, 200 + 2 * 30 + 3 * 7, 30 * 7), + ("b", 1, 2, 100 + 2 * 40 + 3 * 8, 40 * 8), + ("b", 2, 1, 200 + 2 * 10 + 3 * 6, 10 * 6), + ("b", 2, 2, 300 + 2 * 60 + 3 * 6, 60 * 6), + ] + + +@pytest.mark.parametrize( + "orchestrator", + [SyncPipelineOrchestrator, AsyncPipelineOrchestrator], + ids=["sync", "async"], +) +@pytest.mark.parametrize("role", ROLES) +def test_a_job_over_the_inputs_in_another_order_finds_every_result_stored( + role: str, orchestrator: type +) -> None: + database = InMemoryArrowDatabase() + stored = {} + for permutation in ((0, 1, 2), (2, 0, 1), (1, 2, 0)): + inputs = _inputs(role) + job = PipelineJob(name="several", database=database) + with job: + combine.pod(*(inputs[i] for i in permutation), label="combine") + summary = job.run(orchestrator=orchestrator()) + node = job.nodes["combine"] + stored[permutation] = ( + rows_fingerprint(list(node.iter_data()), source_info=False), + node.pipeline_hash(), + node.content_hash(), + presentation(node), + ) + if permutation != (0, 1, 2): + assert summary.nodes["combine"].computed == 0, permutation + assert summary.nodes["combine"].reused == 6, permutation + first = stored[(0, 1, 2)] + assert all(result == first for result in stored.values()) + + +@function_pod(output_keys="labelled") +def label_rows(t1: str, d3: str, t3: int) -> str: + return f"{t1}{t3}{d3}" + + +@pytest.mark.parametrize("role", [DATA_TAGS, MIXED]) +def test_a_function_reads_several_data_tags_and_data_in_any_arrangement( + role: str, +) -> None: + """t1 and t3 are data-tags; the tag order and layout change no row.""" + results = {} + for order in MAIN.tag_orders(): + for layout in LAYOUTS: + stream = label_rows.pod(make_source(MAIN, Arrangement(order, layout, role))) + results[(order, layout)] = rows_fingerprint( + list(stream.iter_data()), source_info=False + ) + values = sorted(str(data["labelled"]) for _, data in stream.iter_data()) + assert values == ["a1v", "a1y", "a2x", "b1w", "b2u", "b2z"] + first = next(iter(results.values())) + assert all(result == first for result in results.values()) + + +@pytest.mark.parametrize("layout", LAYOUTS) +@pytest.mark.parametrize("order", MAIN.tag_orders(), ids="-".join) +@pytest.mark.parametrize("role", [DATA_TAGS, MIXED]) +def test_a_function_over_several_data_tags_gives_the_same_rows_on_both_orchestrators( + role: str, order: tuple[str, ...], layout: str +) -> None: + """In a job, sync and async: same rows, column order and stored results.""" + tables = [] + for orchestrator in (SyncPipelineOrchestrator, AsyncPipelineOrchestrator): + job = PipelineJob(name="labels", database=InMemoryArrowDatabase()) + with job: + label_rows.pod( + make_source(MAIN, Arrangement(order, layout, role)), label="labels" + ) + job.run(orchestrator=orchestrator()) + node = job.nodes["labels"] + tables.append( + ( + presentation(node), + [(tuple(t.keys()), tuple(d.keys())) for t, d in node.iter_data()], + rows_fingerprint(list(node.iter_data()), source_info=False), + sorted(str(data["labelled"]) for _, data in node.iter_data()), + ) + ) + assert tables[0] == tables[1] + assert tables[0][3] == ["a1v", "a1y", "a2x", "b1w", "b2u", "b2z"] + + +@pytest.mark.parametrize("role", [DATA_TAGS, MIXED]) +def test_a_layout_of_the_input_does_not_change_a_fall_through_pods_hashes( + role: str, +) -> None: + hashes = { + layout: fingerprint( + label_rows.pod(make_source(MAIN, Arrangement(MAIN.tags, layout, role))), + source_info=False, + ) + for layout in LAYOUTS + } + first = next(iter(hashes.values())) + assert all(result == first for result in hashes.values()) + + +FALL_THROUGH_ORDER_ISSUE = "ITL-1246" + + +@pytest.mark.xfail( + strict=True, + 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", [DATA_TAGS, MIXED]) +def test_the_tag_order_of_the_input_does_not_change_a_fall_through_pods_hashes( + role: str, +) -> None: + results = { + order: fingerprint( + label_rows.pod(make_source(MAIN, Arrangement(order, TAGS_FIRST, role))), + source_info=False, + ) + for order in MAIN.tag_orders() + } + first = next(iter(results.values())) + assert all(result == first for result in results.values()) + + +OUTPUT_KEYS_ISSUE = "ITL-1244 (rule undecided)" + + +@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. + """ + + def make(keys: list[str]): + @function_pod(output_keys=keys) + def stats(d1: int, t2: int) -> tuple[int, int]: + return d1 + t2, d1 * t2 + + return stats + + forward, backward = make(["sum", "product"]), make(["product", "sum"]) + assert forward.pod.uri != backward.pod.uri diff --git a/tests/test_core/operators/several_items.py b/tests/test_core/operators/several_items.py index e42215024..982f5c311 100644 --- a/tests/test_core/operators/several_items.py +++ b/tests/test_core/operators/several_items.py @@ -218,21 +218,35 @@ def make_source( ) -def row_fingerprint(tag: TagProtocol, data: DataProtocol) -> tuple[str, ...]: - """What identifies one row regardless of column order: values, system tags, hashes.""" +def row_fingerprint( + tag: TagProtocol, data: DataProtocol, *, source_info: bool = True +) -> tuple[str, ...]: + """What identifies one row regardless of column order: values, system tags, hashes. + + Args: + tag: The row's tag. + data: The row's data. + source_info: Include the data's source info. A function's in-memory output + names a fresh random record per computation, so a comparison of two + computations leaves it out. + """ return ( repr(sorted(tag.as_dict().items())), repr(sorted(data.as_dict().items())), repr(sorted(tag.system_tags().items())), tag.content_hash().to_string(), data.content_hash().to_string(), - repr(sorted(data.source_info().items())), + repr(sorted(data.source_info().items())) if source_info else "", ) -def rows_fingerprint(rows: Sequence[Row]) -> list[tuple[str, ...]]: +def rows_fingerprint( + rows: Sequence[Row], *, source_info: bool = True +) -> list[tuple[str, ...]]: """The rows' fingerprints, sorted: row order is not part of it.""" - return sorted(row_fingerprint(tag, data) for tag, data in rows) + return sorted( + row_fingerprint(tag, data, source_info=source_info) for tag, data in rows + ) def ordered_rows_fingerprint(rows: Sequence[Row]) -> list[tuple[str, ...]]: @@ -256,11 +270,12 @@ def ordered_rows_fingerprint(rows: Sequence[Row]) -> list[tuple[str, ...]]: ) -def fingerprint(stream: StreamProtocol) -> dict[str, Any]: +def fingerprint(stream: StreamProtocol, *, source_info: bool = True) -> dict[str, Any]: """What must not depend on the input's arrangement or a set argument's order. Args: stream: An operator's result. + source_info: Include each row's source info (see ``row_fingerprint``). Returns: The rows (``rows_fingerprint``), the content and pipeline hashes, and the @@ -268,7 +283,7 @@ def fingerprint(stream: StreamProtocol) -> dict[str, Any]: """ tag_keys, data_keys = stream.keys(columns={"system_tags": True}) return { - "rows": rows_fingerprint(list(stream.iter_data())), + "rows": rows_fingerprint(list(stream.iter_data()), source_info=source_info), "content_hash": stream.content_hash().to_string(), "pipeline_hash": stream.pipeline_hash().to_string(), "tag_names": sorted(tag_keys), diff --git a/tests/test_core/sources/test_several_items.py b/tests/test_core/sources/test_several_items.py new file mode 100644 index 000000000..ff7ee7c8a --- /dev/null +++ b/tests/test_core/sources/test_several_items.py @@ -0,0 +1,204 @@ +"""Sources with several tag, key and data columns, in several orders and roles (ITL-1236). + +The rules tested (CLAUDE.md, "Important implementation details" and "Two identity +chains"): + +* The order of ``tag_columns`` is the order of the tags (and of the data-tags among the + data columns); it enters no hash, no record id and no system-tag column name. +* ``tag_only_columns`` names a set: its order changes nothing. +* ``record_id_columns`` is in key order: a record id is the canonical JSON of the key + columns in key order, so another key order is another source with the same pipeline + hash and source id, another content hash. An unordered collection is refused. +* ``DerivedSource(tags_as_data=...)``: the entries' order is the order of the new data + columns and nothing else. +* ``CachedSource`` reads back a source of each role as the source itself. +""" + +from __future__ import annotations + +import itertools +import json + +import pyarrow as pa +import pytest + +from orcapod.core.sources import ArrowTableSource, CachedSource, DerivedSource +from orcapod.databases import InMemoryArrowDatabase + +from ..operators.several_items import ( + DATA_TAGS, + LAYOUTS, + MAIN, + MIXED, + PLAIN, + ROLES, + TAGS_FIRST, + Arrangement, + fingerprint, + make_source, + presentation, +) + + +def _tag_only(role: str) -> bool | list[str]: + return {PLAIN: True, DATA_TAGS: [], MIXED: [MAIN.mixed_plain]}[role] + + +def _table() -> pa.Table: + return pa.table({name: MAIN.columns[name] for name in (*MAIN.tags, *MAIN.data)}) + + +def _record_ids(source: ArrowTableSource) -> list[str]: + ids: list[str] = [] + for tag, _ in source.iter_data(): + [record_id] = [ + value for name, value in tag.system_tags().items() if "record_id" in name + ] + ids.append(str(record_id)) + return sorted(ids) + + +def _expected_record_ids(keys: tuple[str, ...]) -> list[str]: + """Each row's record id for ``keys``, built from the input values, sorted. + + The canonical JSON of the key columns in key order: compact separators, the values + as written (``{"t1":"b","t2":2}``). + """ + rows = len(MAIN.columns[keys[0]]) + return sorted( + json.dumps( + {key: MAIN.columns[key][row].as_py() for key in keys}, + separators=(",", ":"), + ensure_ascii=False, + ) + for row in range(rows) + ) + + +@pytest.mark.parametrize("role", ROLES) +def test_tag_order_is_the_order_of_the_tags_and_enters_no_hash(role: str) -> None: + """Every tag order and layout: same rows, hashes and system tags; keys follow.""" + results = {} + for order in itertools.permutations(MAIN.tags): + for layout in LAYOUTS: + source = make_source(MAIN, Arrangement(order, layout, role)) + tag_keys, data_keys = presentation(source) + assert tag_keys == order + # Data-tags come first among the data columns, in tag order (ITL-1205). + data_tags = [t for t in order if role != PLAIN and t != _plain_tag(role)] + assert list(data_keys[: len(data_tags)]) == data_tags + results[(order, layout)] = fingerprint(source) + first = next(iter(results.values())) + assert all(result == first for result in results.values()) + + +def _plain_tag(role: str) -> str | None: + return MAIN.mixed_plain if role == MIXED else None + + +def test_the_order_of_tag_only_columns_changes_nothing() -> None: + sources = [ + ArrowTableSource( + _table(), tag_columns=list(MAIN.tags), source_id="s", tag_only_columns=names + ) + for names in (["t1", "t3"], ["t3", "t1"]) + ] + assert presentation(sources[0]) == presentation(sources[1]) + assert presentation(sources[0]) == (("t1", "t2", "t3"), ("t2", "d1", "d2", "d3")) + assert fingerprint(sources[0]) == fingerprint(sources[1]) + + +@pytest.mark.parametrize("role", ROLES) +def test_record_ids_follow_the_key_order(role: str) -> None: + """Two or three key columns, of the tag and the data role, in several orders.""" + by_keys = {} + for keys in (("t1", "t2", "t3"), ("t3", "t1", "t2"), ("d3", "t1"), ("t1", "d3")): + source = ArrowTableSource( + _table(), + tag_columns=list(MAIN.tags), + source_id="s", + record_id_columns=list(keys), + tag_only_columns=_tag_only(role), + ) + # The whole record id: the canonical JSON of each row's key values, in key + # order, built here from the input columns (Copilot, #443). + assert _record_ids(source) == _expected_record_ids(keys) + by_keys[keys] = source + # The format itself, for the first row (t1="b", t2=2, t3=1, d3="w"). + assert '{"t1":"b","t2":2,"t3":1}' in _expected_record_ids(("t1", "t2", "t3")) + assert '{"d3":"w","t1":"b"}' in _expected_record_ids(("d3", "t1")) + first = by_keys[("t1", "t2", "t3")] + for keys, source in by_keys.items(): + # The keys name the rows: one pipeline hash and one source id ... + assert source.pipeline_hash() == first.pipeline_hash() + assert source.source_id == first.source_id + # ... and another key order is another source. + if keys != ("t1", "t2", "t3"): + assert source.content_hash() != first.content_hash() + assert _record_ids(source) != _record_ids(first) + # The same key columns in another order, compared with each other. + for one, other in ( + (("t1", "t2", "t3"), ("t3", "t1", "t2")), + (("d3", "t1"), ("t1", "d3")), + ): + assert by_keys[one].content_hash() != by_keys[other].content_hash() + assert by_keys[one].pipeline_hash() == by_keys[other].pipeline_hash() + assert _record_ids(by_keys[one]) != _record_ids(by_keys[other]) + # Same keys, same order: the same source. + again = ArrowTableSource( + _table(), + tag_columns=list(MAIN.tags), + source_id="s", + record_id_columns=("t3", "t1", "t2"), + tag_only_columns=_tag_only(role), + ) + assert again.content_hash() == by_keys[("t3", "t1", "t2")].content_hash() + + +def test_record_id_columns_as_a_set_is_refused() -> None: + with pytest.raises(TypeError): + ArrowTableSource( + _table(), + tag_columns=list(MAIN.tags), + source_id="s", + record_id_columns={"t1", "t2"}, + ) + + +@pytest.mark.parametrize("role", ROLES) +def test_tags_as_data_order_is_the_order_of_the_new_columns_only(role: str) -> None: + source = make_source(MAIN, Arrangement(MAIN.tags, TAGS_FIRST, role)) + forward = DerivedSource(source, tags_as_data={"t1": "c1", "t3": "c3"}) + backward = DerivedSource(source, tags_as_data={"t3": "c3", "t1": "c1"}) + assert presentation(forward)[1][-2:] == ("c1", "c3") + assert presentation(backward)[1][-2:] == ("c3", "c1") + assert forward.source_id == backward.source_id + assert fingerprint(forward) == fingerprint(backward) + # Each new column holds its own tag's values. + for tag, data in forward.iter_data(): + assert (data["c1"], data["c3"]) == (tag["t1"], tag["t3"]) + + +@pytest.mark.parametrize("role", ROLES) +def test_a_cached_source_reads_back_every_role_and_arrangement( + role: str, monkeypatch: pytest.MonkeyPatch +) -> None: + for order in MAIN.tag_orders(): + for layout in LAYOUTS: + arrangement = Arrangement(order, layout, role) + database = InMemoryArrowDatabase() + cached = CachedSource( + make_source(MAIN, arrangement), cache_database=database + ) + assert fingerprint(cached) == fingerprint(make_source(MAIN, arrangement)) + # A second CachedSource over the same source (same schema and identity) + # that cannot provide rows: it serves the stored rows only. + unavailable = make_source(MAIN, arrangement) + + def no_rows(*args: object, **kwargs: object) -> pa.Table: + raise NotImplementedError("rows are not available") + + monkeypatch.setattr(unavailable, "as_table", no_rows) + again = CachedSource(unavailable, cache_database=database) + assert presentation(again) == presentation(make_source(MAIN, arrangement)) + assert fingerprint(again) == fingerprint(cached) diff --git a/tests/test_pipeline/test_bind_several_items.py b/tests/test_pipeline/test_bind_several_items.py new file mode 100644 index 000000000..b3ee295d2 --- /dev/null +++ b/tests/test_pipeline/test_bind_several_items.py @@ -0,0 +1,186 @@ +"""Binding several sources, and sources in another column arrangement (ITL-1236). + +``PipelineJob.bind(sources=...)`` takes several sources in one call. Every source is +validated before anything changes, so one refused source leaves every binding as it was +(the ``bind`` docstring). A source whose columns are the slot's in another order (tag +order, table layout) is accepted, and the bind changes no node's hash or columns +(CLAUDE.md, "Important implementation details", ITL-1112). +""" + +from __future__ import annotations + +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import SourceSpecMismatchError +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator + +from ..test_core.operators.several_items import ( + DATA_TAGS, + LAYOUTS, + MAIN, + MIXED, + PLAIN, + TAGS_FIRST, + Arrangement, + P, + make_source, + presentation, + rows_fingerprint, +) + + +@function_pod(output_keys="total") +def total(d1: int, p1: int) -> int: + return d1 + p1 + + +def _job(role: str) -> PipelineJob: + """A job over slots ``s`` (``MAIN``) and ``p`` (``P``), joined by ``total``.""" + job = PipelineJob(name="bind", database=InMemoryArrowDatabase()) + with job: + total.pod( + make_source(MAIN, Arrangement(MAIN.tags, TAGS_FIRST, role)), + make_source(P, Arrangement(P.tags, TAGS_FIRST, role)), + label="total", + ) + return job + + +def _slot_names(job: PipelineJob) -> tuple[str, str]: + return ("s", "p") if {"s", "p"} <= set(job.nodes) else ("", "") + + +def _snapshot(job: PipelineJob) -> dict[str, object]: + return { + name: (node.pipeline_hash(), presentation(node)) + for name, node in job.nodes.items() + } + + +@pytest.mark.parametrize( + "orchestrator", + [SyncPipelineOrchestrator, AsyncPipelineOrchestrator], + ids=["sync", "async"], +) +@pytest.mark.parametrize("role", [PLAIN, DATA_TAGS, MIXED]) +def test_several_sources_bound_in_one_call(role: str, orchestrator: type) -> None: + job = _job(role) + assert _slot_names(job) == ("s", "p") + before = _snapshot(job) + arrangement = Arrangement(MAIN.tags, TAGS_FIRST, role) + # Both replacements hold other rows than the slots' sources, so the result shows + # that both were bound. + sources: dict[str, StreamProtocol] = { + "s": make_source(MAIN, arrangement, source_id="s_new", rows=[0, 1]), + "p": make_source( + P, Arrangement(P.tags, TAGS_FIRST, role), source_id="p_new", rows=[1, 3] + ), + } + job.bind(sources=sources) + for name, source in sources.items(): + assert job.nodes[name].bound_source is source + assert _snapshot(job) == before + job.run(orchestrator=orchestrator()) + rows = sorted( + (tag["t1"], tag["t2"], data["total"]) + for tag, data in job.nodes["total"].iter_data() + ) + # MAIN's rows 0 and 1 are (b, 2, d1=10) and (a, 1, d1=20); P's rows 1 and 3 are + # (b, 1, p1=8) and (b, 2, p1=6). Only (b, 2) matches: with all of P, (a, 1) would + # match too. + assert rows == [("b", 2, 16)] + + +@pytest.mark.parametrize("refused", ["s", "p"]) +def test_one_refused_source_leaves_every_binding_as_it_was(refused: str) -> None: + """Two sources in one call, one of them refused: neither is bound.""" + job = _job(PLAIN) + bound_before = {name: job.nodes[name].bound_source for name in ("s", "p")} + sources: dict[str, StreamProtocol] = { + "s": make_source(MAIN, source_id="s_new"), + "p": make_source(P, source_id="p_new"), + } + # The other slot's source does not fit: other column names. + sources[refused] = make_source(P if refused == "s" else MAIN, source_id="wrong") + with pytest.raises(SourceSpecMismatchError): + job.bind(sources=sources) + assert {name: job.nodes[name].bound_source for name in ("s", "p")} == bound_before + + +def _total_rows(job: PipelineJob) -> list[tuple[str, ...]]: + return rows_fingerprint(list(job.nodes["total"].iter_data()), source_info=False) + + +def _total_values(job: PipelineJob) -> list[tuple[str, str]]: + """The rows' tag and data values only: the bound source has another source id.""" + return sorted( + (repr(sorted(tag.as_dict().items())), repr(sorted(data.as_dict().items()))) + for tag, data in job.nodes["total"].iter_data() + ) + + +def _bind_in( + role: str, + order: tuple[str, ...], + layout: str, + orchestrator: type = SyncPipelineOrchestrator, +) -> PipelineJob: + """Bind ``MAIN`` in another arrangement to slot ``s``: nothing moves, all reads. + + Returns: + The job, run on ``orchestrator``. + """ + job = _job(role) + before = _snapshot(job) + # The columns of the table, not their order: CLAUDE.md promises the declared names, + # roles and types; the column order within the table is a convenience only. + table_before = sorted(job.nodes["s"].as_table().column_names) + job.bind( + sources={ + "s": make_source(MAIN, Arrangement(order, layout, role), source_id="s_new") + } + ) + assert _snapshot(job) == before, (order, layout) + assert sorted(job.nodes["s"].as_table().column_names) == table_before, ( + order, + layout, + ) + job.run(orchestrator=orchestrator()) + return job + + +@pytest.mark.parametrize("layout", LAYOUTS) +@pytest.mark.parametrize("order", MAIN.tag_orders(), ids="-".join) +@pytest.mark.parametrize("role", [PLAIN, DATA_TAGS]) +def test_a_source_in_another_arrangement_is_bound_as_the_slot_declares( + role: str, order: tuple[str, ...], layout: str +) -> None: + """Both orchestrators: the same rows, with the values of the slot's own source.""" + reference = _job(role) + reference.run() + sync = _bind_in(role, order, layout, SyncPipelineOrchestrator) + asynchronous = _bind_in(role, order, layout, AsyncPipelineOrchestrator) + assert _total_rows(asynchronous) == _total_rows(sync) + assert _total_values(sync) == _total_values(reference) + assert len(_total_values(sync)) == 6 + + +BIND_MIXED_ISSUE = "ITL-1245" + + +@pytest.mark.xfail( + strict=True, + reason=f"{BIND_MIXED_ISSUE}: a mixed-role source in another column order is " + + "accepted, then the source node's table repeats a column", + raises=KeyError, +) +def test_a_mixed_role_source_in_another_arrangement_is_bound_as_the_slot_declares() -> ( + None +): + for order in MAIN.tag_orders(): + for layout in LAYOUTS: + _bind_in(MIXED, order, layout)