Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions changelog.d/ITL-1363.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
### Fixed

- **`MapTags(drop_unmapped=True)` predicts the system-tag columns it keeps** — its
predicted output schema (`output_schema(columns={"system_tags": True})`,
`output_schema(all_info=True)`) left out the system-tag columns, which the computed table
keeps, so the prediction and the rows disagreed. Every mapper (`MapTags`, `MapData`,
`MapColumns`) now renames and drops only user columns, in its prediction as in its result;
no row, column, hash or stored path changes. (ITL-1363)
25 changes: 25 additions & 0 deletions docs/dev/design_issues/ITL-1363-MT1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
## Cross-cutting

### MT1 — `MapTags(drop_unmapped=True)` predicted no system-tag columns
**Status:** resolved
**Severity:** high
**Issue:** ITL-1363

`MapTags.unary_output_schema` kept a tag-schema key only when it was a key of `name_map` or
`drop_unmapped` was false. Under `columns={"system_tags": True}` or `all_info=True` the tag
schema holds the system-tag columns, which no `name_map` names, so the prediction left them
out while the computed table keeps them: a node, a stored table or a downstream operator
that reads the prediction expects columns the rows do not match. `MapData`'s prediction
filtered its data schema the same way (by the names of `name_map`, not by the input's user
columns); no column the data schema can hold today was affected, but the rule was the same.
The ITL-1135 sweep missed it: it had no `drop_unmapped` step.

