diff --git a/.zed/rules b/.zed/rules index c4fde9c72..3254121d6 100644 --- a/.zed/rules +++ b/.zed/rules @@ -870,6 +870,24 @@ Base case: RootSource.pipeline_identity_structure() returns (tag_schema, data_sc Each downstream node's pipeline hash commits to its own identity plus upstream pipeline hashes, forming a Merkle chain. +No identity follows column order (developer, November 18, 2026, ITL-1246, ITL-1227): "it +shouldn't depend on tag order -- generally nothing should depend on tag order". A list of tag +or data-tag names enters an identity as a set of sorted names (FallThroughPod's +fall_through_tags, also in its config and a saved job; a raw stream's tag columns and +data-tags). A raw ArrowTableStream (no producer) hashes its whole identity +table once (every column group but _content_hash; hash_table covers the schema, so a stream +with no rows still commits to its columns) with its rows in the canonical row order of an +identity table (arrow_utils.canonical_identity_row_order, developer, November 19, 2026, +"option 2"; the specification is in docs/reference/hashing.md): a pyarrow value sort, ascending +and nulls last, over the user tags in name order then every other column in name order, each +only when its type is on the closed list arrow_utils.canonically_sortable (decided from the +type, never by trying a sort; no extension, list, struct, float16 or decimal256), and rows +still tied ordered by their own one-row hash_table digest (prefixed bytes), computed for tie +groups only. Outputs still list the +data-tags first in the input's tag order: column order is presentation. An operation whose +result could depend on a column order takes that order as an explicit argument that is part +of its identity (GroupBy's member_order), never the input's column order. + ### Column naming conventions __ prefix — System metadata (ColumnConfig meta) diff --git a/CLAUDE.md b/CLAUDE.md index 45bf2ff8a..e4865bbee 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -893,6 +893,24 @@ its upstreams, forming a Merkle chain. The pipeline hash uses a **resolver pattern** — `PipelineElementProtocol` objects route through `pipeline_hash()`, other `ContentIdentifiable` objects route through `content_hash()`. +**No identity follows column order** (developer, November 18, 2026, ITL-1246, ITL-1227): "it +shouldn't depend on tag order -- generally nothing should depend on tag order". A list of tag +or data-tag names enters an identity as a set of sorted names (`FallThroughPod`'s +`fall_through_tags`, also in its config and a saved job; a raw stream's tag columns and +data-tags). A raw `ArrowTableStream` (no producer) hashes its whole identity +table once (every column group but `_content_hash`; `hash_table` covers the schema, so a stream +with no rows still commits to its columns) with its rows in the canonical row order of an +identity table (`arrow_utils.canonical_identity_row_order`, developer, November 19, 2026, +"option 2"; the specification is in `docs/reference/hashing.md`): a pyarrow value sort, ascending +and nulls last, over the user tags in name order then every other column in name order, each +only when its type is on the closed list `arrow_utils.canonically_sortable` (decided from the +type, never by trying a sort; no extension, list, struct, `float16` or `decimal256`), and rows +still tied ordered by their own one-row `hash_table` digest (prefixed bytes), computed for tie +groups only. Outputs still list the +data-tags first in the input's tag order: column order is presentation. An operation whose +result could depend on a column order takes that order as an explicit argument that is part +of its identity (GroupBy's `member_order`), never the input's column order. + ### Column naming conventions | Prefix | Meaning | Example | Controlled by | diff --git a/changelog.d/ITL-1246.md b/changelog.d/ITL-1246.md new file mode 100644 index 000000000..37ceee7dd --- /dev/null +++ b/changelog.d/ITL-1246.md @@ -0,0 +1,35 @@ +### Breaking changes and migration + +- No identity depends on the order of a stream's columns (ITL-1246, ITL-1227; developer, + November 18, 2026: "nothing should depend on tag order"). The identities of streams with + data-tags are now settled and freeze with data context v1 at the 0.4.0 release. This + replaces the "may still change" note of the data-tag entries. + - A function pod called on a stream with data-tags (`pod(stream)`, a `FallThroughPod`) + holds its data-tags as a set of sorted names. Before, it held them in the input's tag + order, which came from `tag_columns` or, after an operator, from the table's physical + layout. Now its content and pipeline hash, its job node's hashes and its pipeline table + path are the same for every order. `FallThroughPod.fall_through_tags`, the pod's config + and a saved job's `fall_through_tags` list the names sorted. The output still lists the + data-tags first, in the input's tag order. A fall-through node whose input listed two + or more data-tags out of name order gets a new pipeline table path. Its results are the + plain pod's and are not recomputed. + - A raw `ArrowTableStream` (one with no producer) hashes its whole identity table once, + with its rows in a canonical order, and holds its tag columns and data-tags as sorted + names. The table covers every column group but `_content_hash`. + - The canonical order is a value sort: the user tags in name order, then every other + column in name order, each only when its type is on a closed list. Rows still tied are + ordered by their own row hash. The specification is in `docs/reference/hashing.md`. + - So the same rows in any order, under any order of `tag_columns`, `data_tags` or + system-tag columns, have one content hash. A duplicated row counts twice, and a stream + with no rows still commits to its columns. + - Before, the rows were sorted by the tags in tag order and the system tags in column + order. A stream with no tag and no system tag could not be hashed. Rows tied on every + tag, or with a list tag, hashed in their given order. + - A raw stream's content hash moves only where that order differed. Among the pinned + values, only `pipeline:list_tag_producerless_stream.as_given` moves. Sources, operator + results and node outputs hash as before. + +### Fixed + +- A raw `ArrowTableStream` with no tag column and no system-tag column has a content hash. + Before, it raised `ArrowInvalid` (nothing to sort by). diff --git a/docs/concepts/data-tags.md b/docs/concepts/data-tags.md index 4966f5959..501a24f58 100644 --- a/docs/concepts/data-tags.md +++ b/docs/concepts/data-tags.md @@ -1,9 +1,9 @@ # Data-tags -!!! warning "Integration branch (ITL-1023)" - Data-tags are the first slice of Orcapod v0.4, on an integration branch. The - identities (content and pipeline hashes) of streams with data-tags are **not - frozen yet** and may change before the release. Streams whose tags are all plain +!!! note "Settled identities (ITL-1246)" + Data-tags are the first slice of Orcapod v0.4. The identities (content and pipeline + hashes) of streams with data-tags are settled (developer, November 18, 2026) and are + frozen with data context v1 at the 0.4.0 release. Streams whose tags are all plain (`tag_only_columns`) keep their v0.3 identities exactly. A tag is either **plain** (it carries its own value, as every tag did in v0.3) or @@ -79,6 +79,27 @@ A function output named like a tag is an error when the pipeline is built. A fun that does not read a data-tag column keeps its result identity: retagging a source does not make it compute again. +The data-tags that fall through are a **set of names**: the pod's identity holds them +sorted by name. The order of the input's tag columns never changes the pod's content or +pipeline hash, nor the table paths of its node in a job. The output lists the data-tags +first, in the input's own tag order: column order is presentation only. Below, the same +spikes are given with `time` before `unit`, a different tag order and table layout: + +```python +by_time = op.sources.DictSource( + [{"time": r["time"], "unit": r["unit"], "amp": r["amp"]} for r in rows], + tag_columns=["time", "unit"], + source_id="spikes", +) +scaled_by_time = scale.pod(by_time) +print(scaled_by_time.keys()) +# (('time', 'unit'), ('time', 'unit', 'scaled')) +print(scaled_by_time.content_hash() == scaled.content_hash()) +# True +print(scaled_by_time.pipeline_hash() == scaled.pipeline_hash()) +# True +``` + ## Moving a column between roles A data-tag is one column in two roles, a tag and a data column. Four steps move a diff --git a/docs/dev/scripts/golden_union_diff.py b/docs/dev/scripts/golden_union_diff.py new file mode 100644 index 000000000..8e413efc1 --- /dev/null +++ b/docs/dev/scripts/golden_union_diff.py @@ -0,0 +1,85 @@ +"""Compare the union of golden entries at a git revision with the working tree. + +Every golden file of the current data context (``tests/test_hashing/golden/data//``) +is a flat JSON object of ``entry: value``. This script reads every file at ``BASE`` (a git +revision) and in the working tree, keys each entry by ``:`` (the group is the +file name before ``-NN.json``), and prints the entries that changed, were added or were +removed. Used in the pull request of ITL-1246 / ITL-1227 to show that exactly the approved +entries changed and every other entry is byte-identical. + +Usage:: + + uv run python docs/dev/scripts/golden_union_diff.py [BASE] # default: origin/main +""" + +from __future__ import annotations + +import json +import subprocess +import sys +from pathlib import Path + +GOLDEN = Path("tests/test_hashing/golden/data") + + +def _group(name: str) -> str: + return name.rsplit("-", 1)[0] + + +def entries_at(revision: str) -> dict[str, str]: + """The union of golden entries in the files at ``revision``.""" + listing = subprocess.run( + ["git", "ls-tree", "-r", "--name-only", revision, str(GOLDEN)], + check=True, + capture_output=True, + text=True, + ).stdout.split() + union: dict[str, str] = {} + for path in listing: + if not path.endswith(".json"): + continue + text = subprocess.run( + ["git", "show", f"{revision}:{path}"], + check=True, + capture_output=True, + text=True, + ).stdout + group = _group(Path(path).stem) + for key, value in json.loads(text).items(): + union[f"{group}:{key}"] = json.dumps(value, sort_keys=True) + return union + + +def entries_in_tree() -> dict[str, str]: + """The union of golden entries in the working tree's files.""" + union: dict[str, str] = {} + for path in sorted(GOLDEN.rglob("*.json")): + group = _group(path.stem) + for key, value in json.loads(path.read_text()).items(): + union[f"{group}:{key}"] = json.dumps(value, sort_keys=True) + return union + + +def main() -> None: + base = sys.argv[1] if len(sys.argv) > 1 else "origin/main" + before = entries_at(base) + after = entries_in_tree() + changed = sorted(k for k in before.keys() & after.keys() if before[k] != after[k]) + added = sorted(after.keys() - before.keys()) + removed = sorted(before.keys() - after.keys()) + same = len(before.keys() & after.keys()) - len(changed) + print(f"base {base}: {len(before)} entries; working tree: {len(after)} entries") + print(f"unchanged (byte-identical values): {same}") + print(f"changed: {len(changed)}") + for key in changed: + print(f" {key}\n before {before[key]}\n after {after[key]}") + print(f"added: {len(added)}") + for key in added: + print(f" {key}") + print(f"removed: {len(removed)}") + for key in removed: + print(f" {key}") + + +if __name__ == "__main__": + main() diff --git a/docs/dev/scripts/itl_1227_value_order.py b/docs/dev/scripts/itl_1227_value_order.py new file mode 100644 index 000000000..849c07f03 --- /dev/null +++ b/docs/dev/scripts/itl_1227_value_order.py @@ -0,0 +1,392 @@ +"""What would ordering a raw stream's identity rows by VALUE take? (ITL-1227, PR 453) + +The developer is weighing a value order (tag columns first, then the other columns in +name order) instead of ordering the rows by a per-row hash. This script measures, on +pyarrow and Polars as locked: + +1. which column types an identity table can hold that each library can sort; +2. which rows stay tied after sorting by every sortable column; +3. the sort semantics a frozen hash would depend on (strings, nulls, NaN, -0.0); +4. the cost per row of per-row hashing, of a value sort, and of the hybrid (a row hash + only for the rows of a tie group). + +Run: ``uv run python docs/dev/scripts/itl_1227_value_order.py``. +""" + +from __future__ import annotations + +import dataclasses +import datetime +import decimal +import pathlib +import time +import uuid +import warnings +from collections.abc import Callable +from typing import Any + +import numpy as np +import pandas as pd +import polars as pl +import pyarrow as pa +import pyarrow.compute as pc + +warnings.simplefilter("ignore") + +import orcapod as op # noqa: E402 +from orcapod.contexts import get_default_context # noqa: E402 +from orcapod.utils.arrow_utils import ( # noqa: E402 + _same_as_previous, # pyright: ignore[reportPrivateUsage] # the rule under measurement + canonical_identity_row_order, + canonically_sortable, +) + +CTX = get_default_context() +CONVERTER = CTX.type_converter +HASHER = CTX.arrow_hasher + + +@dataclasses.dataclass +class Point: + """A user class (an exact class) for the logical-type column.""" + + x: int + y: float + + +def arrow_columns() -> dict[str, Any]: + """One four-row column per Arrow type, with a null where the type allows one.""" + f16 = pa.array(np.array([1.0, -0.0, np.nan, 0.0], np.float16)) + cols: dict[str, Any] = { + **{ + f"int{w}": pa.array([3, None, -1, 3], getattr(pa, f"int{w}")()) + for w in (8, 16, 32, 64) + }, + **{ + f"uint{w}": pa.array([3, None, 1, 3], getattr(pa, f"uint{w}")()) + for w in (8, 16, 32, 64) + }, + "float16": f16, + "float32 NaN -0.0": pa.array([1.0, -0.0, float("nan"), 0.0], pa.float32()), + "float64 NaN -0.0 null": pa.array( + [float("nan"), -0.0, None, 0.0], pa.float64() + ), + "bool": pa.array([True, None, False, True]), + "string": pa.array(["b", None, "é", "a"], pa.string()), + "large_string": pa.array(["b", None, "é", "a"], pa.large_string()), + "binary": pa.array([b"b", None, b"\xff", b"a"], pa.binary()), + "large_binary": pa.array([b"b", None, b"\xff", b"a"], pa.large_binary()), + "fixed_size_binary": pa.array([b"bb", None, b"aa", b"ab"], pa.binary(2)), + "date32": pa.array([datetime.date(2020, 1, 2), None] * 2, pa.date32()), + "date64": pa.array([datetime.date(2020, 1, 2), None] * 2, pa.date64()), + "time64[ns]": pa.array([1, None, 1001, 5], pa.time64("ns")), + "timestamp[us, UTC]": pa.array([1, None, 3, 2], pa.timestamp("us", "UTC")), + "duration[ns]": pa.array([1, None, -3, 2], pa.duration("ns")), + "decimal128(10,2)": pa.array( + [decimal.Decimal("1.50"), None, decimal.Decimal("-2.25"), None], + pa.decimal128(10, 2), + ), + "decimal256(76,40)": pa.array( + [decimal.Decimal("1.5"), None, decimal.Decimal("-2.25"), None], + pa.decimal256(76, 40), + ), + "null": pa.array([None] * 4, pa.null()), + "large_list": pa.array( + [[2, None], None, [1], [2]], pa.large_list(pa.int64()) + ), + "large_list>": pa.array( + [[[2]], None, [[1, None]], [[2]]], pa.large_list(pa.large_list(pa.int64())) + ), + "fixed_size_list": pa.array( + [[1, 2], None, [0, 5], [1, 2]], pa.list_(pa.int64(), 2) + ), + "struct": pa.array( + [{"a": 1, "b": "x"}, None, {"a": 0, "b": "y"}, {"a": 1, "b": "x"}], + pa.struct([("a", pa.int64()), ("b", pa.string())]), + ), + "map": pa.array( + [[("k", 1)], None, [("j", 2)], [("k", 1)]], pa.map_(pa.string(), pa.int64()) + ), + } + return cols + + +def logical_columns() -> dict[str, Any]: + """One column per Orcapod logical type, built by the data context's converter.""" + values: dict[str, tuple[Any, list[Any]]] = { + "pathlib.Path": (pathlib.Path, [pathlib.Path("/b"), pathlib.Path("/a")]), + "uuid.UUID": (uuid.UUID, [uuid.UUID(int=2), uuid.UUID(int=1)]), + "numpy.ndarray": (np.ndarray, [np.array([2, 1]), np.array([1])]), + "pandas.DataFrame": ( + pd.DataFrame, + [pd.DataFrame({"a": [2]}), pd.DataFrame({"a": [1]})], + ), + "polars.DataFrame": ( + pl.DataFrame, + [pl.DataFrame({"a": [2]}), pl.DataFrame({"a": [1]})], + ), + "user class (dataclass)": (Point, [Point(2, 0.5), Point(1, 1.5)]), + } + try: + import torch + + values["torch.Tensor"] = ( + torch.Tensor, + [torch.tensor([2.0]), torch.tensor([1.0])], + ) + except ImportError: # pragma: no cover + pass + out: dict[str, Any] = {} + for name, (python_type, items) in values.items(): + try: + table = CONVERTER.python_dicts_to_arrow_table( + [{"c": v} for v in items], python_schema={"c": python_type} + ) + out[f"{name} [{table.schema.field('c').type}]"] = table.column( + "c" + ).combine_chunks() + except Exception as error: # noqa: BLE001 + out[f"{name}"] = error + for name, python_type in (("op.File", op.File), ("op.Directory", op.Directory)): + try: + arrow_type = CONVERTER.python_type_to_arrow_type(python_type) + out[f"{name} [{arrow_type}]"] = pa.array([None, None], arrow_type) + except Exception as error: # noqa: BLE001 + out[name] = error + return out + + +def try_sort(name: str, column: Any) -> tuple[str, str]: + """Sort a one-column table with pyarrow and with Polars; report each outcome.""" + if isinstance(column, Exception): + return f"build failed: {type(column).__name__}", "" + table = pa.table({"c": column}) + results = [] + try: + pc.sort_indices(table, sort_keys=[("c", "ascending")], null_placement="at_end") + results.append("ok") + except Exception as error: # noqa: BLE001 + results.append(f"{type(error).__name__}: {str(error)[:60]}") + try: + frame = pl.from_arrow(table) + assert isinstance(frame, pl.DataFrame) + frame.with_row_index("i").sort("c", nulls_last=True, maintain_order=True) + results.append("ok") + except BaseException as error: # noqa: BLE001 (a Polars panic is a BaseException) + results.append(f"{type(error).__name__}: {str(error)[:60]}") + return results[0], results[1] + + +def semantics() -> None: + """The sort semantics a frozen hash would rest on.""" + print("\n## 3. Semantics (pyarrow sort_indices / Polars sort)") + values = pa.array(["b", "B", "é", "e", "a", None, "Z", ""], pa.large_string()) + t = pa.table({"c": values}) + pa_order = t.take( + pc.sort_indices(t, sort_keys=[("c", "ascending")], null_placement="at_end") + ) + frame = pl.from_arrow(t) + assert isinstance(frame, pl.DataFrame) + pl_order = frame.sort("c", nulls_last=True) + print("strings pyarrow:", pa_order.column("c").to_pylist()) + print("strings polars: ", pl_order["c"].to_list()) + print("(byte order of UTF-8 = code point order: no locale in either)") + floats = pa.array( + [float("nan"), 1.0, -0.0, None, 0.0, float("-inf"), -1.0], pa.float64() + ) + t = pa.table({"c": floats, "i": pa.array(range(len(floats)))}) + pa_sorted = t.take( + pc.sort_indices(t, sort_keys=[("c", "ascending")], null_placement="at_end") + ) + frame = pl.from_arrow(t) + assert isinstance(frame, pl.DataFrame) + pl_sorted = frame.sort("c", nulls_last=True, maintain_order=True) + print( + "floats pyarrow (value, input index):", + list(zip(pa_sorted["c"].to_pylist(), pa_sorted["i"].to_pylist())), + ) + print( + "floats polars (value, input index):", + list(zip(pl_sorted["c"].to_list(), pl_sorted["i"].to_list())), + ) + # -0.0 against 0.0 and NaN payloads: are they ties (kept in input order)? + bits = np.array( + [0x7FF8000000000001, 0x7FF8000000000000, 0x8000000000000000, 0x0], np.uint64 + ) + t = pa.table({"c": pa.array(bits.view(np.float64)), "i": pa.array([0, 1, 2, 3])}) + for label, rows in (("as given", [0, 1, 2, 3]), ("reversed", [3, 2, 1, 0])): + tt = t.take(rows) + order = tt.take(pc.sort_indices(tt, sort_keys=[("c", "ascending")]))[ + "i" + ].to_pylist() + print(f"NaN payloads and +/-0.0, {label}: pyarrow order of input ids {order}") + + +def tied_rows() -> None: + """Which rows stay tied after a sort over every sortable column (name order).""" + print("\n## 2. Ties after sorting by every sortable column") + cases = { + "identical rows": pa.table({"k": [1, 1], "x": [5, 5]}), + "-0.0 vs 0.0 in a data column": pa.table( + {"k": [1, 1], "x": pa.array([-0.0, 0.0])} + ), + "NaN payloads": pa.table( + { + "k": [1, 1], + "x": pa.array( + np.array([0x7FF8000000000001, 0x7FF8000000000000], np.uint64).view( + np.float64 + ) + ), + } + ), + "differ only in a map column": pa.table( + { + "k": [1, 1], + "m": pa.array( + [[("a", 1)], [("a", 2)]], pa.map_(pa.string(), pa.int64()) + ), + } + ), + "differ only in an extension (ndarray) column": None, + } + arrays = logical_columns() + nd = next(v for k, v in arrays.items() if k.startswith("numpy.ndarray")) + cases["differ only in an extension (ndarray) column"] = pa.table( + {"k": [1, 1], "a": nd} + ) + for name, table in cases.items(): + assert table is not None + # The sort keys of the spec: the closed type list, not what pyarrow can sort. + sortable = [ + col + for col in sorted(table.column_names) + if canonically_sortable(table.schema.field(col).type) + ] + idx = pc.sort_indices(table, sort_keys=[(c, "ascending") for c in sortable]) + st = table.take(idx) + # Ties under the sort's own comparison (nulls equal, every NaN equal, -0.0 equal + # to 0.0), the rule canonical_identity_row_order applies to adjacent rows. + same = pa.array([True] * (st.num_rows - 1), pa.bool_()) + for col in sortable: + same = pc.and_(same, _same_as_previous(st.column(col))) + tied = sum(bool(v) for v in same.to_pylist()) + try: + digests = { + HASHER.hash_table(table.slice(i, 1)).to_hex() + for i in range(table.num_rows) + } + distinct = str(len(digests)) + except ValueError as error: + distinct = f"unhashable ({str(error)[:50]})" + print( + f"{name:<45} sortable={sortable} tied_pairs={tied} distinct_row_hashes={distinct}" + ) + + +def costs(n: int = 20000) -> None: + """Per-row hashing, value sort and the hybrid, on a typical identity table.""" + print( + f"\n## 4. Cost on a {n}-row identity table (two tags, two data, system tags, source info)" + ) + rng = np.random.default_rng(7) + table = pa.table( + { + "k": pa.array(rng.integers(0, 100, n)), + "j": pa.array([f"s{i}" for i in range(n)], pa.large_string()), + "x": pa.array(rng.random(n)), + "y": pa.array(rng.integers(0, 10, n)), + "_tag_record_id::abc": pa.array( + [f"row_{i}" for i in range(n)], pa.large_string() + ), + "_tag_source_id::abc": pa.array(["src"] * n, pa.large_string()), + "_source_x": pa.array( + [f"src::row_{i}::x" for i in range(n)], pa.large_string() + ), + } + ) + + def per_row_hash(t: pa.Table) -> pa.Table: + digests = [ + HASHER.hash_table(t.slice(i, 1)).to_prefixed_digest() + for i in range(t.num_rows) + ] + return t.take( + pa.array(sorted(range(t.num_rows), key=digests.__getitem__), pa.int64()) + ) + + def value_sort(t: pa.Table) -> pa.Table: + tags = [c for c in ("j", "k") if c in t.column_names] + rest = sorted( + c + for c in t.column_names + if c not in tags + and not pa.types.is_map(t.schema.field(c).type) + and not pa.types.is_large_list(t.schema.field(c).type) + ) + return t.take( + pc.sort_indices( + t, + sort_keys=[(c, "ascending") for c in tags + rest], + null_placement="at_end", + ) + ) + + def hybrid(t: pa.Table) -> pa.Table: + # The implementation itself: value sort, tie detection with the sort's own + # comparison, and each tie group ordered by its rows' one-row hashes. + tags = [c for c in ("j", "k") if c in t.column_names] + return canonical_identity_row_order(t, tags, HASHER) + + def timed(fn: Callable[[pa.Table], pa.Table], t: pa.Table) -> float: + best = float("inf") + for _ in range(3): + start = time.perf_counter() + fn(t) + best = min(best, time.perf_counter() - start) + return best + + whole = timed(lambda t: (HASHER.hash_table(t), t)[1], table) + print( + f"one table hash (today's final step): {whole * 1e3:8.1f} ms ({whole / n * 1e6:6.2f} us/row)" + ) + for label, fn in ( + ("per-row hashing + sort", per_row_hash), + ("value sort", value_sort), + ("hybrid, no ties", hybrid), + ): + t = ( + timed(fn, table) + if label != "per-row hashing + sort" + else timed(fn, table.slice(0, 2000)) * n / 2000 + ) + print(f"{label:<40} {t * 1e3:8.1f} ms ({t / n * 1e6:6.2f} us/row)") + one_group = pa.table({"k": pa.array([1] * 2000), "x": pa.array([1.0] * 2000)}) + # Rows tied in every sortable column, differing in a list column (pyarrow cannot + # sort a list): every row is in the one tie group. + one_group = one_group.append_column( + "m", pa.array([[i] for i in range(2000)], pa.large_list(pa.int64())) + ) + t = timed(hybrid, one_group) + print( + f"{'hybrid, one tie group of 2000 rows':<40} {t * 1e3:8.1f} ms ({t / 2000 * 1e6:6.2f} us/row)" + ) + + +def main() -> None: + print(f"pyarrow {pa.__version__}, polars {pl.__version__}") + print("\n## 1. Can each type be sorted? (pyarrow sort_indices | Polars sort)") + columns: dict[str, Any] = {**arrow_columns(), **logical_columns()} + for name, column in columns.items(): + pa_result, pl_result = try_sort(name, column) + short = name.split(" [")[0] + (" [ext]" if "extension<" in name else "") + print( + f"{short[:34]:<34} pyarrow: {pa_result[:58]:<58} polars: {pl_result[:70]}" + ) + tied_rows() + semantics() + costs() + + +if __name__ == "__main__": + main() diff --git a/docs/dev/scripts/itl_1246_measure_tag_order.py b/docs/dev/scripts/itl_1246_measure_tag_order.py new file mode 100644 index 000000000..42ac6491f --- /dev/null +++ b/docs/dev/scripts/itl_1246_measure_tag_order.py @@ -0,0 +1,242 @@ +"""Measure which data-tag identities depend on the order of a stream's tag columns. + +ITL-1246 / ITL-1227. Builds one table under every order of its tag columns (three +data-tags ``a``, ``b``, ``c`` and one plain tag ``p``) and prints, for each element, the +number of distinct values across the orders (1 means order-free). Run with +``uv run python docs/dev/scripts/itl_1246_measure_tag_order.py``. +""" + +from __future__ import annotations + +import asyncio +import itertools +import warnings +from collections import defaultdict +from typing import Any + +import pyarrow as pa + +warnings.simplefilter("ignore") + +import orcapod as op # noqa: E402 +from orcapod.core.streams import ArrowTableStream # noqa: E402 +from orcapod.databases import InMemoryArrowDatabase # noqa: E402 +from orcapod.sources import ArrowTableSource # noqa: E402 + +TAGS = ("a", "b", "c") +ROWS = { + "a": [1, 1, 2, 2], + "b": ["x", "y", "x", "y"], + "c": [True, False, False, True], + "p": ["p1", "p2", "p3", "p4"], + "v": [10, 20, 30, 40], + "w": [1.5, 2.5, 3.5, 4.5], +} + + +@op.function_pod(output_keys="doubled") +def doubled(v: int) -> int: + return 2 * v + + +TYPES = { + "a": pa.int64(), + "b": pa.large_string(), + "c": pa.bool_(), + "p": pa.large_string(), + "v": pa.int64(), + "w": pa.float64(), +} + + +LAYOUT: list[tuple[str, ...]] = [("a", "b", "c")] + + +def table() -> pa.Table: + """The table, its data-tag columns physically laid out in ``LAYOUT[0]`` order.""" + names = [*LAYOUT[0], "p", "v", "w"] + schema = pa.schema([pa.field(k, TYPES[k], nullable=False) for k in names]) + return pa.table({k: pa.array(ROWS[k], TYPES[k]) for k in names}, schema=schema) + + +def small(columns: dict[str, list[Any]]) -> pa.Table: + schema = pa.schema( + [pa.field(k, TYPES.get(k, pa.int64()), nullable=False) for k in columns] + ) + return pa.table( + {k: pa.array(v, schema.field(k).type) for k, v in columns.items()}, + schema=schema, + ) + + +def source(order: tuple[str, ...], source_id: str = "src") -> Any: + return ArrowTableSource( + table(), + tag_columns=[*order, "p"], + tag_only_columns=["p"], + source_id=source_id, + ) + + +def summary(stream: Any) -> dict[str, Any]: + tag_keys, _ = stream.keys() + all_tags, _ = stream.keys(columns={"system_tags": True}) + sys_cols = tuple(k for k in all_tags if k not in tag_keys) + rows = {} + for tag, data in stream.iter_data(): + key = repr(sorted(tag.as_dict().items())) + rows[key] = ( + tag.content_hash().to_string(), + data.content_hash().to_string(), + tuple(sorted((k, str(v)) for k, v in tag.as_dict(all_info=True).items())), + ) + return { + "content_hash": stream.content_hash().to_string(), + "pipeline_hash": stream.pipeline_hash().to_string(), + "system_tag_columns": sys_cols, + "rows": tuple(sorted(rows.items())), + } + + +def saved_fall_through(job: Any) -> tuple[Any, ...]: + import json + import tempfile + from pathlib import Path + + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "job.json" + job.save(path) + text = path.read_text() + found: list[Any] = [] + + def walk(node: Any) -> None: + if isinstance(node, dict): + if "fall_through_tags" in node: + found.append(tuple(node["fall_through_tags"])) + for v in node.values(): + walk(v) + elif isinstance(node, list): + for v in node: + walk(v) + + walk(json.loads(text)) + return tuple(found) + + +def job_summary(order: tuple[str, ...]) -> dict[str, Any]: + db = InMemoryArrowDatabase() + job = op.PipelineJob(name="m", database=db) + with job: + doubled.pod(source(order), label="f") + job.run() + async_db = InMemoryArrowDatabase() + async_job = op.PipelineJob(name="m", database=async_db) + with async_job: + doubled.pod(source(order), label="f") + asyncio.run(async_job.run_async()) + paths = tuple(sorted("/".join(p) for p in db.list_sources())) + out: dict[str, Any] = { + "table_paths": paths, + "async table_paths": tuple( + sorted("/".join(p) for p in async_db.list_sources()) + ), + "saved fall_through_tags": saved_fall_through(job), + } + for label in sorted(job.nodes): + s = summary(job.nodes[label]) + out.update({f"node[{label}].{k}": v for k, v in s.items()}) + for p in db.list_sources(): + recs = db.get_all_records(p, record_id_column="__rid") + assert recs is not None + name = "/".join(p) + if "_result" in name: + out[f"input_data_hashes[{name.split('/')[0]}..result]"] = tuple( + sorted(str(v) for v in recs.column("__input_data_hash").to_pylist()) + ) + else: + out["record_ids[pipeline]"] = tuple( + sorted(str(v) for v in recs.column("__rid").to_pylist()) + ) + return out + + +def async_rows(stream: Any) -> tuple[Any, ...]: + async def collect() -> list[Any]: + return ( + [ + (tag.content_hash().to_string(), data.content_hash().to_string()) + async for tag, data in stream.async_iter_data() + ] + if hasattr(stream, "async_iter_data") + else [] + ) + + return tuple(sorted(asyncio.run(collect()))) + + +def elements(order: tuple[str, ...]) -> dict[str, Any]: + out: dict[str, Any] = {} + + def put(prefix: str, s: dict[str, Any]) -> None: + out.update({f"{prefix}.{k}": v for k, v in s.items()}) + + src = source(order) + put("source", summary(src)) + # Function pod over data-tags (fall-through), with and without an automatic select. + put( + "fall_through(v only)", + summary(doubled.pod(src.select_data_columns([*order, "v"]))), + ) + put("fall_through(auto select drops w)", summary(doubled.pod(src))) + # Operators that carry data-tags. + other = ArrowTableSource( + small({"a": [1, 2], "b": ["x", "y"], "z": [7, 8]}), + tag_columns=["a", "b"], + source_id="other", + ) + put("join", summary(src.join(other))) + put("semi_join", summary(src.semi_join(other))) + from orcapod.operators import MergeJoin + + other_w = ArrowTableSource( + small({"a": [1, 2], "b": ["x", "y"], "c": [True, False], "w": [9.5, 8.5]}), + tag_columns=["a", "b", "c"], + source_id="other_w", + ) + put("merge_join", summary(MergeJoin()(src, other_w))) + put("group_by(a)", summary(src.group_by("a"))) + put("batch(2)", summary(src.batch(2))) + put("tag_by(v,w)", summary(src.tag_by(["v", "w"]))) + put("map_tags(a->aa)", summary(src.map_tags({"a": "aa"}))) + put("drop_nulls()", summary(src.drop_nulls())) + # A raw stream: no producer. + raw = ArrowTableStream(table(), tag_columns=[*order, "p"], data_tags=order) + put("raw(data_tags)", summary(raw)) + raw_plain = ArrowTableStream(table(), tag_columns=[*order, "p"]) + put("raw(plain tags)", summary(raw_plain)) + put("job", job_summary(order)) + return out + + +def main() -> None: + # by_tag_order[key]: the most distinct values over the tag orders, any one layout. + # by_layout[key]: the most distinct values over the layouts, any one tag order. + seen: dict[str, dict[tuple[Any, Any], str]] = defaultdict(dict) + orders = list(itertools.permutations(TAGS)) + for layout in orders: + LAYOUT[0] = layout + for order in orders: + for key, value in elements(order).items(): + seen[key][(layout, order)] = repr(value) + width = max(len(k) for k in seen) + print(f"{'element':<{width}} tag-order layout all (of 36)") + for key, cells in seen.items(): + by_order = max(len({cells[(lay, o)] for o in orders}) for lay in orders) + by_layout = max(len({cells[(lay, o)] for lay in orders}) for o in orders) + total = len(set(cells.values())) + flag = "" if total == 1 else " <--" + print(f"{key:<{width}} {by_order:>9} {by_layout:>6} {total:>3}{flag}") + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1246-data-tag-identity-order.md b/docs/dev/specs/itl-1246-data-tag-identity-order.md new file mode 100644 index 000000000..b346f576f --- /dev/null +++ b/docs/dev/specs/itl-1246-data-tag-identity-order.md @@ -0,0 +1,302 @@ +# Data-tag identities free of tag column order, then pinned (ITL-1246, ITL-1227) + +Status: implemented. The Step 1 plan below was measured on `origin/main` d81eec8d +(2026-11-18). The measurement script is `docs/dev/scripts/itl_1246_measure_tag_order.py`. + +**Decision update, part (b) (developer, 2026-11-18).** The row rule proposed in (b) below +(sort by tag names) was replaced. The developer's words: "the stream's strict identity +should not depend on the row order so making it canonical makes sense", and "I agree with +multiset of rows as the definitive way to sort". + +A raw stream's identity now holds its rows as a multiset: + +- Each row is hashed alone by the Arrow hasher, over the identity table's columns. +- The digests are taken with their label (`to_prefixed_digest`) and sorted into one + `large_binary` column `row_hash`. +- There is no special case for no tags, tied tags, list tags or zero rows. + +Its names are still sorted tuples. Questions F2 and F3 are moot. + +Under this rule 7 pinned entries move: + +- `schema:source_stream_builder.{default_source_id,named_source_id,record_id_column}.content_hash` +- `pipeline:list_tag_producerless_stream.{as_given,reversed}` +- `pipeline:tagless_producerless_stream.{as_given,reordered}` + +They are regenerated only after the developer approves the list. + +The alternative V2 was measured too: tags in name order, then the row digest as a +tiebreak. It moved only `pipeline:list_tag_producerless_stream.as_given`. + +Cost: about 160 µs per row, against about 1 µs per row for one table hash. It is paid only +when a raw stream's content hash is asked for. + +Issues filed from (f): ITL-1269 (F5, AddTags), ITL-1270 (F4, presentation sort) and ITL-1272 +(keyed in-memory default source id). F6 is the existing ITL-1249. + +Developer decisions this rests on: + +- 2026-11-17: the order of a stream's columns never forms identity (ITL-1205, ITL-1226). +- 2026-11-18: data-tags are not provisional. Their identity is settled now and frozen with + data context v1 at 0.4.0, so every data-tag identity gets golden pins. +- 2026-11-18: "it shouldn't depend on tag order -- generally nothing should depend on tag + order -- if any operations COULD vary output by tag order (as in column order of + operation), then explicit ordering of tags to be used should be an explicit input into + the function/operator". + +## Measurement + +One table, three data-tags `a` (int), `b` (str), `c` (bool) and a plain tag `p`, data `v`, +`w`. It is built under every order of `tag_columns` (6) and every physical layout of the +data-tag columns (6), so 36 builds. For each element the script counts distinct values +over the tag orders (one layout), over the layouts (one tag order), and over all 36. 1 +means the element does not depend on order. + +On `origin/main`, only these elements have more than one value: + +| Element | tag order | layout | all 36 | +|---|---|---|---| +| fall-through pod after an explicit select: content and pipeline hash | 1 | **6** | 6 | +| fall-through pod with the automatic select: content and pipeline hash | **6** | 1 | 6 | +| raw `ArrowTableStream` with data-tags: content hash | **6** | 1 | 6 | +| raw `ArrowTableStream`, plain tags: content hash | **6** | 1 | 6 | +| job: function node content and pipeline hash, table paths (sync and async) | **6** | 1 | 6 | +| job: saved `fall_through_tags` | **6** | 1 | 6 | +| `group_by("a")`: rows (member order) | 2 | 1 | 2 (ITL-1226, PR #434) | + +Every other element has one value in all 36 builds: + +- The source: content and pipeline hash, system-tag column names, rows. +- The fall-through pod's rows (tag hashes, data hashes, system tags). +- Join, SemiJoin, MergeJoin over data-tags, Batch, TagBy, MapTags of a data-tag, + DropNulls: content and pipeline hash, system-tag names, rows. +- The job's record ids, the result table's input data hashes, the source and select nodes. + +With the prototype below applied, every element has one value in all 36 builds, except +the `group_by` rows (#434 fixes those). + +The layout-only dependence (first row) comes from operator output keys. Every operator's +output lists its tags in the order of the source's physical table, not in the source's +`keys()` order (question F6). The fall-through tuple takes that order. + +## (a) ITL-1246: the fall-through pod + +**Today.** `FunctionPod.__call__` (`core/function_pod.py:823-866`) takes +`data_tags = stream_data_tags(input_stream)`, which is the input's tag order. It wraps the +pod as `FallThroughPod(pod, data_tags)`. `FallThroughPod.__init__` (`:2016`) keeps +`tuple(fall_through_tags)` as given. Both `identity_structure` and +`pipeline_identity_structure` (`:2072-2076`) are +`(plain_pod, ("fall_through_tags", ))`. + +**Proposed.** The pod holds its data-tags as a set: `tuple(sorted(set(names)))`. The same +element goes into identity, pipeline identity, `to_config` and the saved descriptor. A +sorted tuple, not a `frozenset`: a pod whose input already lists its data-tags in name +order keeps today's hash. Sorted tuples are also the idiom of `DropNulls`, +`Select*`/`Drop*` and `tags_as_data`. + +**Output column order.** The pod's output keeps the data-tags first, in the input's tag +order (the ITL-1205 rule). `output_schema` and `result_data_schema` place them from the +incoming tag schema. Per row, `with_fall_through` places them in the row tag's order. Column +order is presentation only. + +## Every place a list of tag or data-tag names enters a hash, path or name + +| Where | Enters | Ordered today? | +|---|---|---| +| `core/function_pod.py:2072,2075` `FallThroughPod` identity and pipeline identity | content and pipeline hash, so the function node's pipeline table path and every downstream hash and system-tag column name | **yes**, input tag order. Changed here | +| `core/function_pod.py:2040` `to_config`; `pipeline/graph.py:244` descriptor `fall_through_tags` | the saved job file only (not hashed); a load rebuilds the pod from it | **yes**. Written sorted here | +| `core/streams/arrow_table_stream.py:208-215` raw stream identity: `_tag_columns`, `("data_tags", ...)` | raw stream content hash | **yes**. Changed here (ITL-1227) | +| `core/streams/arrow_table_stream.py:237` `_identity_table` row sort by `_all_tag_columns` | raw stream content hash (row order is a table-hash input) | **yes**: user tags in tag order, then system tags in physical column order. Changed here | +| `core/streams/arrow_table_stream.py:244` raw pipeline identity `(tag_schema, data_schema)` | pipeline hash | no: a `Schema` hashes free of key order (checked: `{'a','b'}` equals `{'b','a'}`) | +| `core/sources/base.py:131` source identity: `output_schema()`, `source_id`, `_key_columns` | source content hash | schema no; key columns yes, but that is the explicit `record_id_columns` argument, so by design | +| `core/sources/base.py:185`, `core/nodes/source_node.py:520-530` | pipeline hash, source node identity | no (schemas) | +| `core/sources/derived_source.py:325` `tags_as_data` | content hash | no (sorted items) | +| `core/operators/group_by.py:138` `by` | content and pipeline hash | **yes**. #434 makes it name order | +| `core/operators/tag_by.py:89` names | content and pipeline hash | **yes**. #434 makes it sorted | +| `core/operators/column_selection.py` (all four `Select*`/`Drop*`) | content and pipeline hash | no (`_canonical_columns` sorts) | +| `core/operators/drop_nulls.py:122` | content and pipeline hash | no (sorted) | +| `core/operators/mappers.py:307,586,655` `name_map` | content and pipeline hash | no (dicts hash free of order) | +| `core/operators/add_tags.py:152` `tuple(items)` | content and pipeline hash (pinned: `pipeline/add_tags`) | **yes**, keyword order. Question F5 | +| system-tag column names `::{pipeline_hash}:{position}` (Join, MergeJoin), `::{pipeline_hash}` (Batch, GroupBy) | stored column names | no: canonical order by pipeline hash | +| `core/nodes/function_node.py:189` record-id preimage; tag and data row hashes | record ids, row hashes | no: `hash_table` ignores column order | +| `stream_builder.key_row_identifier` | source record ids | key columns in key order: the explicit argument, by design | +| `core/operators/join.py:96` `join_v1` fold of a data-tag's source info | stored source-info token | no (sorted tokens) | +| `arrow_utils.fold_system_tag_values` (`batch_v1`, `group_v1`) | folded ids | GroupBy member order is ITL-1226 (#434); Batch is row order, not tag order | + +## (b) ITL-1227: the raw `ArrowTableStream` + +**Today** (`arrow_table_stream.py:201-240`). The identity is +`("ArrowTableStream", identity_table, tag_columns)`, plus `("data_tags", data_tags)` when +the stream has any. Both name tuples are in tag order. `_identity_table` sorts the rows by +`_all_tag_columns`: the user tags in tag order, then the system tags in the order of the +physical table. A type Arrow cannot sort (a list tag) leaves the rows unsorted. A stream with +nothing to sort by raises, as on main. + +**Proposed.** + +- `tag_columns` and `data_tags` enter as sorted tuples. +- Rows are sorted by the user tags in name order, then the system tags in name order. Each + key is ascending with nulls last (Arrow's default, unchanged). Rows tied on every tag keep + their given order (stable sort, unchanged). A list tag still leaves the rows unsorted + (unchanged, and pinned by `pipeline/list_tag_producerless_stream`). +- This is the rule #434 uses for GroupBy members: tags in name order, ascending, nulls + last, then the system columns. #434 orders the system columns record id first, then + source id. A raw stream's system-tag columns are arbitrary names, so here plain name + order is the canonical rule. + +**What the comment protects.** "THIS ORDER IS A HASH INPUT AND MUST NOT CHANGE" protects +the content hash of every producer-less stream: the row order it hashes has been that row +order since before ITL-1053. `tests/test_core/streams/test_identity_order_regression.py` +holds a literal copy of main's sort. This change is the approved pre-freeze exception once +the developer accepts the moved list. The comment and the regression test then pin the new +rule: name order, with the battery run in every tag order and system-tag order. + +## (c) Moved golden entries: none + +Measured with the full prototype applied: (a), plus (b) with sorted names and rows ordered +by tag names then system-tag names. The command was +`generate_golden_hashes.py --check`, without regenerating. It reported: +`golden values of semantic, schema, arrow, datagram, pipeline, torch match`. So **0 +entries move**, in every group. + +Why: + +- (a) No golden case has a data-tag. All 25 source fixtures pass `tag_only_columns=True`, + so no `FallThroughPod` is ever built. +- (b) The only pinned raw streams have zero user tags and one system tag + (`tagless_producerless_stream`), or one list tag (`list_tag_producerless_stream`). + With at most one name, sorting changes nothing. + +Operators' internal producer-less results are wrapped in a `DynamicPodStream` with its own +identity, so their content hash is never pinned. + +So no `--remove` is needed. The developer approves the rule (the pre-freeze exception for +the identity-table comment), not a moved list. + +Prototype test run (`tests/test_core/data_tags`, the identity regression test, the saved +data-tag job test, `test_several_items.py`): 39 of 2070 fail. + +- 36 are the regression test shapes with tags `("k", "j")` (not in name order) or system + tags `("s2", "s1")`. These are expected; that test is rewritten to the new rule. +- 3 are output column order (`test_add_tags`, `test_tag_by` job x2). The prototype placed + the fall-through tags in name order; the implementation keeps the input's tag order, so + these 3 stay green. + +## (d) Pins to add (all `pipeline` group, new cases, `--add` only) + +New module-level fixtures go in `tests/test_hashing/golden/cases.py`. Nothing existing is +moved or renamed. Fixtures: + +- `DATA_TAG_ROWS`, `DATA_TAG_SCANS`. +- `_data_tag_sessions()`: a `DictSource` with tags `["subject", "session", "site"]`, + `tag_only_columns=["site"]`. That gives two data-tags and one plain tag, given out of name + order. +- `_data_tag_scans()`: shares the `subject` and `session` data-tags. +- `golden_dt_score`: a function pod over one data column. DO NOT MOVE. + +A new helper, `data_tag_summary`, builds on `stream_summary` and also pins each row's +`_source_` tokens, because source-info tokens are stored. `stream_summary` +itself is not changed, so no existing entry gains keys. + +| Case | Pins | +|---|---| +| `pipeline/data_tag_source` | content and pipeline hash, system-tag names, record ids, data hashes, data-tag source tokens; the same source with `tag_columns` in two orders, pinned equal | +| `pipeline/data_tag_mixed` | a plain tag and two data-tags: summary, and the plain-tag-only form beside it (different) | +| `pipeline/data_tag_fall_through` | `golden_dt_score.pod(src)` in memory: pod and stream hashes, rows; two input tag orders, pinned equal; with and without the automatic select | +| `pipeline/data_tag_fall_through_job` | in a `PipelineJob`, sync: node content and pipeline hashes, table paths, pipeline record ids, result input data hashes. An async run pins the same values under `async.*` | +| `pipeline/data_tag_join` | Join, MergeJoin (colliding data column) and SemiJoin over data-tags: summaries including the `join_v1` source-info token | +| `pipeline/data_tag_group_batch` | `group_by` on a data-tag key and `batch(2)`: summaries (folded ids, `group_v1` token) | +| `pipeline/data_tag_tag_by` | `tag_by` of two data columns on a plain-tag source: operator and stream hashes | +| `pipeline/data_tag_map_tags` | `map_tags` renaming a data-tag | +| `pipeline/data_tag_raw_stream` | a raw `ArrowTableStream` with two data-tags and a plain tag, and two system tags, in two tag orders and two system-tag orders: content hash (equal), pipeline hash | +| `pipeline/data_tag_saved_job` | save the job of `data_tag_fall_through_job` and load it: the saved `fall_through_tags` and `tag_only_columns`, and the loaded nodes' content and pipeline hashes | + +Each case is checked in tests (not only pinned): several orders, sync equal to async. + +## (e) Interactions and order + +- **#448 / #449** (function type id, signature). They move every function pod uri, the pod + and node hashes, and the result paths. The pins that hold a function pod depend on them: + `data_tag_fall_through`, `data_tag_fall_through_job`, `data_tag_saved_job`. +- **#434** (GroupBy member order, `by` in name order, TagBy sorted). `data_tag_group_batch` + and `data_tag_tag_by` depend on it. **#441** (NaN keys) changes nothing for these + fixtures (no NaN), but it shares `pipeline-02.json`. +- **ITL-1266** moves the PolarsFilter cases to a non-frozen file. None of my cases uses + PolarsFilter. It changes the group's file layout, so `--add` must run on its result. + +Proposed order: + +1. Implement (a) and (b), tests and docs now. This PR moves no golden value. +2. When #434, #441, #448, #449 (and ITL-1266) are on `main`, merge `main` into this branch + (a merge, not a rebase). Then add the new cases and run the generator's own `--add` on + main's golden files. +3. Whoever lands second takes main's golden files and re-runs its own tool steps. Digests + are never hand-merged. + +The PR description proves, with a script comparing the union of entries before and after, +that every existing entry is byte-identical and the new ones are additions only. + +## (f) Questions + +**F1. Output order of the fall-through columns.** Should the pod's identity and config hold +the sorted set while its output keeps the data-tags in the input's tag order? Recommended: +yes. Presentation follows the ITL-1205 rule, and identity never depends on it. + +**F2. System tags in the raw-stream row sort.** Should they also go in name order? Today +they follow the physical column order of the table. Recommended: yes; it is the same rule +and moves nothing pinned. + +**F3. Ties and list tags in the raw-stream row sort.** Keep both as they are? Rows tied on +every tag keep their given order. A list tag leaves the rows unsorted, so a raw stream's +content hash depends on its row order there. Recommended: keep. A raw stream's identity is +its rows, and the list-tag behaviour is pinned (`list_tag_producerless_stream`). +Recursively sorting list tags, as `sort_by_tag_columns` does with Polars, would move +that pin. + +**F4. The presentation sort follows tag column order.** `arrow_utils.sort_by_tag_columns` +backs `as_table(sort_by_tags=True)`, `head()`, the preview and `StreamView.sort_by_tags`. +It orders rows by the tags in tag order, then the system tags in column order. Which rows +`head(n)` shows and their order therefore depend on tag order. It is not a hash. +Recommended: name order (the same canonical rule) in a separate issue, or an explicit +`order=` argument on `sort_by_tags`. + +**F5. `AddTags` identity holds its tags in keyword order.** It is `tuple(items)`, pinned in +`pipeline/add_tags`. The order only places the new tags, so it is presentation. +Recommended: as #434 does for `TagBy`, sorted identity and new tags placed in name order, +in a separate pre-freeze issue. Its `every_type` keys are not in name order, so 2 operator +entries and the stream entries of `pipeline/add_tags` would move and need their own list. + +**F6. Operator outputs list tags in the source's physical layout order, not its `keys()` +order.** For a source with `tag_columns=["c", "b", "a", "p"]` over a table laid out +`a, b, c, p`: the source's keys are `c, b, a, p`. Select, DropNulls, MapTags, TagBy, Batch +and DropDataColumns all output `a, b, c, p`. After this PR nothing hash-relevant reads it, +but keys order is inconsistent. Recommended: a low-priority issue. A source's keys should +follow its table, or operators should follow keys. No hash moves either way. + +**F7. The `core/data_tags.py` module docstring** still says data-tag identities "are not +frozen yet ... may still change". Recommended: in this PR, state that they are settled +(2026-11-18) and frozen with v1 at 0.4.0. + +**F8. Explicit order arguments that stay in identity.** These are already consistent with +the principle: a source's `record_id_columns` (key order: record ids and source identity) +and GroupBy's `member_order` (#434). No change. + +## Step 2 outline (after approval) + +TDD. First the failing tests, then the code. + +- Three data-tags in every order (6), mixed with a plain tag, on the sync and the async + path, in memory and in a job: same hashes, table paths and saved descriptor for every + order. +- Raw streams in every tag order and every system-tag order, plain tags and data-tags: + equal content hashes. +- The regression test rewritten to the new rule. + +Then: + +- The code: `FallThroughPod`, the `ArrowTableStream` identity and `_identity_table`, and + the output order helpers. +- Docs: `docs/reference/hashing.md` (fall-through pod identity, raw-stream identity), the + data-tags concept page, `CLAUDE.md` and `.zed/rules`, a `design_issues` entry if one + matches, and `changelog.d/ITL-1246.md`. +- Pins after the dependent PRs land, per (e). diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 2b6da1705..6859e62a7 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -300,6 +300,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | logical-type cell, scalar and container | a value-hashed cell's value hash | the Arrow table hash | `::