From 3840e1eb8e1f7ea6a940104e5af21d1877f1eabc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 17:31:09 -0800 Subject: [PATCH 01/20] feat(logical-types)!: declare value hashes in extension metadata --- src/orcapod/hashing/hash_utils.py | 3 +- .../semantic_hashing/builtin_handlers.py | 14 ++-- src/orcapod/hashing/visitors.py | 4 +- src/orcapod/logical_types/array_format.py | 3 + .../logical_types/builtin_logical_types.py | 2 +- src/orcapod/logical_types/directory_type.py | 3 +- src/orcapod/logical_types/file_type.py | 3 +- src/orcapod/logical_types/identifier.py | 65 ++++++++++++++--- src/orcapod/logical_types/ignore_list.py | 71 +++++++++++++------ src/orcapod/logical_types/numpy_type.py | 2 + src/orcapod/logical_types/pandas_type.py | 4 ++ src/orcapod/logical_types/polars_type.py | 6 ++ src/orcapod/logical_types/registry.py | 13 +++- src/orcapod/logical_types/torch_type.py | 1 + .../logical_types/user_class_logical_type.py | 2 +- 15 files changed, 152 insertions(+), 44 deletions(-) diff --git a/src/orcapod/hashing/hash_utils.py b/src/orcapod/hashing/hash_utils.py index f688fd6ff..e2a507b9c 100644 --- a/src/orcapod/hashing/hash_utils.py +++ b/src/orcapod/hashing/hash_utils.py @@ -9,7 +9,6 @@ from upath import UPath -from orcapod.logical_types.identifier import logical_type_identifier from orcapod.types import ContentHash, PathLike from orcapod.utils.canonical_type_names import stabilize_type_names @@ -81,6 +80,8 @@ class a factory covers (a dataclass, an ``orcapod.dataclass``, a pydantic if type_converter is not None and isinstance(annotation, type): lt = type_converter.get_logical_type_for_python_type(annotation) if lt is not None: + from orcapod.logical_types.identifier import logical_type_identifier + return logical_type_identifier(lt).text # Union types (PEP 604 X | Y and typing.Union): sort members for order-independence diff --git a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py index b98acc96d..8d382d840 100644 --- a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py +++ b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py @@ -41,7 +41,11 @@ ) from orcapod.hashing.semantic_hashing.encoded import Encoded from orcapod.hashing.semantic_hashing.function_info_extractors import ParameterDefault -from orcapod.logical_types.array_format import NDARRAY_EXTENSION_NAME, NDARRAY_OPTIONS +from orcapod.logical_types.array_format import ( + NDARRAY_EXTENSION_NAME, + NDARRAY_HASH_LABEL, + NDARRAY_OPTIONS, +) from orcapod.logical_types.identifier import logical_type_identifier from orcapod.logical_types.ignore_list import IgnoreListHandler from orcapod.logical_types.pandas_type import ( @@ -50,7 +54,9 @@ ) from orcapod.logical_types.polars_type import ( POLARS_DATAFRAME_EXTENSION_NAME, + POLARS_DATAFRAME_HASH_LABEL, POLARS_SERIES_EXTENSION_NAME, + POLARS_SERIES_HASH_LABEL, ) from orcapod.types import ContentHash, Schema from orcapod.utils.canonical_type_names import canonical_type_name @@ -568,7 +574,7 @@ class NumpyArrayHandler(IgnoreListHandler): EXTENSION_NAME = NDARRAY_EXTENSION_NAME OPTIONS = NDARRAY_OPTIONS - HASH_LABEL = "ndarray_v1" + HASH_LABEL = NDARRAY_HASH_LABEL """``ContentHash.method`` of an ndarray hash.""" def digest(self, obj: Any, ignore: frozenset[str]) -> bytes: @@ -778,7 +784,7 @@ class PolarsDataFrameHandler(IgnoreListHandler): EXTENSION_NAME = POLARS_DATAFRAME_EXTENSION_NAME OPTIONS = frozenset({"column_order", "struct_field_order"}) - HASH_LABEL = "polars_dataframe_v1" + HASH_LABEL = POLARS_DATAFRAME_HASH_LABEL """``ContentHash.method`` of a ``pl.DataFrame`` hash.""" def digest(self, obj: Any, ignore: frozenset[str]) -> bytes: @@ -820,7 +826,7 @@ class PolarsSeriesHandler(IgnoreListHandler): EXTENSION_NAME = POLARS_SERIES_EXTENSION_NAME OPTIONS = frozenset({"series_name", "struct_field_order"}) - HASH_LABEL = "polars_series_v1" + HASH_LABEL = POLARS_SERIES_HASH_LABEL """``ContentHash.method`` of a ``pl.Series`` hash.""" def digest(self, obj: Any, ignore: frozenset[str]) -> bytes: diff --git a/src/orcapod/hashing/visitors.py b/src/orcapod/hashing/visitors.py index bdca0a7f9..6ca73c852 100644 --- a/src/orcapod/hashing/visitors.py +++ b/src/orcapod/hashing/visitors.py @@ -466,7 +466,9 @@ def visit_extension( # A value type with an ignore list (ITL-981): the cell is hashed under # the list of its own column, read from the column's extension # metadata, never under the list the data context configures. - _, ignore = parse_ignore_metadata(extension_type.__arrow_ext_serialize__()) + _, ignore, _ = parse_ignore_metadata( + extension_type.__arrow_ext_serialize__() + ) content_hash = handler.hash_ignoring(python_obj, ignore) else: content_hash = self._python_hasher.hash_object(python_obj) diff --git a/src/orcapod/logical_types/array_format.py b/src/orcapod/logical_types/array_format.py index 621de1500..63fd26061 100644 --- a/src/orcapod/logical_types/array_format.py +++ b/src/orcapod/logical_types/array_format.py @@ -34,6 +34,9 @@ It is also the leading type text of the ndarray value hash. """ +NDARRAY_HASH_LABEL = "ndarray_v1" +"""The label of the ndarray value hash built on this element digest.""" + NDARRAY_OPTIONS = frozenset({"byte_order", "memory_order", "struct_layout"}) """The property names the ndarray value hash can ignore (see ``numpy_type``).""" diff --git a/src/orcapod/logical_types/builtin_logical_types.py b/src/orcapod/logical_types/builtin_logical_types.py index 46109017d..510b8e807 100644 --- a/src/orcapod/logical_types/builtin_logical_types.py +++ b/src/orcapod/logical_types/builtin_logical_types.py @@ -40,7 +40,7 @@ from orcapod.logical_types.protocols import TypeConverterProtocol -_IDENTIFIER_METADATA = version_metadata(1) +_IDENTIFIER_METADATA = version_metadata(1, "stored") """Extension metadata of the types in this module: version 1 of their stored layout.""" _LEGACY_METADATA = (b"",) diff --git a/src/orcapod/logical_types/directory_type.py b/src/orcapod/logical_types/directory_type.py index 8eec9b8ad..d8a0c5cb5 100644 --- a/src/orcapod/logical_types/directory_type.py +++ b/src/orcapod/logical_types/directory_type.py @@ -23,6 +23,7 @@ from upath import UPath from upath.extensions import ProxyUPath +from orcapod.hashing.directory_hashers import DIRECTORY_HASH_LABEL from orcapod.logical_types.base_logical_type import BaseLogicalType from orcapod.logical_types.identifier import version_metadata from orcapod.logical_types.registry import ( @@ -34,7 +35,7 @@ from orcapod.logical_types.protocols import TypeConverterProtocol -_IDENTIFIER_METADATA = version_metadata(1) +_IDENTIFIER_METADATA = version_metadata(1, DIRECTORY_HASH_LABEL) """Extension metadata of the types in this module: version 1 of their stored layout.""" _LEGACY_METADATA = (b"",) diff --git a/src/orcapod/logical_types/file_type.py b/src/orcapod/logical_types/file_type.py index 862a913a9..58b74e362 100644 --- a/src/orcapod/logical_types/file_type.py +++ b/src/orcapod/logical_types/file_type.py @@ -19,6 +19,7 @@ from upath import UPath from upath.extensions import ProxyUPath +from orcapod.hashing.hash_utils import SHA256_ALGORITHM from orcapod.logical_types.base_logical_type import BaseLogicalType from orcapod.logical_types.identifier import version_metadata from orcapod.logical_types.registry import ( @@ -30,7 +31,7 @@ from orcapod.logical_types.protocols import TypeConverterProtocol -_IDENTIFIER_METADATA = version_metadata(1) +_IDENTIFIER_METADATA = version_metadata(1, SHA256_ALGORITHM) """Extension metadata of the types in this module: version 1 of their stored layout.""" _LEGACY_METADATA = (b"",) diff --git a/src/orcapod/logical_types/identifier.py b/src/orcapod/logical_types/identifier.py index 840066ff0..7c6d10110 100644 --- a/src/orcapod/logical_types/identifier.py +++ b/src/orcapod/logical_types/identifier.py @@ -2,9 +2,10 @@ A logical type's identifier is the pair (Arrow extension name, Arrow extension metadata) of the extension type it returns from ``get_arrow_extension_type``. -The identifier is owned by the type's implementer and opaque to Orcapod: Orcapod -stores it with the column, hashes all of it wherever the type is hashed, and -compares stored metadata byte for byte with what the type says it can read. +The type's implementer owns the metadata and declares the value hash in it. +Orcapod stores the identifier with the column, hashes all of it wherever the +type is hashed, and compares stored metadata byte for byte with what the type +says it can read. The identifier must change whenever an existing value would be stored or hashed differently, and only then. It is not a package version: a type that learns to @@ -16,6 +17,8 @@ from __future__ import annotations +import json +import re from dataclasses import dataclass from typing import TYPE_CHECKING @@ -24,6 +27,8 @@ from orcapod.logical_types.protocols import LogicalTypeProtocol +_VALUE_HASH_LABEL = re.compile(r"[a-z][a-z0-9_]*_v[1-9][0-9]*") + @dataclass(frozen=True) class LogicalTypeIdentifier: @@ -111,19 +116,59 @@ def for_column(self, column: str) -> "LogicalTypeIdentifierError": return error -def version_metadata(version: int) -> bytes: - """Return the extension metadata Orcapod's built-in types use for ``version``. +def version_metadata(version: int, value_hash: str) -> bytes: + """Return canonical metadata for a built-in type's layout and value hash. + + Args: + version: The version number of the type's stored layout. + value_hash: The value hash label or ``stored``. + + Returns: + The metadata bytes, for example ``b'{"value_hash":"stored","version":1}'``. + """ + return json.dumps( + {"value_hash": value_hash, "version": version}, separators=(",", ":") + ).encode("ascii") + - The convention of the built-in types is canonical JSON ``{"version":N}``. - Third-party types are free to use any bytes. +def read_value_hash(metadata: bytes) -> str: + """Return the value hash declared in a non-container type's metadata. Args: - version: The version number of the type's stored layout and hashing. + metadata: The logical type's Arrow extension metadata. Returns: - The metadata bytes, for example ``b'{"version":1}'``. + The value hash label or ``stored``. + + Raises: + ValueError: If the metadata is not a JSON object or its declaration is + missing or invalid. """ - return b'{"version":%d}' % version + try: + parsed = json.loads(metadata.decode("utf-8")) + except (UnicodeDecodeError, ValueError, RecursionError) as exc: + raise ValueError( + "extension metadata must be a JSON object with value_hash" + ) from exc + if not isinstance(parsed, dict): + raise ValueError("extension metadata must be a JSON object with value_hash") + if "value_hash" not in parsed: + raise ValueError("extension metadata is missing the value_hash declaration") + return validate_value_hash(parsed["value_hash"]) + + +def validate_value_hash(value: object) -> str: + """Return a valid value hash declaration or raise ``ValueError``.""" + from orcapod.hashing.hash_utils import SHA256_ALGORITHM + + if isinstance(value, str) and ( + value in ("stored", SHA256_ALGORITHM) or _VALUE_HASH_LABEL.fullmatch(value) + ): + return value + raise ValueError( + f"value_hash must be 'stored', {SHA256_ALGORITHM!r}, or a label of the form " + f"_v; got {value!r}" + ) def arrow_type_identifier(extension_type: "pa.ExtensionType") -> LogicalTypeIdentifier: diff --git a/src/orcapod/logical_types/ignore_list.py b/src/orcapod/logical_types/ignore_list.py index 98ccc013a..62a44baf8 100644 --- a/src/orcapod/logical_types/ignore_list.py +++ b/src/orcapod/logical_types/ignore_list.py @@ -10,11 +10,12 @@ logical type identifier: two lists are two logical types. The metadata has one shape for every such type, canonical JSON with sorted keys: - {"ignore":[],"version":1} - {"ignore":["byte_order","memory_order"],"version":1} + {"ignore":[],"value_hash":"ndarray_v1","version":1} + {"ignore":["byte_order","memory_order"],"value_hash":"ndarray_v1","version":1} ``ignore`` holds the names sorted by code point, each once; it is present also -when empty. ``version`` is the version of the type's stored layout and hashing. +when empty. ``value_hash`` declares the algorithm's label and ``version`` is the +version of the type's stored layout. The list is not part of the value hash preimage. A handler writes every optional property into its preimage as a field that is always present, with the real @@ -43,6 +44,7 @@ from orcapod.logical_types.identifier import ( LogicalTypeIdentifier, LogicalTypeIdentifierError, + validate_value_hash, ) from orcapod.types import ContentHash @@ -86,20 +88,21 @@ def checked_ignore(ignore: Iterable[str], options: Collection[str]) -> tuple[str return tuple(sorted(set(names))) -def ignore_metadata(version: int, ignore: Iterable[str]) -> bytes: +def ignore_metadata(version: int, ignore: Iterable[str], value_hash: str) -> bytes: """Return the extension metadata for a version and an ignore list. Args: - version: The version of the type's stored layout and hashing. + version: The version of the type's stored layout. ignore: The ignored property names, in any order. + value_hash: The value hash label. Returns: Canonical JSON with sorted keys and no whitespace, for example - ``b'{"ignore":["byte_order"],"version":1}'``. + ``b'{"ignore":["byte_order"],"value_hash":"ndarray_v1","version":1}'``. Raises: ValueError: If a name is not lower-case snake case, or ``version`` is not - a positive integer. + a positive integer, or the value hash declaration is invalid. """ if isinstance(version, bool) or not isinstance(version, int) or version < 1: raise ValueError(f"version must be a positive integer, got {version!r}") @@ -111,21 +114,25 @@ def ignore_metadata(version: int, ignore: Iterable[str]) -> bytes: f"got {name!r}" ) return json.dumps( - {"ignore": names, "version": version}, + { + "ignore": names, + "value_hash": validate_value_hash(value_hash), + "version": version, + }, sort_keys=True, separators=(",", ":"), ensure_ascii=True, ).encode("ascii") -def parse_ignore_metadata(metadata: bytes) -> tuple[int, tuple[str, ...]]: - """Return the version and the ignore list of stored extension metadata. +def parse_ignore_metadata(metadata: bytes) -> tuple[int, tuple[str, ...], str]: + """Return the layout version, ignore list and value hash of stored metadata. Args: metadata: The ``ARROW:extension:metadata`` bytes of a column. Returns: - ``(version, names)`` with the names sorted. + ``(version, names, value_hash)`` with the names sorted. Raises: ValueError: If ``metadata`` is not exactly what ``ignore_metadata`` @@ -140,15 +147,17 @@ def parse_ignore_metadata(metadata: bytes) -> tuple[int, tuple[str, ...]]: ) from exc if ( not isinstance(parsed, dict) - or set(parsed) != {"ignore", "version"} + or set(parsed) != {"ignore", "value_hash", "version"} or not isinstance(parsed["ignore"], list) ): raise ValueError( f"extension metadata {metadata!r} is not ignore-list metadata: expected " - 'an object with exactly the keys "ignore" (a list) and "version"' + 'an object with exactly the keys "ignore" (a list), "value_hash" and "version"' ) try: - canonical = ignore_metadata(parsed["version"], parsed["ignore"]) + canonical = ignore_metadata( + parsed["version"], parsed["ignore"], parsed["value_hash"] + ) except (TypeError, ValueError) as exc: raise ValueError( f"extension metadata {metadata!r} is not ignore-list metadata: {exc}" @@ -158,7 +167,7 @@ def parse_ignore_metadata(metadata: bytes) -> tuple[int, tuple[str, ...]]: f"extension metadata {metadata!r} is not in canonical form; expected " f"{canonical!r}" ) - return parsed["version"], tuple(parsed["ignore"]) + return parsed["version"], tuple(parsed["ignore"]), parsed["value_hash"] class _ExtensionFamily: @@ -176,11 +185,13 @@ def __init__( storage_type: "pa.DataType", version: int, options: frozenset[str], + value_hash: str, ) -> None: self.extension_name = extension_name self.storage_type = storage_type self.version = version self.options = options + self.value_hash = value_hash self._arrow_types: dict[tuple[str, ...], pa.ExtensionType] = {} self._polars_class: type[pl.BaseExtension] | None = None self._polars_types: dict[tuple[str, ...], pl.BaseExtension] = {} @@ -212,16 +223,18 @@ def _deserialize( f"Arrow extension type '{self.extension_name}': expected storage_type " f"{self.storage_type!r} but got {storage_type!r}." ) - version, names = parse_ignore_metadata(serialized) + version, names, value_hash = parse_ignore_metadata(serialized) if version != self.version: raise ValueError(f"version {version} is not version {self.version}") + if value_hash != self.value_hash: + raise ValueError(f"value_hash {value_hash!r} is not {self.value_hash!r}") return self.arrow_type(checked_ignore(names, self.options)) def _make_arrow_class( self, ignore: tuple[str, ...] ) -> Callable[[], "pa.ExtensionType"]: family = self - metadata = ignore_metadata(self.version, ignore) + metadata = ignore_metadata(self.version, ignore, self.value_hash) suffix = "__ignore_" + "_and_".join(ignore) if ignore else "" def _init(self: "pa.ExtensionType") -> None: @@ -269,7 +282,9 @@ def polars_type(self, ignore: tuple[str, ...]) -> "pl.BaseExtension": if cached is None: if self._polars_class is None: self._polars_class = self._make_polars_class() - metadata = ignore_metadata(self.version, ignore).decode("ascii") + metadata = ignore_metadata( + self.version, ignore, self.value_hash + ).decode("ascii") cached = self._polars_class(metadata) # pyright: ignore[reportCallIssue] # the synthesized class takes the metadata text self._polars_types[ignore] = cached return cached @@ -315,27 +330,31 @@ def _family( storage_type: "pa.DataType", version: int, options: frozenset[str], + value_hash: str, ) -> _ExtensionFamily: """Return the one extension family of ``extension_name`` in this process. Raises: ValueError: If the name was already declared with another storage type, - version or set of options. + version, set of options or value hash. """ with _LOCK: family = _FAMILIES.get(extension_name) if family is None: - family = _ExtensionFamily(extension_name, storage_type, version, options) + family = _ExtensionFamily( + extension_name, storage_type, version, options, value_hash + ) _FAMILIES[extension_name] = family elif ( family.storage_type != storage_type or family.version != version or family.options != options + or family.value_hash != value_hash ): raise ValueError( f"extension name {extension_name!r} is already declared with storage " f"type {family.storage_type}, version {family.version} and options " - f"{sorted(family.options)}" + f"{sorted(family.options)}, value_hash {family.value_hash!r}" ) return family @@ -350,7 +369,8 @@ class IgnoreListLogicalType(BaseLogicalType): Attributes: EXTENSION_NAME: The Arrow extension name, also the logical type name. STORAGE_TYPE: The Arrow storage type of one value. - VERSION: The version of the stored layout and hashing. + VERSION: The version of the stored layout. + VALUE_HASH: The label of the algorithm that hashes the column values. OPTIONS: The closed set of property names the hash can ignore. python_type: The Python class of the values (a subclass sets it). @@ -364,6 +384,7 @@ class IgnoreListLogicalType(BaseLogicalType): EXTENSION_NAME: ClassVar[str] STORAGE_TYPE: ClassVar["pa.DataType"] VERSION: ClassVar[int] + VALUE_HASH: ClassVar[str] OPTIONS: ClassVar[frozenset[str]] python_type: type = object @@ -382,7 +403,11 @@ def ignore(self) -> tuple[str, ...]: def _extension_family(self) -> _ExtensionFamily: return _family( - self.EXTENSION_NAME, self.STORAGE_TYPE, self.VERSION, self.OPTIONS + self.EXTENSION_NAME, + self.STORAGE_TYPE, + self.VERSION, + self.OPTIONS, + self.VALUE_HASH, ) def get_arrow_extension_type(self) -> "pa.ExtensionType": diff --git a/src/orcapod/logical_types/numpy_type.py b/src/orcapod/logical_types/numpy_type.py index 8773998ad..8f6cccd49 100644 --- a/src/orcapod/logical_types/numpy_type.py +++ b/src/orcapod/logical_types/numpy_type.py @@ -68,6 +68,7 @@ from orcapod.errors import UnsupportedValueError from orcapod.logical_types.array_format import ( + NDARRAY_HASH_LABEL, NDARRAY_EXTENSION_NAME, NDARRAY_OPTIONS, array_digest_v1, @@ -650,6 +651,7 @@ class LogicalNumpyArray(IgnoreListLogicalType): EXTENSION_NAME = NDARRAY_EXTENSION_NAME STORAGE_TYPE = pa.large_binary() VERSION = 1 + VALUE_HASH = NDARRAY_HASH_LABEL OPTIONS = NDARRAY_OPTIONS python_type: type = np.ndarray diff --git a/src/orcapod/logical_types/pandas_type.py b/src/orcapod/logical_types/pandas_type.py index 5049ca2da..5f8d196f7 100644 --- a/src/orcapod/logical_types/pandas_type.py +++ b/src/orcapod/logical_types/pandas_type.py @@ -21,7 +21,9 @@ import pyarrow.ipc from orcapod.hashing.pandas_value_hash import ( + PANDAS_DATAFRAME_HASH_LABEL, PANDAS_DATAFRAME_OPTIONS, + PANDAS_SERIES_HASH_LABEL, PANDAS_SERIES_OPTIONS, PANDAS_UNNAMED_SERIES_COLUMN, pandas_attrs_as_stored, @@ -101,6 +103,7 @@ class LogicalPandasDataFrame(IgnoreListLogicalType): EXTENSION_NAME = "orcapod.pandas.dataframe" STORAGE_TYPE = pa.large_binary() VERSION = _LAYOUT_VERSION + VALUE_HASH = PANDAS_DATAFRAME_HASH_LABEL OPTIONS = PANDAS_DATAFRAME_OPTIONS python_type: type = pd.DataFrame @@ -172,6 +175,7 @@ class LogicalPandasSeries(IgnoreListLogicalType): EXTENSION_NAME = "orcapod.pandas.series" STORAGE_TYPE = pa.large_binary() VERSION = _LAYOUT_VERSION + VALUE_HASH = PANDAS_SERIES_HASH_LABEL OPTIONS = PANDAS_SERIES_OPTIONS python_type: type = pd.Series diff --git a/src/orcapod/logical_types/polars_type.py b/src/orcapod/logical_types/polars_type.py index 4a7d2b125..5a091d906 100644 --- a/src/orcapod/logical_types/polars_type.py +++ b/src/orcapod/logical_types/polars_type.py @@ -428,6 +428,10 @@ def _digest( return hashlib.sha256(descriptor_bytes + b"\x00" + values_digest).digest() +POLARS_DATAFRAME_HASH_LABEL = "polars_dataframe_v1" +POLARS_SERIES_HASH_LABEL = "polars_series_v1" + + def polars_frame_digest( df: pl.DataFrame, *, @@ -592,6 +596,7 @@ class LogicalPolarsDataFrame(IgnoreListLogicalType): EXTENSION_NAME = POLARS_DATAFRAME_EXTENSION_NAME STORAGE_TYPE = pa.large_binary() VERSION = _VERSION + VALUE_HASH = POLARS_DATAFRAME_HASH_LABEL OPTIONS = frozenset({"column_order", "struct_field_order"}) python_type: type = pl.DataFrame @@ -654,6 +659,7 @@ class LogicalPolarsSeries(IgnoreListLogicalType): EXTENSION_NAME = POLARS_SERIES_EXTENSION_NAME STORAGE_TYPE = pa.large_binary() VERSION = _VERSION + VALUE_HASH = POLARS_SERIES_HASH_LABEL OPTIONS = frozenset({"series_name", "struct_field_order"}) python_type: type = pl.Series diff --git a/src/orcapod/logical_types/registry.py b/src/orcapod/logical_types/registry.py index 147aed480..4c3929a77 100644 --- a/src/orcapod/logical_types/registry.py +++ b/src/orcapod/logical_types/registry.py @@ -18,6 +18,7 @@ from orcapod.logical_types.arrow_lifetime import KeptInstances from orcapod.logical_types.identifier import LogicalTypeIdentifierError from orcapod.logical_types.identifier import LogicalTypeIdentifier +from orcapod.logical_types.identifier import read_value_hash from orcapod.logical_types.provisional import warn_provisional from orcapod.logical_types.protocols import ( LogicalTypeProtocol, @@ -371,8 +372,11 @@ def register_logical_type(self, logical_type: LogicalTypeProtocol) -> None: ``python_type`` only for a logical type that binds it, see ``binds_python_type`` on ``ListLogicalType``), or if the Arrow extension name contains ``;`` (the separator between name - and metadata in the identifier text that is hashed). + and metadata in the identifier text that is hashed), or if a + non-container type lacks a valid value hash declaration. """ + from orcapod.logical_types.list_logical_type_factory import ListLogicalType + arrow_ext = logical_type.get_arrow_extension_type() arrow_ext_name = arrow_ext.extension_name if ";" in arrow_ext_name: @@ -380,6 +384,13 @@ def register_logical_type(self, logical_type: LogicalTypeProtocol) -> None: f"Cannot register logical type with Arrow extension name " f"{arrow_ext_name!r}: an extension name must not contain ';'." ) + if not isinstance(logical_type, ListLogicalType): + try: + read_value_hash(arrow_ext.__arrow_ext_serialize__()) + except ValueError as exc: + raise ValueError( + f"Cannot register logical type {arrow_ext_name!r}: {exc}" + ) from exc py_type = logical_type.python_type logical_name = logical_type.logical_type_name # A logical type whose Python type is shared by other logical types (a set diff --git a/src/orcapod/logical_types/torch_type.py b/src/orcapod/logical_types/torch_type.py index 35efbacfe..9ca99e858 100644 --- a/src/orcapod/logical_types/torch_type.py +++ b/src/orcapod/logical_types/torch_type.py @@ -469,6 +469,7 @@ class LogicalTorchTensor(IgnoreListLogicalType): EXTENSION_NAME = TORCH_TENSOR_EXTENSION_NAME STORAGE_TYPE = pa.large_binary() VERSION = TORCH_TENSOR_VERSION + VALUE_HASH = TORCH_TENSOR_HASH_LABEL OPTIONS = OPTIONS python_type: type = torch.Tensor diff --git a/src/orcapod/logical_types/user_class_logical_type.py b/src/orcapod/logical_types/user_class_logical_type.py index 7f9578b3b..40e9c78eb 100644 --- a/src/orcapod/logical_types/user_class_logical_type.py +++ b/src/orcapod/logical_types/user_class_logical_type.py @@ -117,7 +117,7 @@ def __init__( self._field_annotations = field_annotations self._identity_record = identity_record - metadata: dict[str, Any] = {"category": self.category} + metadata: dict[str, Any] = {"category": self.category, "value_hash": "stored"} if identity_record is not None: metadata["identity"] = identity_record metadata_json = uci.canonical_json(metadata) From 245ffd876af794b2c74d6bac53db59bffc703439 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 17:40:37 -0800 Subject: [PATCH 02/20] docs(hashing): explain logical type value hash declarations --- .zed/rules | 18 ++++- CLAUDE.md | 18 ++++- changelog.d/ITL-980.md | 4 + docs/concepts/arrays.md | 6 +- docs/concepts/logical-type-identifiers.md | 74 ++++++++++--------- docs/concepts/your-own-data-types.md | 5 +- docs/dev/design_issues/ITL-980-BL26.md | 18 +++++ docs/reference/hashing.md | 37 +++++----- src/orcapod/hashing/arrow_hashers.py | 5 +- src/orcapod/hashing/hash_utils.py | 2 +- .../semantic_hashing/builtin_handlers.py | 2 +- .../function_info_extractors.py | 2 +- src/orcapod/logical_types/identifier.py | 6 +- .../list_logical_type_factory.py | 4 +- src/orcapod/logical_types/pandas_type.py | 4 +- src/orcapod/logical_types/torch_type.py | 4 +- .../logical_types/user_class_logical_type.py | 3 +- 17 files changed, 132 insertions(+), 80 deletions(-) create mode 100644 changelog.d/ITL-980.md create mode 100644 docs/dev/design_issues/ITL-980-BL26.md diff --git a/.zed/rules b/.zed/rules index 67395d99a..0fab8e3eb 100644 --- a/.zed/rules +++ b/.zed/rules @@ -365,6 +365,9 @@ What runs where (developer, November 16, 2026; ITL-1181): A logical type's identifier is its Arrow extension name plus its Arrow extension metadata (developer, November 11, 2026, ITL-935/ITL-938); see `docs/concepts/logical-type-identifiers.md`. +- Each non-container logical type declares value_hash in its extension metadata. Use + the algorithm's label constant or stored for a type hashed as stored. Native + containers embed the innermost element's declaration and carry no key of their own. - The identifier is declared in one place, the extension type returned by `get_arrow_extension_type()`, and read through `logical_types/identifier.py` (`logical_type_identifier`, `LogicalTypeIdentifier.text`). Never put a logical type's bare @@ -374,8 +377,8 @@ A logical type's identifier is its Arrow extension name plus its Arrow extension not enter the value's preimage; the full identifier (name plus metadata) still enters every type, schema and cell hash. - Change a type's identifier when, and only when, an existing value would be stored or hashed - differently. It is not a package version. Built-in types use `version_metadata(N)` - (`{"version":N}`); a new built-in type must write one, never empty metadata. + differently. It is not a package version. Built-in types use `version_metadata(N, value_hash)` + (`{"value_hash":"stored","version":N}`); a new built-in type must write one, never empty metadata. - A changed identifier is a schema change: it moves stored paths and golden values of that type. Treat it like any other hash change (developer approval, migration assessment). There is no exemption for a logical type's own change (developer, November 15, 2026, ITL-946): if @@ -413,6 +416,8 @@ A logical type's identifier is its Arrow extension name plus its Arrow extension Developer, November 12, 2026 (ITL-981); see `docs/concepts/arrays.md` and `docs/reference/hashing.md` section 8. +- The type passes its algorithm's label constant to ignore_metadata, which writes + value_hash beside ignore and version. - Storage and hashing are decided separately. A value of a library type (`numpy.ndarray`, later tensors and data frames) is stored with the library's own serialization and reads back as given. Its hash is defined by Orcapod on the content: never hash the stored bytes. @@ -425,7 +430,7 @@ Developer, November 12, 2026 (ITL-981); see `docs/concepts/arrays.md` and a data context ignores are declared once, in `hash_ignore` of `contexts/logical_types.json`, and referred to as `hash_ignore:` by the logical type entry and the value handler entry. -- The list is in the extension metadata, `{"ignore":[...],"version":N}` (sorted names, +- The list is in the extension metadata, `{"ignore":[...],"value_hash":"