**Fix:** one rule, `mappers._plan_group`: only a user column (a tag, or a data column that
is not meta) is renamed or, with `drop_unmapped`, dropped; a system tag, source info, the
context or a meta column never is. `MapTags`' and `MapData`'s predictions and
`MapColumns._plan` use it. No row, column, hash or stored path changes. The ITL-1135 sweep
(`tests/test_pipeline/test_zero_row_column_order.py`) has `drop_unmapped` steps for the
three mappers and `MapColumns` steps, and
`tests/test_core/operators/test_mapper_schema_prediction.py` checks every column
configuration over every arrangement of a source with three tags and three data columns,
on the sync and the async path.
64 changes: 47 additions & 17 deletions src/orcapod/core/operators/mappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,32 @@ def _with_other_group_note(
return InputValidationError(f"{error}{note}")


def _plan_group(
columns: Collection[str], name_map: Mapping[str, str], drop_unmapped: bool
) -> tuple[dict[str, str], list[str]]:
"""Return the renames and the dropped columns of one group's user columns.

The one rule every mapper's schema prediction and result follow (ITL-1363):
only a user column (a tag, or a data column that is not meta) is renamed or,
with ``drop_unmapped``, dropped. A column outside ``columns`` (a system tag,
source info, the context or a meta column) is never renamed and never
dropped, whatever ``name_map`` holds, so a prediction must not filter a whole
schema by the names of ``name_map``.

Args:
columns: The input's user columns of the group, in order.
name_map: The mapper's renames.
drop_unmapped: Whether the user columns not in ``name_map`` are dropped.

Returns:
The renames of the user columns ``name_map`` names, and the user columns
dropped (none without ``drop_unmapped``), in input order.
"""
renames = {c: name_map[c] for c in columns if c in name_map}
dropped = [c for c in columns if c not in name_map] if drop_unmapped else []
return renames, dropped


class MapData(UnaryOperator):
"""Rename data columns.

Expand Down Expand Up @@ -250,12 +276,16 @@ def unary_output_schema(
columns=columns, all_info=all_info
)

# Create new data schema with renamed keys
# Only the user data columns are renamed or dropped (``_plan_group``).
renames, dropped = _plan_group(
[c for c in stream.keys()[1] if not is_meta_column(c)],
self.name_map,
self.drop_unmapped,
)
new_data_schema = {
self.name_map.get(k, k): v
renames.get(k, k): v
for k, v in data_schema.items()
if not k.startswith(constants.META_PREFIX)
and (k in self.name_map or not self.drop_unmapped)
if not k.startswith(constants.META_PREFIX) and k not in dropped
}

return tag_schema, Schema(new_data_schema)
Expand Down Expand Up @@ -518,17 +548,20 @@ def unary_output_schema(
columns=columns, all_info=all_info
)

# Only the user tags are renamed or dropped: the system tags the
# table keeps are kept here too (``_plan_group``, ITL-1363).
renames, dropped = _plan_group(
stream.keys()[0], self.name_map, self.drop_unmapped
)
new_tag_schema = {
self.name_map.get(k, k): v
for k, v in tag_schema.items()
if k in self.name_map or not self.drop_unmapped
renames.get(k, k): v for k, v in tag_schema.items() if k not in dropped
}
if not self.tag_only:
# A data-tag's data column is renamed with it (one column).
data_tags = set(stream_data_tags(stream))
data_schema = Schema(
{
self.name_map.get(k, k) if k in data_tags else k: v
renames.get(k, k) if k in data_tags else k: v
for k, v in data_schema.items()
}
)
Expand Down Expand Up @@ -686,16 +719,13 @@ def _plan(
tag_columns: The input's tag columns, in order.
data_columns: The input's user data columns, in order (no meta column).
"""
tag_renames = {c: self.name_map[c] for c in tag_columns if c in self.name_map}
data_renames = {c: self.name_map[c] for c in data_columns if c in self.name_map}
if not self.drop_unmapped:
return tag_renames, data_renames, [], []
return (
tag_renames,
data_renames,
[c for c in tag_columns if c not in self.name_map],
[c for c in data_columns if c not in self.name_map],
tag_renames, tags_dropped = _plan_group(
tag_columns, self.name_map, self.drop_unmapped
)
data_renames, data_dropped = _plan_group(
data_columns, self.name_map, self.drop_unmapped
)
return tag_renames, data_renames, tags_dropped, data_dropped

def _validate_columns(
self, tag_columns: Collection[str], data_columns: Collection[str]
Expand Down
202 changes: 202 additions & 0 deletions tests/test_core/operators/test_mapper_schema_prediction.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
"""A mapper's predicted schema keeps every column the result keeps (ITL-1363).

``MapTags(drop_unmapped=True)`` used to filter its whole tag schema by the names of
``name_map``, so the system-tag columns, which no ``name_map`` names and the table
keeps, were missing from the prediction under ``system_tags=True`` or
``all_info=True``. Every mapper now renames and drops only user columns
(``mappers._plan_group``). The prediction is checked against
``static_process(...).output_schema(...)``, as CLAUDE.md asks, for every column
configuration, every arrangement of a source with three tags and three data
columns, both orders of a two-entry ``name_map``, with and without
``drop_unmapped``; the async rows carry the same system tags as the sync rows.
"""

from __future__ import annotations

import warnings
from collections.abc import Callable
from typing import Any

import pytest

from orcapod import operators
from orcapod.core.operators import MapColumns, MapData, MapTags
from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod
from orcapod.errors import ProvisionalHashWarning
from orcapod.system_constants import constants

from .several_items import (
MAIN,
PLAIN,
Arrangement,
arrangements,
async_rows,
make_source,
rows_fingerprint,
)

pytestmark = pytest.mark.filterwarnings(
f"ignore::{ProvisionalHashWarning.__module__}.{ProvisionalHashWarning.__name__}"
)

# Every column configuration a schema can be asked for.
CONFIGS: tuple[dict[str, Any], ...] = (
{},
{"columns": {"system_tags": True}},
{"columns": {"source": True}},
{"columns": {"meta": True}},
{"columns": {"context": True}},
{"columns": {"content_hash": True}},
{"columns": {"system_tags": True, "source": True, "meta": True}},
{"all_info": True},
)


def _orders(entries: tuple[tuple[str, str], ...]) -> list[dict[str, str]]:
return [dict(entries), dict(reversed(entries))]


TAG_MAP = (("t1", "u1"), ("t3", "u3"))
DATA_MAP = (("d1", "e1"), ("d3", "e3"))
COLUMN_MAP = (("t1", "u1"), ("d2", "e2"))


def _cases() -> list[Any]:
cases: list[Any] = []
for drop in (False, True):
for i, name_map in enumerate(_orders(TAG_MAP)):
for tag_only in (False, True):
cases.append(
pytest.param(
(
lambda m, d, t: (
lambda: MapTags(m, drop_unmapped=d, tag_only=t)
)
)(name_map, drop, tag_only),
None,
id=f"map_tags-order{i}-drop{drop}-tag_only{tag_only}",
)
)
for i, name_map in enumerate(_orders(DATA_MAP)):
cases.append(
pytest.param(
(lambda m, d: lambda: MapData(m, drop_unmapped=d))(name_map, drop),
None,
id=f"map_data-order{i}-drop{drop}",
)
)
for i, name_map in enumerate(_orders(COLUMN_MAP)):
# MapColumns is refused with data-tags (ITL-1022).
cases.append(
pytest.param(
(lambda m, d: lambda: MapColumns(m, drop_unmapped=d))(
name_map, drop
),
(PLAIN,),
id=f"map_columns-order{i}-drop{drop}",
)
)
return cases


def _arrangement_params(roles: tuple[str, ...] | None) -> list[Arrangement]:
return arrangements(MAIN) if roles is None else arrangements(MAIN, roles)


def _system_tags(names: Any) -> list[str]:
return sorted(n for n in names if n.startswith(constants.SYSTEM_TAG_PREFIX))


@pytest.mark.parametrize(("make", "roles"), _cases())
def test_the_prediction_equals_the_result_schema_in_every_configuration(
make: Callable[[], StaticOutputOperatorPod], roles: tuple[str, ...] | None
) -> None:
for arrangement in _arrangement_params(roles):
source = make_source(MAIN, arrangement)
op = make()
predicted_stream = op(source)
computed = op.static_process(source)
for config in CONFIGS:
predicted = predicted_stream.output_schema(**config)
actual = computed.output_schema(**config)
label = f"{arrangement.id} {config}"
# Names and types; column order is presentation, and a source's own
# schema follows its table layout while its keys follow the tag order.
for p, a in zip(predicted, actual):
assert dict(p) == dict(a), label
# The table holds exactly the system tags the prediction lists.
predicted_tags = predicted_stream.output_schema(all_info=True)[0]
table = predicted_stream.as_table(all_info=True)
assert _system_tags(predicted_tags) == _system_tags(table.column_names)
assert len(_system_tags(predicted_tags)) == 2, arrangement.id


@pytest.mark.parametrize(("make", "roles"), _cases())
def test_the_async_rows_keep_the_system_tags_of_the_sync_rows(
make: Callable[[], StaticOutputOperatorPod], roles: tuple[str, ...] | None
) -> None:
for arrangement in _arrangement_params(roles):
source = make_source(MAIN, arrangement)
op = make()
result = op(source)
sync = list(result.iter_data())
rows = async_rows(op, source)
# Order-free: the data-column order of rows may differ between the paths.
assert rows_fingerprint(rows) == rows_fingerprint(sync)
predicted = _system_tags(result.output_schema(all_info=True)[0])
for tag, _ in rows:
assert sorted(tag.system_tags()) == predicted, arrangement.id


def test_drop_unmapped_keeps_the_system_tags_in_the_prediction() -> None:
"""The reported case: two tags, one renamed, the other dropped."""
source = make_source(MAIN)
with warnings.catch_warnings():
warnings.simplefilter("ignore", ProvisionalHashWarning)
stream = MapTags({"t2": "u2", "t1": "u1"}, drop_unmapped=True)(source)
tag_schema, _ = stream.output_schema(all_info=True)
system_tags = _system_tags(source.output_schema(all_info=True)[0])
assert len(system_tags) == 2
assert [n for n in tag_schema if n not in system_tags] == ["u1", "u2"]
assert _system_tags(tag_schema) == system_tags
assert _system_tags(stream.as_table(all_info=True).column_names) == system_tags


# ── every exported operator: predicted columns are the result's columns ──────


def _operator_streams() -> list[Any]:
"""One case per exported operator, from the order-invariance cases."""
from ..test_order_invariance import OPERATOR_CASES

names = {
name
for name in operators.__all__
if isinstance(obj := getattr(operators, name), type)
and issubclass(obj, StaticOutputOperatorPod)
}
assert names == set(OPERATOR_CASES)
return [
pytest.param(case, id=case.label)
for cases in OPERATOR_CASES.values()
for case in cases
]


@pytest.mark.parametrize("case", _operator_streams())
def test_every_operator_predicts_the_columns_of_its_result(case: Any) -> None:
"""Under every configuration the predicted column names (in order) are the
result's. Column TYPES are not compared here."""
for role in case.roles:
sources = case.sources(role, 0, "tags_first")
op = case.build()
if not isinstance(op, StaticOutputOperatorPod):
# Rejoin's case is a function of the source: its branches are the inputs.
stream = op(*sources)
op, sources = stream.producer, list(stream.upstreams)
computed = op.static_process(*sources)
for config in CONFIGS:
predicted = op.output_schema(*sources, **config)
actual = computed.output_schema(**config)
for p, a in zip(predicted, actual):
assert list(p) == list(a), f"{case.label} {role} {config}"
20 changes: 18 additions & 2 deletions tests/test_pipeline/test_zero_row_column_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
GroupBy,
Index,
Join,
MapColumns,
MapData,
MapTags,
MergeJoin,
Expand Down Expand Up @@ -167,6 +168,17 @@ def _plus_one(x: int) -> int:
"drop_columns": lambda a, g: DropColumns(["id", "l"])(a, label="op"),
"map_tags": lambda a, g: MapTags({"id": "ident"})(a, label="op"),
"map_data": lambda a, g: MapData({"x": "xx"})(a, label="op"),
# ``drop_unmapped`` drops user columns only, never a system tag (ITL-1363).
"map_tags_drop": lambda a, g: MapTags({"id": "ident"}, drop_unmapped=True)(
a, label="op"
),
"map_data_drop": lambda a, g: MapData({"x": "xx", "l": "ll"}, drop_unmapped=True)(
a, label="op"
),
"map_columns": lambda a, g: MapColumns({"id": "ident", "x": "xx"})(a, label="op"),
"map_columns_drop": lambda a, g: MapColumns(
{"id": "ident", "x": "xx"}, drop_unmapped=True
)(a, label="op"),
"filter": lambda a, g: PolarsFilter(constraints={"id": 1})(a, label="op"),
"drop_nulls": lambda a, g: DropNulls(["n"])(a, label="op"),
"drop_nulls_all": lambda a, g: DropNulls()(a, label="op"),
Expand Down Expand Up @@ -542,8 +554,12 @@ def test_job_node(self, step: str, pairs: int, config: str) -> None:

# ── data-tags (ITL-1023) ─────────────────────────────────────────────

# Not supported with data-tags yet: MergeJoin (ITL-1018).
DATA_TAG_STEPS = [step for step in STEPS if step != "merge_join"]
# Not supported with data-tags yet: MergeJoin (ITL-1018), MapColumns (ITL-1022).
DATA_TAG_STEPS = [
step
for step in STEPS
if step not in ("merge_join", "map_columns", "map_columns_drop")
]


@pytest.fixture
Expand Down
Loading