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
11 changes: 7 additions & 4 deletions .zed/rules
Original file line number Diff line number Diff line change
Expand Up @@ -773,10 +773,13 @@ no input tag name may appear among the data columns.
An operator may add a tag, never data (developer, November 16, 2026, ITL-1196): "synthesizing
a tag is fine — that's not a value. Operator may never add data." AddTags
(stream.add_tags(cohort="A", run=3)) adds tags holding one constant value on every row, after
the input's tags; data columns, source info and system tags pass through unchanged. A value is
exactly a bool, int, float, str or bytes (Arrow bool, int64, double,
large_string, large_binary, non-nullable); anything else (None, Decimal, datetime,
date, a subclass) is refused. Its identity is the names and values in order. A function form
the input's tags, in name order; data columns, source info and system tags pass through
unchanged. A value is exactly a bool, int, float, str or bytes (Arrow bool, int64,
double, large_string, large_binary, non-nullable); anything else (None, Decimal,
datetime, date, a subclass) is refused. The new tags are a set (developer, November 18,
2026, ITL-1269: "I absolutely agree to make it entry order independent"): the operator holds
them in name order, and its identity is the names and values in name order, so the order of the
keywords never changes a hash, a stored path or a column name. A function form
(new tags computed from a row's tags and data) is future work, not designed yet.

Two operators reduce row count many→one. Batch groups consecutive rows by count; GroupBy
Expand Down
11 changes: 7 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -792,10 +792,13 @@ no input tag name may appear among the data columns.
**An operator may add a tag, never data** (developer, November 16, 2026, ITL-1196): "synthesizing
a tag is fine — that's not a value. Operator may never add data." `AddTags`
(`stream.add_tags(cohort="A", run=3)`) adds tags holding one constant value on every row, after
the input's tags; data columns, source info and system tags pass through unchanged. A value is
exactly a `bool`, `int`, `float`, `str` or `bytes` (Arrow `bool`, `int64`, `double`,
`large_string`, `large_binary`, non-nullable); anything else (`None`, `Decimal`, `datetime`,
`date`, a subclass) is refused. Its identity is the names and values in order. A function form
the input's tags, in name order; data columns, source info and system tags pass through
unchanged. A value is exactly a `bool`, `int`, `float`, `str` or `bytes` (Arrow `bool`, `int64`,
`double`, `large_string`, `large_binary`, non-nullable); anything else (`None`, `Decimal`,
`datetime`, `date`, a subclass) is refused. The new tags are a set (developer, November 18,
2026, ITL-1269: "I absolutely agree to make it entry order independent"): the operator holds
them in name order, and its identity is the names and values in name order, so the order of the
keywords never changes a hash, a stored path or a column name. A function form
(new tags computed from a row's tags and data) is future work, not designed yet.

Two operators reduce row count many→one. `Batch` groups consecutive rows by count; `GroupBy`
Expand Down
10 changes: 10 additions & 0 deletions changelog.d/ITL-1269.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
### Breaking changes and migration

- `AddTags` (`stream.add_tags(...)`) is the same operator for every order of its tags
(ITL-1269; developer, November 18, 2026: "I absolutely agree to make it entry order
independent"). The new tags are a set. The operator holds them in name order and places them
after the input's tags in name order. Its identity and saved config list them that way.
`add_tags(run=3, cohort="A")` and `add_tags(cohort="A", run=3)` now have one content hash,
one pipeline hash and one stored path. Before, the keyword order was part of the identity
and decided the column order. An `AddTags` whose tags were not given in name order gets a
new identity, so the stored path of its node and every node downstream of it moves.
18 changes: 14 additions & 4 deletions docs/concepts/operators.md
Original file line number Diff line number Diff line change
Expand Up @@ -723,8 +723,17 @@ for tag, data in labelled:
# {'subject_id': 'mouse_02', 'session': 2, 'cohort': 'A', 'run': 3} -> {'age': 8, 'weight': 22.1}
```

The new tags follow the input's tags, in the order given. Data columns, their source info and
the system tags are unchanged. A value's type is the tag's type, with no inference: a `bool`
The new tags follow the input's tags, in name order: they are a set, and the order they are
given in is not kept. `add_tags(run=3, cohort="A")` is the same operator, with the same hashes
and the same columns:

```python
reordered = sessions.add_tags(run=3, cohort="A")
print(reordered.keys()) # (('subject_id', 'session', 'cohort', 'run'), ('age', 'weight'))
print(reordered.content_hash() == labelled.content_hash()) # True
```

Data columns, their source info and the system tags are unchanged. A value's type is the tag's type, with no inference: a `bool`
becomes Arrow `bool`, an `int` `int64`, a `float` `double`, a `str` `large_string` and a `bytes`
`large_binary`, and every new tag is non-nullable:

Expand All @@ -745,8 +754,9 @@ except InputValidationError as error:
# add_tags: cannot add a tag with an existing column's name: 'age' is a data column
```

The names and values, in order, are the operator's identity, so two different values are two
operators, with different hashes and stored tables.
The names and values, in name order, are the operator's identity, so two different values are
two operators, with different hashes and stored tables, while two orders of the same tags are
one operator.

On a stream with [data-tags](data-tags.md), the data-tags stay data-tags and the new tags are
plain: a constant tag is never a data value.
Expand Down
1 change: 1 addition & 0 deletions docs/reference/hashing.md
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,7 @@ The table below shows what each class returns from `identity_structure()`.
| Operators (binary/N-ary) | `(operator_class_name, argument_symmetry(streams))` | `frozenset` for commutative (Join, MergeJoin); `tuple` for ordered (SemiJoin) |
| `SelectTagColumns`, `SelectDataColumns`, `DropTagColumns`, `DropDataColumns`, `SelectColumns`, `DropColumns` | `(operator_class_name, sorted unique column names as a list, strict)` | The operators act on a set of names: a list, a tuple, a set, a single string, a repeated or a reordered name list give one hash (ITL-942) |
| `MapTags`, `MapData`, `MapColumns` | `(operator_class_name, name_map, drop_unmapped, strict)` | An operator's identity is its full configuration, `strict` included, as for the column selection operators (ITL-1160) |
| `AddTags` | `(operator_class_name, ((name, value), ...) in name order)` | The new tags are a set: the order they are given in never enters the identity, and the tags are placed in name order (ITL-1269) |

**Inputs of a commutative operator are a set (kept by decision, ITL-942).** A pipeline hash
covers the structure of the pipeline, not only its schemas. `MergeJoin()(m1, m1)`, a stream
Expand Down
4 changes: 2 additions & 2 deletions src/orcapod/contexts/data/v1.json
Original file line number Diff line number Diff line change
Expand Up @@ -247,10 +247,10 @@
"date": "2026-11-18",
"release": null,
"added": {
"pipeline-02.json": "e5fbe9dd43df61554209ec5261a9c1bdd8059ec6d0d0959f882d1c42170bbb6b"
"pipeline-02.json": "7584d28939fb31907e9b078f91e0d6605222c31b170eb70bd6e4e4254342358f"
},
"previous": "28731f440e29a6004d4cfc9318909a10013abcf9488975e15d4864e9544e73c9",
"digest": "0aeb96ad884544d3d8e9374834a3520041fe693b1c0aa2edacacff17a07ab146"
"digest": "6096da93e09dbe7276d5f171f43f893297d0afc840f8dcd244729d9505c8d122"
}
],
"provisional": {
Expand Down
15 changes: 10 additions & 5 deletions src/orcapod/core/operators/add_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,17 @@ class AddTags(UnaryOperator):
through unchanged, and no data column is added. System tags keep their names
and values (name-preserving), so record ids are unchanged.

The new tags follow the input's tags, in the order given. A value's exact
The new tags are a set: whatever the order they are given in, the operator holds
them in name order (developer, November 18, 2026, ITL-1269), places them after the
input's tags in name order, and lists them that way in its identity and config, so
the order of the keywords never changes a hash, a stored path or a column name
downstream. A value's exact
Python type is the tag's type, mapped to Arrow by the data context's type
converter: ``bool`` to ``bool``, ``int`` to ``int64``, ``float`` to
``double``, ``str`` to ``large_string``, ``bytes`` to ``large_binary``. Every
new tag is non-nullable.

The operator's identity is its tags, names and values in order, so two
The operator's identity is its tags, names and values in name order, so two
different values are two operators with two stored paths.

Data-tags (ITL-1023): the input's data-tags stay data-tags, one column in
Expand Down Expand Up @@ -129,8 +133,9 @@ def __init__(self, tags: Mapping[str, TagConstant], **kwargs: Any):
schema_utils.require_names_not_meta(list(tags))
schema_utils.require_names_not_system(list(tags))
schema_utils.require_names_without_separator(list(tags))
# In name order: the order the tags are given in is not kept (ITL-1269).
self._tags: dict[str, TagConstant] = {}
for name, value in tags.items():
for name, value in sorted(tags.items(), key=lambda item: item[0]):
try:
self._tags[name] = _checked_value(value)
except (TypeError, ValueError) as error:
Expand All @@ -142,7 +147,7 @@ def __init__(self, tags: Mapping[str, TagConstant], **kwargs: Any):

@property
def tags(self) -> Mapping[str, TagConstant]:
"""The new tags, names mapped to values, in order; read-only.
"""The new tags, names mapped to values, in name order; read-only.

Read-only so the identity, the saved config and the cached constants
can never disagree.
Expand Down Expand Up @@ -212,7 +217,7 @@ def _constants(self, converter: TypeConverterProtocol, num_rows: int) -> pa.Tabl
num_rows: The number of rows.

Returns:
A table of the new tag columns, in the order given.
A table of the new tag columns, in name order.
"""
cached = self._one_row.get(id(converter))
if cached is None or cached[0] is not converter:
Expand Down
4 changes: 3 additions & 1 deletion src/orcapod/core/streams/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -628,7 +628,9 @@ def add_tags(
"A"})``), or keyword arguments (``add_tags(cohort="A", run=3)``), not both. A
tag named ``label``, or a name that is not a Python identifier, is given
through the dict. Each new tag holds the same value on every row and follows
the existing tags, in the order given. A value is a ``bool``, ``int``,
the existing tags, in name order: the new tags are a set, and the order they are
given in is not kept (ITL-1269), so ``add_tags(run=3, cohort="A")`` places
``cohort`` before ``run``. A value is a ``bool``, ``int``,
``float``, ``str`` or ``bytes``, and its type is the tag's type. Data
columns, their values and their source info are unchanged.

Expand Down
28 changes: 19 additions & 9 deletions tests/test_core/operators/test_add_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,14 @@ def test_every_row_gets_the_values(self) -> None:
assert table.column("cohort").to_pylist() == ["A", "A", "A"]
assert table.column("run").to_pylist() == [3, 3, 3]

def test_new_tags_follow_the_input_tags_in_the_order_given(self) -> None:
out = _readings().add_tags(run=3, cohort="A")
assert out.keys() == (("subject", "run", "cohort"), ("x", "name"))
assert out.as_table().column_names[:3] == ["subject", "run", "cohort"]
def test_new_tags_follow_the_input_tags_in_name_order(self) -> None:
"""The order the keywords are given in is not kept (ITL-1269)."""
for out in (
_readings().add_tags(run=3, cohort="A"),
_readings().add_tags(cohort="A", run=3),
):
assert out.keys() == (("subject", "cohort", "run"), ("x", "name"))
assert out.as_table().column_names[:3] == ["subject", "cohort", "run"]

def test_arrow_type_of_each_accepted_value_type(self) -> None:
out = _readings().add_tags(b=True, i=3, f=1.5, s="A", raw=b"\x01")
Expand Down Expand Up @@ -135,10 +139,15 @@ def test_different_values_are_different_operators(self) -> None:
}
assert len(hashes) == 6

def test_order_is_part_of_the_identity(self) -> None:
def test_order_is_not_part_of_the_identity(self) -> None:
"""The tags are a set of items: their order never forms identity (ITL-1269)."""
assert (
AddTags({"a": 1, "b": 2}).content_hash()
!= AddTags({"b": 2, "a": 1}).content_hash()
== AddTags({"b": 2, "a": 1}).content_hash()
)
assert (
AddTags({"a": 1, "b": 2}).pipeline_hash()
== AddTags({"b": 2, "a": 1}).pipeline_hash()
)

def test_names_are_part_of_the_identity(self) -> None:
Expand Down Expand Up @@ -227,7 +236,8 @@ def test_round_trip(self) -> None:
op = AddTags({"b": True, "i": 3, "f": 1.5, "s": "A", "raw": b"\x01"})
config = op.to_config()
assert config["class_name"] == "AddTags"
assert config["config"]["tags"][4] == {
# Saved in name order: b, f, i, raw, s.
assert config["config"]["tags"][3] == {
"name": "raw",
"type": "bytes",
"value": "01",
Expand All @@ -236,10 +246,10 @@ def test_round_trip(self) -> None:
assert restored.tags == op.tags
assert [type(v) for v in restored.tags.values()] == [
bool,
int,
float,
str,
int,
bytes,
str,
]
assert restored.content_hash() == op.content_hash()

Expand Down
159 changes: 159 additions & 0 deletions tests/test_core/operators/test_add_tags_order.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
"""``AddTags`` is the same operator for every order of its keywords (ITL-1269).

Developer, November 18, 2026: "I absolutely agree to make it entry order independent",
under the rule "it shouldn't depend on tag order -- generally nothing should depend on tag
order". The order of ``add_tags(cohort="A", run=3)`` only placed the new columns, yet it
was part of the operator's identity: two keyword orders gave two content and pipeline
hashes, two stored paths and two system-tag column names downstream. Now the new tags are
a set: the operator holds them in name order, its identity and config list them that way,
and they are placed in name order after the input's tags (as ``TagBy`` places its new
tags, ITL-1226).

Five new tags of every accepted type are given in all 120 keyword orders, on the shared
several-item inputs (three tags, three data columns; plain, data-tag and mixed roles), on
the sync and the async path and in jobs on both orchestrators.
"""

from __future__ import annotations

import asyncio
import itertools
from typing import Any

import pytest

from orcapod.core.operators import AddTags
from orcapod.databases import InMemoryArrowDatabase
from orcapod.pipeline import (
AsyncPipelineOrchestrator,
PipelineJob,
SyncPipelineOrchestrator,
)

from .several_items import (
MAIN,
ROLES,
TAGS_FIRST,
Arrangement,
async_rows,
fingerprint,
make_source,
ordered_rows_fingerprint,
)

# One value of each accepted type; the names are not in name order as given.
NEW_TAGS: dict[str, Any] = {
"run": 3,
"cohort": "A",
"weight": 1.5,
"ok": True,
"blob": b"\x01",
}
NAME_ORDER = ("blob", "cohort", "ok", "run", "weight")
KEYWORD_ORDERS = [
{name: NEW_TAGS[name] for name in order}
for order in itertools.permutations(NEW_TAGS)
]
# A few keyword orders for the heavier checks (streams, jobs).
SOME_ORDERS = [KEYWORD_ORDERS[0], KEYWORD_ORDERS[-1], KEYWORD_ORDERS[57]]
ORCHESTRATORS = pytest.mark.parametrize(
"orchestrator",
[SyncPipelineOrchestrator, AsyncPipelineOrchestrator],
ids=["sync", "async"],
)


def _source(roles: str) -> Any: # pyright: ignore[reportExplicitAny] # an ArrowTableSource
return make_source(MAIN, Arrangement(MAIN.tags, TAGS_FIRST, roles))


def test_every_keyword_order_is_one_operator() -> None:
"""All 120 orders: one content hash, one pipeline hash, one config, name order."""
operators = [AddTags(tags) for tags in KEYWORD_ORDERS]
assert len({op.content_hash() for op in operators}) == 1
assert len({op.pipeline_hash() for op in operators}) == 1
assert {tuple(op.tags) for op in operators} == {NAME_ORDER}
assert {
tuple(entry["name"] for entry in op.to_config()["config"]["tags"])
for op in operators
} == {NAME_ORDER}


def test_a_saved_config_in_any_order_rebuilds_the_same_operator() -> None:
reference = AddTags(NEW_TAGS)
config = reference.to_config()
entries = config["config"]["tags"]
for order in itertools.permutations(entries):
rebuilt = AddTags.from_config({**config, "config": {"tags": list(order)}})
assert rebuilt.content_hash() == reference.content_hash()
assert tuple(rebuilt.tags) == NAME_ORDER


def test_the_names_and_values_still_count() -> None:
"""A set of items is still identity: another name or value is another operator."""
reference = AddTags(NEW_TAGS).content_hash()
assert AddTags({**NEW_TAGS, "run": 4}).content_hash() != reference
assert AddTags({**NEW_TAGS, "extra": 0}).content_hash() != reference
assert AddTags({k: v for k, v in NEW_TAGS.items() if k != "ok"}).content_hash() != (
reference
)


@pytest.mark.parametrize("roles", ROLES)
def test_the_stream_is_the_same_for_every_keyword_order(roles: str) -> None:
"""Rows, hashes and column names equal; the new tags placed in name order."""
source = _source(roles)
prints = []
for tags in SOME_ORDERS:
stream = source.add_tags(**tags)
prints.append(fingerprint(stream))
tag_keys, _ = stream.keys()
assert tag_keys == (*source.keys()[0], *NAME_ORDER)
for tag, _ in stream.iter_data():
assert tuple(tag.keys()) == tag_keys
assert all(p == prints[0] for p in prints)


@pytest.mark.parametrize("roles", ROLES)
def test_the_async_path_gives_the_sync_rows_for_every_keyword_order(roles: str) -> None:
source = _source(roles)
for tags in SOME_ORDERS:
operator = AddTags(tags)
sync = ordered_rows_fingerprint(list(operator(source).iter_data()))
assert ordered_rows_fingerprint(async_rows(operator, source)) == sync


def _job_record(tags: dict[str, Any], roles: str, orchestrator: Any) -> dict[str, Any]: # pyright: ignore[reportExplicitAny] # an orchestrator class
db = InMemoryArrowDatabase()
job = PipelineJob(name="add_tags_order", database=db)
with job:
_source(roles).add_tags(label="tagged", **tags).drop_nulls(label="after")
job.run(orchestrator=orchestrator())
record: dict[str, Any] = {
"table_paths": sorted("/".join(p) for p in db.list_sources()),
}
for label in sorted(job.nodes):
node = job.nodes[label]
record[label] = (
node.content_hash().to_string(),
node.pipeline_hash().to_string(),
fingerprint(node)["rows"],
)
return record


@ORCHESTRATORS
@pytest.mark.parametrize("roles", ROLES)
def test_a_job_has_the_same_nodes_and_paths_for_every_keyword_order(
roles: str, orchestrator: Any
) -> None:
records = [_job_record(tags, roles, orchestrator) for tags in SOME_ORDERS]
assert all(record == records[0] for record in records)


def test_the_async_runs_match_the_sync_runs() -> None:
assert asyncio.iscoroutinefunction(AddTags.async_execute)
tags = KEYWORD_ORDERS[-1]
assert _job_record(tags, ROLES[2], SyncPipelineOrchestrator) == _job_record(
tags, ROLES[2], AsyncPipelineOrchestrator
)
Loading
Loading