diff --git a/.zed/rules b/.zed/rules index 909cc51d5..48b2f4209 100644 --- a/.zed/rules +++ b/.zed/rules @@ -659,9 +659,12 @@ algorithm produced it.** alike). - Record ids (developer, November 16, 2026, ITL-1154): the record-id system tag holds the row identifier itself, as text (`large_string`): `row_`, or the canonical JSON of the key - columns in key order (`{"unit":"u1","time":1700000000}`, built only by - `stream_builder.key_row_identifier`). It is not a hash, holds no source id and carries no - label; never build it with `uuid5`. A source-info token is `::::`. + columns in key order (`{"unit":"u1","time":1700000000}`). Build these identifiers only in + `stream_builder`. `key_row_identifier` defines the canonical key text row by row. + `row_identifiers` writes the same text for whole columns, and a property test in CI checks + that the two agree byte for byte over generated keys. Never format a record id by hand + or build it with `uuid5`. It is not a hash, holds no source id and carries no label. + A source-info token is `::::`. - A hash stored as a value in its own column or field carries its label: `to_string()` as text, `to_prefixed_digest()` in a binary column. - A random identifier (`uuid7`, `uuid4`) is not a hash and carries no label. diff --git a/CLAUDE.md b/CLAUDE.md index 8c6ad7207..b544f018c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -670,9 +670,12 @@ algorithm produced it.** alike). - Record ids (developer, November 16, 2026, ITL-1154): the record-id system tag holds the row identifier itself, as text (`large_string`): `row_`, or the canonical JSON of the key - columns in key order (`{"unit":"u1","time":1700000000}`, built only by - `stream_builder.key_row_identifier`). It is not a hash, holds no source id and carries no - label; never build it with `uuid5`. A source-info token is `::::`. + columns in key order (`{"unit":"u1","time":1700000000}`). Build these identifiers only in + `stream_builder`. `key_row_identifier` defines the canonical key text row by row. + `row_identifiers` writes the same text for whole columns, and a property test in CI checks + that the two agree byte for byte over generated keys. Never format a record id by hand + or build it with `uuid5`. It is not a hash, holds no source id and carries no label. + A source-info token is `::::`. - A hash stored as a value in its own column or field carries its label: `to_string()` as text, `to_prefixed_digest()` in a binary column. - A random identifier (`uuid7`, `uuid4`) is not a hash and carries no label. diff --git a/changelog.d/ITL-1790.md b/changelog.d/ITL-1790.md new file mode 100644 index 000000000..bc79100ce --- /dev/null +++ b/changelog.d/ITL-1790.md @@ -0,0 +1,6 @@ +### Changed + +- A source with key columns (`record_id_columns`) writes its rows' record ids over whole + columns with Arrow compute instead of one `json.dumps` per row, several times faster + (ITL-1790). The record ids are byte for byte the same text as before, and a null, + repeated or out-of-range key is refused with the same error. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index edb21d4c0..365a3703d 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -21,7 +21,7 @@ appended, because it is a variant of the same system tag mechanism.) | 2 | `pipeline_hash()` | `SemanticAwarePythonHasher` → JSON + SHA-256 | `ContentHash` | Unique per pipeline topology + schema; data-exclusive | | 3 | Schema hash (system tag column naming) | `SemanticAwarePythonHasher.hash_object((hash_schema(tag), hash_schema(data))).to_hex()` over the Arrow schemas | Full hex digest (`str`) | Unique per Arrow `(tag, data)` schema pair; embedded in system tag column names | | 4 | Default `source_id` of an in-memory source | `":" + StarfixArrowHasher.hash_table(table).to_string()` | `str`, `_v::` | Unique per kind, implementation version and raw table content; the hash is the source's name when none is given | -| 5 | Per-row `record_id` (system tag value) | the row identifier itself: `row_`, or the canonical JSON of the key columns (`key_row_identifier`) | `str` (`large_string`) | Names the row within its source; stable as long as its position or its key is | +| 5 | Per-row `record_id` (system tag value) | `stream_builder.row_identifiers` writes `row_` or the canonical JSON of the key columns | `str` (`large_string`) | Names the row within its source; stable as long as its position or its key is | | 6 | Join system tag suffix | `stream.pipeline_hash().to_hex()` + `:{idx}` appended to column name | Column name suffix | Unique per `(input topology, canonical join position)`; encodes full join lineage in column name | | 6b | Aggregating operator system tag fold | SHA-256 of the canonical JSON list of member values, after the operation's label, for both system tags | `":"` `str`, plus a column name suffix | Deterministic per ordered member set; keeps system tags scalar through a many-to-one reduction | | 7 | Entry id (`row_ids.entry_id`) | `StarfixArrowHasher.hash_table(tags + system_tags + INPUT_DATA_HASH_COL)` | `ContentHash`; stored as `bytes` (`b"method:digest"`) | Unique per `(tag lineage, input_data content)`: an entry of the pipeline table | @@ -1211,11 +1211,16 @@ topology suffix, encoding the full join lineage into each column name. | Field | Value | |---|---| | **Inputs** | The row's position, or the values of the key columns (`record_id_columns`, or a database table's primary key) | -| **Algorithm** | `row_`, or the canonical JSON object of the key columns in key order with no spaces (`stream_builder.key_row_identifier`) | +| **Algorithm** | `row_`, or the canonical JSON object of the key columns in key order with no spaces | | **Output format** | `str`, stored in a `large_string` Arrow column; the column keeps that type through tags, operators and stored tables. Not a hash; it holds no source id | | **Uniqueness guarantee** | Unique within the source: a key repeated in two rows, and a null key value, are refused when the source is built | | **Known exclusions** | A positional identifier changes when rows are inserted before the row or reordered; a key-based one follows the row | +Only `stream_builder` builds these row identifiers. `key_row_identifier` defines the +canonical key text row by row. `row_identifiers` writes the same text for whole columns, and +a property test in CI checks that the two agree byte for byte over generated keys. Never +format a record id by hand. + The record id names the row, and the source-info token names the row and its column. A key value may contain `::`, so the record id may too; a source id and a column name cannot, so the token is split at its first `::` and its last `::` only, never at every `::`. diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 74e104683..762758cdb 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -15,6 +15,7 @@ from typing import TYPE_CHECKING, Any, cast import pyarrow as pa +import pyarrow.compute as pc from orcapod.core.sources import dict_keys from orcapod.core.sources.source_ids import ( @@ -339,8 +340,11 @@ def key_row_identifier(key: Sequence[tuple[str, object]]) -> str: The canonical JSON object of the key columns in the declared key order, with no spaces: ``{"unit":"u1","time":1700000000}``. It handles composite keys and keeps - value types apart (``17`` and ``"17"`` differ). This is the one definition of the - form (ITL-1154). + value types apart (``17`` and ``"17"`` differ). This function defines the canonical + key text (ITL-1154). ``row_identifiers`` writes the same text for whole columns + (ITL-1790). The ``TestByteIdentity`` property tests in + ``test_record_ids_in_arrow.py`` check byte-for-byte agreement over generated keys + in CI. Args: key: ``(column, value)`` pairs in the declared key order; each value a @@ -380,6 +384,13 @@ def key_column_type_allowed(arrow_type: pa.DataType) -> bool: def row_identifiers(table: pa.Table, record_id_columns: Sequence[str]) -> list[str]: """Return each row's identifier: its key, or its position when no key is named. + A key identifier is written over whole columns with Arrow compute (ITL-1790), + byte for byte the text ``key_row_identifier`` writes for the row: each key + column's values as JSON text, joined after their names in key order. A row + holding a string that JSON escapes is written again with ``key_row_identifier`` + itself, and a null or repeated key is found and worded row by row + (``_row_identifiers_per_row``), so the errors are those of the per-row form. + Args: table: The source's rows. record_id_columns: The key columns, in key order; empty for position. @@ -410,15 +421,268 @@ def row_identifiers(table: pa.Table, record_id_columns: Sequence[str]) -> list[s "record_id_columns, or pass record_id_columns=() to identify rows by " "position." ) + if table.num_rows == 0: + return [] + if any(table.column(c).null_count for c in record_id_columns): + # A null key: the per-row form finds the first one in row order and words + # the error. + return _row_identifiers_per_row(table, record_id_columns) + keys = _wide_key_columns(table, record_id_columns) + texts: dict[str, pa.Array[Any]] = {} + needs_escape: pa.Array[Any] | None = None + for column in keys.column_names: + try: + text, escape = _key_value_texts(keys.column(column)) + except OverflowError as exc: + raise _key_out_of_range_error(table, column) from exc + texts[column] = text + if escape is not None: + needs_escape = ( + escape if needs_escape is None else pc.or_(needs_escape, escape) + ) + identifiers = _joined_key_texts(texts) + if needs_escape is not None and pc.any(needs_escape).as_py(): + identifiers = _with_escaped_rows( + identifiers, needs_escape, keys, record_id_columns + ) + if pc.count_distinct(identifiers).as_py() != table.num_rows: + # A repeated key: the per-row form finds the first one in row order and + # words the error. + return _row_identifiers_per_row(table, record_id_columns) + # Through NumPy: the same ``str`` values, without a pyarrow scalar per row. + return cast("list[str]", identifiers.to_numpy(zero_copy_only=False).tolist()) + + +_JSON_ESCAPED = r'[\x00-\x1f"\\]' +"""RE2 class of the characters ``json.dumps`` escapes in a string. + +With ``ensure_ascii=False`` it escapes exactly the quote, the backslash and the +control characters U+0000 to U+001F (``json.encoder.ESCAPE``); every other character, +U+007F and U+2028 included, is written as it is. +""" + +_SECONDS_YEAR_1 = -62_135_596_800 +"""Seconds from the epoch to 0001-01-01T00:00:00, the first writable moment.""" + +_SECONDS_YEAR_10000 = 253_402_300_800 +"""Seconds from the epoch to 10000-01-01T00:00:00, the first moment past year 9999.""" + +_DAYS_YEAR_1 = -719_162 +"""Days from the epoch to 0001-01-01, the first writable date.""" + +_DAYS_YEAR_10000 = 2_932_897 +"""Days from the epoch to 10000-01-01, the first date past year 9999.""" + +_MILLIS_PER_DAY = 86_400_000 + + +def _require_iso_years(values: pa.Array[Any], start: int, stop: int) -> None: + """Raise ``OverflowError`` if a valid value of ``values`` is outside ``[start, stop)``. + + Args: + values: Integers (units since the epoch); nulls are ignored. + start: The smallest value whose moment lies in year 1. + stop: The smallest value whose moment lies past year 9999. + + Raises: + OverflowError: If a value lies outside years 1 to 9999, as the per-row + formatting raises (``_key_values``). + """ + bounds = pc.min_max(values) + low, high = bounds["min"].as_py(), bounds["max"].as_py() + if low is not None and (low < start or high >= stop): + raise OverflowError("key value outside years 1 to 9999") + + +def _wide_key_columns(table: pa.Table, record_id_columns: Sequence[str]) -> pa.Table: + """Return the key columns, each once, with a ``string`` column as ``large_string``. + + A ``string`` column may hold more than 2 GiB across its chunks, which one + ``string`` array cannot (its offsets are 32-bit): concatenating or taking from + it raises. The cast is made chunk by chunk, before anything concatenates the + chunks, so every array built from the keys has 64-bit offsets. The values are + unchanged. + + Args: + table: The source's rows. + record_id_columns: The key columns, in key order. + + Returns: + A table of the key columns in key order, each named once. + """ + keys = table.select(list(dict.fromkeys(record_id_columns))) + for i, field in enumerate(keys.schema): + if pa.types.is_string(field.type): + keys = keys.set_column( + i, + field.with_type(pa.large_string()), + keys.column(i).cast(pa.large_string()), + ) + return keys + + +def _key_value_texts( + column: "pa.ChunkedArray[Any]", +) -> tuple[pa.Array[Any], pa.Array[Any] | None]: + """Return a key column's values as JSON text, computed over the whole column. + + The vectorized form of ``_key_values`` followed by ``key_row_identifier``'s JSON + writing of each value: an integer as its decimal digits, a boolean as ``true`` + or ``false``, a string, a timestamp (``_timestamp_text``) and a date + (``YYYY-MM-DD``) as a quoted JSON string. A string holding a character that + JSON escapes is written here without its escapes; the second array marks those + values, which the caller writes again row by row. + + Args: + column: A key column of an allowed type (``key_column_type_allowed``), a + string column as ``large_string`` (``_wide_key_columns``), so that its + chunks combine into one array whatever their total size. + + Returns: + One ``large_string`` text per row (null for a null value), and for a string + column the mask of values that need escaping (``None`` for other types). + + Raises: + OverflowError: If a timestamp or date lies outside years 1 to 9999. + """ + values = column.combine_chunks() + arrow_type = values.type + escape: pa.Array[Any] | None = None + if pa.types.is_timestamp(arrow_type): + unit = arrow_type.unit + scale = 10 ** _FRACTION_DIGITS[unit] + ints = values.cast(pa.int64()) + _require_iso_years(ints, _SECONDS_YEAR_1 * scale, _SECONDS_YEAR_10000 * scale) + # Arrow writes ``YYYY-MM-DD HH:MM:SS[.fraction]`` with the unit's digits, as + # ``_timestamp_text`` does after the ``T``; a zoned value is written as its + # UTC moment, from the stored integer. + text = pc.replace_substring( + ints.cast(pa.timestamp(unit)).cast(pa.large_string()), + " ", + "T", + max_replacements=1, + ) + if arrow_type.tz is not None: + text = pc.binary_join_element_wise(text, _large("Z"), _large("")) # pyright: ignore[reportCallIssue, reportArgumentType] # pyarrow joins arrays and scalars; the stubs type scalars only + elif pa.types.is_date32(arrow_type): + days = values.cast(pa.int32()) + _require_iso_years(days, _DAYS_YEAR_1, _DAYS_YEAR_10000) + text = values.cast(pa.large_string()) + elif pa.types.is_date64(arrow_type): + millis = values.cast(pa.int64()) + _require_iso_years( + millis, _DAYS_YEAR_1 * _MILLIS_PER_DAY, _DAYS_YEAR_10000 * _MILLIS_PER_DAY + ) + # The day holding the moment (floored, as ``date + timedelta`` does): the + # date part of the moment's text, always ten characters in years 1 to 9999. + text = pc.utf8_slice_codeunits( + millis.cast(pa.timestamp("ms")).cast(pa.large_string()), 0, 10 + ) + elif pa.types.is_boolean(arrow_type) or pa.types.is_integer(arrow_type): + return values.cast(pa.large_string()), None + else: + text = values.cast(pa.large_string()) + escape = cast( + "pa.Array[Any]", + pc.fill_null( + pc.match_substring_regex(text, _JSON_ESCAPED), pa.scalar(False) + ), + ) + quote = _large('"') + joined = pc.binary_join_element_wise(quote, text, quote, _large("")) # pyright: ignore[reportCallIssue, reportArgumentType] # pyarrow joins arrays and scalars; the stubs type scalars only + return joined, escape + + +def _large(text: str) -> pa.Scalar[Any]: + """Return ``text`` as a ``large_string`` scalar, for Arrow's string kernels.""" + return pa.scalar(text, pa.large_string()) + + +def _joined_key_texts(texts: dict[str, pa.Array[Any]]) -> pa.Array[Any]: + """Join each row's key value texts into the row's JSON object, in key order. + + Each value follows its column name written as JSON (``json.dumps`` of the name, + as ``key_row_identifier`` writes a dictionary key), with no spaces. + + Args: + texts: Each key column's value texts (``_key_value_texts``), in key order, + each column once. + + Returns: + One identifier per row; null where a value is null. + """ + parts: list[pa.Scalar[Any] | pa.Array[Any]] = [] + for position, (name, text) in enumerate(texts.items()): + lead = "{" if position == 0 else "," + parts += [_large(f"{lead}{json.dumps(name, ensure_ascii=False)}:"), text] + parts.append(_large("}")) + return pc.binary_join_element_wise(*parts, _large("")) # pyright: ignore[reportCallIssue, reportArgumentType] # pyarrow joins arrays and scalars; the stubs type scalars only + + +def _with_escaped_rows( + identifiers: pa.Array[Any], + rows: pa.Array[Any], + keys: pa.Table, + record_id_columns: Sequence[str], +) -> pa.Array[Any]: + """Write the identifiers of the marked rows again with ``key_row_identifier``. + + Args: + identifiers: The joined identifiers, wrong at the marked rows. + rows: Marks the rows holding a string key value that JSON escapes. + keys: The key columns (``_wide_key_columns``), so that taking rows from a + string column never concatenates it with 32-bit offsets. + record_id_columns: The key columns, in key order. + + Returns: + ``identifiers`` with each marked row's identifier replaced. + """ + marked = keys.take(pc.indices_nonzero(rows)) + columns = { + c: _key_values(marked.column(c)) for c in dict.fromkeys(record_id_columns) + } + replacements = [ + key_row_identifier([(c, columns[c][i]) for c in record_id_columns]) + for i in range(marked.num_rows) + ] + return pc.replace_with_mask( + identifiers, rows, pa.array(replacements, pa.large_string()) + ) + + +def _key_out_of_range_error(table: pa.Table, column: str) -> RowIdentifierError: + """Return the error for a timestamp or date key outside years 1 to 9999.""" + return RowIdentifierError( + f"key column {column!r} holds a {table.schema.field(column).type} " + "value outside years 1 to 9999, which a row identifier cannot write" + ) + + +def _row_identifiers_per_row( + table: pa.Table, record_id_columns: Sequence[str] +) -> list[str]: + """Return each row's key identifier, written row by row with ``key_row_identifier``. + + The per-row form of ``row_identifiers``: ``row_identifiers`` uses it to find and + word the first null or repeated key in row order. + + Args: + table: The source's rows; its key columns are present and of allowed types. + record_id_columns: The key columns, in key order (at least one). + + Returns: + One identifier per row, in row order. + + Raises: + RowIdentifierError: If a timestamp or date key lies outside years 1 to 9999, + a key value is null, or two rows have the same key. + """ columns: dict[str, list[object]] = {} for column in record_id_columns: try: columns[column] = _key_values(table.column(column)) except OverflowError as exc: - raise RowIdentifierError( - f"key column {column!r} holds a {table.schema.field(column).type} " - "value outside years 1 to 9999, which a row identifier cannot write" - ) from exc + raise _key_out_of_range_error(table, column) from exc identifiers: list[str] = [] seen: dict[str, int] = {} for i in range(table.num_rows): diff --git a/tests/test_core/sources/test_record_ids_in_arrow.py b/tests/test_core/sources/test_record_ids_in_arrow.py new file mode 100644 index 000000000..37880beb8 --- /dev/null +++ b/tests/test_core/sources/test_record_ids_in_arrow.py @@ -0,0 +1,470 @@ +"""Key record ids written over whole columns equal the per-row JSON (ITL-1790). + +``row_identifiers`` writes a keyed row's identifier with Arrow compute. The text +enters stored values and golden pins, so it must be byte for byte the text +``key_row_identifier`` writes for the row (ITL-1154), and every refusal (a null, a +repeated key, a moment outside years 1 to 9999) must be the one the per-row form +raises, with the same message. The per-row form (``_row_identifiers_per_row``) is +the reference these tests compare against; the tests are about that equivalence, +so they call both directly. +""" + +from __future__ import annotations + +import datetime +import json +import os +from typing import Any, cast + +import pyarrow as pa +import pytest +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st + +from orcapod.core.sources.arrow_table_source import ArrowTableSource +from orcapod.core.sources.stream_builder import ( + _row_identifiers_per_row, + _wide_key_columns, + key_row_identifier, + row_identifiers, +) +from orcapod.errors import RowIdentifierError +from orcapod.system_constants import constants + +_SECONDS_YEAR_1 = -62_135_596_800 +_SECONDS_YEAR_10000 = 253_402_300_800 +_DAYS_YEAR_1 = -719_162 +_DAYS_YEAR_10000 = 2_932_897 +_SCALE = {"s": 1, "ms": 10**3, "us": 10**6, "ns": 10**9} +_INT64 = (-(2**63), 2**63 - 1) + +# Characters JSON escapes, and some it does not (U+007F, U+2028, non-BMP). +_SPECIAL = '"\\\x00\x01\x08\x09\x0a\x0c\x0d\x1b\x1f\x7f
é\U0001f600 ' +_TEXT = st.text( + alphabet=st.one_of( + st.sampled_from(_SPECIAL), + st.characters(blacklist_categories=("Cs",)), + ), + max_size=8, +) +_TIMESTAMP_TYPES: list[pa.TimestampType[Any, Any]] = [ + t + for zone in ("UTC", "America/New_York", "+05:30") + for t in ( + pa.timestamp("s"), + pa.timestamp("ms"), + pa.timestamp("us"), + pa.timestamp("ns"), + pa.timestamp("s", tz=zone), + pa.timestamp("ms", tz=zone), + pa.timestamp("us", tz=zone), + pa.timestamp("ns", tz=zone), + ) +] +_INT_TYPES = { + pa.int8(): (-(2**7), 2**7 - 1), + pa.int16(): (-(2**15), 2**15 - 1), + pa.int32(): (-(2**31), 2**31 - 1), + pa.int64(): _INT64, + pa.uint8(): (0, 2**8 - 1), + pa.uint16(): (0, 2**16 - 1), + pa.uint32(): (0, 2**32 - 1), + pa.uint64(): (0, 2**64 - 1), +} + + +def _edges(low: int, high: int) -> st.SearchStrategy[int]: + """Integers in ``[low, high]``, often at or next to either end.""" + return st.one_of( + st.integers(low, high), + st.sampled_from([low, min(low + 1, high), max(high - 1, low), high]), + ) + + +def _bounded(start: int, stop: int, low: int, high: int) -> st.SearchStrategy[int]: + """Stored integers of a moment column: mostly in ``[start, stop)``, sometimes not.""" + inside = _edges(max(start, low), min(stop - 1, high)) + outside = [v for v in (start - 1, stop) if low <= v <= high] + if not outside: + return inside + return st.one_of(inside, inside, inside, st.sampled_from(outside)) + + +@st.composite +def _key_column(draw: st.DrawFn) -> tuple[pa.DataType, st.SearchStrategy[Any]]: + """An allowed key type and a strategy for its stored values (nulls included).""" + kind = draw( + st.sampled_from(["string", "large_string", "int", "bool", "ts", "d32", "d64"]) + ) + if kind == "string": + arrow_type, values = pa.string(), _TEXT + elif kind == "large_string": + arrow_type, values = pa.large_string(), _TEXT + elif kind == "int": + arrow_type = draw(st.sampled_from(list(_INT_TYPES))) + values = _edges(*_INT_TYPES[arrow_type]) + elif kind == "bool": + arrow_type, values = pa.bool_(), st.booleans() + elif kind == "ts": + arrow_type = draw(st.sampled_from(_TIMESTAMP_TYPES)) + scale = _SCALE[arrow_type.unit] + values = _bounded(_SECONDS_YEAR_1 * scale, _SECONDS_YEAR_10000 * scale, *_INT64) + elif kind == "d32": + arrow_type = pa.date32() + values = _bounded(_DAYS_YEAR_1, _DAYS_YEAR_10000, -(2**31), 2**31 - 1) + else: + arrow_type = pa.date64() + day = 86_400_000 + values = _bounded(_DAYS_YEAR_1 * day, _DAYS_YEAR_10000 * day, *_INT64) + with_nulls = st.one_of(values, values, values, values, values, st.none()) + return arrow_type, with_nulls + + +def _array(values: list[Any], arrow_type: pa.DataType) -> pa.Array[Any]: + """Build a column from stored values: integers for the moment types.""" + if pa.types.is_timestamp(arrow_type) or pa.types.is_date64(arrow_type): + return pa.array(values, pa.int64()).cast(arrow_type) + if pa.types.is_date32(arrow_type): + return pa.array(values, pa.int32()).cast(arrow_type) + return pa.array(values, arrow_type) + + +def _outcome(function: Any, table: pa.Table, key: list[str]) -> tuple[str, Any]: + """Return ``("ok", identifiers)`` or ``("refused", message)``.""" + try: + return "ok", function(table, key) + except RowIdentifierError as exc: + return "refused", str(exc) + + +@st.composite +def _keyed_tables(draw: st.DrawFn) -> tuple[pa.Table, list[str]]: + """A table of 1 to 3 key columns of any allowed types, and its key order.""" + count = draw(st.integers(1, 3)) + names = draw(st.lists(_TEXT, min_size=count, max_size=count, unique=True)) + rows = draw(st.integers(1, 12)) + columns = {} + for name in names: + arrow_type, values = draw(_key_column()) + data = draw(st.lists(values, min_size=rows, max_size=rows)) + columns[name] = _array(data, arrow_type) + key = draw(st.permutations(names)) + if draw(st.booleans()): + # A key column named twice: the per-row form writes it once. + key = [*key, key[0]] + return pa.table(columns), list(key) + + +class TestByteIdentity: + @settings( + max_examples=1500, + deadline=None, + suppress_health_check=[HealthCheck.too_slow, HealthCheck.data_too_large], + ) + @given(_keyed_tables()) + def test_arrow_text_equals_the_per_row_text( + self, case: tuple[pa.Table, list[str]] + ) -> None: + """Every allowed type, any values: the same text, or the same refusal.""" + table, key = case + expected = _outcome(_row_identifiers_per_row, table, key) + assert _outcome(row_identifiers, table, key) == expected + if expected[0] == "ok": + assert all(type(i) is str for i in expected[1]) + + @settings(max_examples=500, deadline=None) + @given( + st.lists( + st.tuples(_TEXT, st.integers(-(2**63), 2**63 - 1), st.booleans()), + min_size=1, + max_size=10, + unique_by=lambda row: row[0], + ) + ) + def test_arrow_text_equals_key_row_identifier_of_the_python_values( + self, rows: list[tuple[str, int, bool]] + ) -> None: + """Strings, integers and booleans: ``key_row_identifier`` of each row's values.""" + table = pa.table( + { + "s": pa.array([r[0] for r in rows], pa.large_string()), + 'q"\\': pa.array([r[1] for r in rows], pa.int64()), + "bé": pa.array([r[2] for r in rows], pa.bool_()), + } + ) + key = ["bé", "s", 'q"\\'] + expected = [ + key_row_identifier([("bé", b), ("s", s), ('q"\\', q)]) for s, q, b in rows + ] + assert row_identifiers(table, key) == expected + + +class TestFixedCases: + def test_moments_at_the_edges(self) -> None: + """Timestamps of every unit and dates at years 1 and 9999 and around the epoch.""" + cases: list[tuple[pa.DataType, list[int], list[str]]] = [ + ( + pa.timestamp("s"), + [_SECONDS_YEAR_1, -1, 0, _SECONDS_YEAR_10000 - 1], + [ + "0001-01-01T00:00:00", + "1969-12-31T23:59:59", + "1970-01-01T00:00:00", + "9999-12-31T23:59:59", + ], + ), + ( + pa.timestamp("ms", tz="UTC"), + [-1, 5], + ["1969-12-31T23:59:59.999Z", "1970-01-01T00:00:00.005Z"], + ), + ( + pa.timestamp("us", tz="Asia/Tokyo"), + [1], + ["1970-01-01T00:00:00.000001Z"], + ), + ( + pa.timestamp("ns"), + [_INT64[0], _INT64[1]], + ["1677-09-21T00:12:43.145224192", "2262-04-11T23:47:16.854775807"], + ), + ( + pa.date32(), + [_DAYS_YEAR_1, -1, _DAYS_YEAR_10000 - 1], + ["0001-01-01", "1969-12-31", "9999-12-31"], + ), + ( + pa.date64(), + [-1, 86_400_000 - 1, _DAYS_YEAR_1 * 86_400_000], + ["1969-12-31", "1970-01-01", "0001-01-01"], + ), + ] + for arrow_type, stored, texts in cases: + table = pa.table({"k": _array(stored, arrow_type)}) + expected = [json.dumps({"k": t}, separators=(",", ":")) for t in texts] + assert row_identifiers(table, ["k"]) == expected, arrow_type + assert _row_identifiers_per_row(table, ["k"]) == expected, arrow_type + + def test_rows_that_need_escaping_among_many_and_differently_chunked(self) -> None: + """Escaped rows are written again in place; chunking does not matter.""" + n = 5000 + names = [f"r{i}" if i % 997 else f'r{i}"\\\n\x01' for i in range(n)] + name_column = pa.chunked_array( + [names[:1234], names[1234:]], type=pa.large_string() + ) + index_column = pa.chunked_array( + [list(range(0, 3000)), list(range(3000, n))], type=pa.int32() + ) + table = pa.table([name_column, index_column], names=["name", "i"]) + expected = [ + json.dumps({"i": i, "name": s}, separators=(",", ":"), ensure_ascii=False) + for i, s in enumerate(names) + ] + assert row_identifiers(table, ["i", "name"]) == expected + + @pytest.mark.parametrize( + ("columns", "message"), + [ + ( + {"a": ["x", "y", "x", None]}, + 'key {"a":"x"} appears in rows 0 and 2', + ), + ( + {"a": ["x", None, "x", "z"]}, + "key column 'a' is null in row 1", + ), + ( + {"a": ["x", "y", None], "b": [1, None, None]}, + "key column 'b' is null in row 1", + ), + ( + # Found by the property test: the escaped row is written again, and + # its text must not hide the null beside it. + {"a": ['"'], "b": pa.array([None], pa.int64())}, + "key column 'b' is null in row 0", + ), + ( + {"a": ['"', '"']}, + 'key {"a":"\\""} appears in rows 0 and 1', + ), + ], + ids=[ + "repeat-before-null", + "null-before-repeat", + "first-null-column", + "null-beside-escaped-string", + "escaped", + ], + ) + def test_the_first_refusal_in_row_order( + self, columns: dict[str, Any], message: str + ) -> None: + """A null or a repeat is reported where the per-row form reports it.""" + table = pa.table(columns) + with pytest.raises(RowIdentifierError) as caught: + row_identifiers(table, list(columns)) + assert message in str(caught.value) + + def test_a_moment_past_year_9999_is_refused_before_a_null(self) -> None: + """A key column out of range is refused before any null, as row by row.""" + table = pa.table( + { + "a": pa.array([None, "y"]), + "t": pa.array([0, _SECONDS_YEAR_10000], pa.int64()).cast( + pa.timestamp("s") + ), + } + ) + with pytest.raises(RowIdentifierError, match="outside years 1 to 9999"): + row_identifiers(table, ["a", "t"]) + + def test_no_rows(self) -> None: + """A table without rows has no identifiers.""" + table = pa.table({"k": pa.array([], pa.large_string())}) + assert row_identifiers(table, ["k"]) == [] + + def test_a_date_is_written_from_the_python_date(self) -> None: + """A date32 key is ``YYYY-MM-DD``, as ``date.isoformat`` writes it.""" + day = datetime.date(2000, 2, 29) + table = pa.table({"d": pa.array([day], pa.date32())}) + assert row_identifiers(table, ["d"]) == ['{"d":"2000-02-29"}'] + + +# A ``string`` column has 32-bit offsets, so one ``string`` array holds at most +# 2 GiB of text; a chunked ``string`` column can hold more across its chunks, and +# combining or taking from it then overflows. ``_wide_key_columns`` decides from the +# column's Arrow type alone (``string`` becomes ``large_string``, chunk by chunk), +# never from its size, so the tests in the default run check that decision on small +# chunked columns: the 64-bit path a 2 GiB column takes is the path these take. One +# opt-in test below builds a real column above 2 GiB. + + +def _chunked_string_key(*chunks: list[str | None]) -> pa.ChunkedArray[Any]: + return pa.chunked_array([pa.array(chunk, pa.string()) for chunk in chunks]) + + +def _keyed_table(key: pa.ChunkedArray[Any]) -> pa.Table: + return pa.Table.from_arrays( + [key, pa.chunked_array([pa.array(range(len(key)), pa.int64())])], + names=["key", "part"], + ) + + +class TestStringKeyColumnsAreReadWide: + """A ``string`` key column is read with 64-bit offsets, whatever its size.""" + + def test_a_string_key_column_is_read_as_large_string_with_its_chunks( + self, + ) -> None: + # Each chunk is cast on its own, before anything combines the chunks, so + # no array built from the keys has 32-bit offsets. + key = _chunked_string_key(["a", "b"], ["c"], ["d", "e"]) + keys = _wide_key_columns(_keyed_table(key), ["part", "key", "part"]) + assert keys.column_names == ["part", "key"] + assert keys.schema.field("key").type == pa.large_string() + assert keys.schema.field("part").type == pa.int64() + assert keys.column("key").num_chunks == key.num_chunks + assert keys.column("key").to_pylist() == key.to_pylist() + taken = keys.take(pa.array([0, len(key) - 1])) + assert taken.column("key").to_pylist() == ["a", "e"] + + def test_a_large_string_key_column_is_kept_as_it_is(self) -> None: + key = pa.chunked_array( + [pa.array(["a"], pa.large_string()), pa.array(["b"], pa.large_string())] + ) + keys = _wide_key_columns(_keyed_table(key), ["key", "part"]) + assert keys.column("key").equals(key) + + def test_a_chunked_string_key_gives_the_per_row_identifiers(self) -> None: + # A key JSON escapes in a later chunk is written again by the per-row + # form, from rows taken out of the wide key columns. + key = _chunked_string_key(["a", "b"], ['c"d', "e\\f"], ["g"]) + table = _keyed_table(key) + expected = _row_identifiers_per_row(table, ["key", "part"]) + assert row_identifiers(table, ["key", "part"]) == expected + assert expected[2] == key_row_identifier([("key", 'c"d'), ("part", 2)]) + + def test_a_null_in_a_later_chunk_is_refused_as_by_the_per_row_form( + self, + ) -> None: + key = _chunked_string_key(["a", "b"], ["c", None]) + with pytest.raises(RowIdentifierError) as error: + _ = row_identifiers(_keyed_table(key), ["key", "part"]) + assert str(error.value) == ( + "key column 'key' is null in row 3: a key value identifies the row and " + "cannot be null" + ) + + +# The one test that builds a ``string`` key column above 2 GiB. Each chunk is the +# same 32 MiB array, so the source table holds 32 MiB of text, but reading it writes +# several GiB (the wide key columns and the identifiers). It is opt in, and never +# runs beside other tests: run it alone with +# ``ORCAPOD_LARGE_MEMORY_TESTS=1 uv run pytest -n 0 ``. +_CHUNK_BYTES = 32 * 1024 * 1024 +_CHUNKS_ABOVE_2_GIB = 65 +_LARGE_MEMORY_BYTES = 16 * 1024**3 + + +def _physical_memory() -> int | None: + try: + return os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") + except (AttributeError, ValueError, OSError): + return None + + +def _large_memory_skip_reason() -> str | None: + if os.environ.get("ORCAPOD_LARGE_MEMORY_TESTS") != "1": + return ( + "builds several GiB of key text; opt in with ORCAPOD_LARGE_MEMORY_TESTS=1" + ) + if os.environ.get("PYTEST_XDIST_WORKER") is not None: + return "builds several GiB of key text; run it serially (-n 0), not on an xdist worker" + memory = _physical_memory() + if memory is None or memory < _LARGE_MEMORY_BYTES: + return "builds several GiB of key text; needs at least 16 GiB of memory" + return None + + +def _record_ids(source: ArrowTableSource) -> list[str]: + table = source.as_table(columns={"system_tags": True}) + [name] = [ + c + for c in table.column_names + if c.startswith(constants.SYSTEM_TAG_RECORD_ID_PREFIX) + ] + return cast("list[str]", table.column(name).to_pylist()) + + +@pytest.mark.skipif( + _large_memory_skip_reason() is not None, + reason=_large_memory_skip_reason() or "", +) +def test_a_string_key_column_above_2_gib_gives_the_per_row_identifiers() -> None: + # Overflowed concatenating the key's chunks (ArrowInvalid), and taking the + # escaped row from the narrow column overflowed too. + chunk = pa.array(["x" * _CHUNK_BYTES], pa.string()) + key = pa.chunked_array( + [pa.array(['a"b'], pa.string()), *[chunk] * _CHUNKS_ABOVE_2_GIB] + ) + table = pa.Table.from_arrays( + [ + key, + pa.chunked_array([pa.array(range(len(key)), pa.int64())]), + pa.chunked_array([pa.array([1] * len(key), pa.int64())]), + ], + names=["key", "part", "value"], + ) + assert table.column("key").nbytes > 2**31 + source = ArrowTableSource( + table, + tag_columns=["key", "part"], + tag_only_columns=True, + record_id_columns=["key", "part"], + ) + ids = _record_ids(source) + assert ids[0] == key_row_identifier([("key", 'a"b'), ("part", 0)]) + assert ids[1:] == [ + key_row_identifier([("key", "x" * _CHUNK_BYTES), ("part", i)]) + for i in range(1, _CHUNKS_ABOVE_2_GIB + 1) + ]