diff --git a/.zed/rules b/.zed/rules index 20696ba54..63e52b65f 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1314,8 +1314,9 @@ these preimages anywhere else. 1. Name-preserving — single-stream ops. Column name/value pass through unchanged. 2. Name-extending — multi-input ops. System tag column name gets ::{pipeline_hash}:{canonical_position} appended. Commutative operators sort by - pipeline_hash and sort system tag values per row. MergeJoin is ordered (ITL-1281): the - position is the argument index and nothing is sorted. + pipeline_hash. For tied inputs, Join orders each row's complete provenance bundles, + keeping all of an input's source and record IDs together. MergeJoin is ordered + (ITL-1281): the position is the argument index. 3. Reducing — many→one ops (Batch, GroupBy). Data columns become list[T]; Batch makes every user tag list[T] and keeps it a tag, while GroupBy keeps its scalar keys and drops every other user tag (ITL-1070). No tag ever moves to the data group. Source-info columns become @@ -1529,9 +1530,10 @@ data. The rules: and storage reads enter through the private Arrow stream factory. It preserves system-tag field declarations and requires string values without nulls. Cached source rows also require non-nullable fields without metadata, pending ITL-1561. - Join's sync and batch sort source and record ID pairs within each printed provenance - path. Join rows infer tied system-tag fields from values. Non-tied system-tag fields - keep their Arrow declarations. + Join sorts each row's complete provenance bundles among tied inputs after all operands + are present, keeping each input's source and record IDs together. The sync table, row + channel, and record-batch paths use the declared Arrow system-tag types and nullability, + widening corresponding fields among tied inputs when any declaration is nullable. Streams, rows and record batches declare every `_source_*` token field nullable (ITL-1557). The top-level flag comes from `arrow_utils.source_info_field` and is independent of the token values and of any list item fields. CachedSource writes these fields diff --git a/CLAUDE.md b/CLAUDE.md index 610eb1866..8b45e6619 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1344,8 +1344,9 @@ are defined in one module, `core/row_ids.py`; never build one of these preimages through unchanged. 2. **Name-extending** — multi-input ops (join, merge join). Each input's system tag column name gets `::{pipeline_hash}:{canonical_position}` appended. Commutative operators - canonically order inputs by `pipeline_hash` and sort system tag values per row. `MergeJoin` - is ordered (ITL-1281): the position is the argument index and nothing is sorted. + canonically order inputs by `pipeline_hash`. For tied inputs, `Join` orders each row's + complete provenance bundles, keeping all of an input's source and record IDs together. + `MergeJoin` is ordered (ITL-1281): the position is the argument index. 3. **Reducing** — many→one ops (`Batch`, `GroupBy`). Data columns become `list[T]`; `Batch` makes every user tag `list[T]` and keeps it a tag, while `GroupBy` keeps its scalar keys and drops every other user tag (ITL-1070). No tag ever moves to the data group. Source-info @@ -1574,9 +1575,10 @@ data. The rules: and storage reads enter through the private Arrow stream factory. It preserves system-tag field declarations and requires string values without nulls. Cached source rows also require non-nullable fields without metadata, pending ITL-1561. - Join's sync and batch sort source and record ID pairs within each printed provenance - path. Join rows infer tied system-tag fields from values. Non-tied system-tag fields - keep their Arrow declarations. + Join sorts each row's complete provenance bundles among tied inputs after all operands + are present, keeping each input's source and record IDs together. The sync table, row + channel, and record-batch paths use the declared Arrow system-tag types and nullability, + widening corresponding fields among tied inputs when any declaration is nullable. Streams, rows and record batches declare every `_source_*` token field nullable (ITL-1557). The top-level flag comes from `arrow_utils.source_info_field` and is independent of the token values and of any list item fields. CachedSource writes these fields diff --git a/changelog.d/ITL-1628.md b/changelog.d/ITL-1628.md new file mode 100644 index 000000000..2ef4955ae --- /dev/null +++ b/changelog.d/ITL-1628.md @@ -0,0 +1,12 @@ +### Breaking changes and migration + +- Entry IDs can change for rows from a Join with structurally tied inputs, such + as a diamond whose old output mixed branches' provenance. Recompute affected + outputs and any downstream results keyed by their entry IDs. The same stored + path can contain old and corrected records if it is reused. + +### Fixed + +- Join keeps all source and record IDs of each tied input together, including + joined and folded provenance. Tables, row channels, and record batches use + the same ordering and keep the declared nullability of the identifiers. diff --git a/docs/dev/design_issues/ITL-1628-CJ1.md b/docs/dev/design_issues/ITL-1628-CJ1.md new file mode 100644 index 000000000..8b7053c44 --- /dev/null +++ b/docs/dev/design_issues/ITL-1628-CJ1.md @@ -0,0 +1,13 @@ +## `src/orcapod/core/operators/join.py` — tied inputs + +### CJ1 — Tied diamond Joins mix provenance between branches +**Status:** resolved +**Severity:** high +**Issue:** ITL-1628 + +Sorting each source/record pair independently could mix leaves of tied nested +Joins. For example, branches over `(0, a, z)` and `(0, b, c)` could become +`(0, a, c)` and `(0, b, z)`. + +**Fix:** Join compares each tied operand's complete provenance tuple and moves +all of its source and record IDs together. diff --git a/docs/dev/design_issues/ITL-1629-CJ2.md b/docs/dev/design_issues/ITL-1629-CJ2.md new file mode 100644 index 000000000..8b28c7d42 --- /dev/null +++ b/docs/dev/design_issues/ITL-1629-CJ2.md @@ -0,0 +1,13 @@ +## `src/orcapod/core/operators/join.py` — tied inputs + +### CJ2 — Pairwise row joins diverged from tables on sparse system tags +**Status:** resolved +**Severity:** high +**Issue:** ITL-1629 + +A custom system tag missing from one tied operand could appear at different +positions on row channels and tables. + +**Fix:** ITL-1751 reserves system tags for the library. For its paired +identifiers, the row channel, table and batch kernel use the same whole-bundle +ordering after the last join step. The regression covers three tied operands. diff --git a/docs/dev/design_issues/ITL-1631-CJ3.md b/docs/dev/design_issues/ITL-1631-CJ3.md new file mode 100644 index 000000000..1fe0f56bc --- /dev/null +++ b/docs/dev/design_issues/ITL-1631-CJ3.md @@ -0,0 +1,12 @@ +## `src/orcapod/core/operators/join.py` — tied inputs + +### CJ3 — Tied Join rows narrowed record ID declarations +**Status:** resolved +**Severity:** high +**Issue:** ITL-1631 + +Row channels and table iteration inferred tied record ID fields from individual +values, even when the table declared those fields nullable. + +**Fix:** Join preserves Arrow field declarations on every path. A position's +record ID field is nullable when any corresponding input field is nullable. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index ae1a5c41e..904a0ba6d 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1263,10 +1263,12 @@ and `k` such stages stacked carry each one `2 ** k` times (ITL-1114). The table `head()` and the notebook preview of a stream that has not run are built from carries the system tag columns too, so those calls are as wide as the joins make them (ITL-1132). -Join sorts source and record IDs as pairs within each printed provenance path. -Sync and record-batch tables keep custom system tags in their input positions. -Standalone row channels sort custom tags on the same path with the ID pair. -Join rows on these tied paths infer their system-tag fields from values. +For inputs with the same pipeline hash, Join orders each row's complete provenance bundles. +All source and record IDs of one input travel together, including IDs from earlier joins +and folds. It orders provenance paths by name and compares the source ID before the record +ID at each path. A standalone raw stream has an empty provenance bundle, which comes first. +Tables, row channels, and record batches keep the same field declarations. A field is +nullable if any corresponding field that can move into it is nullable. --- diff --git a/src/orcapod/contexts/data/v1.json b/src/orcapod/contexts/data/v1.json index 107a08dbd..0450514e5 100644 --- a/src/orcapod/contexts/data/v1.json +++ b/src/orcapod/contexts/data/v1.json @@ -253,10 +253,10 @@ "date": "2026-11-29", "release": null, "added": { - "pipeline-02.json": "cca93cb45ed48622bc58e77d344f8e536a89ee1d5da63c6a8d0b121361c64b5f" + "pipeline-02.json": "b4566234fe4fe71cb0eece34ee2987c95dac503beb40896df1d7acb4d17121f6" }, "previous": "4d7e6efa1eb0e72175a18d6b40b933d61c6817b1499d590b10e7d016b642f6ba", - "digest": "a900909f035bbec5eb67869b6b0c87648bcf3446171f2d16a862f5f3e672c437" + "digest": "5f06ae2f640b36fe24b6c04648495dd2d6643d7d4c501cfaa3f87803ebf8a917" } ], "provisional": { diff --git a/src/orcapod/core/datagrams/tag_data.py b/src/orcapod/core/datagrams/tag_data.py index 2b3d7f124..9b0c286d1 100644 --- a/src/orcapod/core/datagrams/tag_data.py +++ b/src/orcapod/core/datagrams/tag_data.py @@ -18,7 +18,7 @@ import logging import uuid -from collections.abc import Collection, Iterator, Mapping, Sequence +from collections.abc import Iterator, Mapping, Sequence from typing import cast, TYPE_CHECKING, Any, Self import pyarrow as pa @@ -204,8 +204,6 @@ def rows_of( cls, table: "pa.Table", data_context: "str | contexts.DataContext | None" = None, - *, - infer_system_tags: Collection[str] = (), ) -> Iterator[Self]: """Yield the tag of each row of ``table``, in row order. @@ -220,7 +218,6 @@ def rows_of( table: The rows: user-tag and system-tag columns. data_context: The data context of every tag; ``None`` reads each row's own from the table's data-context column, or takes the default. - infer_system_tags: Tied Join fields built from Python values. Yields: One tag per row. @@ -234,20 +231,6 @@ def rows_of( for tag, system_tag_row, _ in rows: if system_tag_row is None: tag._set_system_tags({}) - elif infer_system_tags: - names = system_tag_row.column_names - infer = [name for name in names if name in infer_system_tags] - values = tag.converter.arrow_table_to_python_dicts( - system_tag_row.select(infer) - )[0] - tag._set_system_tags(values) - if len(infer) != len(names): - kept = system_tag_row.drop_columns(infer) - tag._set_system_tag_table( - arrow_utils.hstack_tables( - kept, tag._ensure_system_tags_table() - ).select(names) - ) else: tag._set_system_tag_table(system_tag_row) yield tag diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 611e0c242..bbdb1794c 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1490,17 +1490,6 @@ def _store_output_stream(self, stream: StreamProtocol) -> None: declared = self._typed_zero_row_table() if declared is not None: - from orcapod.core.operators.join import Join - - # On tied Join paths, the table describes the input declarations - # while rows infer their own provenance fields from the values. - row_inferred = ( - self._operator.row_inferred_system_tags( - self._input_streams, declared.column_names - ) - if isinstance(self._operator, Join) - else frozenset() - ) expected_fields = {field.name: field for field in declared.schema} actual_fields = {field.name: field for field in output_table.schema} for name in sorted(expected_fields.keys() | actual_fields.keys()): @@ -1509,10 +1498,7 @@ def _store_output_stream(self, stream: StreamProtocol) -> None: if ( expected is not None and actual is not None - and ( - name in row_inferred - or expected.equals(actual, check_metadata=True) - ) + and expected.equals(actual, check_metadata=True) ): continue raise InputValidationError( diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index ff3c1fb35..b7b99e3e5 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -2,8 +2,8 @@ import functools import itertools import json -from collections import Counter -from collections.abc import Callable, Collection, Iterator, Sequence +import re +from collections.abc import Callable, Collection, Sequence from typing import Any, ClassVar, get_args import polars as pl @@ -76,27 +76,158 @@ _COMMON_JOIN_KEY = "_common" -def repeated_system_tag_suffixes(suffixes: Sequence[str]) -> frozenset[str]: - """Return the printed positional suffixes whose hash prefix occurs twice or more.""" - prefixes = [suffix.rsplit(constants.FIELD_SEPARATOR, 1)[0] for suffix in suffixes] - counts = Counter(prefixes) - return frozenset( - constants.BLOCK_SEPARATOR + suffix - for suffix, prefix in zip(suffixes, prefixes, strict=True) - if counts[prefix] > 1 - ) +# A source schema digest followed by joined or folded pipeline digests. +_PROVENANCE_PATH = re.compile(r"[0-9a-f]{64}(?:::[0-9a-f]{64}(?::(?:0|[1-9][0-9]*))?)*") + + +@functools.lru_cache(maxsize=256) +def _system_tag_bundle_layout( + names: tuple[str, ...], suffixes: tuple[str, ...] +) -> tuple[tuple[str, ...], tuple[str, ...], tuple[tuple[tuple[str, ...], ...], ...]]: + """Plan column moves and align comparable bundles by their provenance paths.""" + source_prefix, record_prefix = arrow_utils.system_tag_column_names("") + by_suffix: dict[str, set[str]] = {suffix: set() for suffix in suffixes} + for name in names: + base, _, suffix = name.rpartition(constants.BLOCK_SEPARATOR) + prefix, separator, path = base.partition(constants.BLOCK_SEPARATOR) + if ( + suffix not in by_suffix + or prefix + separator not in (source_prefix, record_prefix) + or not _PROVENANCE_PATH.fullmatch(path) + ): + raise InputValidationError( + f"Join: unrecognized system-tag column {name!r}." + ) + by_suffix[suffix].add(base) + groups: dict[str, list[str]] = {} + for suffix, fields in by_suffix.items(): + for field in fields: + _, _, path = field.partition(constants.BLOCK_SEPARATOR) + if not set(arrow_utils.system_tag_column_names(path)) <= fields: + raise InputValidationError( + f"Join: system-tag column {field!r} has no matching identifier column." + ) + digest, _, _ = suffix.rpartition(constants.FIELD_SEPARATOR) + groups.setdefault(digest, []).append(suffix) + + inputs: dict[str, tuple[str, ...]] = {} + outputs: dict[str, tuple[str, ...]] = {} + tied = [] + for group in groups.values(): + if len(group) < 2: + continue + group.sort( + key=lambda suffix: int(suffix.rsplit(constants.FIELD_SEPARATOR, 1)[1]) + ) + paths = { + suffix: tuple( + name + for source in sorted( + field + for field in by_suffix[suffix] + if field.startswith(source_prefix) + ) + for name in (source, record_prefix + source.removeprefix(source_prefix)) + ) + for suffix in group + } + # A standalone raw stream can tie with a source and carry no provenance. + # Order layouts first (an empty bundle first), then sort values among + # operands with the same layout so every row has the same columns. + ranked = sorted(group, key=paths.__getitem__) + matched: dict[tuple[str, ...], list[tuple[str, ...]]] = {} + if len(set(paths.values())) > 1: + group_names = [ + ( + f"{name}{constants.BLOCK_SEPARATOR}{current}", + f"{name}{constants.BLOCK_SEPARATOR}{position}", + ) + for current, position in zip(ranked, group, strict=True) + for name in paths[current] + ] + inputs[group[0]], outputs[group[0]] = map( + tuple, zip(*group_names, strict=True) + ) + for current, position in zip(ranked, group, strict=True): + if shape := paths[current]: + matched.setdefault(shape, []).append( + tuple( + f"{name}{constants.BLOCK_SEPARATOR}{position}" for name in shape + ) + ) + tied.extend(tuple(group) for group in matched.values() if len(group) > 1) + + # Keep the existing physical layout for equally shaped ties and untied + # operands. For a mixed layout, fill its column slots in canonical order. + def column_order(moves: dict[str, tuple[str, ...]]) -> tuple[str, ...]: + slots = {name: suffix for suffix, group in inputs.items() for name in group} + ordered = {suffix: iter(group) for suffix, group in moves.items()} + return tuple( + next(ordered[suffix]) if (suffix := slots.get(name)) else name + for name in names + ) + + return column_order(inputs), column_order(outputs), tuple(tied) -def _system_tag_names_with_suffixes( - names: Collection[str], suffixes: Collection[str] -) -> frozenset[str]: - """Select system-tag fields from operands whose printed hash suffix is shared.""" - endings = tuple(suffixes) - return frozenset( + +def sort_join_system_tag_bundles(table: pa.Table, suffixes: Sequence[str]) -> pa.Table: + """Sort each row's tied operands as whole bundles, with null IDs last.""" + names = tuple( name - for name in names - if name.startswith(constants.SYSTEM_TAG_PREFIX) and name.endswith(endings) + for name in table.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) ) + original, canonical, ties = _system_tag_bundle_layout(names, tuple(suffixes)) + if original != names or canonical != names: + columns = set(names) + source, target = iter(original), iter(canonical) + indices = [ + next(source) if name in columns else name for name in table.column_names + ] + renamed = [ + next(target) if name in columns else name for name in table.column_names + ] + table = table.select(indices).rename_columns(renamed) + for bundles in ties: + fields = [ + tuple(table.schema.field(name) for name in bundle) for bundle in bundles + ] + if any( + not pa.types.is_large_string(field.type) + for bundle in fields + for field in bundle + ): + raise InputValidationError( + "Join: system-tag identifiers must be large strings." + ) + nullable = [ + any(field.nullable for field in aligned) + for aligned in zip(*fields, strict=True) + ] + members = [ + zip(*(table[name].to_pylist() for name in bundle), strict=True) + for bundle in bundles + ] + ordered_rows = [ + sorted( + row, + key=lambda bundle: tuple((value is None, value) for value in bundle), + ) + for row in zip(*members, strict=True) + ] + for position, bundle in enumerate(fields): + for index, field in enumerate(bundle): + # A tied field can receive the value declared by any member. + declared = pa.field(field.name, field.type, nullable=nullable[index]) + table = table.set_column( + table.schema.get_field_index(field.name), + declared, + pa.array( + [row[position][index] for row in ordered_rows], type=field.type + ), + ) + return table def _with_common_key(table: "pa.Table") -> "pa.Table": @@ -611,18 +742,28 @@ def _predict_system_tag_schema(self, *streams: StreamProtocol) -> Schema: f"{stream.pipeline_hash().to_hex()}:{idx}" ) system_tag_fields[new_name] = col_type - nullable = arrow_utils.sorted_system_tag_nullability( - { - name: kind is type(None) or type(None) in get_args(kind) - for name, kind in system_tag_fields.items() - } + suffixes = tuple( + self._compute_system_tag_suffixes( + [stream.pipeline_hash() for stream in streams] + ) ) - return Schema( - { - name: kind | None if nullable[name] else kind - for name, kind in system_tag_fields.items() - } + original, canonical, ties = _system_tag_bundle_layout( + tuple(system_tag_fields), suffixes ) + system_tag_fields = { + target: system_tag_fields[source] + for source, target in zip(original, canonical, strict=True) + } + for bundles in ties: + for aligned in zip(*bundles, strict=True): + if any( + (kind := system_tag_fields[name]) is type(None) + or type(None) in get_args(kind) + for name in aligned + ): + for name in aligned: + system_tag_fields[name] |= type(None) + return Schema(system_tag_fields) def static_process(self, *streams: StreamProtocol) -> StreamProtocol: """Join the streams on their shared tag columns. @@ -743,8 +884,10 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: for name in sorted(merged_source): table = self._fold_source_column(table, name) - # Sort system tag values for same-pipeline-hash streams to ensure commutativity - table = arrow_utils.sort_system_tag_values(table) + suffixes = self._compute_system_tag_suffixes( + [stream.pipeline_hash() for stream in streams] + ) + table = sort_join_system_tag_bundles(table, suffixes) # Lay the columns out in the order ``output_schema`` defines (see # ``_joined_user_schemas``): tags, then data, then the hidden columns. @@ -760,52 +903,12 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: + data_order + [col for col in table.column_names if col not in listed] ) - return self._join_result_stream( + return ArrowTableStream._from_derived_table( result_table, - streams, tag_columns=tuple(tag_order), data_tags=data_tag_names(tag_schema, data_schema), ) - def row_inferred_system_tags( - self, streams: Sequence[StreamProtocol], names: Collection[str] - ) -> frozenset[str]: - """Return the Join output columns whose row tags are built from values.""" - suffixes = self._compute_system_tag_suffixes( - [stream.pipeline_hash() for stream in streams] - ) - return _system_tag_names_with_suffixes( - names, repeated_system_tag_suffixes(suffixes) - ) - - def _join_result_stream( - self, - result_table: pa.Table, - streams: Sequence[StreamProtocol], - *, - tag_columns: Collection[str], - data_tags: Collection[str], - ) -> ArrowTableStream: - """Keep the table's fields and apply tied provenance inference to row reads.""" - inferred = self.row_inferred_system_tags(streams, result_table.column_names) - if any( - field.name in inferred - and ( - field.nullable - or field.metadata - or not pa.types.is_large_string(field.type) - ) - for field in result_table.schema - ): - tied = _TiedJoinStream._from_derived_table( - result_table, tag_columns=tag_columns, data_tags=data_tags - ) - tied._inferred_system_tags = inferred - return tied - return ArrowTableStream._from_derived_table( - result_table, tag_columns=tag_columns, data_tags=data_tags - ) - @staticmethod def _merge_source_columns( table: "pa.Table", left_name: str, right_name: str @@ -1005,7 +1108,6 @@ async def _streaming_join( """ n = len(inputs) if n == 2: - repeated_suffixes = repeated_system_tag_suffixes(suffixes) # Join in canonical order so the merged tag and data keys follow # the order ``output_schema`` defines, whatever the operand order. left_idx, right_idx = self._canonical_input_order(suffixes) @@ -1017,9 +1119,7 @@ def merge_fn( rt: TagProtocol, rp: DataProtocol, ) -> tuple[TagProtocol, DataProtocol]: - return self._merge_pair_rename( - lt, lp, rt, rp, pair_suffixes, repeated_suffixes - ) + return self._merge_pair_rename(lt, lp, rt, rp, pair_suffixes) await self._binary_streaming_join( inputs[left_idx], @@ -1087,7 +1187,6 @@ async def _staggered_join( # compared with every other input's as it arrives, whether or not any row # matches (the sync path compares the inputs' tables before it joins). first_rows: dict[int, tuple[TagProtocol, DataProtocol]] = {} - repeated_suffixes = repeated_system_tag_suffixes(suffixes) def declare(position: int, tag: TagProtocol, data: DataProtocol) -> None: for other, (other_tag, other_data) in sorted(first_rows.items()): @@ -1110,7 +1209,6 @@ def declare(position: int, tag: TagProtocol, data: DataProtocol) -> None: inputs[orig_idx], ch.writer, suffixes[orig_idx], - repeated_suffixes, functools.partial(declare, position), ) ) @@ -1137,7 +1235,7 @@ def declare(position: int, tag: TagProtocol, data: DataProtocol) -> None: self._merge_pair_passthrough, final=is_last, merged_so_far=merged_so_far, - repeated_suffixes=repeated_suffixes, + suffixes=suffixes, ), ) ) @@ -1331,7 +1429,6 @@ async def _rename_sys_tags( ch_in: ReadableChannel[tuple[TagProtocol, DataProtocol]], ch_out: WritableChannel[tuple[TagProtocol, DataProtocol]], suffix: str, - repeated_suffixes: Collection[str], on_first_row: Callable[[TagProtocol, DataProtocol], None], ) -> None: """Read rows and rename system-tag keys by appending the per-input suffix. @@ -1352,7 +1449,6 @@ async def _rename_sys_tags( Join._merge_tag_tables(tag, None), arrow_utils.append_to_system_tags(system_tags, suffix), tag.data_context_key, - repeated_suffixes, ) await ch_out.send((tag, pkt)) finally: @@ -1439,35 +1535,13 @@ def _build_tag( table: "pa.Table | None", system_tags: "pa.Table | None", data_context_key: str, - repeated_suffixes: Collection[str], ) -> TagProtocol: - """Build a tag, sorting by value for tied system-tag paths.""" + """Build a tag from its declared Arrow fields.""" if system_tags is None: return Tag( table if table is not None else {}, data_context=data_context_key ) - names = system_tags.column_names - tied_names = _system_tag_names_with_suffixes(names, repeated_suffixes) - if tied_names: - from orcapod.contexts import resolve_context - - converter = resolve_context(data_context_key).type_converter - tied = system_tags.select([name for name in names if name in tied_names]) - values = Join._sort_merged_system_tags( - converter.arrow_table_to_python_dicts(tied)[0] - ) - if len(tied_names) == len(names): - return Tag( - table if table is not None else {}, - system_tags=values, - data_context=data_context_key, - ) - inferred = Tag({}, system_tags=values, data_context=data_context_key) - kept = system_tags.drop_columns(list(tied_names)) - inferred_table = inferred._ensure_system_tags_table() # pyright: ignore[reportPrivateUsage] # use Tag's system-field inference - system_tags = arrow_utils.hstack_tables(kept, inferred_table).select(names) - if table is not None: system_tags = arrow_utils.hstack_tables(table, system_tags) return Tag(system_tags, data_context=data_context_key) @@ -1713,7 +1787,6 @@ def _merge_pair_rename( right_tag: TagProtocol, right_pkt: DataProtocol, suffixes: list[str], - repeated_suffixes: Collection[str], ) -> tuple[TagProtocol, DataProtocol]: """Merge a matched pair, renaming system tags with per-side suffixes. @@ -1726,12 +1799,15 @@ def _merge_pair_rename( for tag, suffix in zip((left_tag, right_tag), suffixes, strict=True) if (table := Join._system_tag_table(tag)) is not None ] - merged_sys = arrow_utils.hstack_tables(*tables) if tables else None + merged_sys = ( + sort_join_system_tag_bundles(arrow_utils.hstack_tables(*tables), suffixes) + if tables + else None + ) merged_tag = Join._build_tag( Join._merge_tag_tables(left_tag, right_tag), merged_sys, left_tag.data_context_key, - repeated_suffixes, ) return merged_tag, Join._merge_data(left_tag, left_pkt, right_tag, right_pkt) @@ -1742,7 +1818,7 @@ def _merge_pair_passthrough( right_tag: TagProtocol, right_pkt: DataProtocol, *, - repeated_suffixes: Collection[str], + suffixes: Sequence[str], final: bool = True, merged_so_far: set[str] | None = None, ) -> tuple[TagProtocol, DataProtocol]: @@ -1760,11 +1836,12 @@ def _merge_pair_passthrough( if (table := Join._system_tag_table(tag)) is not None ] merged_sys = arrow_utils.hstack_tables(*tables) if tables else None + if final and merged_sys is not None: + merged_sys = sort_join_system_tag_bundles(merged_sys, suffixes) merged_tag = Join._build_tag( Join._merge_tag_tables(left_tag, right_tag), merged_sys, left_tag.data_context_key, - repeated_suffixes, ) return merged_tag, Join._merge_data( left_tag, @@ -1775,64 +1852,6 @@ def _merge_pair_passthrough( merged_so_far=merged_so_far, ) - @staticmethod - def _sort_merged_system_tags(merged_sys: dict) -> dict: - """Sort system tag values within same-provenance-path groups. - - When two joined inputs share a pipeline_hash, their system tag - columns share a provenance path but occupy different canonical - positions. Sorting the paired (source_id, record_id) values - across positions ensures commutativity — mirroring what - ``sort_system_tag_values`` does on Arrow tables in - ``static_process``. - """ - sys_prefix = constants.SYSTEM_TAG_PREFIX - block_sep = constants.BLOCK_SEPARATOR - field_sep = constants.FIELD_SEPARATOR - - # Parse keys → groups[provenance_path][position][field_type] = key - groups: dict[str, dict[str, dict[str, str]]] = {} - for key in merged_sys: - if not key.startswith(sys_prefix): - continue - base, sep, position = key.rpartition(field_sep) - if not sep or not position.isdigit(): - continue - after_prefix = base[len(sys_prefix) :] - field_type, bsep, prov_path = after_prefix.partition(block_sep) - if not bsep: - continue - groups.setdefault(prov_path, {}).setdefault(position, {})[field_type] = key - - sid_field = constants.SYSTEM_TAG_SOURCE_ID_PREFIX[len(sys_prefix) :] - rid_field = constants.SYSTEM_TAG_RECORD_ID_PREFIX[len(sys_prefix) :] - - for _prov_path, positions in groups.items(): - if len(positions) <= 1: - continue - - sorted_pos_keys = sorted(positions.keys(), key=int) - - # Collect (sort_key, {field_type: value}) per position - entries: list[tuple[tuple, dict[str, object]]] = [] - for pos in sorted_pos_keys: - fmap = positions[pos] - sid_val = merged_sys.get(fmap.get(sid_field, "")) - rid_val = merged_sys.get(fmap.get(rid_field, "")) - vals = {ft: merged_sys[k] for ft, k in fmap.items()} - entries.append(((sid_val or "", rid_val or b""), vals)) - - entries.sort(key=lambda e: e[0]) - - # Write sorted values back to the original position keys - for pos, (_, sorted_vals) in zip(sorted_pos_keys, entries): - fmap = positions[pos] - for field_type, key in fmap.items(): - if field_type in sorted_vals: - merged_sys[key] = sorted_vals[field_type] - - return merged_sys - def rows_dropped_text( self, position: int, @@ -1851,14 +1870,3 @@ def identity_structure(self) -> Any: def __repr__(self) -> str: return "Join()" - - -class _TiedJoinStream(ArrowTableStream): - """A Join table whose tied system-tag fields are inferred on row reads.""" - - _inferred_system_tags: frozenset[str] - - def _iter_tags(self, table: pa.Table) -> Iterator[Tag]: - return Tag.rows_of( - table, self.data_context, infer_system_tags=self._inferred_system_tags - ) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 8bf696552..0efc2fc3b 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -76,7 +76,7 @@ from __future__ import annotations from abc import ABC, abstractmethod -from collections.abc import Callable, Collection, Mapping, Sequence +from collections.abc import Callable, Mapping, Sequence from typing import Any, ClassVar import numpy as np @@ -94,7 +94,7 @@ _matched_pairs, # pyright: ignore[reportPrivateUsage] # Join's one rule _with_common_key, # pyright: ignore[reportPrivateUsage] # Join's one rule null_token_list_error, - repeated_system_tag_suffixes, + sort_join_system_tag_bundles, ) from orcapod.core.operators.base import require_shared_arrow_type from orcapod.core.operators.merge_join import ( @@ -130,9 +130,7 @@ _ROW = ("__streaming_left_row", "__streaming_right_row") -def _row_built_zero_rows( - stream: StreamProtocol, *, strip_system_tag_metadata: bool = False -) -> tuple[StreamProtocol, bool]: +def _row_built_zero_rows(stream: StreamProtocol) -> tuple[StreamProtocol, bool]: """``stream`` with no rows, as an input rebuilt from rows of it reads. The zero-row input (``_materialize_upstream`` with no rows) put through F: what @@ -140,7 +138,6 @@ def _row_built_zero_rows( Args: stream: An input stream (its description). - strip_system_tag_metadata: Use the row-built fields of a tied Join input. Returns: The zero-row stream in the row-built form, and whether its Arrow types differ @@ -151,14 +148,6 @@ def _row_built_zero_rows( zero = pod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the operators' one form of an input table = zero.as_table(columns=ZERO_ROW_INPUT_COLUMNS) row_built = row_built_columns(table, stream.keys()).replace_schema_metadata(None) - if strip_system_tag_metadata: - fields = [ - field.remove_metadata() - if field.name.startswith(constants.SYSTEM_TAG_PREFIX) - else field - for field in row_built.schema - ] - row_built = pa.Table.from_arrays(row_built.columns, schema=pa.schema(fields)) differs = any( field.type != table.schema.field(field.name).type for field in row_built.schema ) @@ -411,8 +400,6 @@ def __init__( self, operator: StaticOutputOperatorPod, inputs: Sequence[StreamProtocol], - *, - strip_system_tag_metadata: Collection[int] = (), ) -> None: if not inputs or (self.ARITY is not None and len(inputs) != self.ARITY): raise ValueError( @@ -424,12 +411,7 @@ def __init__( self.inputs: tuple[StreamProtocol, ...] = tuple(inputs) # Each input as the sync path reads rows of it, with no rows (the row-built # form), and whether that differs from how it reads the input with none. - built = [ - _row_built_zero_rows( - stream, strip_system_tag_metadata=index in strip_system_tag_metadata - ) - for index, stream in enumerate(self.inputs) - ] + built = [_row_built_zero_rows(stream) for stream in self.inputs] self._zero_rows: tuple[StreamProtocol, ...] = tuple(z for z, _ in built) self._null_typed: tuple[bool, ...] = tuple(d for _, d in built) # Every batch uses its input's declared fields in the row-built layout. @@ -687,17 +669,8 @@ class StreamingJoin(StreamingJoinKernel): def __init__(self, operator: Join, inputs: Sequence[StreamProtocol]) -> None: hashes = [stream.pipeline_hash() for stream in inputs] - suffixes = operator._compute_system_tag_suffixes(hashes) # pyright: ignore[reportPrivateUsage] # Join's naming rule - repeated = repeated_system_tag_suffixes(suffixes) - super().__init__( - operator, - inputs, - strip_system_tag_metadata={ - i - for i, suffix in enumerate(suffixes) - if constants.BLOCK_SEPARATOR + suffix in repeated - }, - ) + self._suffixes = operator._compute_system_tag_suffixes(hashes) # pyright: ignore[reportPrivateUsage] # Join's naming rule + super().__init__(operator, inputs) self._join = operator order = sorted(range(len(inputs)), key=lambda i: hashes[i].to_hex()) self._position = {index: position for position, index in enumerate(order)} @@ -766,7 +739,7 @@ def finish( return table for name in sorted(self._merged_source): table = Join._fold_source_column(table, name) # pyright: ignore[reportPrivateUsage] # Join's one rule - return arrow_utils.sort_system_tag_values(table) + return sort_join_system_tag_bundles(table, self._suffixes) return finish diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 3f2b56572..3da7acb64 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -1762,177 +1762,6 @@ def aggregated_list_array( return pa.LargeListArray.from_arrays(offsets, values, type=list_type) -def _parse_system_tag_column( - col_name: str, -) -> tuple[str, str, str] | None: - """Parse a system tag column name into (field_type, provenance_path, position). - - For example: - _tag_source_id::abc123::def456:0 - → field_type="source_id", provenance_path="abc123::def456", position="0" - - _tag_record_id::abc123::def456:0 - → field_type="record_id", provenance_path="abc123::def456", position="0" - - Returns None if the column doesn't end with a :position suffix. - """ - # Strip the trailing :position - base, sep, position = col_name.rpartition(constants.FIELD_SEPARATOR) - if not sep or not position.isdigit(): - return None - - # Determine field type by checking known prefixes - prefix = constants.SYSTEM_TAG_PREFIX - if not base.startswith(prefix): - return None - - after_prefix = base[len(prefix) :] # e.g. "source_id::abc123::def456" - - # Extract field_type and provenance_path - # field_type is everything before the first BLOCK_SEPARATOR - field_type, block_sep, provenance_path = after_prefix.partition( - constants.BLOCK_SEPARATOR - ) - if not block_sep: - return None - - return field_type, provenance_path, position - - -def _system_tag_position_groups( - names: Collection[str], -) -> dict[str, dict[str, dict[str, str]]]: - """Group system-tag columns by provenance path, position, and field kind.""" - groups: dict[str, dict[str, dict[str, str]]] = {} - for name in names: - if (parsed := _parse_system_tag_column(name)) is not None: - field_type, provenance_path, position = parsed - groups.setdefault(provenance_path, {}).setdefault(position, {})[ - field_type - ] = name - return groups - - -def sorted_system_tag_nullability( - nullable_by_name: Mapping[str, bool], -) -> dict[str, bool]: - """Give each movable system-tag field the nullability of all its inputs.""" - nullable = dict(nullable_by_name) - for positions in _system_tag_position_groups(nullable).values(): - if len(positions) <= 1: - continue - for prefix in ( - constants.SYSTEM_TAG_SOURCE_ID_PREFIX, - constants.SYSTEM_TAG_RECORD_ID_PREFIX, - ): - kind = prefix.removeprefix(constants.SYSTEM_TAG_PREFIX) - names = [fields[kind] for fields in positions.values() if kind in fields] - can_hold_null = len(names) != len(positions) or any( - nullable_by_name[name] for name in names - ) - nullable.update(dict.fromkeys(names, can_hold_null)) - return nullable - - -def sort_system_tag_values(table: "pa.Table") -> "pa.Table": - """Sort paired system tag values for columns that share the same provenance path. - - System tag columns come in (source_id, record_id) pairs. Columns that differ - only by their canonical position (the final :N) represent streams with the same - pipeline_hash that were joined. For commutativity, paired (source_id, record_id) - tuples must be sorted together per row so that the result is independent of - input order. - - Algorithm: - 1. Parse each system tag column into (field_type, provenance_path, position) - 2. Group by provenance_path — source_id and record_id at the same path+position - are paired - 3. For each group with >1 position, sort per-row by (source_id, record_id) tuples - 4. Assign sorted values back to both columns at each position - """ - sys_tag_cols = [ - c for c in table.column_names if c.startswith(constants.SYSTEM_TAG_PREFIX) - ] - - if not sys_tag_cols: - return table - - groups = _system_tag_position_groups(sys_tag_cols) - nullable = sorted_system_tag_nullability( - {name: table.schema.field(name).nullable for name in sys_tag_cols} - ) - - source_id_field = constants.SYSTEM_TAG_SOURCE_ID_PREFIX[ - len(constants.SYSTEM_TAG_PREFIX) : - ] - record_id_field = constants.SYSTEM_TAG_RECORD_ID_PREFIX[ - len(constants.SYSTEM_TAG_PREFIX) : - ] - - # For each provenance_path group with >1 position, sort paired tuples per row - for positions in groups.values(): - if len(positions) <= 1: - continue - - # Sort positions numerically - sorted_positions = sorted(positions.keys(), key=int) - - # Collect paired column names for each position - paired_cols: list[tuple[str | None, str | None]] = [] - for pos in sorted_positions: - field_map = positions[pos] - sid_col = field_map.get(source_id_field) - rid_col = field_map.get(record_id_field) - paired_cols.append((sid_col, rid_col)) - - # Get values for all paired columns - sid_values = [] - rid_values = [] - for sid_col, rid_col in paired_cols: - sid_values.append( - table.column(sid_col).to_pylist() - if sid_col - else [None] * table.num_rows - ) - rid_values.append( - table.column(rid_col).to_pylist() - if rid_col - else [None] * table.num_rows - ) - - # Sort per row by (source_id, record_id) tuples - n_positions = len(sorted_positions) - sorted_sid: list[list] = [[] for _ in range(n_positions)] - sorted_rid: list[list] = [[] for _ in range(n_positions)] - - for row_idx in range(table.num_rows): - row_tuples = [ - (sid_values[pos_idx][row_idx], rid_values[pos_idx][row_idx]) - for pos_idx in range(n_positions) - ] - row_tuples.sort() - for pos_idx, (sid_val, rid_val) in enumerate(row_tuples): - sorted_sid[pos_idx].append(sid_val) - sorted_rid[pos_idx].append(rid_val) - - # Replace columns with sorted values - for pos_idx, (sid_col, rid_col) in enumerate(paired_cols): - for name, values in ( - (sid_col, sorted_sid[pos_idx]), - (rid_col, sorted_rid[pos_idx]), - ): - if name is not None: - index = table.schema.get_field_index(name) - field = pa.field( - name, table.schema.field(index).type, nullable=nullable[name] - ) - table = table.set_column( - index, field, pa.array(values, type=field.type) - ) - - return table - - def add_source_info( table: "pa.Table", source_info: str | Collection[str] | None, diff --git a/test-specification/unit/test_arrow_data_utils.py b/test-specification/unit/test_arrow_data_utils.py index dfc17c7a2..cffcb28c3 100644 --- a/test-specification/unit/test_arrow_data_utils.py +++ b/test-specification/unit/test_arrow_data_utils.py @@ -18,7 +18,6 @@ append_to_system_tags, drop_columns_with_prefix, drop_system_columns, - sort_system_tag_values, ) @@ -120,30 +119,6 @@ def test_empty_table_returns_empty(self): assert result.num_rows == 0 -# --------------------------------------------------------------------------- -# sort_system_tag_values -# --------------------------------------------------------------------------- - - -class TestSortSystemTagValues: - """Per design, system tag values must be sorted for commutativity in - multi-input operators. Paired (source_id, record_id) tuples are sorted - together per row.""" - - def test_sorts_system_tag_values(self): - # This is a structural test — ensure the function runs without error - # and produces a table with the same shape - table = pa.table({"id": [1, 2], "value": [10, 20]}) - table_with_tags = add_system_tag_columns( - table, - schema_hash="abc", - source_ids="src1", - record_ids=[_make_row_identifier(), _make_row_identifier()], - ) - result = sort_system_tag_values(table_with_tags) - assert result.num_rows == table_with_tags.num_rows - - # --------------------------------------------------------------------------- # add_source_info # --------------------------------------------------------------------------- diff --git a/tests/test_channels/test_native_async_operators.py b/tests/test_channels/test_native_async_operators.py index 2028c19a0..9f5da3a1e 100644 --- a/tests/test_channels/test_native_async_operators.py +++ b/tests/test_channels/test_native_async_operators.py @@ -2343,48 +2343,6 @@ async def test_three_way_system_tags_match_sync(self): assert sync_sys == async_sys -class TestSortMergedSystemTags: - """Unit tests for Join._sort_merged_system_tags.""" - - def test_sorts_same_provenance_path_by_value(self): - """System tag values at different positions within the same provenance - path should be sorted by (source_id, record_id) tuple.""" - merged_sys = { - # Provenance path "abc123", position 0 — higher values - "_tag_source_id::abc123:0": "z_source", - "_tag_record_id::abc123:0": "z_record", - # Provenance path "abc123", position 1 — lower values - "_tag_source_id::abc123:1": "a_source", - "_tag_record_id::abc123:1": "a_record", - } - result = Join._sort_merged_system_tags(merged_sys) - - # After sorting, position 0 should have the smaller values - assert result["_tag_source_id::abc123:0"] == "a_source" - assert result["_tag_record_id::abc123:0"] == "a_record" - assert result["_tag_source_id::abc123:1"] == "z_source" - assert result["_tag_record_id::abc123:1"] == "z_record" - - def test_single_position_unchanged(self): - """Groups with only one position should not be modified.""" - merged_sys = { - "_tag_source_id::abc123:0": "only_source", - "_tag_record_id::abc123:0": "only_record", - } - result = Join._sort_merged_system_tags(merged_sys) - assert result == merged_sys - - def test_non_system_tag_keys_ignored(self): - """Non-system-tag keys should pass through unchanged.""" - merged_sys = { - "regular_key": "value", - "_tag_source_id::abc123:0": "src0", - "_tag_record_id::abc123:0": "rec0", - } - result = Join._sort_merged_system_tags(merged_sys) - assert result["regular_key"] == "value" - - class TestSemiJoinSystemTagEquivalence: """Verify SemiJoin system-tag handling matches between sync and async.""" diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index 1ae19b56b..d97759752 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -16,11 +16,9 @@ import asyncio import decimal import itertools -import math import re from collections.abc import Callable, Sequence from dataclasses import dataclass -from hashlib import sha256 from pathlib import Path from typing import Any, TypeAlias, cast @@ -405,7 +403,7 @@ def _row_schema(tag: TagProtocol, data: DataProtocol) -> pa.Schema: return arrow_utils.join_arrow_schemas(tag_schema, data_schema) -def _paired(expected: list[Row], actual: list[Row]) -> list[tuple[Row, Row]]: +def _paired(expected: Sequence[Row], actual: Sequence[Row]) -> list[tuple[Row, Row]]: """Pair each async row with the sync row that has the same user tags.""" by_key = {_row_key(tag): (tag, data) for tag, data in expected} assert len(by_key) == len(expected), "test inputs must give unique tag rows" @@ -413,7 +411,7 @@ def _paired(expected: list[Row], actual: list[Row]) -> list[tuple[Row, Row]]: return [((tag, data), by_key[_row_key(tag)]) for tag, data in actual] -def assert_equivalent(expected: list[Row], actual: list[Row]) -> None: +def assert_equivalent(expected: Sequence[Row], actual: Sequence[Row]) -> None: """Assert the async rows equal the sync rows in types, order, tags and hashes.""" context = get_default_context() for (tag, data), (sync_tag, sync_data) in _paired(expected, actual): @@ -442,7 +440,7 @@ def assert_equivalent(expected: list[Row], actual: list[Row]) -> None: ) -def assert_same_provenance(expected: list[Row], actual: list[Row]) -> None: +def assert_same_provenance(expected: Sequence[Row], actual: Sequence[Row]) -> None: """Assert the async rows carry the sync rows' source info, column for column.""" for (_, data), (_, sync_data) in _paired(expected, actual): assert data.source_info() == sync_data.source_info() @@ -505,8 +503,10 @@ def _float_tag_branch(values: Sequence[float], data: str) -> ArrowTableStream: "k": pa.array([1, 2, 3], pa.int16()), "f": pa.array(values, pa.float64()), data: pa.array([10, 20, 30], pa.int32()), - "_tag_source_id::x": pa.array(["s", "s", "s"], pa.large_string()), - "_tag_record_id::x": pa.array(["r1", "r2", "r3"], pa.large_string()), + f"_tag_source_id::{'a' * 64}": pa.array(["s", "s", "s"], pa.large_string()), + f"_tag_record_id::{'a' * 64}": pa.array( + ["r1", "r2", "r3"], pa.large_string() + ), } ) return ArrowTableStream._from_derived_table(table, tag_columns=["k", "f"]) @@ -1076,526 +1076,237 @@ def test_projection_miss_has_the_same_policy_on_both_paths( assert sync_rows(op, empty) == async_rows(op, empty) == [] -@pytest.mark.parametrize("reverse_columns", [False, True]) -@pytest.mark.parametrize("metadata", ["none", "same", "different"]) -def test_tied_join_table_keeps_declared_identifier_fields( - reverse_columns: bool, - metadata: str, -) -> None: - """Keep table identifier flags and infer tied identifiers when reading rows.""" - source_id = "_tag_source_id::seed" - record_id = "_tag_record_id::seed" - schema = pa.schema( - [ - pa.field("k", pa.int64(), False), - pa.field("g", pa.large_string(), False), - pa.field(source_id, pa.large_string(), False), - pa.field(record_id, pa.large_string(), True), - ] - ) - inputs = [] - empty_inputs = [] - for source, records in (("a", ["p", "q"]), ("b", ["r", "t"]), ("c", ["s", "u"])): - field_metadata: dict[bytes | str, bytes | str] | None = ( - None - if metadata == "none" - else {b"owner": b"a" if metadata == "same" else source.encode()} - ) - fields = pa.schema( - [ - field.with_metadata(field_metadata) - if field_metadata is not None and field.name in (source_id, record_id) - else field - for field in schema - ] - ) - table = pa.Table.from_pylist( - [ - {"k": i, "g": group, source_id: source, record_id: record} - for i, (group, record) in enumerate( - zip(("x", "y"), records, strict=True) - ) - ], - schema=fields, - ) - if reverse_columns: - table = table.select(list(reversed(schema.names))) - inputs.append( - ArrowTableStream._from_derived_table( - table, tag_columns=("k", "g"), data_tags=("k", "g") - ) - ) - empty_inputs.append( - ArrowTableStream._from_derived_table( - table.slice(0, 0), tag_columns=("k", "g"), data_tags=("k", "g") - ) - ) - assert len({stream.pipeline_hash() for stream in inputs}) == 1 - columns = {"system_tags": True} - for positions in itertools.permutations(range(len(inputs))): - ordered = [inputs[i] for i in positions] - empty = [empty_inputs[i] for i in positions] - join = Join() - stream = join(*ordered) - table = stream.as_table(columns=columns) - empty_table = join(*empty).as_table(columns=columns) - assert empty_table.num_rows == 0 - assert empty_table.schema.equals(table.schema, check_metadata=True) - tags, _ = join.output_schema(*ordered, columns=columns) - tag_names = [name for name in tags if name.startswith("_tag_")] - assert len(tag_names) == 6 - for name in tag_names: - field = table.schema.field(name) - assert field.metadata is None - assert field.nullable == name.startswith(record_id) - assert tags[name] == (str | None if field.nullable else str) - for rows in (list(stream.iter_data()), async_rows(join, *ordered)): - assert len(rows) == table.num_rows == 2 - for tag, data in rows: - tag_table = tag.as_table(columns=columns) - for field in tag_table.schema: - if field.name.startswith(record_id): - assert field.nullable == (tag_table[field.name].null_count > 0) - assert field.metadata is None - else: - assert field.equals( - table.schema.field(field.name), check_metadata=True - ) - data_table = data.as_table() - assert data_table.schema.equals( - table.select(data_table.column_names).schema, check_metadata=True - ) - - -def _tied_join_inputs( - arity: int, - *, - distinct_revisions: bool = False, -) -> list[ArrowTableStream]: - """Build equal-pipeline inputs with distinct identifiers and optional revision values.""" - names = ["k", "_tag_source_id", "_tag_record_id", "_tag_rev"] - schema = pa.schema( - [pa.field("k", pa.int64(), nullable=False)] - + [pa.field(name, pa.large_string(), nullable=False) for name in names[1:]] - ) - inputs = [] - pairs = ( - ("az", "record-a"), - ("z", "record-z"), - ("zzzz", "record-last"), - ("z", "record-b"), - ) - for index, (source_id, record_id) in enumerate(pairs[:arity]): - key = 1 - revision = f"revision-{index}" if distinct_revisions else "shared" - table = pa.Table.from_pylist( - [dict(zip(names, (key, source_id, record_id, revision), strict=True))], - schema=schema, - ) - inputs.append( - ArrowTableStream._from_derived_table( - table, tag_columns=["k"], data_tags=["k"] - ) - ) - assert len({stream.pipeline_hash() for stream in inputs}) == 1 - return inputs - - -def _tied_join_outputs( - mode: str, join: Join, inputs: Sequence[StreamProtocol] -) -> tuple[pa.Table, list[Row]]: - """Return the system-tag view and rows for a tied Join. - - Sync uses the Join table, rows uses the async row tags, and batches uses - the emitted Arrow fields in Join's column order. - """ - columns = {"system_tags": True} - if mode == "rows": - rows = async_rows(join, *inputs) - return ( - pa.concat_tables([tag.as_table(columns=columns) for tag, _ in rows]) - if rows - else pa.table({}) - ), rows - if mode == "sync": - stream = join(*inputs) - return stream.as_table(columns=columns), list(stream.iter_data()) +def _join_batch_table(join: Join, inputs: Sequence[StreamProtocol]) -> pa.Table: + """Run the record-batch kernel to completion, splitting inputs into single rows.""" kernel = StreamingJoin(join, inputs) batches = [ result - for i, operand in enumerate(inputs) - for packet in operand.as_table(columns=TRANSPORT_COLUMNS).to_batches() - for result in kernel.push(i, packet) + for index, stream in enumerate(inputs) + for batch in stream.as_table(columns=TRANSPORT_COLUMNS).to_batches( + max_chunksize=1 + ) + for result in kernel.push(index, batch) ] - batches.extend(result for i in range(len(inputs)) for result in kernel.close(i)) - if not batches: - return kernel.zero_row_result.as_table(columns=columns), [] - table = pa.Table.from_batches(batches) - # The kernel returns Arrow batches. Use Join's row reader to calculate the - # entry IDs corresponding to those tables, and check the emitted fields as-is. - tag_names = inputs[0].keys()[0] - stream = join._join_result_stream( # pyright: ignore[reportPrivateUsage] # the kernel returns tables, not rows - table, inputs, tag_columns=tag_names, data_tags=tag_names - ) - layout = stream.as_table(columns=columns).column_names - return table.select(layout), list(stream.iter_data()) - - -def _symmetric_tie_snapshot(arity: int, mode: str) -> tuple[str, ...]: - """Digest the Arrow IPC tables and collect the entry IDs in permutation order.""" - hasher = get_default_arrow_hasher() - snapshot = [] - for order in itertools.permutations(_tied_join_inputs(arity)): - table, rows = _tied_join_outputs(mode, Join(), order) - output = pa.BufferOutputStream() - with pa.ipc.new_stream(output, table.schema) as writer: - writer.write_table(table.combine_chunks()) - snapshot.append(sha256(output.getvalue().to_pybytes()).hexdigest()) - snapshot.extend(entry_id(hasher, tag, data).to_string() for tag, data in rows) - return tuple(snapshot) - - -@pytest.mark.parametrize("peer_is_join", [False, True]) -def test_nested_self_join_system_tags_match_in_all_modes(peer_is_join: bool) -> None: - """Raw row channels and batches use the same structural suffixes as tables.""" - table = pa.table({"k": [1, 2], "m": [3, 4]}) - a = ArrowTableSource(table, tag_columns=("k", "m"), source_id="a") - b = ArrowTableSource(table, tag_columns=("k", "m"), source_id="b") - repeated = Join()(a, a) - peer = Join()(a, b) if peer_is_join else b - _, expected = _tied_join_outputs("sync", Join(), (repeated, peer)) - assert expected - hasher = get_default_arrow_hasher() - expected_ids = sorted( - entry_id(hasher, tag, data).to_hex() for tag, data in expected + batches.extend( + result for index in range(len(inputs)) for result in kernel.close(index) ) - - for inputs in ((repeated, peer), (peer, repeated)): - for mode in ("sync", "rows", "batches"): - _, actual = _tied_join_outputs(mode, Join(), inputs) - assert_equivalent(expected, actual) - assert ( - sorted(entry_id(hasher, tag, data).to_hex() for tag, data in actual) - == expected_ids - ) - - -# Captured from origin/main at 37f78431, where all permutations and modes agree. -@pytest.mark.parametrize( - ("arity", "table_digest", "expected_entry_id"), - [ - ( - 2, - "da59e70321d0172c50fe3e828b4a1889ce7bab343e24e1c288405a43056b061e", - "arrow_v1:0000029a37059d124668f54cd4a141a99266d84c5ba57f4007947f0ac0bee1e88eadbf", - ), - ( - 3, - "c0745b28e9bfcb112a8ef786e01e9188de67c1f8c9bd15c9dc633dc6ce031bb4", - "arrow_v1:000002b259085d031998a9850c2a998f2e41a76e931410be81f8b1f5198dd1416d5170", - ), - ( - 4, - "e1f1b75a17ac2d9006a7c3bf606050703a8216db58901cb0e515c3da84e90f4a", - "arrow_v1:00000278a840e460fa1d24285bfec361a11ac9a3efc5d0ddea290a6683cdaec5c119fc", - ), - ], -) -@pytest.mark.parametrize("mode", ["sync", "rows", "batches"]) -def test_symmetric_tied_join_matches_main( - arity: int, mode: str, table_digest: str, expected_entry_id: str -) -> None: - """Pin the table and entry IDs for every symmetric input permutation.""" - assert _symmetric_tie_snapshot(arity, mode) == ( - table_digest, - expected_entry_id, - ) * math.factorial(arity) + if not batches: + return kernel.zero_row_result.as_table(columns=TRANSPORT_COLUMNS) + return pa.Table.from_batches(batches) @pytest.mark.parametrize("arity", [2, 3, 4]) -def test_standalone_tied_join_keeps_custom_tags_with_ids(arity: int) -> None: - """Keep each revision value paired with the identifiers from its input.""" - inputs = _tied_join_inputs(arity, distinct_revisions=True) - suffix = inputs[0].pipeline_hash().to_hex() - expected = {} - names = ("_tag_source_id", "_tag_record_id", "_tag_rev") - bundles = [ - tuple(table[name][0].as_py() for name in names) - for table in ( - stream.as_table(columns={"system_tags": True}) for stream in inputs +@pytest.mark.parametrize("shape", ["source", "diamond", "batch", "group"]) +def test_tied_join_bundles_agree_across_modes(arity: int, shape: str) -> None: + """Every permutation emits the same intact joined or folded provenance bundles.""" + + def source(name: str) -> ArrowTableSource: + keys = [2, 1] if name in ("b", "z", "v") else [1, 2] + return _source({"k": pa.array(keys)}, ("k",), name, with_data_tags=True) + + pairs = (("a", "z"), ("b", "w"), ("c", "v"), ("d", "u"))[:arity] + branches: list[StreamProtocol] + if shape == "source": + branches = [source(low) for low, _ in pairs] + else: + shared = source("0") + branches = [Join()(shared, source(low), source(high)) for low, high in pairs] + if shape == "batch": + branches = [Batch(batch_size=1)(branch) for branch in branches] + elif shape == "group": + branches = [GroupBy(["k"])(branch) for branch in branches] + + hashes = {branch.pipeline_hash() for branch in branches} + assert len(hashes) == 1 + digest = hashes.pop().to_hex() + columns = {"system_tags": True} + source_names = sorted( + name + for name in branches[0].keys(columns=columns)[0] + if name.startswith("_tag_source_id::") + ) + names = [ + name + for source_name in source_names + for name in ( + source_name, + source_name.replace("_tag_source_id", "_tag_record_id", 1), ) ] - for position, values in enumerate(sorted(bundles)): - for name, value in zip(names, values, strict=True): - expected[f"{name}::{suffix}:{position}"] = value - - for order in itertools.permutations(inputs): - [(tag, _)] = async_rows(Join(), *order) - assert tag.system_tags() == expected - - -def _tied_declaration_inputs( - arity: int, variant: str, *, revision_first: bool = False -) -> list[StreamProtocol]: - """Vary the declaration or values of the tied Join's custom revision tag. + members = [ + arrow_utils.sort_by_tag_columns(branch.as_table(columns=columns), ("k",)) + .select(names) + .to_pylist() + for branch in branches + ] + expected = [ + { + f"{name}::{digest}:{position}": value + for position, bundle in enumerate( + sorted(tuple(row.values()) for row in rows) + ) + for name, value in zip(names, bundle, strict=True) + } + for rows in zip(*members, strict=True) + ] - Nullable changes the first field's nullability, owner and extension add - their respective metadata keys, and distinct varies the values. Source - uses the library provenance pair with a required revision field and data-tag k. - """ - if variant == "source": - ids = ("az", "z", "zz", "zzz")[:arity] - schema = pa.schema( - [ - pa.field("k", pa.int64(), False), - pa.field("rev", pa.large_string(), False), - ] + baseline = None + hasher = get_default_arrow_hasher() + for order in itertools.permutations(branches): + join = Join() + stream = join(*order) + table = arrow_utils.sort_by_tag_columns( + stream.as_table(columns=TRANSPORT_COLUMNS), ("k",) ) - sources = [ - ArrowTableSource( - pa.Table.from_pylist([{"k": 1, "rev": f"rev-{source_id}"}], schema), - tag_columns=["k"], - source_id=source_id, - ) - for source_id in ids - ] - for source in sources: - table = source.as_table(columns={"system_tags": True, "source": True}) - revision = table["rev"] - table = table.drop_columns(["rev", "_source_rev"]) - # The historical table put the revision before the provenance pair. - # Its row schema put the pair first. Supply each mode its original order. - position = 1 if revision_first else table.num_columns - table = table.add_column( - position, pa.field("_tag_rev", pa.large_string(), False), revision - ) - source._stream = ArrowTableStream._from_derived_table( - table, tag_columns=["k"], data_tags=["k"] - ) - assert source.keys() == (("k",), ("k",)) - return list(sources) - inputs: list[StreamProtocol] = [] - for position in range(arity): - metadata_key = { - "owner": b"owner", - "extension": b"ARROW:extension:name", - }.get(variant) - schema = pa.schema( - [ - pa.field("k", pa.int64(), nullable=False), - pa.field("_tag_source_id", pa.large_string(), nullable=False), - pa.field("_tag_record_id", pa.large_string(), nullable=False), - pa.field( - "_tag_rev", - pa.large_string(), - nullable=variant == "nullable" and position == 0, - metadata={metadata_key: str(position).encode()} - if metadata_key - else None, - ), - ] + sync = list(stream.iter_data()) + row_channel = async_rows(join, *order) + batch_table = arrow_utils.sort_by_tag_columns( + _join_batch_table(join, order), ("k",) ) - ids = ("a", "z") if arity == 2 else ("a", "b", "c", "z")[:arity] - source_ids = [ids[position], ids[arity - position - 1]] - table = pa.Table.from_pydict( - { - "k": [0, 1], - "_tag_source_id": source_ids, - "_tag_record_id": [f"record-{source_id}" for source_id in source_ids], - "_tag_rev": [str(position)] * 2 - if variant == "distinct" - else ["same"] * 2, - }, - schema=schema, + assert table.select(list(expected[0])).to_pylist() == expected + assert batch_table.schema.equals(table.schema, check_metadata=True) + assert batch_table.equals(table) + batches = ArrowTableStream._from_derived_table( + batch_table, tag_columns=["k"], data_tags=["k"] ) + for rows in (row_channel, list(batches.iter_data())): + assert_equivalent(sync, rows) + assert_same_provenance(sync, rows) + assert {entry_id(hasher, tag, data) for tag, data in rows} == { + entry_id(hasher, tag, data) for tag, data in sync + } + identity = (stream.pipeline_hash(), stream.content_hash(), table) + if baseline is None: + baseline = identity + else: + assert identity == baseline + + +@pytest.mark.parametrize("arity", [2, 3, 4]) +@pytest.mark.parametrize("mode", ["run", "execute", "channel"]) +def test_tied_join_keeps_nullable_record_id_declarations(arity: int, mode: str) -> None: + """Table iteration, batches, and direct LOG writes keep the output declaration.""" + originals = [ + _source({"k": pa.array([1, 2])}, ("k",), name, with_data_tags=True) + for name in ("a", "b", "c", "z")[:arity] + ] + inputs = [] + for index, source in enumerate(originals): + table = source.as_table(columns=TRANSPORT_COLUMNS) + if index == 0: + record = next( + name + for name in table.column_names + if name.startswith("_tag_record_id::") + ) + field_index = table.schema.get_field_index(record) + field = table.schema.field(field_index).with_nullable(True) + table = table.set_column(field_index, field, table[record]) inputs.append( ArrowTableStream._from_derived_table( table, tag_columns=["k"], data_tags=["k"] ) ) assert len({stream.pipeline_hash() for stream in inputs}) == 1 - return inputs - - -def _ipc_bytes(table: pa.Table) -> bytes: - """Serialize a table with rebuilt buffers for a stable snapshot.""" - output = pa.BufferOutputStream() - with pa.ipc.new_stream(output, table.schema) as writer: - writer.write_table(pa.Table.from_pylist(table.to_pylist(), schema=table.schema)) - return output.getvalue().to_pybytes() - - -@pytest.mark.parametrize("arity", [2, 3, 4]) -def test_commutative_hash_counts_content_equal_inputs(arity: int) -> None: - """Source equality changes neither the flat nor the nested structure.""" - distinct = _tied_declaration_inputs(arity, "same") - equal = _tied_declaration_inputs(arity, "same")[0] - first = distinct[0] - assert first is not equal and first == equal - - variants = (distinct, [first] * arity, [first, equal, *distinct[2:]]) - direct = [Join()(*inputs) for inputs in variants] - assert len({stream.pipeline_hash() for stream in direct}) == 1 - assert len({Join()(stream, first).pipeline_hash() for stream in direct}) == 1 - assert direct[1].pipeline_hash() != Join()(*([first] * (arity + 1))).pipeline_hash() - - for inputs, stream in zip(variants, direct, strict=True): - sync = list(stream.iter_data()) - async_ = async_rows(Join(), *inputs) - assert len(sync) == len(async_) == 2 - hasher = get_default_arrow_hasher() - assert sorted( - entry_id(hasher, tag, data).to_string() for tag, data in sync - ) == (sorted(entry_id(hasher, tag, data).to_string() for tag, data in async_)) - -def _tied_declaration_snapshot(arity: int, variant: str, mode: str) -> str: - """Digest all tables, row declarations, and entry IDs in permutation order.""" - hasher = get_default_arrow_hasher() - snapshot = sha256() columns = {"system_tags": True} - inputs = _tied_declaration_inputs(arity, variant, revision_first=mode != "rows") - for order in itertools.permutations(inputs): - table, rows = _tied_join_outputs(mode, Join(), order) - snapshot.update(_ipc_bytes(table.sort_by("k"))) - for tag, data in sorted(rows, key=lambda row: cast(int, row[0].as_dict()["k"])): - snapshot.update(_ipc_bytes(tag.as_table(columns=columns))) - snapshot.update(entry_id(hasher, tag, data).to_string().encode()) - return snapshot.hexdigest() - - -# Captured from origin/main at 37f78431. Normalize IPC array buffers before -# hashing so representation details such as buffer padding cannot affect this. -@pytest.mark.parametrize( - ("arity", "mode", "expected"), - [ - (2, "sync", "280a42832ee7f60b55ad196d02b9cfaf1e2c85d7d0503db828ab303ebb1320c0"), - (2, "rows", "9314587b25beec1a7584b1d1591aba5897a4f0d31e6a281582160153931764a2"), - ( - 2, - "batches", - "26d1cbeaa025d775dedb3f0d961c40d15cd958c7684d9c616d1ceced779545dd", - ), - (3, "sync", "cd68e71f26e095b30152cf7957d282c6aa5d136e0975098c327566e75e83f87b"), - (3, "rows", "f0845a9b6838c6fe841f070cdf2c488395132e8da736e5356c73e7fa64997ee2"), - ( - 3, - "batches", - "033fe0d17906706f270dac8d17123d4f97e88b661fe7c2c0f692e3fdd087e0b8", - ), - (4, "sync", "fb5f218d39d728d6f2f5d30baa0858ae72964208b0a66c99d6886d94ba90b5ae"), - (4, "rows", "a5c00b4f0b7b1e63c687bb0f08cf4a6adfddf652aebf5534773b0f1dc5869454"), - ( - 4, - "batches", - "2e1e2be35f60e429a95c62526db88cdee44912e1d65fe5b1afd825d4132e5c56", - ), - ], -) -def test_tied_join_declarations_and_entry_ids_match_main( - arity: int, mode: str, expected: str -) -> None: - """Pin main's per-mode table and row declarations and entry IDs.""" - fingerprints = [ - _tied_declaration_snapshot(arity, variant, mode) - for variant in ("nullable", "extension", "owner", "distinct", "source") - ] - assert sha256("".join(fingerprints).encode()).hexdigest() == expected - - -@pytest.mark.parametrize("variant", ["nullable", "extension", "owner"]) -@pytest.mark.parametrize("mode", ["run", "sync", "async"]) -def test_tied_join_direct_log_matches_main(variant: str, mode: str) -> None: - """Pin the stored system-tag fields and entry IDs of all direct LOG routes.""" - operands = _tied_declaration_inputs(2, variant) - store = InMemoryArrowDatabase() - node = OperatorJobNode( - Join(), operands, pipeline_database=store, cache_mode=CacheMode.LOG - ) + for ordered in (inputs, inputs[::-1]): + join = Join() + stream = join(*ordered) + table = stream.as_table(columns=columns) + records = [ + field.name + for field in table.schema + if field.name.startswith("_tag_record_id::") + ] + assert len(records) == arity + tags, _ = join.output_schema(*ordered, columns=columns) + assert all(tags[name] == str | None for name in records) + assert all(table.schema.field(name).nullable for name in records) + batch = _join_batch_table(join, ordered) + assert batch.select(table.column_names).schema.equals( + table.schema, check_metadata=True + ) + for rows in (stream.iter_data(), async_rows(join, *ordered)): + for tag, _ in rows: + assert tag.as_table(columns=columns).schema.equals( + table.schema, check_metadata=True + ) - async def run() -> list[Row]: - """Execute the node over row channels and collect its output.""" - channels: list[Channel[Row]] = [Channel(buffer_size=8) for _ in operands] - output: Channel[Row] = Channel(buffer_size=8) - for stream, channel in zip(operands, channels, strict=True): - for row in stream.iter_data(): - await channel.writer.send(row) - await channel.writer.close() - await node.async_execute( - [channel.reader for channel in channels], output.writer + store = InMemoryArrowDatabase() + node = OperatorJobNode( + join, ordered, pipeline_database=store, cache_mode=CacheMode.LOG ) - return await output.reader.collect() - if mode == "run": - node.run() - rows = list(node.iter_data()) - elif mode == "sync": - rows = list(node.execute(*operands).iter_data()) - else: - rows = asyncio.run(run()) - columns = {"system_tags": True} - hasher = get_default_arrow_hasher() - ids = [entry_id(hasher, tag, data) for tag, data in rows] - assert sorted(digest.to_string() for digest in ids) == [ - "arrow_v1:00000237bf6d56a4fbd90a304813372028248268b9561e94a279986a92d83506c6b1d6", - "arrow_v1:0000023c89fc6badf559f658c77af9ee84b5a1d3644995eb9a6c24d0b9e0193e958ce1", - ] - store.flush() - (path,) = store.list_table_paths() - stored = store.get_all_records(path, record_id_column="_record_hash") - assert stored is not None - assert sorted(cast(list[bytes], stored[ENTRY_ID_COL].to_pylist())) == sorted( - digest.to_prefixed_digest() for digest in ids - ) - for tag, _ in rows: - for field in tag.as_table(columns=columns).schema: - if field.name.startswith("_tag_"): - assert stored.schema.field(field.name).equals( - field, check_metadata=True - ) + async def run_channel() -> list[Row]: + channels = [Channel[Row](buffer_size=8) for _ in ordered] + output = Channel[Row](buffer_size=8) + for operand, channel in zip(ordered, channels, strict=True): + for row in operand.iter_data(): + await channel.writer.send(row) + await channel.writer.close() + await node.async_execute( + [channel.reader for channel in channels], output.writer + ) + return await output.reader.collect() + + if mode == "run": + _ = node.run() + rows = list(node.iter_data()) + elif mode == "execute": + rows = list(node.execute(*ordered).iter_data()) + else: + rows = asyncio.run(run_channel()) + store.flush() + (path,) = store.list_table_paths() + stored = store.get_all_records(path, record_id_column="_record_hash") + assert stored is not None + assert stored.select(records).schema.equals( + table.select(records).schema, check_metadata=True + ) + assert sorted(cast(list[bytes], stored[ENTRY_ID_COL].to_pylist())) == sorted( + entry_id(get_default_arrow_hasher(), tag, data).to_prefixed_digest() + for tag, data in rows + ) -@pytest.mark.parametrize("arity", [2, 3, 4]) -@pytest.mark.parametrize("mode", ["sync", "rows", "batches"]) -def test_tied_join_with_asymmetric_empty_input_matches_main( - arity: int, mode: str -) -> None: - """Keep the zero-row layout when a tied input omits its identifier pair.""" - inputs = _tied_join_inputs(arity) - columns = {"system_tags": True} - empty_table = ( - inputs[-1] - .as_table(columns=columns) - .drop(["_tag_source_id", "_tag_record_id"]) - .slice(0, 0) - ) - inputs[-1] = ArrowTableStream._from_derived_table( - empty_table, tag_columns=["k"], data_tags=["k"] +@pytest.mark.parametrize("empty", [False, True]) +def test_tied_join_orders_raw_and_sourced_layouts(empty: bool) -> None: + """A raw operand naturally has the empty provenance bundle.""" + table = pa.table({"k": [1]}) + raw = ArrowTableStream( + table.slice(0, 0) if empty else table, tag_columns=["k"], data_tags=["k"] ) - for order in itertools.permutations(inputs): + a, z = [ + ArrowTableSource(table, tag_columns=["k"], source_id=name) + for name in ("a", "z") + ] + operands: tuple[StreamProtocol, ...] = (raw, a, z) + assert len({operand.pipeline_hash() for operand in operands}) == 1 + columns = {"system_tags": True} + expected = Join()(*operands).as_table(columns=TRANSPORT_COLUMNS) + for ordered in itertools.permutations(operands): join = Join() - tags, _ = join.output_schema(*order, columns=columns) - for prefix in ("_tag_source_id", "_tag_record_id"): - assert sum(name.startswith(prefix) for name in tags) == arity - 1 - table, rows = _tied_join_outputs(mode, join, order) - assert not rows and not table.num_rows - if mode != "rows": - assert set(table.column_names) == set(tags) + stream = join(*ordered) + result = stream.as_table(columns=TRANSPORT_COLUMNS) + assert result.equals(expected, check_metadata=True) + assert _join_batch_table(join, ordered).equals(expected, check_metadata=True) + assert_equivalent(list(stream.iter_data()), async_rows(join, *ordered)) + tags, _ = join.output_schema(*ordered, columns=columns) + assert tuple(tags) == stream.keys(columns=columns)[0] @pytest.mark.parametrize("reverse", [False, True]) def test_join_suffixes_distinguish_hashes_with_the_same_prefix(reverse: bool) -> None: """Disambiguate inputs by full pipeline hash in every Join mode.""" - source_id, record_id, custom = "_tag_source_id", "_tag_record_id", "_tag_rev" left, right = [ ArrowTableStream._from_derived_table( pa.table( { "k": [1], data: [1], - source_id: [owner], - record_id: [f"{owner}-record"], - custom: [f"{owner}-revision"], + f"_tag_source_id::{'a' * 64}": [owner], + f"_tag_record_id::{'a' * 64}": [f"{owner}-record"], } ), tag_columns=["k"], @@ -1607,33 +1318,21 @@ def test_join_suffixes_distinguish_hashes_with_the_same_prefix(reverse: bool) -> right.pipeline_hash().to_hex(), ) assert left_hash[0] == right_hash[0] - assert right_hash < left_hash operands = (right, left) if reverse else (left, right) join = Join() columns = {"system_tags": True} [(tag, _)] = async_rows(join, *operands) - kernel = StreamingJoin(join, operands) - batches = [ - result - for index, operand in enumerate(operands) - for batch in operand.as_table(columns=TRANSPORT_COLUMNS).to_batches() - for result in kernel.push(index, batch) - ] expected = { - f"{field}::{digest}:{position}": value - for position, (digest, owner) in enumerate( - ((right_hash, "right"), (left_hash, "left")) - ) - for field, value in ( - (source_id, owner), - (record_id, f"{owner}-record"), - (custom, f"{owner}-revision"), + f"{name}::{stream.pipeline_hash().to_hex()}:{position}": value + for position, stream in enumerate( + sorted(operands, key=lambda operand: operand.pipeline_hash().to_hex()) ) + for name, value in next(stream.iter_data())[0].system_tags().items() } for result in ( tag.as_table(columns=columns), join(*operands).as_table(columns=columns), - pa.Table.from_batches(batches), + _join_batch_table(join, operands), ): assert result.select(list(expected)).to_pylist() == [expected] @@ -2098,7 +1797,7 @@ def _meta_table(data: DataProtocol) -> pa.Table: return data.as_table(columns={"meta": True}).select(list(data.meta_columns)) -def assert_same_meta(expected: list[Row], actual: list[Row]) -> None: +def assert_same_meta(expected: Sequence[Row], actual: Sequence[Row]) -> None: """Assert the async rows carry the sync rows' meta columns. Names, order, Arrow types, nullability and values must all match. diff --git a/tests/test_core/operators/test_operators.py b/tests/test_core/operators/test_operators.py index ab4db2c5b..503abfb3c 100644 --- a/tests/test_core/operators/test_operators.py +++ b/tests/test_core/operators/test_operators.py @@ -1697,152 +1697,31 @@ def test_intermediate_operators_produce_different_stream_hash(self): assert index_str == str(expected_idx) -class TestSortSystemTagValues: - """Tests for the sort_system_tag_values utility that ensures commutativity - by sorting paired (source_id, record_id) system tag values per row.""" - - @staticmethod - def _make_paired_cols(constants, provenance_path, position): - """Build paired source_id/record_id column names for a given provenance path and position.""" - sid = f"{constants.SYSTEM_TAG_SOURCE_ID_PREFIX}{constants.BLOCK_SEPARATOR}{provenance_path}{constants.FIELD_SEPARATOR}{position}" - rid = f"{constants.SYSTEM_TAG_RECORD_ID_PREFIX}{constants.BLOCK_SEPARATOR}{provenance_path}{constants.FIELD_SEPARATOR}{position}" - return sid, rid - - def test_sorts_paired_values_across_same_provenance_path(self): - """Paired (source_id, record_id) columns sharing a provenance path - should have their values sorted per row by (source_id, record_id) tuples.""" - from orcapod.system_constants import constants - from orcapod.utils.arrow_utils import sort_system_tag_values - - sid_0, rid_0 = self._make_paired_cols(constants, "abc::ph123", "0") - sid_1, rid_1 = self._make_paired_cols(constants, "abc::ph123", "1") - - table = pa.table( - { - "id": [1, 2], - sid_0: pa.array(["zzz_source", "aaa_source"], type=pa.large_string()), - rid_0: pa.array(["row_0", "row_0"], type=pa.large_string()), - sid_1: pa.array(["aaa_source", "zzz_source"], type=pa.large_string()), - rid_1: pa.array(["row_1", "row_1"], type=pa.large_string()), - } - ) - - result = sort_system_tag_values(table) - - # After sorting by (source_id, record_id), position :0 should have the smaller tuple - # Row 0: ("zzz_source", "row_0") vs ("aaa_source", "row_1") → sorted: aaa first - assert result.column(sid_0).to_pylist()[0] == "aaa_source" - assert result.column(rid_0).to_pylist()[0] == "row_1" - assert result.column(sid_1).to_pylist()[0] == "zzz_source" - assert result.column(rid_1).to_pylist()[0] == "row_0" - - # Row 1: ("aaa_source", "row_0") vs ("zzz_source", "row_1") → already sorted - assert result.column(sid_0).to_pylist()[1] == "aaa_source" - assert result.column(rid_0).to_pylist()[1] == "row_0" - assert result.column(sid_1).to_pylist()[1] == "zzz_source" - assert result.column(rid_1).to_pylist()[1] == "row_1" - - def test_does_not_sort_different_provenance_paths(self): - """Columns with different provenance paths should NOT have their values sorted.""" - from orcapod.system_constants import constants - from orcapod.utils.arrow_utils import sort_system_tag_values - - # Two different provenance paths (different pipeline hashes) - sid_a, rid_a = self._make_paired_cols(constants, "abc::ph_AAA", "0") - sid_b, rid_b = self._make_paired_cols(constants, "abc::ph_BBB", "0") - - table = pa.table( - { - "id": [1], - sid_a: pa.array(["zzz"], type=pa.large_string()), - rid_a: pa.array(["row_0"], type=pa.large_string()), - sid_b: pa.array(["aaa"], type=pa.large_string()), - rid_b: pa.array(["row_1"], type=pa.large_string()), - } - ) - - result = sort_system_tag_values(table) - - # Values should be untouched since provenance paths differ - assert result.column(sid_a).to_pylist() == ["zzz"] - assert result.column(sid_b).to_pylist() == ["aaa"] - - def test_no_op_for_single_position_groups(self): - """Groups with only one position should be left untouched.""" - from orcapod.system_constants import constants - from orcapod.utils.arrow_utils import sort_system_tag_values - - sid, rid = self._make_paired_cols(constants, "abc::ph123", "0") - - table = pa.table( - { - "id": [1, 2], - sid: pa.array(["hello", "world"], type=pa.large_string()), - rid: pa.array(["row_0", "row_1"], type=pa.large_string()), - } - ) - - result = sort_system_tag_values(table) - assert result.column(sid).to_pylist() == ["hello", "world"] - assert result.column(rid).to_pylist() == ["row_0", "row_1"] - - def test_preserves_non_system_tag_columns(self): - """Non-system-tag columns should be completely unaffected.""" - from orcapod.system_constants import constants - from orcapod.utils.arrow_utils import sort_system_tag_values - - sid_0, rid_0 = self._make_paired_cols(constants, "abc::ph123", "0") - sid_1, rid_1 = self._make_paired_cols(constants, "abc::ph123", "1") +@pytest.mark.parametrize("kind", ["custom", "unpaired", "bad_path"]) +def test_join_refuses_unrecognized_system_tag_layout(kind: str) -> None: + """A tied Join cannot order corrupt library-owned provenance.""" + from orcapod.errors import InputValidationError + from orcapod.utils.arrow_utils import system_tag_column_names + def operand(path: str, names: tuple[str, ...]) -> ArrowTableStream: table = pa.table( - { - "id": [1, 2], - "data": ["foo", "bar"], - sid_0: pa.array(["zzz", "aaa"], type=pa.large_string()), - rid_0: pa.array(["r0", "r0"], type=pa.large_string()), - sid_1: pa.array(["aaa", "zzz"], type=pa.large_string()), - rid_1: pa.array(["r1", "r1"], type=pa.large_string()), - } + {"k": [1], **{name: pa.array([path], pa.large_string()) for name in names}} ) - - result = sort_system_tag_values(table) - assert result.column("id").to_pylist() == [1, 2] - assert result.column("data").to_pylist() == ["foo", "bar"] - - def test_three_way_group_sorts_correctly(self): - """Three positions sharing the same provenance path should all be sorted together.""" - from orcapod.system_constants import constants - from orcapod.utils.arrow_utils import sort_system_tag_values - - sid_0, rid_0 = self._make_paired_cols(constants, "abc::ph123", "0") - sid_1, rid_1 = self._make_paired_cols(constants, "abc::ph123", "1") - sid_2, rid_2 = self._make_paired_cols(constants, "abc::ph123", "2") - - table = pa.table( - { - sid_0: pa.array(["cherry", "banana"], type=pa.large_string()), - rid_0: pa.array(["r0", "r0"], type=pa.large_string()), - sid_1: pa.array(["apple", "cherry"], type=pa.large_string()), - rid_1: pa.array(["r1", "r1"], type=pa.large_string()), - sid_2: pa.array(["banana", "apple"], type=pa.large_string()), - rid_2: pa.array(["r2", "r2"], type=pa.large_string()), - } + return ArrowTableStream._from_derived_table( + table, tag_columns=["k"], data_tags=["k"] ) - result = sort_system_tag_values(table) - - # Row 0: tuples are (cherry,r0), (apple,r1), (banana,r2) → sorted: (apple,r1), (banana,r2), (cherry,r0) - assert result.column(sid_0).to_pylist()[0] == "apple" - assert result.column(rid_0).to_pylist()[0] == "r1" - assert result.column(sid_1).to_pylist()[0] == "banana" - assert result.column(rid_1).to_pylist()[0] == "r2" - assert result.column(sid_2).to_pylist()[0] == "cherry" - assert result.column(rid_2).to_pylist()[0] == "r0" - - # Row 1: tuples are (banana,r0), (cherry,r1), (apple,r2) → sorted: (apple,r2), (banana,r0), (cherry,r1) - assert result.column(sid_0).to_pylist()[1] == "apple" - assert result.column(rid_0).to_pylist()[1] == "r2" - assert result.column(sid_1).to_pylist()[1] == "banana" - assert result.column(rid_1).to_pylist()[1] == "r0" - assert result.column(sid_2).to_pylist()[1] == "cherry" - assert result.column(rid_2).to_pylist()[1] == "r1" + digest = "a" * 64 + pair = system_tag_column_names(digest) + names, message = { + "custom": ((*pair, "_tag_extra"), "unrecognized system-tag column"), + "unpaired": (pair[:1], "has no matching identifier"), + "bad_path": ( + system_tag_column_names("unrecognized"), + "unrecognized system-tag column", + ), + }[kind] + left, right = operand("left", pair), operand("right", names) + assert left.pipeline_hash() == right.pipeline_hash() + with pytest.raises(InputValidationError, match=message): + _ = Join().static_process(left, right) diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index b7307dc18..89477aac5 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -900,8 +900,8 @@ def test_join_keeps_nullable_tied_raw_system_tag_fields() -> None: schema = pa.schema( [ pa.field("k", pa.int64(), False), - pa.field("_tag_source_id::seed", pa.large_string(), False), - pa.field("_tag_record_id::seed", pa.large_string(), True), + pa.field(f"_tag_source_id::{'a' * 64}", pa.large_string(), False), + pa.field(f"_tag_record_id::{'a' * 64}", pa.large_string(), True), ] ) inputs = tuple( diff --git a/tests/test_core/streams/test_system_tag_validation.py b/tests/test_core/streams/test_system_tag_validation.py index 619057ca0..06ce419c9 100644 --- a/tests/test_core/streams/test_system_tag_validation.py +++ b/tests/test_core/streams/test_system_tag_validation.py @@ -13,9 +13,7 @@ from orcapod.errors import InputValidationError from orcapod.sources import ArrowTableSource from orcapod.system_constants import constants -from orcapod.utils.arrow_utils import add_system_tag_columns, system_tag_column_names - -SOURCE_ID, RECORD_ID = system_tag_column_names("origin") +from orcapod.utils.arrow_utils import add_system_tag_columns @pytest.mark.parametrize("name", ["_tag_application", "_tag::application"]) @@ -65,35 +63,36 @@ def test_nullable_string_field_is_preserved_when_values_are_present() -> None: assert result.schema.field(name).equals(pa.field(name, pa.large_string())) -def test_join_extends_complete_pairs_and_custom_system_tags() -> None: - """Joined output can carry multiple valid pairs and preserve custom tags.""" - left_table = add_system_tag_columns(pa.table({"x": [1]}), "left", "l", ["row"]) - left_table = left_table.append_column( - pa.field("_tag_label", pa.string_view(), nullable=False), - pa.array(["custom"], type=pa.string_view()), - ) - right_table = add_system_tag_columns(pa.table({"y": [2]}), "right", "r", ["row"]) - left = ArrowTableStream._from_derived_table(left_table) - right = ArrowTableStream._from_derived_table(right_table) - joined = Join()(left, right).as_table(columns={"system_tags": True}) - system_names = [ - name - for name in joined.column_names +def test_join_extends_complete_identifier_pairs() -> None: + """Join extends each source's qualified source-ID and record-ID pair.""" + left = ArrowTableSource(pa.table({"x": [1]}), source_id="left") + right = ArrowTableSource(pa.table({"y": [2]}), source_id="right") + config = {"system_tags": True} + joined = Join()(left, right).as_table(columns=config) + system_tags = { + name: value + for name, value in joined.to_pylist()[0].items() if name.startswith(constants.SYSTEM_TAG_PREFIX) - ] - assert len(system_names) == 5 - custom = next(name for name in system_names if name.startswith("_tag_label::")) - assert joined.column(custom).to_pylist() == ["custom"] + } + ordered = sorted((left, right), key=lambda stream: stream.pipeline_hash().to_hex()) + expected = { + f"{name}::{stream.pipeline_hash().to_hex()}:{position}": values[0] + for position, stream in enumerate(ordered) + for name, values in stream.as_table(columns=config).to_pydict().items() + if name.startswith(constants.SYSTEM_TAG_PREFIX) + } + assert len(expected) == 4 + assert system_tags == expected @pytest.mark.asyncio -@pytest.mark.parametrize("custom_name", ["source_id", "record_id"]) +@pytest.mark.parametrize("identifier", ["source_id", "record_id"]) @pytest.mark.parametrize("operation", ["join", "merge_join", "batch", "group_by"]) @pytest.mark.parametrize("execution", ["sync", "async"]) -async def test_extended_custom_id_tags_survive_operator_log( - custom_name: str, operation: str, execution: str +async def test_extended_identifier_tags_survive_operator_log( + identifier: str, operation: str, execution: str ) -> None: - """An ordinary custom string tag survives extension, LOG and further operators.""" + """A library identifier survives extension, LOG and further operators.""" from orcapod.channels import Channel, ReadableChannel from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.databases import InMemoryArrowDatabase @@ -105,12 +104,11 @@ async def test_extended_custom_id_tags_survive_operator_log( ) from orcapod.types import CacheMode - table = pa.table({"k": [1, 2], "x": [3, 4]}).append_column( - pa.field(f"_tag_{custom_name}", pa.string(), nullable=False), - pa.array(["a", "b"]), - ) - left: StreamProtocol = ArrowTableStream._from_derived_table( - table, tag_columns=["k"] + left: StreamProtocol = ArrowTableSource( + pa.table({"k": [1, 2], "x": [3, 4]}), + tag_columns=["k"], + tag_only_columns=True, + source_id="left", ) right: StreamProtocol = ArrowTableSource( pa.table({"k": [1, 2], "y": [5, 6]}), @@ -128,14 +126,15 @@ async def test_extended_custom_id_tags_survive_operator_log( config = {"system_tags": True} expected = operator(*inputs).as_table(columns=config) - suffix = left.pipeline_hash().to_hex() - prefix = f"{constants.SYSTEM_TAG_PREFIX}{custom_name}{constants.BLOCK_SEPARATOR}" + prefix = f"{constants.SYSTEM_TAG_PREFIX}{identifier}{constants.BLOCK_SEPARATOR}" + (base_name,) = ( + name for name in left.keys(columns=config)[0] if name.startswith(prefix) + ) + path = f"{base_name}{constants.BLOCK_SEPARATOR}{left.pipeline_hash().to_hex()}" [extended_name] = [ name for name in expected.column_names - if name == prefix + suffix - or name.startswith(prefix + suffix + constants.FIELD_SEPARATOR) - and constants.BLOCK_SEPARATOR not in name[len(prefix) :] + if name == path or name.startswith(path + constants.FIELD_SEPARATOR) ] assert expected[extended_name].null_count == 0 projected = SelectDataColumns(["x"])(operator(*inputs)).as_table(columns=config) @@ -176,10 +175,9 @@ def test_public_stream_refuses_a_detached_system_tag() -> None: """A detached system-tag column still belongs to Orcapod.""" from orcapod.operators import Batch - table = pa.table({"x": [1], "_tag_source_id": ["derived"]}) - source = ArrowTableStream._from_derived_table(table) + source = ArrowTableSource(pa.table({"x": [1]}), source_id="original") detached = Batch(batch_size=1)(source).as_table(columns={"system_tags": True}) (name,) = (c for c in detached.column_names if c.startswith("_tag_source_id")) with pytest.raises(InputValidationError, match=rf"{re.escape(name)}.*reserved"): - _ = ArrowTableStream(detached) + _ = ArrowTableStream(detached.select(["x", name])) diff --git a/tests/test_core/test_order_invariance.py b/tests/test_core/test_order_invariance.py index 2f8109ac1..f304cf75d 100644 --- a/tests/test_core/test_order_invariance.py +++ b/tests/test_core/test_order_invariance.py @@ -677,6 +677,46 @@ def test_the_order_of_the_inputs_of_a_commutative_operator_changes_nothing( ) +def test_tied_join_diamond_keeps_each_branch_together() -> None: + """The outer Join keeps (0, a, z) and (0, b, c) as intact cohorts.""" + table = pa.table({"k": [1, 2]}) + shared, a, b, c, z = [ + ArrowTableSource(table, tag_columns=["k"], source_id=name) + for name in ("0", "a", "b", "c", "z") + ] + results = {} + for left in itertools.permutations((shared, a, z)): + for right in itertools.permutations((shared, b, c)): + branches = (Join()(*left), Join()(*right)) + assert branches[0].pipeline_hash() == branches[1].pipeline_hash() + digest = branches[0].pipeline_hash().to_hex() + branch_values = [ + sorted( + str(value) + for name, value in tag.system_tags().items() + if name.startswith("_tag_source_id::") + ) + for branch in branches + for tag, _ in itertools.islice(branch.iter_data(), 1) + ] + for reverse in (False, True): + joined = Join()(*(branches[::-1] if reverse else branches)) + for tag, _ in joined.iter_data(): + cohorts = [ + sorted( + str(value) + for name, value in tag.system_tags().items() + if name.startswith("_tag_source_id::") + and name.endswith(f"::{digest}:{i}") + ) + for i in range(2) + ] + assert cohorts == branch_values + results[str(len(results))] = with_async(joined) + assert len(results) == 72 + assert_all_equal(results) + + def test_the_commutative_case_is_the_join() -> None: """``Join`` declares itself commutative; ``SemiJoin`` and ``MergeJoin`` (ITL-1281) are ordered.""" diff --git a/tests/test_hashing/golden/cases.py b/tests/test_hashing/golden/cases.py index b4b48ab4b..4641aff05 100644 --- a/tests/test_hashing/golden/cases.py +++ b/tests/test_hashing/golden/cases.py @@ -2053,6 +2053,60 @@ def pipeline_join_pod() -> dict[str, Any]: return out +def tied_join_sources() -> tuple[Any, Any, Any, Any, Any]: + """Build two matching rows in each branch of the tied Join review example.""" + from orcapod.sources import ArrowTableSource + + table = pa.Table.from_arrays( + [pa.array([1, 2]), pa.array([3, 4])], + schema=pa.schema( + [pa.field("k", pa.int64(), False), pa.field("l", pa.int64(), False)] + ), + ) + + def source(name: str) -> Any: + return ArrowTableSource(table, tag_columns=["k", "l"], source_id=name) + + return source("0"), source("a"), source("b"), source("c"), source("z") + + +def _join_entry_ids_and_system_tags(stream: Any) -> dict[str, Any]: + """Pin the provenance fields of each row and the entry ID hashed from them.""" + from orcapod.contexts import get_default_arrow_hasher + from orcapod.core.row_ids import entry_id + from orcapod.system_constants import constants + + hasher = get_default_arrow_hasher() + out: dict[str, Any] = {} + for tag, data in stream.iter_data(): + row = _row_key(tag.as_dict()) + for name, value in tag.as_dict(columns={"system_tags": True}).items(): + if name.startswith(constants.SYSTEM_TAG_PREFIX): + out[f"row[{row}].{name}"] = _jsonable(value) + out[f"row[{row}].entry_id"] = entry_id(hasher, tag, data).to_string() + return out + + +@case("pipeline", "tied_join") +def pipeline_tied_join() -> dict[str, Any]: + """Two equal-schema inputs preserve their system tags and row identities.""" + from orcapod.operators import Join + + _, a, b, _, _ = tied_join_sources() + return _join_entry_ids_and_system_tags(Join()(a, b)) + + +@case("pipeline", "tied_join_diamond") +def pipeline_tied_join_diamond() -> dict[str, Any]: + """An outer tie keeps the two inner branches' provenance bundles intact.""" + from orcapod.operators import Join + + shared, a, b, c, z = tied_join_sources() + return _join_entry_ids_and_system_tags( + Join()(Join()(shared, a, z), Join()(shared, b, c)) + ) + + @case("pipeline", "merge_join", provisional=("MergeJoin",)) def pipeline_merge_join() -> dict[str, Any]: from orcapod.operators import MergeJoin, SelectDataColumns diff --git a/tests/test_hashing/golden/data/v1/pipeline-02.json b/tests/test_hashing/golden/data/v1/pipeline-02.json index 47164f1de..fe34c92b7 100644 --- a/tests/test_hashing/golden/data/v1/pipeline-02.json +++ b/tests/test_hashing/golden/data/v1/pipeline-02.json @@ -492,5 +492,41 @@ "_tag_record_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc" ], "tagless_producerless_stream.as_given": "content_hash_v1:fa17a6e9bf92315a00d492fed8e98d95deaec4421b124a001896393d3cd77462", - "tagless_producerless_stream.reordered": "content_hash_v1:fa17a6e9bf92315a00d492fed8e98d95deaec4421b124a001896393d3cd77462" + "tagless_producerless_stream.reordered": "content_hash_v1:fa17a6e9bf92315a00d492fed8e98d95deaec4421b124a001896393d3cd77462", + "tied_join.row[{\"k\":1,\"l\":3}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0": "row_0", + "tied_join.row[{\"k\":1,\"l\":3}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1": "row_0", + "tied_join.row[{\"k\":1,\"l\":3}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0": "arrow_table_v1:a", + "tied_join.row[{\"k\":1,\"l\":3}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1": "arrow_table_v1:b", + "tied_join.row[{\"k\":1,\"l\":3}].entry_id": "arrow_v1:000002bda2b2721ffcd32058b94c1f7b5244ddc8af0985d9a8cfc592cb0c3aaf1d572e", + "tied_join.row[{\"k\":2,\"l\":4}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0": "row_1", + "tied_join.row[{\"k\":2,\"l\":4}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1": "row_1", + "tied_join.row[{\"k\":2,\"l\":4}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0": "arrow_table_v1:a", + "tied_join.row[{\"k\":2,\"l\":4}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1": "arrow_table_v1:b", + "tied_join.row[{\"k\":2,\"l\":4}].entry_id": "arrow_v1:000002d836247c0e8fe6764547481ae36b419265d2393f840388ee2db76f200f9e8657", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "row_0", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "row_0", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "row_0", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "row_0", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:2::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "row_0", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:2::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "row_0", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "arrow_table_v1:0", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "arrow_table_v1:0", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "arrow_table_v1:a", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "arrow_table_v1:b", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:2::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "arrow_table_v1:z", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:2::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "arrow_table_v1:c", + "tied_join_diamond.row[{\"k\":1,\"l\":3}].entry_id": "arrow_v1:000002b6ad095086966d207ea3cef12b1a3cf55f699ab2ad59a19a5d3f2c2bf8bd3019", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "row_1", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "row_1", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "row_1", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "row_1", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:2::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "row_1", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:2::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "row_1", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "arrow_table_v1:0", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "arrow_table_v1:0", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "arrow_table_v1:a", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "arrow_table_v1:b", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:2::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "arrow_table_v1:z", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:2::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "arrow_table_v1:c", + "tied_join_diamond.row[{\"k\":2,\"l\":4}].entry_id": "arrow_v1:0000028a9b6e40369d0350a8b84ec071cd267d2ea581c8055bfa1e0ed55bc914af175d" }