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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions .zed/rules
Original file line number Diff line number Diff line change
Expand Up @@ -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_<n>`, 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 `<source id>::<record id>::<column>`.
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 `<source id>::<record id>::<column>`.
- 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.
Expand Down
9 changes: 6 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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_<n>`, 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 `<source id>::<record id>::<column>`.
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 `<source id>::<record id>::<column>`.
- 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.
Expand Down
6 changes: 6 additions & 0 deletions changelog.d/ITL-1790.md
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 7 additions & 2 deletions docs/reference/hashing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 | `"<kind part>:" + StarfixArrowHasher.hash_table(table).to_string()` | `str`, `<kind>_v<N>:<algorithm label>:<hex>` | 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_<n>`, 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_<n>` 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 | `"<fold label>:<hex>"` `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 |
Expand Down Expand Up @@ -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_<n>`, or the canonical JSON object of the key columns in key order with no spaces (`stream_builder.key_row_identifier`) |
| **Algorithm** | `row_<n>`, 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 `::`.
Expand Down
276 changes: 270 additions & 6 deletions src/orcapod/core/sources/stream_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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):
Expand Down
Loading
Loading